xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 77013d11e6483b970af25e13c9b892075742f7e5)
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, cnp)
625 	struct vnode *dvp;
626 	struct vnode *vp;
627 	struct componentname *cnp;
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 	LIST_REMOVE(item, wk_all);
1237 	free(item, DtoM(type));
1238 }
1239 
1240 static void
1241 workitem_alloc(item, type, mp)
1242 	struct worklist *item;
1243 	int type;
1244 	struct mount *mp;
1245 {
1246 	struct ufsmount *ump;
1247 
1248 	item->wk_type = type;
1249 	item->wk_mp = mp;
1250 	item->wk_state = 0;
1251 
1252 	ump = VFSTOUFS(mp);
1253 	ACQUIRE_GBLLOCK(&lk);
1254 	dep_current[type]++;
1255 	if (dep_current[type] > dep_highuse[type])
1256 		dep_highuse[type] = dep_current[type];
1257 	dep_total[type]++;
1258 	FREE_GBLLOCK(&lk);
1259 	ACQUIRE_LOCK(ump);
1260 	ump->softdep_curdeps[type] += 1;
1261 	ump->softdep_deps++;
1262 	ump->softdep_accdeps++;
1263 	LIST_INSERT_HEAD(&ump->softdep_alldeps[type], item, wk_all);
1264 	FREE_LOCK(ump);
1265 }
1266 
1267 static void
1268 workitem_reassign(item, newtype)
1269 	struct worklist *item;
1270 	int newtype;
1271 {
1272 	struct ufsmount *ump;
1273 
1274 	ump = VFSTOUFS(item->wk_mp);
1275 	LOCK_OWNED(ump);
1276 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1277 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1278 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1279 	ump->softdep_curdeps[item->wk_type] -= 1;
1280 	ump->softdep_curdeps[newtype] += 1;
1281 	KASSERT(dep_current[item->wk_type] > 0,
1282 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1283 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1284 	ACQUIRE_GBLLOCK(&lk);
1285 	dep_current[newtype]++;
1286 	dep_current[item->wk_type]--;
1287 	if (dep_current[newtype] > dep_highuse[newtype])
1288 		dep_highuse[newtype] = dep_current[newtype];
1289 	dep_total[newtype]++;
1290 	FREE_GBLLOCK(&lk);
1291 	item->wk_type = newtype;
1292 	LIST_REMOVE(item, wk_all);
1293 	LIST_INSERT_HEAD(&ump->softdep_alldeps[newtype], item, wk_all);
1294 }
1295 
1296 /*
1297  * Workitem queue management
1298  */
1299 static int max_softdeps;	/* maximum number of structs before slowdown */
1300 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1301 static int proc_waiting;	/* tracks whether we have a timeout posted */
1302 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1303 static struct callout softdep_callout;
1304 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1305 static int req_clear_remove;	/* syncer process flush some freeblks */
1306 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1307 
1308 /*
1309  * runtime statistics
1310  */
1311 static int stat_flush_threads;	/* number of softdep flushing threads */
1312 static int stat_worklist_push;	/* number of worklist cleanups */
1313 static int stat_delayed_inact;	/* number of delayed inactivation cleanups */
1314 static int stat_blk_limit_push;	/* number of times block limit neared */
1315 static int stat_ino_limit_push;	/* number of times inode limit neared */
1316 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1317 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1318 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1319 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1320 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1321 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1322 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1323 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1324 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1325 static int stat_journal_min;	/* Times hit journal min threshold */
1326 static int stat_journal_low;	/* Times hit journal low threshold */
1327 static int stat_journal_wait;	/* Times blocked in jwait(). */
1328 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1329 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1330 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1331 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1332 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1333 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1334 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1335 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1336 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1337 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1338 
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1340     &max_softdeps, 0, "");
1341 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1342     &tickdelay, 0, "");
1343 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1344     &stat_flush_threads, 0, "");
1345 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1346     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1347 SYSCTL_INT(_debug_softdep, OID_AUTO, delayed_inactivations, CTLFLAG_RD,
1348     &stat_delayed_inact, 0, "");
1349 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1350     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1351 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1352     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1353 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1354     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1355 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1356     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1357 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1358     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1359 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1360     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1361 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1362     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1363 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1364     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1365 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1366     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1367 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1368     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1369 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1370     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1371 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1372     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1373 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1374     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1375 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1376     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1377 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1378     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1379 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1380     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1381 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1382     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1383 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1384     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1385 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1386     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1387 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1388     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1389 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1390     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1391 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1392     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1393 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1394     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1395 
1396 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1397     &softdep_flushcache, 0, "");
1398 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1399     &stat_emptyjblocks, 0, "");
1400 
1401 SYSCTL_DECL(_vfs_ffs);
1402 
1403 /* Whether to recompute the summary at mount time */
1404 static int compute_summary_at_mount = 0;
1405 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1406 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1407 static int print_threads = 0;
1408 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1409     &print_threads, 0, "Notify flusher thread start/stop");
1410 
1411 /* List of all filesystems mounted with soft updates */
1412 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1413 
1414 static void
1415 get_parent_vp_unlock_bp(struct mount *mp, struct buf *bp,
1416     struct diraddhd *diraddhdp, struct diraddhd *unfinishedp)
1417 {
1418 	struct diradd *dap;
1419 
1420 	/*
1421 	 * Requeue unfinished dependencies before
1422 	 * unlocking buffer, which could make
1423 	 * diraddhdp invalid.
1424 	 */
1425 	ACQUIRE_LOCK(VFSTOUFS(mp));
1426 	while ((dap = LIST_FIRST(unfinishedp)) != NULL) {
1427 		LIST_REMOVE(dap, da_pdlist);
1428 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
1429 	}
1430 	FREE_LOCK(VFSTOUFS(mp));
1431 
1432 	bp->b_vflags &= ~BV_SCANNED;
1433 	BUF_NOREC(bp);
1434 	BUF_UNLOCK(bp);
1435 }
1436 
1437 /*
1438  * This function fetches inode inum on mount point mp.  We already
1439  * hold a locked vnode vp, and might have a locked buffer bp belonging
1440  * to vp.
1441 
1442  * We must not block on acquiring the new inode lock as we will get
1443  * into a lock-order reversal with the buffer lock and possibly get a
1444  * deadlock.  Thus if we cannot instantiate the requested vnode
1445  * without sleeping on its lock, we must unlock the vnode and the
1446  * buffer before doing a blocking on the vnode lock.  We return
1447  * ERELOOKUP if we have had to unlock either the vnode or the buffer so
1448  * that the caller can reassess its state.
1449  *
1450  * Top-level VFS code (for syscalls and other consumers, e.g. callers
1451  * of VOP_FSYNC() in syncer) check for ERELOOKUP and restart at safe
1452  * point.
1453  *
1454  * Since callers expect to operate on fully constructed vnode, we also
1455  * recheck v_data after relock, and return ENOENT if NULL.
1456  *
1457  * If unlocking bp, we must unroll dequeueing its unfinished
1458  * dependencies, and clear scan flag, before unlocking.  If unlocking
1459  * vp while it is under deactivation, we re-queue deactivation.
1460  */
1461 static int
1462 get_parent_vp(struct vnode *vp, struct mount *mp, ino_t inum, struct buf *bp,
1463     struct diraddhd *diraddhdp, struct diraddhd *unfinishedp,
1464     struct vnode **rvp)
1465 {
1466 	struct vnode *pvp;
1467 	int error;
1468 	bool bplocked;
1469 
1470 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked");
1471 	for (bplocked = true, pvp = NULL;;) {
1472 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE | LK_NOWAIT, &pvp,
1473 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
1474 		if (error == 0) {
1475 			/*
1476 			 * Since we could have unlocked vp, the inode
1477 			 * number could no longer indicate a
1478 			 * constructed node.  In this case, we must
1479 			 * restart the syscall.
1480 			 */
1481 			if (VTOI(pvp)->i_mode == 0 || !bplocked) {
1482 				if (bp != NULL && bplocked)
1483 					get_parent_vp_unlock_bp(mp, bp,
1484 					    diraddhdp, unfinishedp);
1485 				if (VTOI(pvp)->i_mode == 0)
1486 					vgone(pvp);
1487 				error = ERELOOKUP;
1488 				goto out2;
1489 			}
1490 			goto out1;
1491 		}
1492 		if (bp != NULL && bplocked) {
1493 			get_parent_vp_unlock_bp(mp, bp, diraddhdp, unfinishedp);
1494 			bplocked = false;
1495 		}
1496 
1497 		/*
1498 		 * Do not drop vnode lock while inactivating during
1499 		 * vunref.  This would result in leaks of the VI flags
1500 		 * and reclaiming of non-truncated vnode.  Instead,
1501 		 * re-schedule inactivation hoping that we would be
1502 		 * able to sync inode later.
1503 		 */
1504 		if ((vp->v_iflag & VI_DOINGINACT) != 0 &&
1505 		    (vp->v_vflag & VV_UNREF) != 0) {
1506 			VI_LOCK(vp);
1507 			vp->v_iflag |= VI_OWEINACT;
1508 			VI_UNLOCK(vp);
1509 			return (ERELOOKUP);
1510 		}
1511 
1512 		VOP_UNLOCK(vp);
1513 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &pvp,
1514 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
1515 		if (error != 0) {
1516 			MPASS(error != ERELOOKUP);
1517 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1518 			break;
1519 		}
1520 		if (VTOI(pvp)->i_mode == 0) {
1521 			vgone(pvp);
1522 			vput(pvp);
1523 			pvp = NULL;
1524 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1525 			error = ERELOOKUP;
1526 			break;
1527 		}
1528 		error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
1529 		if (error == 0)
1530 			break;
1531 		vput(pvp);
1532 		pvp = NULL;
1533 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1534 		if (vp->v_data == NULL) {
1535 			error = ENOENT;
1536 			break;
1537 		}
1538 	}
1539 	if (bp != NULL) {
1540 		MPASS(!bplocked);
1541 		error = ERELOOKUP;
1542 	}
1543 out2:
1544 	if (error != 0 && pvp != NULL) {
1545 		vput(pvp);
1546 		pvp = NULL;
1547 	}
1548 out1:
1549 	*rvp = pvp;
1550 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked on return");
1551 	return (error);
1552 }
1553 
1554 /*
1555  * This function cleans the worklist for a filesystem.
1556  * Each filesystem running with soft dependencies gets its own
1557  * thread to run in this function. The thread is started up in
1558  * softdep_mount and shutdown in softdep_unmount. They show up
1559  * as part of the kernel "bufdaemon" process whose process
1560  * entry is available in bufdaemonproc.
1561  */
1562 static int searchfailed;
1563 extern struct proc *bufdaemonproc;
1564 static void
1565 softdep_flush(addr)
1566 	void *addr;
1567 {
1568 	struct mount *mp;
1569 	struct thread *td;
1570 	struct ufsmount *ump;
1571 	int cleanups;
1572 
1573 	td = curthread;
1574 	td->td_pflags |= TDP_NORUNNINGBUF;
1575 	mp = (struct mount *)addr;
1576 	ump = VFSTOUFS(mp);
1577 	atomic_add_int(&stat_flush_threads, 1);
1578 	ACQUIRE_LOCK(ump);
1579 	ump->softdep_flags &= ~FLUSH_STARTING;
1580 	wakeup(&ump->softdep_flushtd);
1581 	FREE_LOCK(ump);
1582 	if (print_threads) {
1583 		if (stat_flush_threads == 1)
1584 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1585 			    bufdaemonproc->p_pid);
1586 		printf("Start thread %s\n", td->td_name);
1587 	}
1588 	for (;;) {
1589 		while (softdep_process_worklist(mp, 0) > 0 ||
1590 		    (MOUNTEDSUJ(mp) &&
1591 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1592 			kthread_suspend_check();
1593 		ACQUIRE_LOCK(ump);
1594 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1595 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1596 			    "sdflush", hz / 2);
1597 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1598 		/*
1599 		 * Check to see if we are done and need to exit.
1600 		 */
1601 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1602 			FREE_LOCK(ump);
1603 			continue;
1604 		}
1605 		ump->softdep_flags &= ~FLUSH_EXIT;
1606 		cleanups = ump->um_softdep->sd_cleanups;
1607 		FREE_LOCK(ump);
1608 		wakeup(&ump->softdep_flags);
1609 		if (print_threads) {
1610 			printf("Stop thread %s: searchfailed %d, "
1611 			    "did cleanups %d\n",
1612 			    td->td_name, searchfailed, cleanups);
1613 		}
1614 		atomic_subtract_int(&stat_flush_threads, 1);
1615 		kthread_exit();
1616 		panic("kthread_exit failed\n");
1617 	}
1618 }
1619 
1620 static void
1621 worklist_speedup(mp)
1622 	struct mount *mp;
1623 {
1624 	struct ufsmount *ump;
1625 
1626 	ump = VFSTOUFS(mp);
1627 	LOCK_OWNED(ump);
1628 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1629 		ump->softdep_flags |= FLUSH_CLEANUP;
1630 	wakeup(&ump->softdep_flushtd);
1631 }
1632 
1633 static void
1634 softdep_send_speedup(struct ufsmount *ump, off_t shortage, u_int flags)
1635 {
1636 	struct buf *bp;
1637 
1638 	if ((ump->um_flags & UM_CANSPEEDUP) == 0)
1639 		return;
1640 
1641 	bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
1642 	bp->b_iocmd = BIO_SPEEDUP;
1643 	bp->b_ioflags = flags;
1644 	bp->b_bcount = omin(shortage, LONG_MAX);
1645 	g_vfs_strategy(ump->um_bo, bp);
1646 	bufwait(bp);
1647 	free(bp, M_TRIM);
1648 }
1649 
1650 static int
1651 softdep_speedup(ump)
1652 	struct ufsmount *ump;
1653 {
1654 	struct ufsmount *altump;
1655 	struct mount_softdeps *sdp;
1656 
1657 	LOCK_OWNED(ump);
1658 	worklist_speedup(ump->um_mountp);
1659 	bd_speedup();
1660 	/*
1661 	 * If we have global shortages, then we need other
1662 	 * filesystems to help with the cleanup. Here we wakeup a
1663 	 * flusher thread for a filesystem that is over its fair
1664 	 * share of resources.
1665 	 */
1666 	if (req_clear_inodedeps || req_clear_remove) {
1667 		ACQUIRE_GBLLOCK(&lk);
1668 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1669 			if ((altump = sdp->sd_ump) == ump)
1670 				continue;
1671 			if (((req_clear_inodedeps &&
1672 			    altump->softdep_curdeps[D_INODEDEP] >
1673 			    max_softdeps / stat_flush_threads) ||
1674 			    (req_clear_remove &&
1675 			    altump->softdep_curdeps[D_DIRREM] >
1676 			    (max_softdeps / 2) / stat_flush_threads)) &&
1677 			    TRY_ACQUIRE_LOCK(altump))
1678 				break;
1679 		}
1680 		if (sdp == NULL) {
1681 			searchfailed++;
1682 			FREE_GBLLOCK(&lk);
1683 		} else {
1684 			/*
1685 			 * Move to the end of the list so we pick a
1686 			 * different one on out next try.
1687 			 */
1688 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1689 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1690 			FREE_GBLLOCK(&lk);
1691 			if ((altump->softdep_flags &
1692 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1693 				altump->softdep_flags |= FLUSH_CLEANUP;
1694 			altump->um_softdep->sd_cleanups++;
1695 			wakeup(&altump->softdep_flushtd);
1696 			FREE_LOCK(altump);
1697 		}
1698 	}
1699 	return (speedup_syncer());
1700 }
1701 
1702 /*
1703  * Add an item to the end of the work queue.
1704  * This routine requires that the lock be held.
1705  * This is the only routine that adds items to the list.
1706  * The following routine is the only one that removes items
1707  * and does so in order from first to last.
1708  */
1709 
1710 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1711 #define	WK_NODELAY	0x0002	/* Process immediately. */
1712 
1713 static void
1714 add_to_worklist(wk, flags)
1715 	struct worklist *wk;
1716 	int flags;
1717 {
1718 	struct ufsmount *ump;
1719 
1720 	ump = VFSTOUFS(wk->wk_mp);
1721 	LOCK_OWNED(ump);
1722 	if (wk->wk_state & ONWORKLIST)
1723 		panic("add_to_worklist: %s(0x%X) already on list",
1724 		    TYPENAME(wk->wk_type), wk->wk_state);
1725 	wk->wk_state |= ONWORKLIST;
1726 	if (ump->softdep_on_worklist == 0) {
1727 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1728 		ump->softdep_worklist_tail = wk;
1729 	} else if (flags & WK_HEAD) {
1730 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1731 	} else {
1732 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1733 		ump->softdep_worklist_tail = wk;
1734 	}
1735 	ump->softdep_on_worklist += 1;
1736 	if (flags & WK_NODELAY)
1737 		worklist_speedup(wk->wk_mp);
1738 }
1739 
1740 /*
1741  * Remove the item to be processed. If we are removing the last
1742  * item on the list, we need to recalculate the tail pointer.
1743  */
1744 static void
1745 remove_from_worklist(wk)
1746 	struct worklist *wk;
1747 {
1748 	struct ufsmount *ump;
1749 
1750 	ump = VFSTOUFS(wk->wk_mp);
1751 	if (ump->softdep_worklist_tail == wk)
1752 		ump->softdep_worklist_tail =
1753 		    (struct worklist *)wk->wk_list.le_prev;
1754 	WORKLIST_REMOVE(wk);
1755 	ump->softdep_on_worklist -= 1;
1756 }
1757 
1758 static void
1759 wake_worklist(wk)
1760 	struct worklist *wk;
1761 {
1762 	if (wk->wk_state & IOWAITING) {
1763 		wk->wk_state &= ~IOWAITING;
1764 		wakeup(wk);
1765 	}
1766 }
1767 
1768 static void
1769 wait_worklist(wk, wmesg)
1770 	struct worklist *wk;
1771 	char *wmesg;
1772 {
1773 	struct ufsmount *ump;
1774 
1775 	ump = VFSTOUFS(wk->wk_mp);
1776 	wk->wk_state |= IOWAITING;
1777 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1778 }
1779 
1780 /*
1781  * Process that runs once per second to handle items in the background queue.
1782  *
1783  * Note that we ensure that everything is done in the order in which they
1784  * appear in the queue. The code below depends on this property to ensure
1785  * that blocks of a file are freed before the inode itself is freed. This
1786  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1787  * until all the old ones have been purged from the dependency lists.
1788  */
1789 static int
1790 softdep_process_worklist(mp, full)
1791 	struct mount *mp;
1792 	int full;
1793 {
1794 	int cnt, matchcnt;
1795 	struct ufsmount *ump;
1796 	long starttime;
1797 
1798 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1799 	ump = VFSTOUFS(mp);
1800 	if (ump->um_softdep == NULL)
1801 		return (0);
1802 	matchcnt = 0;
1803 	ACQUIRE_LOCK(ump);
1804 	starttime = time_second;
1805 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1806 	check_clear_deps(mp);
1807 	while (ump->softdep_on_worklist > 0) {
1808 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1809 			break;
1810 		else
1811 			matchcnt += cnt;
1812 		check_clear_deps(mp);
1813 		/*
1814 		 * We do not generally want to stop for buffer space, but if
1815 		 * we are really being a buffer hog, we will stop and wait.
1816 		 */
1817 		if (should_yield()) {
1818 			FREE_LOCK(ump);
1819 			kern_yield(PRI_USER);
1820 			bwillwrite();
1821 			ACQUIRE_LOCK(ump);
1822 		}
1823 		/*
1824 		 * Never allow processing to run for more than one
1825 		 * second. This gives the syncer thread the opportunity
1826 		 * to pause if appropriate.
1827 		 */
1828 		if (!full && starttime != time_second)
1829 			break;
1830 	}
1831 	if (full == 0)
1832 		journal_unsuspend(ump);
1833 	FREE_LOCK(ump);
1834 	return (matchcnt);
1835 }
1836 
1837 /*
1838  * Process all removes associated with a vnode if we are running out of
1839  * journal space.  Any other process which attempts to flush these will
1840  * be unable as we have the vnodes locked.
1841  */
1842 static void
1843 process_removes(vp)
1844 	struct vnode *vp;
1845 {
1846 	struct inodedep *inodedep;
1847 	struct dirrem *dirrem;
1848 	struct ufsmount *ump;
1849 	struct mount *mp;
1850 	ino_t inum;
1851 
1852 	mp = vp->v_mount;
1853 	ump = VFSTOUFS(mp);
1854 	LOCK_OWNED(ump);
1855 	inum = VTOI(vp)->i_number;
1856 	for (;;) {
1857 top:
1858 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1859 			return;
1860 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1861 			/*
1862 			 * If another thread is trying to lock this vnode
1863 			 * it will fail but we must wait for it to do so
1864 			 * before we can proceed.
1865 			 */
1866 			if (dirrem->dm_state & INPROGRESS) {
1867 				wait_worklist(&dirrem->dm_list, "pwrwait");
1868 				goto top;
1869 			}
1870 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1871 			    (COMPLETE | ONWORKLIST))
1872 				break;
1873 		}
1874 		if (dirrem == NULL)
1875 			return;
1876 		remove_from_worklist(&dirrem->dm_list);
1877 		FREE_LOCK(ump);
1878 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1879 			panic("process_removes: suspended filesystem");
1880 		handle_workitem_remove(dirrem, 0);
1881 		vn_finished_secondary_write(mp);
1882 		ACQUIRE_LOCK(ump);
1883 	}
1884 }
1885 
1886 /*
1887  * Process all truncations associated with a vnode if we are running out
1888  * of journal space.  This is called when the vnode lock is already held
1889  * and no other process can clear the truncation.  This function returns
1890  * a value greater than zero if it did any work.
1891  */
1892 static void
1893 process_truncates(vp)
1894 	struct vnode *vp;
1895 {
1896 	struct inodedep *inodedep;
1897 	struct freeblks *freeblks;
1898 	struct ufsmount *ump;
1899 	struct mount *mp;
1900 	ino_t inum;
1901 	int cgwait;
1902 
1903 	mp = vp->v_mount;
1904 	ump = VFSTOUFS(mp);
1905 	LOCK_OWNED(ump);
1906 	inum = VTOI(vp)->i_number;
1907 	for (;;) {
1908 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1909 			return;
1910 		cgwait = 0;
1911 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1912 			/* Journal entries not yet written.  */
1913 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1914 				jwait(&LIST_FIRST(
1915 				    &freeblks->fb_jblkdephd)->jb_list,
1916 				    MNT_WAIT);
1917 				break;
1918 			}
1919 			/* Another thread is executing this item. */
1920 			if (freeblks->fb_state & INPROGRESS) {
1921 				wait_worklist(&freeblks->fb_list, "ptrwait");
1922 				break;
1923 			}
1924 			/* Freeblks is waiting on a inode write. */
1925 			if ((freeblks->fb_state & COMPLETE) == 0) {
1926 				FREE_LOCK(ump);
1927 				ffs_update(vp, 1);
1928 				ACQUIRE_LOCK(ump);
1929 				break;
1930 			}
1931 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1932 			    (ALLCOMPLETE | ONWORKLIST)) {
1933 				remove_from_worklist(&freeblks->fb_list);
1934 				freeblks->fb_state |= INPROGRESS;
1935 				FREE_LOCK(ump);
1936 				if (vn_start_secondary_write(NULL, &mp,
1937 				    V_NOWAIT))
1938 					panic("process_truncates: "
1939 					    "suspended filesystem");
1940 				handle_workitem_freeblocks(freeblks, 0);
1941 				vn_finished_secondary_write(mp);
1942 				ACQUIRE_LOCK(ump);
1943 				break;
1944 			}
1945 			if (freeblks->fb_cgwait)
1946 				cgwait++;
1947 		}
1948 		if (cgwait) {
1949 			FREE_LOCK(ump);
1950 			sync_cgs(mp, MNT_WAIT);
1951 			ffs_sync_snap(mp, MNT_WAIT);
1952 			ACQUIRE_LOCK(ump);
1953 			continue;
1954 		}
1955 		if (freeblks == NULL)
1956 			break;
1957 	}
1958 	return;
1959 }
1960 
1961 /*
1962  * Process one item on the worklist.
1963  */
1964 static int
1965 process_worklist_item(mp, target, flags)
1966 	struct mount *mp;
1967 	int target;
1968 	int flags;
1969 {
1970 	struct worklist sentinel;
1971 	struct worklist *wk;
1972 	struct ufsmount *ump;
1973 	int matchcnt;
1974 	int error;
1975 
1976 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1977 	/*
1978 	 * If we are being called because of a process doing a
1979 	 * copy-on-write, then it is not safe to write as we may
1980 	 * recurse into the copy-on-write routine.
1981 	 */
1982 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1983 		return (-1);
1984 	PHOLD(curproc);	/* Don't let the stack go away. */
1985 	ump = VFSTOUFS(mp);
1986 	LOCK_OWNED(ump);
1987 	matchcnt = 0;
1988 	sentinel.wk_mp = NULL;
1989 	sentinel.wk_type = D_SENTINEL;
1990 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1991 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1992 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1993 		if (wk->wk_type == D_SENTINEL) {
1994 			LIST_REMOVE(&sentinel, wk_list);
1995 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1996 			continue;
1997 		}
1998 		if (wk->wk_state & INPROGRESS)
1999 			panic("process_worklist_item: %p already in progress.",
2000 			    wk);
2001 		wk->wk_state |= INPROGRESS;
2002 		remove_from_worklist(wk);
2003 		FREE_LOCK(ump);
2004 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
2005 			panic("process_worklist_item: suspended filesystem");
2006 		switch (wk->wk_type) {
2007 		case D_DIRREM:
2008 			/* removal of a directory entry */
2009 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
2010 			break;
2011 
2012 		case D_FREEBLKS:
2013 			/* releasing blocks and/or fragments from a file */
2014 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
2015 			    flags);
2016 			break;
2017 
2018 		case D_FREEFRAG:
2019 			/* releasing a fragment when replaced as a file grows */
2020 			handle_workitem_freefrag(WK_FREEFRAG(wk));
2021 			error = 0;
2022 			break;
2023 
2024 		case D_FREEFILE:
2025 			/* releasing an inode when its link count drops to 0 */
2026 			handle_workitem_freefile(WK_FREEFILE(wk));
2027 			error = 0;
2028 			break;
2029 
2030 		default:
2031 			panic("%s_process_worklist: Unknown type %s",
2032 			    "softdep", TYPENAME(wk->wk_type));
2033 			/* NOTREACHED */
2034 		}
2035 		vn_finished_secondary_write(mp);
2036 		ACQUIRE_LOCK(ump);
2037 		if (error == 0) {
2038 			if (++matchcnt == target)
2039 				break;
2040 			continue;
2041 		}
2042 		/*
2043 		 * We have to retry the worklist item later.  Wake up any
2044 		 * waiters who may be able to complete it immediately and
2045 		 * add the item back to the head so we don't try to execute
2046 		 * it again.
2047 		 */
2048 		wk->wk_state &= ~INPROGRESS;
2049 		wake_worklist(wk);
2050 		add_to_worklist(wk, WK_HEAD);
2051 	}
2052 	/* Sentinal could've become the tail from remove_from_worklist. */
2053 	if (ump->softdep_worklist_tail == &sentinel)
2054 		ump->softdep_worklist_tail =
2055 		    (struct worklist *)sentinel.wk_list.le_prev;
2056 	LIST_REMOVE(&sentinel, wk_list);
2057 	PRELE(curproc);
2058 	return (matchcnt);
2059 }
2060 
2061 /*
2062  * Move dependencies from one buffer to another.
2063  */
2064 int
2065 softdep_move_dependencies(oldbp, newbp)
2066 	struct buf *oldbp;
2067 	struct buf *newbp;
2068 {
2069 	struct worklist *wk, *wktail;
2070 	struct ufsmount *ump;
2071 	int dirty;
2072 
2073 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
2074 		return (0);
2075 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
2076 	    ("softdep_move_dependencies called on non-softdep filesystem"));
2077 	dirty = 0;
2078 	wktail = NULL;
2079 	ump = VFSTOUFS(wk->wk_mp);
2080 	ACQUIRE_LOCK(ump);
2081 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
2082 		LIST_REMOVE(wk, wk_list);
2083 		if (wk->wk_type == D_BMSAFEMAP &&
2084 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
2085 			dirty = 1;
2086 		if (wktail == NULL)
2087 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
2088 		else
2089 			LIST_INSERT_AFTER(wktail, wk, wk_list);
2090 		wktail = wk;
2091 	}
2092 	FREE_LOCK(ump);
2093 
2094 	return (dirty);
2095 }
2096 
2097 /*
2098  * Purge the work list of all items associated with a particular mount point.
2099  */
2100 int
2101 softdep_flushworklist(oldmnt, countp, td)
2102 	struct mount *oldmnt;
2103 	int *countp;
2104 	struct thread *td;
2105 {
2106 	struct vnode *devvp;
2107 	struct ufsmount *ump;
2108 	int count, error;
2109 
2110 	/*
2111 	 * Alternately flush the block device associated with the mount
2112 	 * point and process any dependencies that the flushing
2113 	 * creates. We continue until no more worklist dependencies
2114 	 * are found.
2115 	 */
2116 	*countp = 0;
2117 	error = 0;
2118 	ump = VFSTOUFS(oldmnt);
2119 	devvp = ump->um_devvp;
2120 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
2121 		*countp += count;
2122 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2123 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2124 		VOP_UNLOCK(devvp);
2125 		if (error != 0)
2126 			break;
2127 	}
2128 	return (error);
2129 }
2130 
2131 #define	SU_WAITIDLE_RETRIES	20
2132 static int
2133 softdep_waitidle(struct mount *mp, int flags __unused)
2134 {
2135 	struct ufsmount *ump;
2136 	struct vnode *devvp;
2137 	struct thread *td;
2138 	int error, i;
2139 
2140 	ump = VFSTOUFS(mp);
2141 	KASSERT(ump->um_softdep != NULL,
2142 	    ("softdep_waitidle called on non-softdep filesystem"));
2143 	devvp = ump->um_devvp;
2144 	td = curthread;
2145 	error = 0;
2146 	ACQUIRE_LOCK(ump);
2147 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
2148 		ump->softdep_req = 1;
2149 		KASSERT((flags & FORCECLOSE) == 0 ||
2150 		    ump->softdep_on_worklist == 0,
2151 		    ("softdep_waitidle: work added after flush"));
2152 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
2153 		    "softdeps", 10 * hz);
2154 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2155 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2156 		VOP_UNLOCK(devvp);
2157 		ACQUIRE_LOCK(ump);
2158 		if (error != 0)
2159 			break;
2160 	}
2161 	ump->softdep_req = 0;
2162 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
2163 		error = EBUSY;
2164 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
2165 		    mp);
2166 	}
2167 	FREE_LOCK(ump);
2168 	return (error);
2169 }
2170 
2171 /*
2172  * Flush all vnodes and worklist items associated with a specified mount point.
2173  */
2174 int
2175 softdep_flushfiles(oldmnt, flags, td)
2176 	struct mount *oldmnt;
2177 	int flags;
2178 	struct thread *td;
2179 {
2180 	struct ufsmount *ump;
2181 #ifdef QUOTA
2182 	int i;
2183 #endif
2184 	int error, early, depcount, loopcnt, retry_flush_count, retry;
2185 	int morework;
2186 
2187 	ump = VFSTOUFS(oldmnt);
2188 	KASSERT(ump->um_softdep != NULL,
2189 	    ("softdep_flushfiles called on non-softdep filesystem"));
2190 	loopcnt = 10;
2191 	retry_flush_count = 3;
2192 retry_flush:
2193 	error = 0;
2194 
2195 	/*
2196 	 * Alternately flush the vnodes associated with the mount
2197 	 * point and process any dependencies that the flushing
2198 	 * creates. In theory, this loop can happen at most twice,
2199 	 * but we give it a few extra just to be sure.
2200 	 */
2201 	for (; loopcnt > 0; loopcnt--) {
2202 		/*
2203 		 * Do another flush in case any vnodes were brought in
2204 		 * as part of the cleanup operations.
2205 		 */
2206 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2207 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2208 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2209 			break;
2210 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2211 		    depcount == 0)
2212 			break;
2213 	}
2214 	/*
2215 	 * If we are unmounting then it is an error to fail. If we
2216 	 * are simply trying to downgrade to read-only, then filesystem
2217 	 * activity can keep us busy forever, so we just fail with EBUSY.
2218 	 */
2219 	if (loopcnt == 0) {
2220 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2221 			panic("softdep_flushfiles: looping");
2222 		error = EBUSY;
2223 	}
2224 	if (!error)
2225 		error = softdep_waitidle(oldmnt, flags);
2226 	if (!error) {
2227 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2228 			retry = 0;
2229 			MNT_ILOCK(oldmnt);
2230 			morework = oldmnt->mnt_nvnodelistsize > 0;
2231 #ifdef QUOTA
2232 			UFS_LOCK(ump);
2233 			for (i = 0; i < MAXQUOTAS; i++) {
2234 				if (ump->um_quotas[i] != NULLVP)
2235 					morework = 1;
2236 			}
2237 			UFS_UNLOCK(ump);
2238 #endif
2239 			if (morework) {
2240 				if (--retry_flush_count > 0) {
2241 					retry = 1;
2242 					loopcnt = 3;
2243 				} else
2244 					error = EBUSY;
2245 			}
2246 			MNT_IUNLOCK(oldmnt);
2247 			if (retry)
2248 				goto retry_flush;
2249 		}
2250 	}
2251 	return (error);
2252 }
2253 
2254 /*
2255  * Structure hashing.
2256  *
2257  * There are four types of structures that can be looked up:
2258  *	1) pagedep structures identified by mount point, inode number,
2259  *	   and logical block.
2260  *	2) inodedep structures identified by mount point and inode number.
2261  *	3) newblk structures identified by mount point and
2262  *	   physical block number.
2263  *	4) bmsafemap structures identified by mount point and
2264  *	   cylinder group number.
2265  *
2266  * The "pagedep" and "inodedep" dependency structures are hashed
2267  * separately from the file blocks and inodes to which they correspond.
2268  * This separation helps when the in-memory copy of an inode or
2269  * file block must be replaced. It also obviates the need to access
2270  * an inode or file page when simply updating (or de-allocating)
2271  * dependency structures. Lookup of newblk structures is needed to
2272  * find newly allocated blocks when trying to associate them with
2273  * their allocdirect or allocindir structure.
2274  *
2275  * The lookup routines optionally create and hash a new instance when
2276  * an existing entry is not found. The bmsafemap lookup routine always
2277  * allocates a new structure if an existing one is not found.
2278  */
2279 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2280 
2281 /*
2282  * Structures and routines associated with pagedep caching.
2283  */
2284 #define	PAGEDEP_HASH(ump, inum, lbn) \
2285 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2286 
2287 static int
2288 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2289 	struct pagedep_hashhead *pagedephd;
2290 	ino_t ino;
2291 	ufs_lbn_t lbn;
2292 	struct pagedep **pagedeppp;
2293 {
2294 	struct pagedep *pagedep;
2295 
2296 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2297 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2298 			*pagedeppp = pagedep;
2299 			return (1);
2300 		}
2301 	}
2302 	*pagedeppp = NULL;
2303 	return (0);
2304 }
2305 /*
2306  * Look up a pagedep. Return 1 if found, 0 otherwise.
2307  * If not found, allocate if DEPALLOC flag is passed.
2308  * Found or allocated entry is returned in pagedeppp.
2309  */
2310 static int
2311 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2312 	struct mount *mp;
2313 	struct buf *bp;
2314 	ino_t ino;
2315 	ufs_lbn_t lbn;
2316 	int flags;
2317 	struct pagedep **pagedeppp;
2318 {
2319 	struct pagedep *pagedep;
2320 	struct pagedep_hashhead *pagedephd;
2321 	struct worklist *wk;
2322 	struct ufsmount *ump;
2323 	int ret;
2324 	int i;
2325 
2326 	ump = VFSTOUFS(mp);
2327 	LOCK_OWNED(ump);
2328 	if (bp) {
2329 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2330 			if (wk->wk_type == D_PAGEDEP) {
2331 				*pagedeppp = WK_PAGEDEP(wk);
2332 				return (1);
2333 			}
2334 		}
2335 	}
2336 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2337 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2338 	if (ret) {
2339 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2340 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2341 		return (1);
2342 	}
2343 	if ((flags & DEPALLOC) == 0)
2344 		return (0);
2345 	FREE_LOCK(ump);
2346 	pagedep = malloc(sizeof(struct pagedep),
2347 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2348 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2349 	ACQUIRE_LOCK(ump);
2350 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2351 	if (*pagedeppp) {
2352 		/*
2353 		 * This should never happen since we only create pagedeps
2354 		 * with the vnode lock held.  Could be an assert.
2355 		 */
2356 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2357 		return (ret);
2358 	}
2359 	pagedep->pd_ino = ino;
2360 	pagedep->pd_lbn = lbn;
2361 	LIST_INIT(&pagedep->pd_dirremhd);
2362 	LIST_INIT(&pagedep->pd_pendinghd);
2363 	for (i = 0; i < DAHASHSZ; i++)
2364 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2365 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2366 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2367 	*pagedeppp = pagedep;
2368 	return (0);
2369 }
2370 
2371 /*
2372  * Structures and routines associated with inodedep caching.
2373  */
2374 #define	INODEDEP_HASH(ump, inum) \
2375       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2376 
2377 static int
2378 inodedep_find(inodedephd, inum, inodedeppp)
2379 	struct inodedep_hashhead *inodedephd;
2380 	ino_t inum;
2381 	struct inodedep **inodedeppp;
2382 {
2383 	struct inodedep *inodedep;
2384 
2385 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2386 		if (inum == inodedep->id_ino)
2387 			break;
2388 	if (inodedep) {
2389 		*inodedeppp = inodedep;
2390 		return (1);
2391 	}
2392 	*inodedeppp = NULL;
2393 
2394 	return (0);
2395 }
2396 /*
2397  * Look up an inodedep. Return 1 if found, 0 if not found.
2398  * If not found, allocate if DEPALLOC flag is passed.
2399  * Found or allocated entry is returned in inodedeppp.
2400  */
2401 static int
2402 inodedep_lookup(mp, inum, flags, inodedeppp)
2403 	struct mount *mp;
2404 	ino_t inum;
2405 	int flags;
2406 	struct inodedep **inodedeppp;
2407 {
2408 	struct inodedep *inodedep;
2409 	struct inodedep_hashhead *inodedephd;
2410 	struct ufsmount *ump;
2411 	struct fs *fs;
2412 
2413 	ump = VFSTOUFS(mp);
2414 	LOCK_OWNED(ump);
2415 	fs = ump->um_fs;
2416 	inodedephd = INODEDEP_HASH(ump, inum);
2417 
2418 	if (inodedep_find(inodedephd, inum, inodedeppp))
2419 		return (1);
2420 	if ((flags & DEPALLOC) == 0)
2421 		return (0);
2422 	/*
2423 	 * If the system is over its limit and our filesystem is
2424 	 * responsible for more than our share of that usage and
2425 	 * we are not in a rush, request some inodedep cleanup.
2426 	 */
2427 	if (softdep_excess_items(ump, D_INODEDEP))
2428 		schedule_cleanup(mp);
2429 	else
2430 		FREE_LOCK(ump);
2431 	inodedep = malloc(sizeof(struct inodedep),
2432 		M_INODEDEP, M_SOFTDEP_FLAGS);
2433 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2434 	ACQUIRE_LOCK(ump);
2435 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2436 		WORKITEM_FREE(inodedep, D_INODEDEP);
2437 		return (1);
2438 	}
2439 	inodedep->id_fs = fs;
2440 	inodedep->id_ino = inum;
2441 	inodedep->id_state = ALLCOMPLETE;
2442 	inodedep->id_nlinkdelta = 0;
2443 	inodedep->id_nlinkwrote = -1;
2444 	inodedep->id_savedino1 = NULL;
2445 	inodedep->id_savedsize = -1;
2446 	inodedep->id_savedextsize = -1;
2447 	inodedep->id_savednlink = -1;
2448 	inodedep->id_bmsafemap = NULL;
2449 	inodedep->id_mkdiradd = NULL;
2450 	LIST_INIT(&inodedep->id_dirremhd);
2451 	LIST_INIT(&inodedep->id_pendinghd);
2452 	LIST_INIT(&inodedep->id_inowait);
2453 	LIST_INIT(&inodedep->id_bufwait);
2454 	TAILQ_INIT(&inodedep->id_inoreflst);
2455 	TAILQ_INIT(&inodedep->id_inoupdt);
2456 	TAILQ_INIT(&inodedep->id_newinoupdt);
2457 	TAILQ_INIT(&inodedep->id_extupdt);
2458 	TAILQ_INIT(&inodedep->id_newextupdt);
2459 	TAILQ_INIT(&inodedep->id_freeblklst);
2460 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2461 	*inodedeppp = inodedep;
2462 	return (0);
2463 }
2464 
2465 /*
2466  * Structures and routines associated with newblk caching.
2467  */
2468 #define	NEWBLK_HASH(ump, inum) \
2469 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2470 
2471 static int
2472 newblk_find(newblkhd, newblkno, flags, newblkpp)
2473 	struct newblk_hashhead *newblkhd;
2474 	ufs2_daddr_t newblkno;
2475 	int flags;
2476 	struct newblk **newblkpp;
2477 {
2478 	struct newblk *newblk;
2479 
2480 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2481 		if (newblkno != newblk->nb_newblkno)
2482 			continue;
2483 		/*
2484 		 * If we're creating a new dependency don't match those that
2485 		 * have already been converted to allocdirects.  This is for
2486 		 * a frag extend.
2487 		 */
2488 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2489 			continue;
2490 		break;
2491 	}
2492 	if (newblk) {
2493 		*newblkpp = newblk;
2494 		return (1);
2495 	}
2496 	*newblkpp = NULL;
2497 	return (0);
2498 }
2499 
2500 /*
2501  * Look up a newblk. Return 1 if found, 0 if not found.
2502  * If not found, allocate if DEPALLOC flag is passed.
2503  * Found or allocated entry is returned in newblkpp.
2504  */
2505 static int
2506 newblk_lookup(mp, newblkno, flags, newblkpp)
2507 	struct mount *mp;
2508 	ufs2_daddr_t newblkno;
2509 	int flags;
2510 	struct newblk **newblkpp;
2511 {
2512 	struct newblk *newblk;
2513 	struct newblk_hashhead *newblkhd;
2514 	struct ufsmount *ump;
2515 
2516 	ump = VFSTOUFS(mp);
2517 	LOCK_OWNED(ump);
2518 	newblkhd = NEWBLK_HASH(ump, newblkno);
2519 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2520 		return (1);
2521 	if ((flags & DEPALLOC) == 0)
2522 		return (0);
2523 	if (softdep_excess_items(ump, D_NEWBLK) ||
2524 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2525 	    softdep_excess_items(ump, D_ALLOCINDIR))
2526 		schedule_cleanup(mp);
2527 	else
2528 		FREE_LOCK(ump);
2529 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2530 	    M_SOFTDEP_FLAGS | M_ZERO);
2531 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2532 	ACQUIRE_LOCK(ump);
2533 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2534 		WORKITEM_FREE(newblk, D_NEWBLK);
2535 		return (1);
2536 	}
2537 	newblk->nb_freefrag = NULL;
2538 	LIST_INIT(&newblk->nb_indirdeps);
2539 	LIST_INIT(&newblk->nb_newdirblk);
2540 	LIST_INIT(&newblk->nb_jwork);
2541 	newblk->nb_state = ATTACHED;
2542 	newblk->nb_newblkno = newblkno;
2543 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2544 	*newblkpp = newblk;
2545 	return (0);
2546 }
2547 
2548 /*
2549  * Structures and routines associated with freed indirect block caching.
2550  */
2551 #define	INDIR_HASH(ump, blkno) \
2552 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2553 
2554 /*
2555  * Lookup an indirect block in the indir hash table.  The freework is
2556  * removed and potentially freed.  The caller must do a blocking journal
2557  * write before writing to the blkno.
2558  */
2559 static int
2560 indirblk_lookup(mp, blkno)
2561 	struct mount *mp;
2562 	ufs2_daddr_t blkno;
2563 {
2564 	struct freework *freework;
2565 	struct indir_hashhead *wkhd;
2566 	struct ufsmount *ump;
2567 
2568 	ump = VFSTOUFS(mp);
2569 	wkhd = INDIR_HASH(ump, blkno);
2570 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2571 		if (freework->fw_blkno != blkno)
2572 			continue;
2573 		indirblk_remove(freework);
2574 		return (1);
2575 	}
2576 	return (0);
2577 }
2578 
2579 /*
2580  * Insert an indirect block represented by freework into the indirblk
2581  * hash table so that it may prevent the block from being re-used prior
2582  * to the journal being written.
2583  */
2584 static void
2585 indirblk_insert(freework)
2586 	struct freework *freework;
2587 {
2588 	struct jblocks *jblocks;
2589 	struct jseg *jseg;
2590 	struct ufsmount *ump;
2591 
2592 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2593 	jblocks = ump->softdep_jblocks;
2594 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2595 	if (jseg == NULL)
2596 		return;
2597 
2598 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2599 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2600 	    fw_next);
2601 	freework->fw_state &= ~DEPCOMPLETE;
2602 }
2603 
2604 static void
2605 indirblk_remove(freework)
2606 	struct freework *freework;
2607 {
2608 	struct ufsmount *ump;
2609 
2610 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2611 	LIST_REMOVE(freework, fw_segs);
2612 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2613 	freework->fw_state |= DEPCOMPLETE;
2614 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2615 		WORKITEM_FREE(freework, D_FREEWORK);
2616 }
2617 
2618 /*
2619  * Executed during filesystem system initialization before
2620  * mounting any filesystems.
2621  */
2622 void
2623 softdep_initialize()
2624 {
2625 
2626 	TAILQ_INIT(&softdepmounts);
2627 #ifdef __LP64__
2628 	max_softdeps = desiredvnodes * 4;
2629 #else
2630 	max_softdeps = desiredvnodes * 2;
2631 #endif
2632 
2633 	/* initialise bioops hack */
2634 	bioops.io_start = softdep_disk_io_initiation;
2635 	bioops.io_complete = softdep_disk_write_complete;
2636 	bioops.io_deallocate = softdep_deallocate_dependencies;
2637 	bioops.io_countdeps = softdep_count_dependencies;
2638 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2639 
2640 	/* Initialize the callout with an mtx. */
2641 	callout_init_mtx(&softdep_callout, &lk, 0);
2642 }
2643 
2644 /*
2645  * Executed after all filesystems have been unmounted during
2646  * filesystem module unload.
2647  */
2648 void
2649 softdep_uninitialize()
2650 {
2651 
2652 	/* clear bioops hack */
2653 	bioops.io_start = NULL;
2654 	bioops.io_complete = NULL;
2655 	bioops.io_deallocate = NULL;
2656 	bioops.io_countdeps = NULL;
2657 	softdep_ast_cleanup = NULL;
2658 
2659 	callout_drain(&softdep_callout);
2660 }
2661 
2662 /*
2663  * Called at mount time to notify the dependency code that a
2664  * filesystem wishes to use it.
2665  */
2666 int
2667 softdep_mount(devvp, mp, fs, cred)
2668 	struct vnode *devvp;
2669 	struct mount *mp;
2670 	struct fs *fs;
2671 	struct ucred *cred;
2672 {
2673 	struct csum_total cstotal;
2674 	struct mount_softdeps *sdp;
2675 	struct ufsmount *ump;
2676 	struct cg *cgp;
2677 	struct buf *bp;
2678 	u_int cyl, i;
2679 	int error;
2680 
2681 	ump = VFSTOUFS(mp);
2682 
2683 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2684 	    M_WAITOK | M_ZERO);
2685 	rw_init(&sdp->sd_fslock, "SUrw");
2686 	sdp->sd_ump = ump;
2687 	LIST_INIT(&sdp->sd_workitem_pending);
2688 	LIST_INIT(&sdp->sd_journal_pending);
2689 	TAILQ_INIT(&sdp->sd_unlinked);
2690 	LIST_INIT(&sdp->sd_dirtycg);
2691 	sdp->sd_worklist_tail = NULL;
2692 	sdp->sd_on_worklist = 0;
2693 	sdp->sd_deps = 0;
2694 	LIST_INIT(&sdp->sd_mkdirlisthd);
2695 	sdp->sd_pdhash = hashinit(desiredvnodes / 5, M_PAGEDEP,
2696 	    &sdp->sd_pdhashsize);
2697 	sdp->sd_pdnextclean = 0;
2698 	sdp->sd_idhash = hashinit(desiredvnodes, M_INODEDEP,
2699 	    &sdp->sd_idhashsize);
2700 	sdp->sd_idnextclean = 0;
2701 	sdp->sd_newblkhash = hashinit(max_softdeps / 2,  M_NEWBLK,
2702 	    &sdp->sd_newblkhashsize);
2703 	sdp->sd_bmhash = hashinit(1024, M_BMSAFEMAP, &sdp->sd_bmhashsize);
2704 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2705 	sdp->sd_indirhash = malloc(i * sizeof(struct indir_hashhead),
2706 	    M_FREEWORK, M_WAITOK);
2707 	sdp->sd_indirhashsize = i - 1;
2708 	for (i = 0; i <= sdp->sd_indirhashsize; i++)
2709 		TAILQ_INIT(&sdp->sd_indirhash[i]);
2710 	for (i = 0; i <= D_LAST; i++)
2711 		LIST_INIT(&sdp->sd_alldeps[i]);
2712 	ACQUIRE_GBLLOCK(&lk);
2713 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2714 	FREE_GBLLOCK(&lk);
2715 
2716 	ump->um_softdep = sdp;
2717 	MNT_ILOCK(mp);
2718 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2719 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2720 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2721 		    MNTK_SOFTDEP | MNTK_NOASYNC;
2722 	}
2723 	MNT_IUNLOCK(mp);
2724 
2725 	if ((fs->fs_flags & FS_SUJ) &&
2726 	    (error = journal_mount(mp, fs, cred)) != 0) {
2727 		printf("Failed to start journal: %d\n", error);
2728 		softdep_unmount(mp);
2729 		return (error);
2730 	}
2731 	/*
2732 	 * Start our flushing thread in the bufdaemon process.
2733 	 */
2734 	ACQUIRE_LOCK(ump);
2735 	ump->softdep_flags |= FLUSH_STARTING;
2736 	FREE_LOCK(ump);
2737 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2738 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2739 	    mp->mnt_stat.f_mntonname);
2740 	ACQUIRE_LOCK(ump);
2741 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2742 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2743 		    hz / 2);
2744 	}
2745 	FREE_LOCK(ump);
2746 	/*
2747 	 * When doing soft updates, the counters in the
2748 	 * superblock may have gotten out of sync. Recomputation
2749 	 * can take a long time and can be deferred for background
2750 	 * fsck.  However, the old behavior of scanning the cylinder
2751 	 * groups and recalculating them at mount time is available
2752 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2753 	 */
2754 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2755 		return (0);
2756 	bzero(&cstotal, sizeof cstotal);
2757 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2758 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2759 		    fs->fs_cgsize, cred, &bp)) != 0) {
2760 			brelse(bp);
2761 			softdep_unmount(mp);
2762 			return (error);
2763 		}
2764 		cgp = (struct cg *)bp->b_data;
2765 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2766 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2767 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2768 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2769 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2770 		brelse(bp);
2771 	}
2772 #ifdef INVARIANTS
2773 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2774 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2775 #endif
2776 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2777 	return (0);
2778 }
2779 
2780 void
2781 softdep_unmount(mp)
2782 	struct mount *mp;
2783 {
2784 	struct ufsmount *ump;
2785 	struct mount_softdeps *ums;
2786 
2787 	ump = VFSTOUFS(mp);
2788 	KASSERT(ump->um_softdep != NULL,
2789 	    ("softdep_unmount called on non-softdep filesystem"));
2790 	MNT_ILOCK(mp);
2791 	mp->mnt_flag &= ~MNT_SOFTDEP;
2792 	if ((mp->mnt_flag & MNT_SUJ) == 0) {
2793 		MNT_IUNLOCK(mp);
2794 	} else {
2795 		mp->mnt_flag &= ~MNT_SUJ;
2796 		MNT_IUNLOCK(mp);
2797 		journal_unmount(ump);
2798 	}
2799 	/*
2800 	 * Shut down our flushing thread. Check for NULL is if
2801 	 * softdep_mount errors out before the thread has been created.
2802 	 */
2803 	if (ump->softdep_flushtd != NULL) {
2804 		ACQUIRE_LOCK(ump);
2805 		ump->softdep_flags |= FLUSH_EXIT;
2806 		wakeup(&ump->softdep_flushtd);
2807 		while ((ump->softdep_flags & FLUSH_EXIT) != 0) {
2808 			msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM,
2809 			    "sdwait", 0);
2810 		}
2811 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2812 		    ("Thread shutdown failed"));
2813 		FREE_LOCK(ump);
2814 	}
2815 
2816 	/*
2817 	 * We are no longer have softdep structure attached to ump.
2818 	 */
2819 	ums = ump->um_softdep;
2820 	ACQUIRE_GBLLOCK(&lk);
2821 	TAILQ_REMOVE(&softdepmounts, ums, sd_next);
2822 	FREE_GBLLOCK(&lk);
2823 	ump->um_softdep = NULL;
2824 
2825 	KASSERT(ums->sd_on_journal == 0,
2826 	    ("ump %p ums %p on_journal %d", ump, ums, ums->sd_on_journal));
2827 	KASSERT(ums->sd_on_worklist == 0,
2828 	    ("ump %p ums %p on_worklist %d", ump, ums, ums->sd_on_worklist));
2829 	KASSERT(ums->sd_deps == 0,
2830 	    ("ump %p ums %p deps %d", ump, ums, ums->sd_deps));
2831 
2832 	/*
2833 	 * Free up our resources.
2834 	 */
2835 	rw_destroy(&ums->sd_fslock);
2836 	hashdestroy(ums->sd_pdhash, M_PAGEDEP, ums->sd_pdhashsize);
2837 	hashdestroy(ums->sd_idhash, M_INODEDEP, ums->sd_idhashsize);
2838 	hashdestroy(ums->sd_newblkhash, M_NEWBLK, ums->sd_newblkhashsize);
2839 	hashdestroy(ums->sd_bmhash, M_BMSAFEMAP, ums->sd_bmhashsize);
2840 	free(ums->sd_indirhash, M_FREEWORK);
2841 #ifdef INVARIANTS
2842 	for (int i = 0; i <= D_LAST; i++) {
2843 		KASSERT(ums->sd_curdeps[i] == 0,
2844 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2845 		    TYPENAME(i), ums->sd_curdeps[i]));
2846 		KASSERT(LIST_EMPTY(&ums->sd_alldeps[i]),
2847 		    ("Unmount %s: Dep type %s not empty (%p)",
2848 		    ump->um_fs->fs_fsmnt,
2849 		    TYPENAME(i), LIST_FIRST(&ums->sd_alldeps[i])));
2850 	}
2851 #endif
2852 	free(ums, M_MOUNTDATA);
2853 }
2854 
2855 static struct jblocks *
2856 jblocks_create(void)
2857 {
2858 	struct jblocks *jblocks;
2859 
2860 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2861 	TAILQ_INIT(&jblocks->jb_segs);
2862 	jblocks->jb_avail = 10;
2863 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2864 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2865 
2866 	return (jblocks);
2867 }
2868 
2869 static ufs2_daddr_t
2870 jblocks_alloc(jblocks, bytes, actual)
2871 	struct jblocks *jblocks;
2872 	int bytes;
2873 	int *actual;
2874 {
2875 	ufs2_daddr_t daddr;
2876 	struct jextent *jext;
2877 	int freecnt;
2878 	int blocks;
2879 
2880 	blocks = bytes / DEV_BSIZE;
2881 	jext = &jblocks->jb_extent[jblocks->jb_head];
2882 	freecnt = jext->je_blocks - jblocks->jb_off;
2883 	if (freecnt == 0) {
2884 		jblocks->jb_off = 0;
2885 		if (++jblocks->jb_head > jblocks->jb_used)
2886 			jblocks->jb_head = 0;
2887 		jext = &jblocks->jb_extent[jblocks->jb_head];
2888 		freecnt = jext->je_blocks;
2889 	}
2890 	if (freecnt > blocks)
2891 		freecnt = blocks;
2892 	*actual = freecnt * DEV_BSIZE;
2893 	daddr = jext->je_daddr + jblocks->jb_off;
2894 	jblocks->jb_off += freecnt;
2895 	jblocks->jb_free -= freecnt;
2896 
2897 	return (daddr);
2898 }
2899 
2900 static void
2901 jblocks_free(jblocks, mp, bytes)
2902 	struct jblocks *jblocks;
2903 	struct mount *mp;
2904 	int bytes;
2905 {
2906 
2907 	LOCK_OWNED(VFSTOUFS(mp));
2908 	jblocks->jb_free += bytes / DEV_BSIZE;
2909 	if (jblocks->jb_suspended)
2910 		worklist_speedup(mp);
2911 	wakeup(jblocks);
2912 }
2913 
2914 static void
2915 jblocks_destroy(jblocks)
2916 	struct jblocks *jblocks;
2917 {
2918 
2919 	if (jblocks->jb_extent)
2920 		free(jblocks->jb_extent, M_JBLOCKS);
2921 	free(jblocks, M_JBLOCKS);
2922 }
2923 
2924 static void
2925 jblocks_add(jblocks, daddr, blocks)
2926 	struct jblocks *jblocks;
2927 	ufs2_daddr_t daddr;
2928 	int blocks;
2929 {
2930 	struct jextent *jext;
2931 
2932 	jblocks->jb_blocks += blocks;
2933 	jblocks->jb_free += blocks;
2934 	jext = &jblocks->jb_extent[jblocks->jb_used];
2935 	/* Adding the first block. */
2936 	if (jext->je_daddr == 0) {
2937 		jext->je_daddr = daddr;
2938 		jext->je_blocks = blocks;
2939 		return;
2940 	}
2941 	/* Extending the last extent. */
2942 	if (jext->je_daddr + jext->je_blocks == daddr) {
2943 		jext->je_blocks += blocks;
2944 		return;
2945 	}
2946 	/* Adding a new extent. */
2947 	if (++jblocks->jb_used == jblocks->jb_avail) {
2948 		jblocks->jb_avail *= 2;
2949 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2950 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2951 		memcpy(jext, jblocks->jb_extent,
2952 		    sizeof(struct jextent) * jblocks->jb_used);
2953 		free(jblocks->jb_extent, M_JBLOCKS);
2954 		jblocks->jb_extent = jext;
2955 	}
2956 	jext = &jblocks->jb_extent[jblocks->jb_used];
2957 	jext->je_daddr = daddr;
2958 	jext->je_blocks = blocks;
2959 	return;
2960 }
2961 
2962 int
2963 softdep_journal_lookup(mp, vpp)
2964 	struct mount *mp;
2965 	struct vnode **vpp;
2966 {
2967 	struct componentname cnp;
2968 	struct vnode *dvp;
2969 	ino_t sujournal;
2970 	int error;
2971 
2972 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2973 	if (error)
2974 		return (error);
2975 	bzero(&cnp, sizeof(cnp));
2976 	cnp.cn_nameiop = LOOKUP;
2977 	cnp.cn_flags = ISLASTCN;
2978 	cnp.cn_thread = curthread;
2979 	cnp.cn_cred = curthread->td_ucred;
2980 	cnp.cn_pnbuf = SUJ_FILE;
2981 	cnp.cn_nameptr = SUJ_FILE;
2982 	cnp.cn_namelen = strlen(SUJ_FILE);
2983 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2984 	vput(dvp);
2985 	if (error != 0)
2986 		return (error);
2987 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2988 	return (error);
2989 }
2990 
2991 /*
2992  * Open and verify the journal file.
2993  */
2994 static int
2995 journal_mount(mp, fs, cred)
2996 	struct mount *mp;
2997 	struct fs *fs;
2998 	struct ucred *cred;
2999 {
3000 	struct jblocks *jblocks;
3001 	struct ufsmount *ump;
3002 	struct vnode *vp;
3003 	struct inode *ip;
3004 	ufs2_daddr_t blkno;
3005 	int bcount;
3006 	int error;
3007 	int i;
3008 
3009 	ump = VFSTOUFS(mp);
3010 	ump->softdep_journal_tail = NULL;
3011 	ump->softdep_on_journal = 0;
3012 	ump->softdep_accdeps = 0;
3013 	ump->softdep_req = 0;
3014 	ump->softdep_jblocks = NULL;
3015 	error = softdep_journal_lookup(mp, &vp);
3016 	if (error != 0) {
3017 		printf("Failed to find journal.  Use tunefs to create one\n");
3018 		return (error);
3019 	}
3020 	ip = VTOI(vp);
3021 	if (ip->i_size < SUJ_MIN) {
3022 		error = ENOSPC;
3023 		goto out;
3024 	}
3025 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
3026 	jblocks = jblocks_create();
3027 	for (i = 0; i < bcount; i++) {
3028 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
3029 		if (error)
3030 			break;
3031 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
3032 	}
3033 	if (error) {
3034 		jblocks_destroy(jblocks);
3035 		goto out;
3036 	}
3037 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
3038 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
3039 	ump->softdep_jblocks = jblocks;
3040 
3041 	MNT_ILOCK(mp);
3042 	mp->mnt_flag |= MNT_SUJ;
3043 	MNT_IUNLOCK(mp);
3044 
3045 	/*
3046 	 * Only validate the journal contents if the
3047 	 * filesystem is clean, otherwise we write the logs
3048 	 * but they'll never be used.  If the filesystem was
3049 	 * still dirty when we mounted it the journal is
3050 	 * invalid and a new journal can only be valid if it
3051 	 * starts from a clean mount.
3052 	 */
3053 	if (fs->fs_clean) {
3054 		DIP_SET(ip, i_modrev, fs->fs_mtime);
3055 		ip->i_flags |= IN_MODIFIED;
3056 		ffs_update(vp, 1);
3057 	}
3058 out:
3059 	vput(vp);
3060 	return (error);
3061 }
3062 
3063 static void
3064 journal_unmount(ump)
3065 	struct ufsmount *ump;
3066 {
3067 
3068 	if (ump->softdep_jblocks)
3069 		jblocks_destroy(ump->softdep_jblocks);
3070 	ump->softdep_jblocks = NULL;
3071 }
3072 
3073 /*
3074  * Called when a journal record is ready to be written.  Space is allocated
3075  * and the journal entry is created when the journal is flushed to stable
3076  * store.
3077  */
3078 static void
3079 add_to_journal(wk)
3080 	struct worklist *wk;
3081 {
3082 	struct ufsmount *ump;
3083 
3084 	ump = VFSTOUFS(wk->wk_mp);
3085 	LOCK_OWNED(ump);
3086 	if (wk->wk_state & ONWORKLIST)
3087 		panic("add_to_journal: %s(0x%X) already on list",
3088 		    TYPENAME(wk->wk_type), wk->wk_state);
3089 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
3090 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
3091 		ump->softdep_jblocks->jb_age = ticks;
3092 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
3093 	} else
3094 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
3095 	ump->softdep_journal_tail = wk;
3096 	ump->softdep_on_journal += 1;
3097 }
3098 
3099 /*
3100  * Remove an arbitrary item for the journal worklist maintain the tail
3101  * pointer.  This happens when a new operation obviates the need to
3102  * journal an old operation.
3103  */
3104 static void
3105 remove_from_journal(wk)
3106 	struct worklist *wk;
3107 {
3108 	struct ufsmount *ump;
3109 
3110 	ump = VFSTOUFS(wk->wk_mp);
3111 	LOCK_OWNED(ump);
3112 #ifdef INVARIANTS
3113 	{
3114 		struct worklist *wkn;
3115 
3116 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
3117 			if (wkn == wk)
3118 				break;
3119 		if (wkn == NULL)
3120 			panic("remove_from_journal: %p is not in journal", wk);
3121 	}
3122 #endif
3123 	/*
3124 	 * We emulate a TAILQ to save space in most structures which do not
3125 	 * require TAILQ semantics.  Here we must update the tail position
3126 	 * when removing the tail which is not the final entry. This works
3127 	 * only if the worklist linkage are at the beginning of the structure.
3128 	 */
3129 	if (ump->softdep_journal_tail == wk)
3130 		ump->softdep_journal_tail =
3131 		    (struct worklist *)wk->wk_list.le_prev;
3132 	WORKLIST_REMOVE(wk);
3133 	ump->softdep_on_journal -= 1;
3134 }
3135 
3136 /*
3137  * Check for journal space as well as dependency limits so the prelink
3138  * code can throttle both journaled and non-journaled filesystems.
3139  * Threshold is 0 for low and 1 for min.
3140  */
3141 static int
3142 journal_space(ump, thresh)
3143 	struct ufsmount *ump;
3144 	int thresh;
3145 {
3146 	struct jblocks *jblocks;
3147 	int limit, avail;
3148 
3149 	jblocks = ump->softdep_jblocks;
3150 	if (jblocks == NULL)
3151 		return (1);
3152 	/*
3153 	 * We use a tighter restriction here to prevent request_cleanup()
3154 	 * running in threads from running into locks we currently hold.
3155 	 * We have to be over the limit and our filesystem has to be
3156 	 * responsible for more than our share of that usage.
3157 	 */
3158 	limit = (max_softdeps / 10) * 9;
3159 	if (dep_current[D_INODEDEP] > limit &&
3160 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
3161 		return (0);
3162 	if (thresh)
3163 		thresh = jblocks->jb_min;
3164 	else
3165 		thresh = jblocks->jb_low;
3166 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
3167 	avail = jblocks->jb_free - avail;
3168 
3169 	return (avail > thresh);
3170 }
3171 
3172 static void
3173 journal_suspend(ump)
3174 	struct ufsmount *ump;
3175 {
3176 	struct jblocks *jblocks;
3177 	struct mount *mp;
3178 	bool set;
3179 
3180 	mp = UFSTOVFS(ump);
3181 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
3182 		return;
3183 
3184 	jblocks = ump->softdep_jblocks;
3185 	vfs_op_enter(mp);
3186 	set = false;
3187 	MNT_ILOCK(mp);
3188 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
3189 		stat_journal_min++;
3190 		mp->mnt_kern_flag |= MNTK_SUSPEND;
3191 		mp->mnt_susp_owner = ump->softdep_flushtd;
3192 		set = true;
3193 	}
3194 	jblocks->jb_suspended = 1;
3195 	MNT_IUNLOCK(mp);
3196 	if (!set)
3197 		vfs_op_exit(mp);
3198 }
3199 
3200 static int
3201 journal_unsuspend(struct ufsmount *ump)
3202 {
3203 	struct jblocks *jblocks;
3204 	struct mount *mp;
3205 
3206 	mp = UFSTOVFS(ump);
3207 	jblocks = ump->softdep_jblocks;
3208 
3209 	if (jblocks != NULL && jblocks->jb_suspended &&
3210 	    journal_space(ump, jblocks->jb_min)) {
3211 		jblocks->jb_suspended = 0;
3212 		FREE_LOCK(ump);
3213 		mp->mnt_susp_owner = curthread;
3214 		vfs_write_resume(mp, 0);
3215 		ACQUIRE_LOCK(ump);
3216 		return (1);
3217 	}
3218 	return (0);
3219 }
3220 
3221 static void
3222 journal_check_space(struct ufsmount *ump)
3223 {
3224 	struct mount *mp;
3225 
3226 	LOCK_OWNED(ump);
3227 
3228 	if (journal_space(ump, 0) == 0) {
3229 		softdep_speedup(ump);
3230 		mp = UFSTOVFS(ump);
3231 		FREE_LOCK(ump);
3232 		VFS_SYNC(mp, MNT_NOWAIT);
3233 		ffs_sbupdate(ump, MNT_WAIT, 0);
3234 		ACQUIRE_LOCK(ump);
3235 		if (journal_space(ump, 1) == 0)
3236 			journal_suspend(ump);
3237 	}
3238 }
3239 
3240 /*
3241  * Called before any allocation function to be certain that there is
3242  * sufficient space in the journal prior to creating any new records.
3243  * Since in the case of block allocation we may have multiple locked
3244  * buffers at the time of the actual allocation we can not block
3245  * when the journal records are created.  Doing so would create a deadlock
3246  * if any of these buffers needed to be flushed to reclaim space.  Instead
3247  * we require a sufficiently large amount of available space such that
3248  * each thread in the system could have passed this allocation check and
3249  * still have sufficient free space.  With 20% of a minimum journal size
3250  * of 1MB we have 6553 records available.
3251  */
3252 int
3253 softdep_prealloc(vp, waitok)
3254 	struct vnode *vp;
3255 	int waitok;
3256 {
3257 	struct ufsmount *ump;
3258 
3259 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3260 	    ("softdep_prealloc called on non-softdep filesystem"));
3261 	/*
3262 	 * Nothing to do if we are not running journaled soft updates.
3263 	 * If we currently hold the snapshot lock, we must avoid
3264 	 * handling other resources that could cause deadlock.  Do not
3265 	 * touch quotas vnode since it is typically recursed with
3266 	 * other vnode locks held.
3267 	 */
3268 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3269 	    (vp->v_vflag & VV_SYSTEM) != 0)
3270 		return (0);
3271 	ump = VFSTOUFS(vp->v_mount);
3272 	ACQUIRE_LOCK(ump);
3273 	if (journal_space(ump, 0)) {
3274 		FREE_LOCK(ump);
3275 		return (0);
3276 	}
3277 	stat_journal_low++;
3278 	FREE_LOCK(ump);
3279 	if (waitok == MNT_NOWAIT)
3280 		return (ENOSPC);
3281 	/*
3282 	 * Attempt to sync this vnode once to flush any journal
3283 	 * work attached to it.
3284 	 */
3285 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3286 		ffs_syncvnode(vp, waitok, 0);
3287 	ACQUIRE_LOCK(ump);
3288 	process_removes(vp);
3289 	process_truncates(vp);
3290 	journal_check_space(ump);
3291 	FREE_LOCK(ump);
3292 
3293 	return (0);
3294 }
3295 
3296 /*
3297  * Try hard to sync all data and metadata for the vnode, and workitems
3298  * flushing which might conflict with the vnode lock.  This is a
3299  * helper for softdep_prerename().
3300  */
3301 static int
3302 softdep_prerename_vnode(ump, vp)
3303 	struct ufsmount *ump;
3304 	struct vnode *vp;
3305 {
3306 	int error;
3307 
3308 	ASSERT_VOP_ELOCKED(vp, "prehandle");
3309 	if (vp->v_data == NULL)
3310 		return (0);
3311 	error = VOP_FSYNC(vp, MNT_WAIT, curthread);
3312 	if (error != 0)
3313 		return (error);
3314 	ACQUIRE_LOCK(ump);
3315 	process_removes(vp);
3316 	process_truncates(vp);
3317 	FREE_LOCK(ump);
3318 	return (0);
3319 }
3320 
3321 /*
3322  * Must be called from VOP_RENAME() after all vnodes are locked.
3323  * Ensures that there is enough journal space for rename.  It is
3324  * sufficiently different from softdep_prelink() by having to handle
3325  * four vnodes.
3326  */
3327 int
3328 softdep_prerename(fdvp, fvp, tdvp, tvp)
3329 	struct vnode *fdvp;
3330 	struct vnode *fvp;
3331 	struct vnode *tdvp;
3332 	struct vnode *tvp;
3333 {
3334 	struct ufsmount *ump;
3335 	int error;
3336 
3337 	ump = VFSTOUFS(fdvp->v_mount);
3338 
3339 	if (journal_space(ump, 0))
3340 		return (0);
3341 
3342 	VOP_UNLOCK(tdvp);
3343 	VOP_UNLOCK(fvp);
3344 	if (tvp != NULL && tvp != tdvp)
3345 		VOP_UNLOCK(tvp);
3346 
3347 	error = softdep_prerename_vnode(ump, fdvp);
3348 	VOP_UNLOCK(fdvp);
3349 	if (error != 0)
3350 		return (error);
3351 
3352 	VOP_LOCK(fvp, LK_EXCLUSIVE | LK_RETRY);
3353 	error = softdep_prerename_vnode(ump, fvp);
3354 	VOP_UNLOCK(fvp);
3355 	if (error != 0)
3356 		return (error);
3357 
3358 	if (tdvp != fdvp) {
3359 		VOP_LOCK(tdvp, LK_EXCLUSIVE | LK_RETRY);
3360 		error = softdep_prerename_vnode(ump, tdvp);
3361 		VOP_UNLOCK(tdvp);
3362 		if (error != 0)
3363 			return (error);
3364 	}
3365 
3366 	if (tvp != fvp && tvp != NULL) {
3367 		VOP_LOCK(tvp, LK_EXCLUSIVE | LK_RETRY);
3368 		error = softdep_prerename_vnode(ump, tvp);
3369 		VOP_UNLOCK(tvp);
3370 		if (error != 0)
3371 			return (error);
3372 	}
3373 
3374 	ACQUIRE_LOCK(ump);
3375 	softdep_speedup(ump);
3376 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3377 	journal_check_space(ump);
3378 	FREE_LOCK(ump);
3379 	return (ERELOOKUP);
3380 }
3381 
3382 /*
3383  * Before adjusting a link count on a vnode verify that we have sufficient
3384  * journal space.  If not, process operations that depend on the currently
3385  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3386  * and softdep flush threads can not acquire these locks to reclaim space.
3387  *
3388  * Returns 0 if all owned locks are still valid and were not dropped
3389  * in the process, in other case it returns either an error from sync,
3390  * or ERELOOKUP if any of the locks were re-acquired.  In the later
3391  * case, the state of the vnodes cannot be relied upon and our VFS
3392  * syscall must be restarted at top level from the lookup.
3393  */
3394 int
3395 softdep_prelink(dvp, vp, cnp)
3396 	struct vnode *dvp;
3397 	struct vnode *vp;
3398 	struct componentname *cnp;
3399 {
3400 	struct ufsmount *ump;
3401 	struct nameidata *ndp;
3402 
3403 	ASSERT_VOP_ELOCKED(dvp, "prelink dvp");
3404 	if (vp != NULL)
3405 		ASSERT_VOP_ELOCKED(vp, "prelink vp");
3406 	ump = VFSTOUFS(dvp->v_mount);
3407 
3408 	/*
3409 	 * Nothing to do if we have sufficient journal space.  We skip
3410 	 * flushing when vp is a snapshot to avoid deadlock where
3411 	 * another thread is trying to update the inodeblock for dvp
3412 	 * and is waiting on snaplk that vp holds.
3413 	 */
3414 	if (journal_space(ump, 0) || (vp != NULL && IS_SNAPSHOT(VTOI(vp))))
3415 		return (0);
3416 
3417 	/*
3418 	 * Check if the journal space consumption can in theory be
3419 	 * accounted on dvp and vp.  If the vnodes metadata was not
3420 	 * changed comparing with the previous round-trip into
3421 	 * softdep_prelink(), as indicated by the seqc generation
3422 	 * recorded in the nameidata, then there is no point in
3423 	 * starting the sync.
3424 	 */
3425 	ndp = __containerof(cnp, struct nameidata, ni_cnd);
3426 	if (!seqc_in_modify(ndp->ni_dvp_seqc) &&
3427 	    vn_seqc_consistent(dvp, ndp->ni_dvp_seqc) &&
3428 	    (vp == NULL || (!seqc_in_modify(ndp->ni_vp_seqc) &&
3429 	    vn_seqc_consistent(vp, ndp->ni_vp_seqc))))
3430 		return (0);
3431 
3432 	stat_journal_low++;
3433 	if (vp != NULL) {
3434 		VOP_UNLOCK(dvp);
3435 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3436 		vn_lock_pair(dvp, false, vp, true);
3437 		if (dvp->v_data == NULL)
3438 			goto out;
3439 	}
3440 	if (vp != NULL)
3441 		VOP_UNLOCK(vp);
3442 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3443 	/* Process vp before dvp as it may create .. removes. */
3444 	if (vp != NULL) {
3445 		VOP_UNLOCK(dvp);
3446 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3447 		if (vp->v_data == NULL) {
3448 			vn_lock_pair(dvp, false, vp, true);
3449 			goto out;
3450 		}
3451 		ACQUIRE_LOCK(ump);
3452 		process_removes(vp);
3453 		process_truncates(vp);
3454 		FREE_LOCK(ump);
3455 		VOP_UNLOCK(vp);
3456 		vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
3457 		if (dvp->v_data == NULL) {
3458 			vn_lock_pair(dvp, true, vp, false);
3459 			goto out;
3460 		}
3461 	}
3462 
3463 	ACQUIRE_LOCK(ump);
3464 	process_removes(dvp);
3465 	process_truncates(dvp);
3466 	VOP_UNLOCK(dvp);
3467 	softdep_speedup(ump);
3468 
3469 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3470 	journal_check_space(ump);
3471 	FREE_LOCK(ump);
3472 
3473 	vn_lock_pair(dvp, false, vp, false);
3474 out:
3475 	ndp->ni_dvp_seqc = vn_seqc_read_any(dvp);
3476 	if (vp != NULL)
3477 		ndp->ni_vp_seqc = vn_seqc_read_any(vp);
3478 	return (ERELOOKUP);
3479 }
3480 
3481 static void
3482 jseg_write(ump, jseg, data)
3483 	struct ufsmount *ump;
3484 	struct jseg *jseg;
3485 	uint8_t *data;
3486 {
3487 	struct jsegrec *rec;
3488 
3489 	rec = (struct jsegrec *)data;
3490 	rec->jsr_seq = jseg->js_seq;
3491 	rec->jsr_oldest = jseg->js_oldseq;
3492 	rec->jsr_cnt = jseg->js_cnt;
3493 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3494 	rec->jsr_crc = 0;
3495 	rec->jsr_time = ump->um_fs->fs_mtime;
3496 }
3497 
3498 static inline void
3499 inoref_write(inoref, jseg, rec)
3500 	struct inoref *inoref;
3501 	struct jseg *jseg;
3502 	struct jrefrec *rec;
3503 {
3504 
3505 	inoref->if_jsegdep->jd_seg = jseg;
3506 	rec->jr_ino = inoref->if_ino;
3507 	rec->jr_parent = inoref->if_parent;
3508 	rec->jr_nlink = inoref->if_nlink;
3509 	rec->jr_mode = inoref->if_mode;
3510 	rec->jr_diroff = inoref->if_diroff;
3511 }
3512 
3513 static void
3514 jaddref_write(jaddref, jseg, data)
3515 	struct jaddref *jaddref;
3516 	struct jseg *jseg;
3517 	uint8_t *data;
3518 {
3519 	struct jrefrec *rec;
3520 
3521 	rec = (struct jrefrec *)data;
3522 	rec->jr_op = JOP_ADDREF;
3523 	inoref_write(&jaddref->ja_ref, jseg, rec);
3524 }
3525 
3526 static void
3527 jremref_write(jremref, jseg, data)
3528 	struct jremref *jremref;
3529 	struct jseg *jseg;
3530 	uint8_t *data;
3531 {
3532 	struct jrefrec *rec;
3533 
3534 	rec = (struct jrefrec *)data;
3535 	rec->jr_op = JOP_REMREF;
3536 	inoref_write(&jremref->jr_ref, jseg, rec);
3537 }
3538 
3539 static void
3540 jmvref_write(jmvref, jseg, data)
3541 	struct jmvref *jmvref;
3542 	struct jseg *jseg;
3543 	uint8_t *data;
3544 {
3545 	struct jmvrec *rec;
3546 
3547 	rec = (struct jmvrec *)data;
3548 	rec->jm_op = JOP_MVREF;
3549 	rec->jm_ino = jmvref->jm_ino;
3550 	rec->jm_parent = jmvref->jm_parent;
3551 	rec->jm_oldoff = jmvref->jm_oldoff;
3552 	rec->jm_newoff = jmvref->jm_newoff;
3553 }
3554 
3555 static void
3556 jnewblk_write(jnewblk, jseg, data)
3557 	struct jnewblk *jnewblk;
3558 	struct jseg *jseg;
3559 	uint8_t *data;
3560 {
3561 	struct jblkrec *rec;
3562 
3563 	jnewblk->jn_jsegdep->jd_seg = jseg;
3564 	rec = (struct jblkrec *)data;
3565 	rec->jb_op = JOP_NEWBLK;
3566 	rec->jb_ino = jnewblk->jn_ino;
3567 	rec->jb_blkno = jnewblk->jn_blkno;
3568 	rec->jb_lbn = jnewblk->jn_lbn;
3569 	rec->jb_frags = jnewblk->jn_frags;
3570 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3571 }
3572 
3573 static void
3574 jfreeblk_write(jfreeblk, jseg, data)
3575 	struct jfreeblk *jfreeblk;
3576 	struct jseg *jseg;
3577 	uint8_t *data;
3578 {
3579 	struct jblkrec *rec;
3580 
3581 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3582 	rec = (struct jblkrec *)data;
3583 	rec->jb_op = JOP_FREEBLK;
3584 	rec->jb_ino = jfreeblk->jf_ino;
3585 	rec->jb_blkno = jfreeblk->jf_blkno;
3586 	rec->jb_lbn = jfreeblk->jf_lbn;
3587 	rec->jb_frags = jfreeblk->jf_frags;
3588 	rec->jb_oldfrags = 0;
3589 }
3590 
3591 static void
3592 jfreefrag_write(jfreefrag, jseg, data)
3593 	struct jfreefrag *jfreefrag;
3594 	struct jseg *jseg;
3595 	uint8_t *data;
3596 {
3597 	struct jblkrec *rec;
3598 
3599 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3600 	rec = (struct jblkrec *)data;
3601 	rec->jb_op = JOP_FREEBLK;
3602 	rec->jb_ino = jfreefrag->fr_ino;
3603 	rec->jb_blkno = jfreefrag->fr_blkno;
3604 	rec->jb_lbn = jfreefrag->fr_lbn;
3605 	rec->jb_frags = jfreefrag->fr_frags;
3606 	rec->jb_oldfrags = 0;
3607 }
3608 
3609 static void
3610 jtrunc_write(jtrunc, jseg, data)
3611 	struct jtrunc *jtrunc;
3612 	struct jseg *jseg;
3613 	uint8_t *data;
3614 {
3615 	struct jtrncrec *rec;
3616 
3617 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3618 	rec = (struct jtrncrec *)data;
3619 	rec->jt_op = JOP_TRUNC;
3620 	rec->jt_ino = jtrunc->jt_ino;
3621 	rec->jt_size = jtrunc->jt_size;
3622 	rec->jt_extsize = jtrunc->jt_extsize;
3623 }
3624 
3625 static void
3626 jfsync_write(jfsync, jseg, data)
3627 	struct jfsync *jfsync;
3628 	struct jseg *jseg;
3629 	uint8_t *data;
3630 {
3631 	struct jtrncrec *rec;
3632 
3633 	rec = (struct jtrncrec *)data;
3634 	rec->jt_op = JOP_SYNC;
3635 	rec->jt_ino = jfsync->jfs_ino;
3636 	rec->jt_size = jfsync->jfs_size;
3637 	rec->jt_extsize = jfsync->jfs_extsize;
3638 }
3639 
3640 static void
3641 softdep_flushjournal(mp)
3642 	struct mount *mp;
3643 {
3644 	struct jblocks *jblocks;
3645 	struct ufsmount *ump;
3646 
3647 	if (MOUNTEDSUJ(mp) == 0)
3648 		return;
3649 	ump = VFSTOUFS(mp);
3650 	jblocks = ump->softdep_jblocks;
3651 	ACQUIRE_LOCK(ump);
3652 	while (ump->softdep_on_journal) {
3653 		jblocks->jb_needseg = 1;
3654 		softdep_process_journal(mp, NULL, MNT_WAIT);
3655 	}
3656 	FREE_LOCK(ump);
3657 }
3658 
3659 static void softdep_synchronize_completed(struct bio *);
3660 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3661 
3662 static void
3663 softdep_synchronize_completed(bp)
3664         struct bio *bp;
3665 {
3666 	struct jseg *oldest;
3667 	struct jseg *jseg;
3668 	struct ufsmount *ump;
3669 
3670 	/*
3671 	 * caller1 marks the last segment written before we issued the
3672 	 * synchronize cache.
3673 	 */
3674 	jseg = bp->bio_caller1;
3675 	if (jseg == NULL) {
3676 		g_destroy_bio(bp);
3677 		return;
3678 	}
3679 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3680 	ACQUIRE_LOCK(ump);
3681 	oldest = NULL;
3682 	/*
3683 	 * Mark all the journal entries waiting on the synchronize cache
3684 	 * as completed so they may continue on.
3685 	 */
3686 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3687 		jseg->js_state |= COMPLETE;
3688 		oldest = jseg;
3689 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3690 	}
3691 	/*
3692 	 * Restart deferred journal entry processing from the oldest
3693 	 * completed jseg.
3694 	 */
3695 	if (oldest)
3696 		complete_jsegs(oldest);
3697 
3698 	FREE_LOCK(ump);
3699 	g_destroy_bio(bp);
3700 }
3701 
3702 /*
3703  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3704  * barriers.  The journal must be written prior to any blocks that depend
3705  * on it and the journal can not be released until the blocks have be
3706  * written.  This code handles both barriers simultaneously.
3707  */
3708 static void
3709 softdep_synchronize(bp, ump, caller1)
3710 	struct bio *bp;
3711 	struct ufsmount *ump;
3712 	void *caller1;
3713 {
3714 
3715 	bp->bio_cmd = BIO_FLUSH;
3716 	bp->bio_flags |= BIO_ORDERED;
3717 	bp->bio_data = NULL;
3718 	bp->bio_offset = ump->um_cp->provider->mediasize;
3719 	bp->bio_length = 0;
3720 	bp->bio_done = softdep_synchronize_completed;
3721 	bp->bio_caller1 = caller1;
3722 	g_io_request(bp, ump->um_cp);
3723 }
3724 
3725 /*
3726  * Flush some journal records to disk.
3727  */
3728 static void
3729 softdep_process_journal(mp, needwk, flags)
3730 	struct mount *mp;
3731 	struct worklist *needwk;
3732 	int flags;
3733 {
3734 	struct jblocks *jblocks;
3735 	struct ufsmount *ump;
3736 	struct worklist *wk;
3737 	struct jseg *jseg;
3738 	struct buf *bp;
3739 	struct bio *bio;
3740 	uint8_t *data;
3741 	struct fs *fs;
3742 	int shouldflush;
3743 	int segwritten;
3744 	int jrecmin;	/* Minimum records per block. */
3745 	int jrecmax;	/* Maximum records per block. */
3746 	int size;
3747 	int cnt;
3748 	int off;
3749 	int devbsize;
3750 
3751 	ump = VFSTOUFS(mp);
3752 	if (ump->um_softdep == NULL || ump->um_softdep->sd_jblocks == NULL)
3753 		return;
3754 	shouldflush = softdep_flushcache;
3755 	bio = NULL;
3756 	jseg = NULL;
3757 	LOCK_OWNED(ump);
3758 	fs = ump->um_fs;
3759 	jblocks = ump->softdep_jblocks;
3760 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3761 	/*
3762 	 * We write anywhere between a disk block and fs block.  The upper
3763 	 * bound is picked to prevent buffer cache fragmentation and limit
3764 	 * processing time per I/O.
3765 	 */
3766 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3767 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3768 	segwritten = 0;
3769 	for (;;) {
3770 		cnt = ump->softdep_on_journal;
3771 		/*
3772 		 * Criteria for writing a segment:
3773 		 * 1) We have a full block.
3774 		 * 2) We're called from jwait() and haven't found the
3775 		 *    journal item yet.
3776 		 * 3) Always write if needseg is set.
3777 		 * 4) If we are called from process_worklist and have
3778 		 *    not yet written anything we write a partial block
3779 		 *    to enforce a 1 second maximum latency on journal
3780 		 *    entries.
3781 		 */
3782 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3783 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3784 			break;
3785 		cnt++;
3786 		/*
3787 		 * Verify some free journal space.  softdep_prealloc() should
3788 		 * guarantee that we don't run out so this is indicative of
3789 		 * a problem with the flow control.  Try to recover
3790 		 * gracefully in any event.
3791 		 */
3792 		while (jblocks->jb_free == 0) {
3793 			if (flags != MNT_WAIT)
3794 				break;
3795 			printf("softdep: Out of journal space!\n");
3796 			softdep_speedup(ump);
3797 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3798 		}
3799 		FREE_LOCK(ump);
3800 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3801 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3802 		LIST_INIT(&jseg->js_entries);
3803 		LIST_INIT(&jseg->js_indirs);
3804 		jseg->js_state = ATTACHED;
3805 		if (shouldflush == 0)
3806 			jseg->js_state |= COMPLETE;
3807 		else if (bio == NULL)
3808 			bio = g_alloc_bio();
3809 		jseg->js_jblocks = jblocks;
3810 		bp = geteblk(fs->fs_bsize, 0);
3811 		ACQUIRE_LOCK(ump);
3812 		/*
3813 		 * If there was a race while we were allocating the block
3814 		 * and jseg the entry we care about was likely written.
3815 		 * We bail out in both the WAIT and NOWAIT case and assume
3816 		 * the caller will loop if the entry it cares about is
3817 		 * not written.
3818 		 */
3819 		cnt = ump->softdep_on_journal;
3820 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3821 			bp->b_flags |= B_INVAL | B_NOCACHE;
3822 			WORKITEM_FREE(jseg, D_JSEG);
3823 			FREE_LOCK(ump);
3824 			brelse(bp);
3825 			ACQUIRE_LOCK(ump);
3826 			break;
3827 		}
3828 		/*
3829 		 * Calculate the disk block size required for the available
3830 		 * records rounded to the min size.
3831 		 */
3832 		if (cnt == 0)
3833 			size = devbsize;
3834 		else if (cnt < jrecmax)
3835 			size = howmany(cnt, jrecmin) * devbsize;
3836 		else
3837 			size = fs->fs_bsize;
3838 		/*
3839 		 * Allocate a disk block for this journal data and account
3840 		 * for truncation of the requested size if enough contiguous
3841 		 * space was not available.
3842 		 */
3843 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3844 		bp->b_lblkno = bp->b_blkno;
3845 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3846 		bp->b_bcount = size;
3847 		bp->b_flags &= ~B_INVAL;
3848 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3849 		/*
3850 		 * Initialize our jseg with cnt records.  Assign the next
3851 		 * sequence number to it and link it in-order.
3852 		 */
3853 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3854 		jseg->js_buf = bp;
3855 		jseg->js_cnt = cnt;
3856 		jseg->js_refs = cnt + 1;	/* Self ref. */
3857 		jseg->js_size = size;
3858 		jseg->js_seq = jblocks->jb_nextseq++;
3859 		if (jblocks->jb_oldestseg == NULL)
3860 			jblocks->jb_oldestseg = jseg;
3861 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3862 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3863 		if (jblocks->jb_writeseg == NULL)
3864 			jblocks->jb_writeseg = jseg;
3865 		/*
3866 		 * Start filling in records from the pending list.
3867 		 */
3868 		data = bp->b_data;
3869 		off = 0;
3870 
3871 		/*
3872 		 * Always put a header on the first block.
3873 		 * XXX As with below, there might not be a chance to get
3874 		 * into the loop.  Ensure that something valid is written.
3875 		 */
3876 		jseg_write(ump, jseg, data);
3877 		off += JREC_SIZE;
3878 		data = bp->b_data + off;
3879 
3880 		/*
3881 		 * XXX Something is wrong here.  There's no work to do,
3882 		 * but we need to perform and I/O and allow it to complete
3883 		 * anyways.
3884 		 */
3885 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3886 			stat_emptyjblocks++;
3887 
3888 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3889 		    != NULL) {
3890 			if (cnt == 0)
3891 				break;
3892 			/* Place a segment header on every device block. */
3893 			if ((off % devbsize) == 0) {
3894 				jseg_write(ump, jseg, data);
3895 				off += JREC_SIZE;
3896 				data = bp->b_data + off;
3897 			}
3898 			if (wk == needwk)
3899 				needwk = NULL;
3900 			remove_from_journal(wk);
3901 			wk->wk_state |= INPROGRESS;
3902 			WORKLIST_INSERT(&jseg->js_entries, wk);
3903 			switch (wk->wk_type) {
3904 			case D_JADDREF:
3905 				jaddref_write(WK_JADDREF(wk), jseg, data);
3906 				break;
3907 			case D_JREMREF:
3908 				jremref_write(WK_JREMREF(wk), jseg, data);
3909 				break;
3910 			case D_JMVREF:
3911 				jmvref_write(WK_JMVREF(wk), jseg, data);
3912 				break;
3913 			case D_JNEWBLK:
3914 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3915 				break;
3916 			case D_JFREEBLK:
3917 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3918 				break;
3919 			case D_JFREEFRAG:
3920 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3921 				break;
3922 			case D_JTRUNC:
3923 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3924 				break;
3925 			case D_JFSYNC:
3926 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3927 				break;
3928 			default:
3929 				panic("process_journal: Unknown type %s",
3930 				    TYPENAME(wk->wk_type));
3931 				/* NOTREACHED */
3932 			}
3933 			off += JREC_SIZE;
3934 			data = bp->b_data + off;
3935 			cnt--;
3936 		}
3937 
3938 		/* Clear any remaining space so we don't leak kernel data */
3939 		if (size > off)
3940 			bzero(data, size - off);
3941 
3942 		/*
3943 		 * Write this one buffer and continue.
3944 		 */
3945 		segwritten = 1;
3946 		jblocks->jb_needseg = 0;
3947 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3948 		FREE_LOCK(ump);
3949 		bp->b_xflags |= BX_CVTENXIO;
3950 		pbgetvp(ump->um_devvp, bp);
3951 		/*
3952 		 * We only do the blocking wait once we find the journal
3953 		 * entry we're looking for.
3954 		 */
3955 		if (needwk == NULL && flags == MNT_WAIT)
3956 			bwrite(bp);
3957 		else
3958 			bawrite(bp);
3959 		ACQUIRE_LOCK(ump);
3960 	}
3961 	/*
3962 	 * If we wrote a segment issue a synchronize cache so the journal
3963 	 * is reflected on disk before the data is written.  Since reclaiming
3964 	 * journal space also requires writing a journal record this
3965 	 * process also enforces a barrier before reclamation.
3966 	 */
3967 	if (segwritten && shouldflush) {
3968 		softdep_synchronize(bio, ump,
3969 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3970 	} else if (bio)
3971 		g_destroy_bio(bio);
3972 	/*
3973 	 * If we've suspended the filesystem because we ran out of journal
3974 	 * space either try to sync it here to make some progress or
3975 	 * unsuspend it if we already have.
3976 	 */
3977 	if (flags == 0 && jblocks->jb_suspended) {
3978 		if (journal_unsuspend(ump))
3979 			return;
3980 		FREE_LOCK(ump);
3981 		VFS_SYNC(mp, MNT_NOWAIT);
3982 		ffs_sbupdate(ump, MNT_WAIT, 0);
3983 		ACQUIRE_LOCK(ump);
3984 	}
3985 }
3986 
3987 /*
3988  * Complete a jseg, allowing all dependencies awaiting journal writes
3989  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3990  * structures so that the journal segment can be freed to reclaim space.
3991  */
3992 static void
3993 complete_jseg(jseg)
3994 	struct jseg *jseg;
3995 {
3996 	struct worklist *wk;
3997 	struct jmvref *jmvref;
3998 #ifdef INVARIANTS
3999 	int i = 0;
4000 #endif
4001 
4002 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
4003 		WORKLIST_REMOVE(wk);
4004 		wk->wk_state &= ~INPROGRESS;
4005 		wk->wk_state |= COMPLETE;
4006 		KASSERT(i++ < jseg->js_cnt,
4007 		    ("handle_written_jseg: overflow %d >= %d",
4008 		    i - 1, jseg->js_cnt));
4009 		switch (wk->wk_type) {
4010 		case D_JADDREF:
4011 			handle_written_jaddref(WK_JADDREF(wk));
4012 			break;
4013 		case D_JREMREF:
4014 			handle_written_jremref(WK_JREMREF(wk));
4015 			break;
4016 		case D_JMVREF:
4017 			rele_jseg(jseg);	/* No jsegdep. */
4018 			jmvref = WK_JMVREF(wk);
4019 			LIST_REMOVE(jmvref, jm_deps);
4020 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
4021 				free_pagedep(jmvref->jm_pagedep);
4022 			WORKITEM_FREE(jmvref, D_JMVREF);
4023 			break;
4024 		case D_JNEWBLK:
4025 			handle_written_jnewblk(WK_JNEWBLK(wk));
4026 			break;
4027 		case D_JFREEBLK:
4028 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
4029 			break;
4030 		case D_JTRUNC:
4031 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
4032 			break;
4033 		case D_JFSYNC:
4034 			rele_jseg(jseg);	/* No jsegdep. */
4035 			WORKITEM_FREE(wk, D_JFSYNC);
4036 			break;
4037 		case D_JFREEFRAG:
4038 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
4039 			break;
4040 		default:
4041 			panic("handle_written_jseg: Unknown type %s",
4042 			    TYPENAME(wk->wk_type));
4043 			/* NOTREACHED */
4044 		}
4045 	}
4046 	/* Release the self reference so the structure may be freed. */
4047 	rele_jseg(jseg);
4048 }
4049 
4050 /*
4051  * Determine which jsegs are ready for completion processing.  Waits for
4052  * synchronize cache to complete as well as forcing in-order completion
4053  * of journal entries.
4054  */
4055 static void
4056 complete_jsegs(jseg)
4057 	struct jseg *jseg;
4058 {
4059 	struct jblocks *jblocks;
4060 	struct jseg *jsegn;
4061 
4062 	jblocks = jseg->js_jblocks;
4063 	/*
4064 	 * Don't allow out of order completions.  If this isn't the first
4065 	 * block wait for it to write before we're done.
4066 	 */
4067 	if (jseg != jblocks->jb_writeseg)
4068 		return;
4069 	/* Iterate through available jsegs processing their entries. */
4070 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
4071 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
4072 		jsegn = TAILQ_NEXT(jseg, js_next);
4073 		complete_jseg(jseg);
4074 		jseg = jsegn;
4075 	}
4076 	jblocks->jb_writeseg = jseg;
4077 	/*
4078 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
4079 	 */
4080 	free_jsegs(jblocks);
4081 }
4082 
4083 /*
4084  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
4085  * the final completions.
4086  */
4087 static void
4088 handle_written_jseg(jseg, bp)
4089 	struct jseg *jseg;
4090 	struct buf *bp;
4091 {
4092 
4093 	if (jseg->js_refs == 0)
4094 		panic("handle_written_jseg: No self-reference on %p", jseg);
4095 	jseg->js_state |= DEPCOMPLETE;
4096 	/*
4097 	 * We'll never need this buffer again, set flags so it will be
4098 	 * discarded.
4099 	 */
4100 	bp->b_flags |= B_INVAL | B_NOCACHE;
4101 	pbrelvp(bp);
4102 	complete_jsegs(jseg);
4103 }
4104 
4105 static inline struct jsegdep *
4106 inoref_jseg(inoref)
4107 	struct inoref *inoref;
4108 {
4109 	struct jsegdep *jsegdep;
4110 
4111 	jsegdep = inoref->if_jsegdep;
4112 	inoref->if_jsegdep = NULL;
4113 
4114 	return (jsegdep);
4115 }
4116 
4117 /*
4118  * Called once a jremref has made it to stable store.  The jremref is marked
4119  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
4120  * for the jremref to complete will be awoken by free_jremref.
4121  */
4122 static void
4123 handle_written_jremref(jremref)
4124 	struct jremref *jremref;
4125 {
4126 	struct inodedep *inodedep;
4127 	struct jsegdep *jsegdep;
4128 	struct dirrem *dirrem;
4129 
4130 	/* Grab the jsegdep. */
4131 	jsegdep = inoref_jseg(&jremref->jr_ref);
4132 	/*
4133 	 * Remove us from the inoref list.
4134 	 */
4135 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
4136 	    0, &inodedep) == 0)
4137 		panic("handle_written_jremref: Lost inodedep");
4138 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
4139 	/*
4140 	 * Complete the dirrem.
4141 	 */
4142 	dirrem = jremref->jr_dirrem;
4143 	jremref->jr_dirrem = NULL;
4144 	LIST_REMOVE(jremref, jr_deps);
4145 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
4146 	jwork_insert(&dirrem->dm_jwork, jsegdep);
4147 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
4148 	    (dirrem->dm_state & COMPLETE) != 0)
4149 		add_to_worklist(&dirrem->dm_list, 0);
4150 	free_jremref(jremref);
4151 }
4152 
4153 /*
4154  * Called once a jaddref has made it to stable store.  The dependency is
4155  * marked complete and any dependent structures are added to the inode
4156  * bufwait list to be completed as soon as it is written.  If a bitmap write
4157  * depends on this entry we move the inode into the inodedephd of the
4158  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
4159  */
4160 static void
4161 handle_written_jaddref(jaddref)
4162 	struct jaddref *jaddref;
4163 {
4164 	struct jsegdep *jsegdep;
4165 	struct inodedep *inodedep;
4166 	struct diradd *diradd;
4167 	struct mkdir *mkdir;
4168 
4169 	/* Grab the jsegdep. */
4170 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4171 	mkdir = NULL;
4172 	diradd = NULL;
4173 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4174 	    0, &inodedep) == 0)
4175 		panic("handle_written_jaddref: Lost inodedep.");
4176 	if (jaddref->ja_diradd == NULL)
4177 		panic("handle_written_jaddref: No dependency");
4178 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
4179 		diradd = jaddref->ja_diradd;
4180 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
4181 	} else if (jaddref->ja_state & MKDIR_PARENT) {
4182 		mkdir = jaddref->ja_mkdir;
4183 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
4184 	} else if (jaddref->ja_state & MKDIR_BODY)
4185 		mkdir = jaddref->ja_mkdir;
4186 	else
4187 		panic("handle_written_jaddref: Unknown dependency %p",
4188 		    jaddref->ja_diradd);
4189 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
4190 	/*
4191 	 * Remove us from the inode list.
4192 	 */
4193 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
4194 	/*
4195 	 * The mkdir may be waiting on the jaddref to clear before freeing.
4196 	 */
4197 	if (mkdir) {
4198 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
4199 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
4200 		    TYPENAME(mkdir->md_list.wk_type)));
4201 		mkdir->md_jaddref = NULL;
4202 		diradd = mkdir->md_diradd;
4203 		mkdir->md_state |= DEPCOMPLETE;
4204 		complete_mkdir(mkdir);
4205 	}
4206 	jwork_insert(&diradd->da_jwork, jsegdep);
4207 	if (jaddref->ja_state & NEWBLOCK) {
4208 		inodedep->id_state |= ONDEPLIST;
4209 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
4210 		    inodedep, id_deps);
4211 	}
4212 	free_jaddref(jaddref);
4213 }
4214 
4215 /*
4216  * Called once a jnewblk journal is written.  The allocdirect or allocindir
4217  * is placed in the bmsafemap to await notification of a written bitmap.  If
4218  * the operation was canceled we add the segdep to the appropriate
4219  * dependency to free the journal space once the canceling operation
4220  * completes.
4221  */
4222 static void
4223 handle_written_jnewblk(jnewblk)
4224 	struct jnewblk *jnewblk;
4225 {
4226 	struct bmsafemap *bmsafemap;
4227 	struct freefrag *freefrag;
4228 	struct freework *freework;
4229 	struct jsegdep *jsegdep;
4230 	struct newblk *newblk;
4231 
4232 	/* Grab the jsegdep. */
4233 	jsegdep = jnewblk->jn_jsegdep;
4234 	jnewblk->jn_jsegdep = NULL;
4235 	if (jnewblk->jn_dep == NULL)
4236 		panic("handle_written_jnewblk: No dependency for the segdep.");
4237 	switch (jnewblk->jn_dep->wk_type) {
4238 	case D_NEWBLK:
4239 	case D_ALLOCDIRECT:
4240 	case D_ALLOCINDIR:
4241 		/*
4242 		 * Add the written block to the bmsafemap so it can
4243 		 * be notified when the bitmap is on disk.
4244 		 */
4245 		newblk = WK_NEWBLK(jnewblk->jn_dep);
4246 		newblk->nb_jnewblk = NULL;
4247 		if ((newblk->nb_state & GOINGAWAY) == 0) {
4248 			bmsafemap = newblk->nb_bmsafemap;
4249 			newblk->nb_state |= ONDEPLIST;
4250 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
4251 			    nb_deps);
4252 		}
4253 		jwork_insert(&newblk->nb_jwork, jsegdep);
4254 		break;
4255 	case D_FREEFRAG:
4256 		/*
4257 		 * A newblock being removed by a freefrag when replaced by
4258 		 * frag extension.
4259 		 */
4260 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
4261 		freefrag->ff_jdep = NULL;
4262 		jwork_insert(&freefrag->ff_jwork, jsegdep);
4263 		break;
4264 	case D_FREEWORK:
4265 		/*
4266 		 * A direct block was removed by truncate.
4267 		 */
4268 		freework = WK_FREEWORK(jnewblk->jn_dep);
4269 		freework->fw_jnewblk = NULL;
4270 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
4271 		break;
4272 	default:
4273 		panic("handle_written_jnewblk: Unknown type %d.",
4274 		    jnewblk->jn_dep->wk_type);
4275 	}
4276 	jnewblk->jn_dep = NULL;
4277 	free_jnewblk(jnewblk);
4278 }
4279 
4280 /*
4281  * Cancel a jfreefrag that won't be needed, probably due to colliding with
4282  * an in-flight allocation that has not yet been committed.  Divorce us
4283  * from the freefrag and mark it DEPCOMPLETE so that it may be added
4284  * to the worklist.
4285  */
4286 static void
4287 cancel_jfreefrag(jfreefrag)
4288 	struct jfreefrag *jfreefrag;
4289 {
4290 	struct freefrag *freefrag;
4291 
4292 	if (jfreefrag->fr_jsegdep) {
4293 		free_jsegdep(jfreefrag->fr_jsegdep);
4294 		jfreefrag->fr_jsegdep = NULL;
4295 	}
4296 	freefrag = jfreefrag->fr_freefrag;
4297 	jfreefrag->fr_freefrag = NULL;
4298 	free_jfreefrag(jfreefrag);
4299 	freefrag->ff_state |= DEPCOMPLETE;
4300 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
4301 }
4302 
4303 /*
4304  * Free a jfreefrag when the parent freefrag is rendered obsolete.
4305  */
4306 static void
4307 free_jfreefrag(jfreefrag)
4308 	struct jfreefrag *jfreefrag;
4309 {
4310 
4311 	if (jfreefrag->fr_state & INPROGRESS)
4312 		WORKLIST_REMOVE(&jfreefrag->fr_list);
4313 	else if (jfreefrag->fr_state & ONWORKLIST)
4314 		remove_from_journal(&jfreefrag->fr_list);
4315 	if (jfreefrag->fr_freefrag != NULL)
4316 		panic("free_jfreefrag:  Still attached to a freefrag.");
4317 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
4318 }
4319 
4320 /*
4321  * Called when the journal write for a jfreefrag completes.  The parent
4322  * freefrag is added to the worklist if this completes its dependencies.
4323  */
4324 static void
4325 handle_written_jfreefrag(jfreefrag)
4326 	struct jfreefrag *jfreefrag;
4327 {
4328 	struct jsegdep *jsegdep;
4329 	struct freefrag *freefrag;
4330 
4331 	/* Grab the jsegdep. */
4332 	jsegdep = jfreefrag->fr_jsegdep;
4333 	jfreefrag->fr_jsegdep = NULL;
4334 	freefrag = jfreefrag->fr_freefrag;
4335 	if (freefrag == NULL)
4336 		panic("handle_written_jfreefrag: No freefrag.");
4337 	freefrag->ff_state |= DEPCOMPLETE;
4338 	freefrag->ff_jdep = NULL;
4339 	jwork_insert(&freefrag->ff_jwork, jsegdep);
4340 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
4341 		add_to_worklist(&freefrag->ff_list, 0);
4342 	jfreefrag->fr_freefrag = NULL;
4343 	free_jfreefrag(jfreefrag);
4344 }
4345 
4346 /*
4347  * Called when the journal write for a jfreeblk completes.  The jfreeblk
4348  * is removed from the freeblks list of pending journal writes and the
4349  * jsegdep is moved to the freeblks jwork to be completed when all blocks
4350  * have been reclaimed.
4351  */
4352 static void
4353 handle_written_jblkdep(jblkdep)
4354 	struct jblkdep *jblkdep;
4355 {
4356 	struct freeblks *freeblks;
4357 	struct jsegdep *jsegdep;
4358 
4359 	/* Grab the jsegdep. */
4360 	jsegdep = jblkdep->jb_jsegdep;
4361 	jblkdep->jb_jsegdep = NULL;
4362 	freeblks = jblkdep->jb_freeblks;
4363 	LIST_REMOVE(jblkdep, jb_deps);
4364 	jwork_insert(&freeblks->fb_jwork, jsegdep);
4365 	/*
4366 	 * If the freeblks is all journaled, we can add it to the worklist.
4367 	 */
4368 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4369 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4370 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4371 
4372 	free_jblkdep(jblkdep);
4373 }
4374 
4375 static struct jsegdep *
4376 newjsegdep(struct worklist *wk)
4377 {
4378 	struct jsegdep *jsegdep;
4379 
4380 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4381 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4382 	jsegdep->jd_seg = NULL;
4383 
4384 	return (jsegdep);
4385 }
4386 
4387 static struct jmvref *
4388 newjmvref(dp, ino, oldoff, newoff)
4389 	struct inode *dp;
4390 	ino_t ino;
4391 	off_t oldoff;
4392 	off_t newoff;
4393 {
4394 	struct jmvref *jmvref;
4395 
4396 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4397 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4398 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4399 	jmvref->jm_parent = dp->i_number;
4400 	jmvref->jm_ino = ino;
4401 	jmvref->jm_oldoff = oldoff;
4402 	jmvref->jm_newoff = newoff;
4403 
4404 	return (jmvref);
4405 }
4406 
4407 /*
4408  * Allocate a new jremref that tracks the removal of ip from dp with the
4409  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4410  * DEPCOMPLETE as we have all the information required for the journal write
4411  * and the directory has already been removed from the buffer.  The caller
4412  * is responsible for linking the jremref into the pagedep and adding it
4413  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4414  * a DOTDOT addition so handle_workitem_remove() can properly assign
4415  * the jsegdep when we're done.
4416  */
4417 static struct jremref *
4418 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4419     off_t diroff, nlink_t nlink)
4420 {
4421 	struct jremref *jremref;
4422 
4423 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4424 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4425 	jremref->jr_state = ATTACHED;
4426 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4427 	   nlink, ip->i_mode);
4428 	jremref->jr_dirrem = dirrem;
4429 
4430 	return (jremref);
4431 }
4432 
4433 static inline void
4434 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4435     nlink_t nlink, uint16_t mode)
4436 {
4437 
4438 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4439 	inoref->if_diroff = diroff;
4440 	inoref->if_ino = ino;
4441 	inoref->if_parent = parent;
4442 	inoref->if_nlink = nlink;
4443 	inoref->if_mode = mode;
4444 }
4445 
4446 /*
4447  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4448  * directory offset may not be known until later.  The caller is responsible
4449  * adding the entry to the journal when this information is available.  nlink
4450  * should be the link count prior to the addition and mode is only required
4451  * to have the correct FMT.
4452  */
4453 static struct jaddref *
4454 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4455     uint16_t mode)
4456 {
4457 	struct jaddref *jaddref;
4458 
4459 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4460 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4461 	jaddref->ja_state = ATTACHED;
4462 	jaddref->ja_mkdir = NULL;
4463 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4464 
4465 	return (jaddref);
4466 }
4467 
4468 /*
4469  * Create a new free dependency for a freework.  The caller is responsible
4470  * for adjusting the reference count when it has the lock held.  The freedep
4471  * will track an outstanding bitmap write that will ultimately clear the
4472  * freework to continue.
4473  */
4474 static struct freedep *
4475 newfreedep(struct freework *freework)
4476 {
4477 	struct freedep *freedep;
4478 
4479 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4480 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4481 	freedep->fd_freework = freework;
4482 
4483 	return (freedep);
4484 }
4485 
4486 /*
4487  * Free a freedep structure once the buffer it is linked to is written.  If
4488  * this is the last reference to the freework schedule it for completion.
4489  */
4490 static void
4491 free_freedep(freedep)
4492 	struct freedep *freedep;
4493 {
4494 	struct freework *freework;
4495 
4496 	freework = freedep->fd_freework;
4497 	freework->fw_freeblks->fb_cgwait--;
4498 	if (--freework->fw_ref == 0)
4499 		freework_enqueue(freework);
4500 	WORKITEM_FREE(freedep, D_FREEDEP);
4501 }
4502 
4503 /*
4504  * Allocate a new freework structure that may be a level in an indirect
4505  * when parent is not NULL or a top level block when it is.  The top level
4506  * freework structures are allocated without the per-filesystem lock held
4507  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4508  */
4509 static struct freework *
4510 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4511 	struct ufsmount *ump;
4512 	struct freeblks *freeblks;
4513 	struct freework *parent;
4514 	ufs_lbn_t lbn;
4515 	ufs2_daddr_t nb;
4516 	int frags;
4517 	int off;
4518 	int journal;
4519 {
4520 	struct freework *freework;
4521 
4522 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4523 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4524 	freework->fw_state = ATTACHED;
4525 	freework->fw_jnewblk = NULL;
4526 	freework->fw_freeblks = freeblks;
4527 	freework->fw_parent = parent;
4528 	freework->fw_lbn = lbn;
4529 	freework->fw_blkno = nb;
4530 	freework->fw_frags = frags;
4531 	freework->fw_indir = NULL;
4532 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4533 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4534 	freework->fw_start = freework->fw_off = off;
4535 	if (journal)
4536 		newjfreeblk(freeblks, lbn, nb, frags);
4537 	if (parent == NULL) {
4538 		ACQUIRE_LOCK(ump);
4539 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4540 		freeblks->fb_ref++;
4541 		FREE_LOCK(ump);
4542 	}
4543 
4544 	return (freework);
4545 }
4546 
4547 /*
4548  * Eliminate a jfreeblk for a block that does not need journaling.
4549  */
4550 static void
4551 cancel_jfreeblk(freeblks, blkno)
4552 	struct freeblks *freeblks;
4553 	ufs2_daddr_t blkno;
4554 {
4555 	struct jfreeblk *jfreeblk;
4556 	struct jblkdep *jblkdep;
4557 
4558 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4559 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4560 			continue;
4561 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4562 		if (jfreeblk->jf_blkno == blkno)
4563 			break;
4564 	}
4565 	if (jblkdep == NULL)
4566 		return;
4567 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4568 	free_jsegdep(jblkdep->jb_jsegdep);
4569 	LIST_REMOVE(jblkdep, jb_deps);
4570 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4571 }
4572 
4573 /*
4574  * Allocate a new jfreeblk to journal top level block pointer when truncating
4575  * a file.  The caller must add this to the worklist when the per-filesystem
4576  * lock is held.
4577  */
4578 static struct jfreeblk *
4579 newjfreeblk(freeblks, lbn, blkno, frags)
4580 	struct freeblks *freeblks;
4581 	ufs_lbn_t lbn;
4582 	ufs2_daddr_t blkno;
4583 	int frags;
4584 {
4585 	struct jfreeblk *jfreeblk;
4586 
4587 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4588 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4589 	    freeblks->fb_list.wk_mp);
4590 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4591 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4592 	jfreeblk->jf_ino = freeblks->fb_inum;
4593 	jfreeblk->jf_lbn = lbn;
4594 	jfreeblk->jf_blkno = blkno;
4595 	jfreeblk->jf_frags = frags;
4596 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4597 
4598 	return (jfreeblk);
4599 }
4600 
4601 /*
4602  * The journal is only prepared to handle full-size block numbers, so we
4603  * have to adjust the record to reflect the change to a full-size block.
4604  * For example, suppose we have a block made up of fragments 8-15 and
4605  * want to free its last two fragments. We are given a request that says:
4606  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4607  * where frags are the number of fragments to free and oldfrags are the
4608  * number of fragments to keep. To block align it, we have to change it to
4609  * have a valid full-size blkno, so it becomes:
4610  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4611  */
4612 static void
4613 adjust_newfreework(freeblks, frag_offset)
4614 	struct freeblks *freeblks;
4615 	int frag_offset;
4616 {
4617 	struct jfreeblk *jfreeblk;
4618 
4619 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4620 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4621 	    ("adjust_newfreework: Missing freeblks dependency"));
4622 
4623 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4624 	jfreeblk->jf_blkno -= frag_offset;
4625 	jfreeblk->jf_frags += frag_offset;
4626 }
4627 
4628 /*
4629  * Allocate a new jtrunc to track a partial truncation.
4630  */
4631 static struct jtrunc *
4632 newjtrunc(freeblks, size, extsize)
4633 	struct freeblks *freeblks;
4634 	off_t size;
4635 	int extsize;
4636 {
4637 	struct jtrunc *jtrunc;
4638 
4639 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4640 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4641 	    freeblks->fb_list.wk_mp);
4642 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4643 	jtrunc->jt_dep.jb_freeblks = freeblks;
4644 	jtrunc->jt_ino = freeblks->fb_inum;
4645 	jtrunc->jt_size = size;
4646 	jtrunc->jt_extsize = extsize;
4647 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4648 
4649 	return (jtrunc);
4650 }
4651 
4652 /*
4653  * If we're canceling a new bitmap we have to search for another ref
4654  * to move into the bmsafemap dep.  This might be better expressed
4655  * with another structure.
4656  */
4657 static void
4658 move_newblock_dep(jaddref, inodedep)
4659 	struct jaddref *jaddref;
4660 	struct inodedep *inodedep;
4661 {
4662 	struct inoref *inoref;
4663 	struct jaddref *jaddrefn;
4664 
4665 	jaddrefn = NULL;
4666 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4667 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4668 		if ((jaddref->ja_state & NEWBLOCK) &&
4669 		    inoref->if_list.wk_type == D_JADDREF) {
4670 			jaddrefn = (struct jaddref *)inoref;
4671 			break;
4672 		}
4673 	}
4674 	if (jaddrefn == NULL)
4675 		return;
4676 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4677 	jaddrefn->ja_state |= jaddref->ja_state &
4678 	    (ATTACHED | UNDONE | NEWBLOCK);
4679 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4680 	jaddref->ja_state |= ATTACHED;
4681 	LIST_REMOVE(jaddref, ja_bmdeps);
4682 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4683 	    ja_bmdeps);
4684 }
4685 
4686 /*
4687  * Cancel a jaddref either before it has been written or while it is being
4688  * written.  This happens when a link is removed before the add reaches
4689  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4690  * and inode to prevent the link count or bitmap from reaching the disk
4691  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4692  * required.
4693  *
4694  * Returns 1 if the canceled addref requires journaling of the remove and
4695  * 0 otherwise.
4696  */
4697 static int
4698 cancel_jaddref(jaddref, inodedep, wkhd)
4699 	struct jaddref *jaddref;
4700 	struct inodedep *inodedep;
4701 	struct workhead *wkhd;
4702 {
4703 	struct inoref *inoref;
4704 	struct jsegdep *jsegdep;
4705 	int needsj;
4706 
4707 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4708 	    ("cancel_jaddref: Canceling complete jaddref"));
4709 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4710 		needsj = 1;
4711 	else
4712 		needsj = 0;
4713 	if (inodedep == NULL)
4714 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4715 		    0, &inodedep) == 0)
4716 			panic("cancel_jaddref: Lost inodedep");
4717 	/*
4718 	 * We must adjust the nlink of any reference operation that follows
4719 	 * us so that it is consistent with the in-memory reference.  This
4720 	 * ensures that inode nlink rollbacks always have the correct link.
4721 	 */
4722 	if (needsj == 0) {
4723 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4724 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4725 			if (inoref->if_state & GOINGAWAY)
4726 				break;
4727 			inoref->if_nlink--;
4728 		}
4729 	}
4730 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4731 	if (jaddref->ja_state & NEWBLOCK)
4732 		move_newblock_dep(jaddref, inodedep);
4733 	wake_worklist(&jaddref->ja_list);
4734 	jaddref->ja_mkdir = NULL;
4735 	if (jaddref->ja_state & INPROGRESS) {
4736 		jaddref->ja_state &= ~INPROGRESS;
4737 		WORKLIST_REMOVE(&jaddref->ja_list);
4738 		jwork_insert(wkhd, jsegdep);
4739 	} else {
4740 		free_jsegdep(jsegdep);
4741 		if (jaddref->ja_state & DEPCOMPLETE)
4742 			remove_from_journal(&jaddref->ja_list);
4743 	}
4744 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4745 	/*
4746 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4747 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4748 	 * no longer need this addref attached to the inoreflst and it
4749 	 * will incorrectly adjust nlink if we leave it.
4750 	 */
4751 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4752 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4753 		    if_deps);
4754 		jaddref->ja_state |= COMPLETE;
4755 		free_jaddref(jaddref);
4756 		return (needsj);
4757 	}
4758 	/*
4759 	 * Leave the head of the list for jsegdeps for fast merging.
4760 	 */
4761 	if (LIST_FIRST(wkhd) != NULL) {
4762 		jaddref->ja_state |= ONWORKLIST;
4763 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4764 	} else
4765 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4766 
4767 	return (needsj);
4768 }
4769 
4770 /*
4771  * Attempt to free a jaddref structure when some work completes.  This
4772  * should only succeed once the entry is written and all dependencies have
4773  * been notified.
4774  */
4775 static void
4776 free_jaddref(jaddref)
4777 	struct jaddref *jaddref;
4778 {
4779 
4780 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4781 		return;
4782 	if (jaddref->ja_ref.if_jsegdep)
4783 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4784 		    jaddref, jaddref->ja_state);
4785 	if (jaddref->ja_state & NEWBLOCK)
4786 		LIST_REMOVE(jaddref, ja_bmdeps);
4787 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4788 		panic("free_jaddref: Bad state %p(0x%X)",
4789 		    jaddref, jaddref->ja_state);
4790 	if (jaddref->ja_mkdir != NULL)
4791 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4792 	WORKITEM_FREE(jaddref, D_JADDREF);
4793 }
4794 
4795 /*
4796  * Free a jremref structure once it has been written or discarded.
4797  */
4798 static void
4799 free_jremref(jremref)
4800 	struct jremref *jremref;
4801 {
4802 
4803 	if (jremref->jr_ref.if_jsegdep)
4804 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4805 	if (jremref->jr_state & INPROGRESS)
4806 		panic("free_jremref: IO still pending");
4807 	WORKITEM_FREE(jremref, D_JREMREF);
4808 }
4809 
4810 /*
4811  * Free a jnewblk structure.
4812  */
4813 static void
4814 free_jnewblk(jnewblk)
4815 	struct jnewblk *jnewblk;
4816 {
4817 
4818 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4819 		return;
4820 	LIST_REMOVE(jnewblk, jn_deps);
4821 	if (jnewblk->jn_dep != NULL)
4822 		panic("free_jnewblk: Dependency still attached.");
4823 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4824 }
4825 
4826 /*
4827  * Cancel a jnewblk which has been been made redundant by frag extension.
4828  */
4829 static void
4830 cancel_jnewblk(jnewblk, wkhd)
4831 	struct jnewblk *jnewblk;
4832 	struct workhead *wkhd;
4833 {
4834 	struct jsegdep *jsegdep;
4835 
4836 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4837 	jsegdep = jnewblk->jn_jsegdep;
4838 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4839 		panic("cancel_jnewblk: Invalid state");
4840 	jnewblk->jn_jsegdep  = NULL;
4841 	jnewblk->jn_dep = NULL;
4842 	jnewblk->jn_state |= GOINGAWAY;
4843 	if (jnewblk->jn_state & INPROGRESS) {
4844 		jnewblk->jn_state &= ~INPROGRESS;
4845 		WORKLIST_REMOVE(&jnewblk->jn_list);
4846 		jwork_insert(wkhd, jsegdep);
4847 	} else {
4848 		free_jsegdep(jsegdep);
4849 		remove_from_journal(&jnewblk->jn_list);
4850 	}
4851 	wake_worklist(&jnewblk->jn_list);
4852 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4853 }
4854 
4855 static void
4856 free_jblkdep(jblkdep)
4857 	struct jblkdep *jblkdep;
4858 {
4859 
4860 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4861 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4862 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4863 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4864 	else
4865 		panic("free_jblkdep: Unexpected type %s",
4866 		    TYPENAME(jblkdep->jb_list.wk_type));
4867 }
4868 
4869 /*
4870  * Free a single jseg once it is no longer referenced in memory or on
4871  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4872  * to disappear.
4873  */
4874 static void
4875 free_jseg(jseg, jblocks)
4876 	struct jseg *jseg;
4877 	struct jblocks *jblocks;
4878 {
4879 	struct freework *freework;
4880 
4881 	/*
4882 	 * Free freework structures that were lingering to indicate freed
4883 	 * indirect blocks that forced journal write ordering on reallocate.
4884 	 */
4885 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4886 		indirblk_remove(freework);
4887 	if (jblocks->jb_oldestseg == jseg)
4888 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4889 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4890 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4891 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4892 	    ("free_jseg: Freed jseg has valid entries."));
4893 	WORKITEM_FREE(jseg, D_JSEG);
4894 }
4895 
4896 /*
4897  * Free all jsegs that meet the criteria for being reclaimed and update
4898  * oldestseg.
4899  */
4900 static void
4901 free_jsegs(jblocks)
4902 	struct jblocks *jblocks;
4903 {
4904 	struct jseg *jseg;
4905 
4906 	/*
4907 	 * Free only those jsegs which have none allocated before them to
4908 	 * preserve the journal space ordering.
4909 	 */
4910 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4911 		/*
4912 		 * Only reclaim space when nothing depends on this journal
4913 		 * set and another set has written that it is no longer
4914 		 * valid.
4915 		 */
4916 		if (jseg->js_refs != 0) {
4917 			jblocks->jb_oldestseg = jseg;
4918 			return;
4919 		}
4920 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4921 			break;
4922 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4923 			break;
4924 		/*
4925 		 * We can free jsegs that didn't write entries when
4926 		 * oldestwrseq == js_seq.
4927 		 */
4928 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4929 		    jseg->js_cnt != 0)
4930 			break;
4931 		free_jseg(jseg, jblocks);
4932 	}
4933 	/*
4934 	 * If we exited the loop above we still must discover the
4935 	 * oldest valid segment.
4936 	 */
4937 	if (jseg)
4938 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4939 		     jseg = TAILQ_NEXT(jseg, js_next))
4940 			if (jseg->js_refs != 0)
4941 				break;
4942 	jblocks->jb_oldestseg = jseg;
4943 	/*
4944 	 * The journal has no valid records but some jsegs may still be
4945 	 * waiting on oldestwrseq to advance.  We force a small record
4946 	 * out to permit these lingering records to be reclaimed.
4947 	 */
4948 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4949 		jblocks->jb_needseg = 1;
4950 }
4951 
4952 /*
4953  * Release one reference to a jseg and free it if the count reaches 0.  This
4954  * should eventually reclaim journal space as well.
4955  */
4956 static void
4957 rele_jseg(jseg)
4958 	struct jseg *jseg;
4959 {
4960 
4961 	KASSERT(jseg->js_refs > 0,
4962 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4963 	if (--jseg->js_refs != 0)
4964 		return;
4965 	free_jsegs(jseg->js_jblocks);
4966 }
4967 
4968 /*
4969  * Release a jsegdep and decrement the jseg count.
4970  */
4971 static void
4972 free_jsegdep(jsegdep)
4973 	struct jsegdep *jsegdep;
4974 {
4975 
4976 	if (jsegdep->jd_seg)
4977 		rele_jseg(jsegdep->jd_seg);
4978 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4979 }
4980 
4981 /*
4982  * Wait for a journal item to make it to disk.  Initiate journal processing
4983  * if required.
4984  */
4985 static int
4986 jwait(wk, waitfor)
4987 	struct worklist *wk;
4988 	int waitfor;
4989 {
4990 
4991 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4992 	/*
4993 	 * Blocking journal waits cause slow synchronous behavior.  Record
4994 	 * stats on the frequency of these blocking operations.
4995 	 */
4996 	if (waitfor == MNT_WAIT) {
4997 		stat_journal_wait++;
4998 		switch (wk->wk_type) {
4999 		case D_JREMREF:
5000 		case D_JMVREF:
5001 			stat_jwait_filepage++;
5002 			break;
5003 		case D_JTRUNC:
5004 		case D_JFREEBLK:
5005 			stat_jwait_freeblks++;
5006 			break;
5007 		case D_JNEWBLK:
5008 			stat_jwait_newblk++;
5009 			break;
5010 		case D_JADDREF:
5011 			stat_jwait_inode++;
5012 			break;
5013 		default:
5014 			break;
5015 		}
5016 	}
5017 	/*
5018 	 * If IO has not started we process the journal.  We can't mark the
5019 	 * worklist item as IOWAITING because we drop the lock while
5020 	 * processing the journal and the worklist entry may be freed after
5021 	 * this point.  The caller may call back in and re-issue the request.
5022 	 */
5023 	if ((wk->wk_state & INPROGRESS) == 0) {
5024 		softdep_process_journal(wk->wk_mp, wk, waitfor);
5025 		if (waitfor != MNT_WAIT)
5026 			return (EBUSY);
5027 		return (0);
5028 	}
5029 	if (waitfor != MNT_WAIT)
5030 		return (EBUSY);
5031 	wait_worklist(wk, "jwait");
5032 	return (0);
5033 }
5034 
5035 /*
5036  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
5037  * appropriate.  This is a convenience function to reduce duplicate code
5038  * for the setup and revert functions below.
5039  */
5040 static struct inodedep *
5041 inodedep_lookup_ip(ip)
5042 	struct inode *ip;
5043 {
5044 	struct inodedep *inodedep;
5045 
5046 	KASSERT(ip->i_nlink >= ip->i_effnlink,
5047 	    ("inodedep_lookup_ip: bad delta"));
5048 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
5049 	    &inodedep);
5050 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
5051 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
5052 
5053 	return (inodedep);
5054 }
5055 
5056 /*
5057  * Called prior to creating a new inode and linking it to a directory.  The
5058  * jaddref structure must already be allocated by softdep_setup_inomapdep
5059  * and it is discovered here so we can initialize the mode and update
5060  * nlinkdelta.
5061  */
5062 void
5063 softdep_setup_create(dp, ip)
5064 	struct inode *dp;
5065 	struct inode *ip;
5066 {
5067 	struct inodedep *inodedep;
5068 	struct jaddref *jaddref;
5069 	struct vnode *dvp;
5070 
5071 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5072 	    ("softdep_setup_create called on non-softdep filesystem"));
5073 	KASSERT(ip->i_nlink == 1,
5074 	    ("softdep_setup_create: Invalid link count."));
5075 	dvp = ITOV(dp);
5076 	ACQUIRE_LOCK(ITOUMP(dp));
5077 	inodedep = inodedep_lookup_ip(ip);
5078 	if (DOINGSUJ(dvp)) {
5079 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5080 		    inoreflst);
5081 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
5082 		    ("softdep_setup_create: No addref structure present."));
5083 	}
5084 	FREE_LOCK(ITOUMP(dp));
5085 }
5086 
5087 /*
5088  * Create a jaddref structure to track the addition of a DOTDOT link when
5089  * we are reparenting an inode as part of a rename.  This jaddref will be
5090  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
5091  * non-journaling softdep.
5092  */
5093 void
5094 softdep_setup_dotdot_link(dp, ip)
5095 	struct inode *dp;
5096 	struct inode *ip;
5097 {
5098 	struct inodedep *inodedep;
5099 	struct jaddref *jaddref;
5100 	struct vnode *dvp;
5101 
5102 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5103 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
5104 	dvp = ITOV(dp);
5105 	jaddref = NULL;
5106 	/*
5107 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
5108 	 * is used as a normal link would be.
5109 	 */
5110 	if (DOINGSUJ(dvp))
5111 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5112 		    dp->i_effnlink - 1, dp->i_mode);
5113 	ACQUIRE_LOCK(ITOUMP(dp));
5114 	inodedep = inodedep_lookup_ip(dp);
5115 	if (jaddref)
5116 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5117 		    if_deps);
5118 	FREE_LOCK(ITOUMP(dp));
5119 }
5120 
5121 /*
5122  * Create a jaddref structure to track a new link to an inode.  The directory
5123  * offset is not known until softdep_setup_directory_add or
5124  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
5125  * softdep.
5126  */
5127 void
5128 softdep_setup_link(dp, ip)
5129 	struct inode *dp;
5130 	struct inode *ip;
5131 {
5132 	struct inodedep *inodedep;
5133 	struct jaddref *jaddref;
5134 	struct vnode *dvp;
5135 
5136 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5137 	    ("softdep_setup_link called on non-softdep filesystem"));
5138 	dvp = ITOV(dp);
5139 	jaddref = NULL;
5140 	if (DOINGSUJ(dvp))
5141 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
5142 		    ip->i_mode);
5143 	ACQUIRE_LOCK(ITOUMP(dp));
5144 	inodedep = inodedep_lookup_ip(ip);
5145 	if (jaddref)
5146 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5147 		    if_deps);
5148 	FREE_LOCK(ITOUMP(dp));
5149 }
5150 
5151 /*
5152  * Called to create the jaddref structures to track . and .. references as
5153  * well as lookup and further initialize the incomplete jaddref created
5154  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
5155  * nlinkdelta for non-journaling softdep.
5156  */
5157 void
5158 softdep_setup_mkdir(dp, ip)
5159 	struct inode *dp;
5160 	struct inode *ip;
5161 {
5162 	struct inodedep *inodedep;
5163 	struct jaddref *dotdotaddref;
5164 	struct jaddref *dotaddref;
5165 	struct jaddref *jaddref;
5166 	struct vnode *dvp;
5167 
5168 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5169 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
5170 	dvp = ITOV(dp);
5171 	dotaddref = dotdotaddref = NULL;
5172 	if (DOINGSUJ(dvp)) {
5173 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
5174 		    ip->i_mode);
5175 		dotaddref->ja_state |= MKDIR_BODY;
5176 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5177 		    dp->i_effnlink - 1, dp->i_mode);
5178 		dotdotaddref->ja_state |= MKDIR_PARENT;
5179 	}
5180 	ACQUIRE_LOCK(ITOUMP(dp));
5181 	inodedep = inodedep_lookup_ip(ip);
5182 	if (DOINGSUJ(dvp)) {
5183 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5184 		    inoreflst);
5185 		KASSERT(jaddref != NULL,
5186 		    ("softdep_setup_mkdir: No addref structure present."));
5187 		KASSERT(jaddref->ja_parent == dp->i_number,
5188 		    ("softdep_setup_mkdir: bad parent %ju",
5189 		    (uintmax_t)jaddref->ja_parent));
5190 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
5191 		    if_deps);
5192 	}
5193 	inodedep = inodedep_lookup_ip(dp);
5194 	if (DOINGSUJ(dvp))
5195 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
5196 		    &dotdotaddref->ja_ref, if_deps);
5197 	FREE_LOCK(ITOUMP(dp));
5198 }
5199 
5200 /*
5201  * Called to track nlinkdelta of the inode and parent directories prior to
5202  * unlinking a directory.
5203  */
5204 void
5205 softdep_setup_rmdir(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_rmdir 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 track nlinkdelta of the inode and parent directories prior to
5222  * unlink.
5223  */
5224 void
5225 softdep_setup_unlink(dp, ip)
5226 	struct inode *dp;
5227 	struct inode *ip;
5228 {
5229 	struct vnode *dvp;
5230 
5231 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5232 	    ("softdep_setup_unlink called on non-softdep filesystem"));
5233 	dvp = ITOV(dp);
5234 	ACQUIRE_LOCK(ITOUMP(dp));
5235 	(void) inodedep_lookup_ip(ip);
5236 	(void) inodedep_lookup_ip(dp);
5237 	FREE_LOCK(ITOUMP(dp));
5238 }
5239 
5240 /*
5241  * Called to release the journal structures created by a failed non-directory
5242  * creation.  Adjusts nlinkdelta for non-journaling softdep.
5243  */
5244 void
5245 softdep_revert_create(dp, ip)
5246 	struct inode *dp;
5247 	struct inode *ip;
5248 {
5249 	struct inodedep *inodedep;
5250 	struct jaddref *jaddref;
5251 	struct vnode *dvp;
5252 
5253 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
5254 	    ("softdep_revert_create called on non-softdep filesystem"));
5255 	dvp = ITOV(dp);
5256 	ACQUIRE_LOCK(ITOUMP(dp));
5257 	inodedep = inodedep_lookup_ip(ip);
5258 	if (DOINGSUJ(dvp)) {
5259 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5260 		    inoreflst);
5261 		KASSERT(jaddref->ja_parent == dp->i_number,
5262 		    ("softdep_revert_create: addref parent mismatch"));
5263 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5264 	}
5265 	FREE_LOCK(ITOUMP(dp));
5266 }
5267 
5268 /*
5269  * Called to release the journal structures created by a failed link
5270  * addition.  Adjusts nlinkdelta for non-journaling softdep.
5271  */
5272 void
5273 softdep_revert_link(dp, ip)
5274 	struct inode *dp;
5275 	struct inode *ip;
5276 {
5277 	struct inodedep *inodedep;
5278 	struct jaddref *jaddref;
5279 	struct vnode *dvp;
5280 
5281 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5282 	    ("softdep_revert_link called on non-softdep filesystem"));
5283 	dvp = ITOV(dp);
5284 	ACQUIRE_LOCK(ITOUMP(dp));
5285 	inodedep = inodedep_lookup_ip(ip);
5286 	if (DOINGSUJ(dvp)) {
5287 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5288 		    inoreflst);
5289 		KASSERT(jaddref->ja_parent == dp->i_number,
5290 		    ("softdep_revert_link: addref parent mismatch"));
5291 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5292 	}
5293 	FREE_LOCK(ITOUMP(dp));
5294 }
5295 
5296 /*
5297  * Called to release the journal structures created by a failed mkdir
5298  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
5299  */
5300 void
5301 softdep_revert_mkdir(dp, ip)
5302 	struct inode *dp;
5303 	struct inode *ip;
5304 {
5305 	struct inodedep *inodedep;
5306 	struct jaddref *jaddref;
5307 	struct jaddref *dotaddref;
5308 	struct vnode *dvp;
5309 
5310 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5311 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
5312 	dvp = ITOV(dp);
5313 
5314 	ACQUIRE_LOCK(ITOUMP(dp));
5315 	inodedep = inodedep_lookup_ip(dp);
5316 	if (DOINGSUJ(dvp)) {
5317 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5318 		    inoreflst);
5319 		KASSERT(jaddref->ja_parent == ip->i_number,
5320 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
5321 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5322 	}
5323 	inodedep = inodedep_lookup_ip(ip);
5324 	if (DOINGSUJ(dvp)) {
5325 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5326 		    inoreflst);
5327 		KASSERT(jaddref->ja_parent == dp->i_number,
5328 		    ("softdep_revert_mkdir: addref parent mismatch"));
5329 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
5330 		    inoreflst, if_deps);
5331 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5332 		KASSERT(dotaddref->ja_parent == ip->i_number,
5333 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
5334 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
5335 	}
5336 	FREE_LOCK(ITOUMP(dp));
5337 }
5338 
5339 /*
5340  * Called to correct nlinkdelta after a failed rmdir.
5341  */
5342 void
5343 softdep_revert_rmdir(dp, ip)
5344 	struct inode *dp;
5345 	struct inode *ip;
5346 {
5347 
5348 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5349 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
5350 	ACQUIRE_LOCK(ITOUMP(dp));
5351 	(void) inodedep_lookup_ip(ip);
5352 	(void) inodedep_lookup_ip(dp);
5353 	FREE_LOCK(ITOUMP(dp));
5354 }
5355 
5356 /*
5357  * Protecting the freemaps (or bitmaps).
5358  *
5359  * To eliminate the need to execute fsck before mounting a filesystem
5360  * after a power failure, one must (conservatively) guarantee that the
5361  * on-disk copy of the bitmaps never indicate that a live inode or block is
5362  * free.  So, when a block or inode is allocated, the bitmap should be
5363  * updated (on disk) before any new pointers.  When a block or inode is
5364  * freed, the bitmap should not be updated until all pointers have been
5365  * reset.  The latter dependency is handled by the delayed de-allocation
5366  * approach described below for block and inode de-allocation.  The former
5367  * dependency is handled by calling the following procedure when a block or
5368  * inode is allocated. When an inode is allocated an "inodedep" is created
5369  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5370  * Each "inodedep" is also inserted into the hash indexing structure so
5371  * that any additional link additions can be made dependent on the inode
5372  * allocation.
5373  *
5374  * The ufs filesystem maintains a number of free block counts (e.g., per
5375  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5376  * in addition to the bitmaps.  These counts are used to improve efficiency
5377  * during allocation and therefore must be consistent with the bitmaps.
5378  * There is no convenient way to guarantee post-crash consistency of these
5379  * counts with simple update ordering, for two main reasons: (1) The counts
5380  * and bitmaps for a single cylinder group block are not in the same disk
5381  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5382  * be written and the other not.  (2) Some of the counts are located in the
5383  * superblock rather than the cylinder group block. So, we focus our soft
5384  * updates implementation on protecting the bitmaps. When mounting a
5385  * filesystem, we recompute the auxiliary counts from the bitmaps.
5386  */
5387 
5388 /*
5389  * Called just after updating the cylinder group block to allocate an inode.
5390  */
5391 void
5392 softdep_setup_inomapdep(bp, ip, newinum, mode)
5393 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5394 	struct inode *ip;	/* inode related to allocation */
5395 	ino_t newinum;		/* new inode number being allocated */
5396 	int mode;
5397 {
5398 	struct inodedep *inodedep;
5399 	struct bmsafemap *bmsafemap;
5400 	struct jaddref *jaddref;
5401 	struct mount *mp;
5402 	struct fs *fs;
5403 
5404 	mp = ITOVFS(ip);
5405 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5406 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5407 	fs = VFSTOUFS(mp)->um_fs;
5408 	jaddref = NULL;
5409 
5410 	/*
5411 	 * Allocate the journal reference add structure so that the bitmap
5412 	 * can be dependent on it.
5413 	 */
5414 	if (MOUNTEDSUJ(mp)) {
5415 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5416 		jaddref->ja_state |= NEWBLOCK;
5417 	}
5418 
5419 	/*
5420 	 * Create a dependency for the newly allocated inode.
5421 	 * Panic if it already exists as something is seriously wrong.
5422 	 * Otherwise add it to the dependency list for the buffer holding
5423 	 * the cylinder group map from which it was allocated.
5424 	 *
5425 	 * We have to preallocate a bmsafemap entry in case it is needed
5426 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5427 	 * have to finish initializing it before we can FREE_LOCK().
5428 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5429 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5430 	 * creating the inodedep as it can be freed during the time
5431 	 * that we FREE_LOCK() while allocating the inodedep. We must
5432 	 * call workitem_alloc() before entering the locked section as
5433 	 * it also acquires the lock and we must avoid trying doing so
5434 	 * recursively.
5435 	 */
5436 	bmsafemap = malloc(sizeof(struct bmsafemap),
5437 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5438 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5439 	ACQUIRE_LOCK(ITOUMP(ip));
5440 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5441 		panic("softdep_setup_inomapdep: dependency %p for new"
5442 		    "inode already exists", inodedep);
5443 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5444 	if (jaddref) {
5445 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5446 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5447 		    if_deps);
5448 	} else {
5449 		inodedep->id_state |= ONDEPLIST;
5450 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5451 	}
5452 	inodedep->id_bmsafemap = bmsafemap;
5453 	inodedep->id_state &= ~DEPCOMPLETE;
5454 	FREE_LOCK(ITOUMP(ip));
5455 }
5456 
5457 /*
5458  * Called just after updating the cylinder group block to
5459  * allocate block or fragment.
5460  */
5461 void
5462 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5463 	struct buf *bp;		/* buffer for cylgroup block with block map */
5464 	struct mount *mp;	/* filesystem doing allocation */
5465 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5466 	int frags;		/* Number of fragments. */
5467 	int oldfrags;		/* Previous number of fragments for extend. */
5468 {
5469 	struct newblk *newblk;
5470 	struct bmsafemap *bmsafemap;
5471 	struct jnewblk *jnewblk;
5472 	struct ufsmount *ump;
5473 	struct fs *fs;
5474 
5475 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5476 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5477 	ump = VFSTOUFS(mp);
5478 	fs = ump->um_fs;
5479 	jnewblk = NULL;
5480 	/*
5481 	 * Create a dependency for the newly allocated block.
5482 	 * Add it to the dependency list for the buffer holding
5483 	 * the cylinder group map from which it was allocated.
5484 	 */
5485 	if (MOUNTEDSUJ(mp)) {
5486 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5487 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5488 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5489 		jnewblk->jn_state = ATTACHED;
5490 		jnewblk->jn_blkno = newblkno;
5491 		jnewblk->jn_frags = frags;
5492 		jnewblk->jn_oldfrags = oldfrags;
5493 #ifdef INVARIANTS
5494 		{
5495 			struct cg *cgp;
5496 			uint8_t *blksfree;
5497 			long bno;
5498 			int i;
5499 
5500 			cgp = (struct cg *)bp->b_data;
5501 			blksfree = cg_blksfree(cgp);
5502 			bno = dtogd(fs, jnewblk->jn_blkno);
5503 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5504 			    i++) {
5505 				if (isset(blksfree, bno + i))
5506 					panic("softdep_setup_blkmapdep: "
5507 					    "free fragment %d from %d-%d "
5508 					    "state 0x%X dep %p", i,
5509 					    jnewblk->jn_oldfrags,
5510 					    jnewblk->jn_frags,
5511 					    jnewblk->jn_state,
5512 					    jnewblk->jn_dep);
5513 			}
5514 		}
5515 #endif
5516 	}
5517 
5518 	CTR3(KTR_SUJ,
5519 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5520 	    newblkno, frags, oldfrags);
5521 	ACQUIRE_LOCK(ump);
5522 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5523 		panic("softdep_setup_blkmapdep: found block");
5524 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5525 	    dtog(fs, newblkno), NULL);
5526 	if (jnewblk) {
5527 		jnewblk->jn_dep = (struct worklist *)newblk;
5528 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5529 	} else {
5530 		newblk->nb_state |= ONDEPLIST;
5531 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5532 	}
5533 	newblk->nb_bmsafemap = bmsafemap;
5534 	newblk->nb_jnewblk = jnewblk;
5535 	FREE_LOCK(ump);
5536 }
5537 
5538 #define	BMSAFEMAP_HASH(ump, cg) \
5539       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5540 
5541 static int
5542 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5543 	struct bmsafemap_hashhead *bmsafemaphd;
5544 	int cg;
5545 	struct bmsafemap **bmsafemapp;
5546 {
5547 	struct bmsafemap *bmsafemap;
5548 
5549 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5550 		if (bmsafemap->sm_cg == cg)
5551 			break;
5552 	if (bmsafemap) {
5553 		*bmsafemapp = bmsafemap;
5554 		return (1);
5555 	}
5556 	*bmsafemapp = NULL;
5557 
5558 	return (0);
5559 }
5560 
5561 /*
5562  * Find the bmsafemap associated with a cylinder group buffer.
5563  * If none exists, create one. The buffer must be locked when
5564  * this routine is called and this routine must be called with
5565  * the softdep lock held. To avoid giving up the lock while
5566  * allocating a new bmsafemap, a preallocated bmsafemap may be
5567  * provided. If it is provided but not needed, it is freed.
5568  */
5569 static struct bmsafemap *
5570 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5571 	struct mount *mp;
5572 	struct buf *bp;
5573 	int cg;
5574 	struct bmsafemap *newbmsafemap;
5575 {
5576 	struct bmsafemap_hashhead *bmsafemaphd;
5577 	struct bmsafemap *bmsafemap, *collision;
5578 	struct worklist *wk;
5579 	struct ufsmount *ump;
5580 
5581 	ump = VFSTOUFS(mp);
5582 	LOCK_OWNED(ump);
5583 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5584 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5585 		if (wk->wk_type == D_BMSAFEMAP) {
5586 			if (newbmsafemap)
5587 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5588 			return (WK_BMSAFEMAP(wk));
5589 		}
5590 	}
5591 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5592 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5593 		if (newbmsafemap)
5594 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5595 		return (bmsafemap);
5596 	}
5597 	if (newbmsafemap) {
5598 		bmsafemap = newbmsafemap;
5599 	} else {
5600 		FREE_LOCK(ump);
5601 		bmsafemap = malloc(sizeof(struct bmsafemap),
5602 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5603 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5604 		ACQUIRE_LOCK(ump);
5605 	}
5606 	bmsafemap->sm_buf = bp;
5607 	LIST_INIT(&bmsafemap->sm_inodedephd);
5608 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5609 	LIST_INIT(&bmsafemap->sm_newblkhd);
5610 	LIST_INIT(&bmsafemap->sm_newblkwr);
5611 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5612 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5613 	LIST_INIT(&bmsafemap->sm_freehd);
5614 	LIST_INIT(&bmsafemap->sm_freewr);
5615 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5616 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5617 		return (collision);
5618 	}
5619 	bmsafemap->sm_cg = cg;
5620 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5621 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5622 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5623 	return (bmsafemap);
5624 }
5625 
5626 /*
5627  * Direct block allocation dependencies.
5628  *
5629  * When a new block is allocated, the corresponding disk locations must be
5630  * initialized (with zeros or new data) before the on-disk inode points to
5631  * them.  Also, the freemap from which the block was allocated must be
5632  * updated (on disk) before the inode's pointer. These two dependencies are
5633  * independent of each other and are needed for all file blocks and indirect
5634  * blocks that are pointed to directly by the inode.  Just before the
5635  * "in-core" version of the inode is updated with a newly allocated block
5636  * number, a procedure (below) is called to setup allocation dependency
5637  * structures.  These structures are removed when the corresponding
5638  * dependencies are satisfied or when the block allocation becomes obsolete
5639  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5640  * fragment that gets upgraded).  All of these cases are handled in
5641  * procedures described later.
5642  *
5643  * When a file extension causes a fragment to be upgraded, either to a larger
5644  * fragment or to a full block, the on-disk location may change (if the
5645  * previous fragment could not simply be extended). In this case, the old
5646  * fragment must be de-allocated, but not until after the inode's pointer has
5647  * been updated. In most cases, this is handled by later procedures, which
5648  * will construct a "freefrag" structure to be added to the workitem queue
5649  * when the inode update is complete (or obsolete).  The main exception to
5650  * this is when an allocation occurs while a pending allocation dependency
5651  * (for the same block pointer) remains.  This case is handled in the main
5652  * allocation dependency setup procedure by immediately freeing the
5653  * unreferenced fragments.
5654  */
5655 void
5656 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5657 	struct inode *ip;	/* inode to which block is being added */
5658 	ufs_lbn_t off;		/* block pointer within inode */
5659 	ufs2_daddr_t newblkno;	/* disk block number being added */
5660 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5661 	long newsize;		/* size of new block */
5662 	long oldsize;		/* size of new block */
5663 	struct buf *bp;		/* bp for allocated block */
5664 {
5665 	struct allocdirect *adp, *oldadp;
5666 	struct allocdirectlst *adphead;
5667 	struct freefrag *freefrag;
5668 	struct inodedep *inodedep;
5669 	struct pagedep *pagedep;
5670 	struct jnewblk *jnewblk;
5671 	struct newblk *newblk;
5672 	struct mount *mp;
5673 	ufs_lbn_t lbn;
5674 
5675 	lbn = bp->b_lblkno;
5676 	mp = ITOVFS(ip);
5677 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5678 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5679 	if (oldblkno && oldblkno != newblkno)
5680 		/*
5681 		 * The usual case is that a smaller fragment that
5682 		 * was just allocated has been replaced with a bigger
5683 		 * fragment or a full-size block. If it is marked as
5684 		 * B_DELWRI, the current contents have not been written
5685 		 * to disk. It is possible that the block was written
5686 		 * earlier, but very uncommon. If the block has never
5687 		 * been written, there is no need to send a BIO_DELETE
5688 		 * for it when it is freed. The gain from avoiding the
5689 		 * TRIMs for the common case of unwritten blocks far
5690 		 * exceeds the cost of the write amplification for the
5691 		 * uncommon case of failing to send a TRIM for a block
5692 		 * that had been written.
5693 		 */
5694 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5695 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5696 	else
5697 		freefrag = NULL;
5698 
5699 	CTR6(KTR_SUJ,
5700 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5701 	    "off %jd newsize %ld oldsize %d",
5702 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5703 	ACQUIRE_LOCK(ITOUMP(ip));
5704 	if (off >= UFS_NDADDR) {
5705 		if (lbn > 0)
5706 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5707 			    lbn, off);
5708 		/* allocating an indirect block */
5709 		if (oldblkno != 0)
5710 			panic("softdep_setup_allocdirect: non-zero indir");
5711 	} else {
5712 		if (off != lbn)
5713 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5714 			    lbn, off);
5715 		/*
5716 		 * Allocating a direct block.
5717 		 *
5718 		 * If we are allocating a directory block, then we must
5719 		 * allocate an associated pagedep to track additions and
5720 		 * deletions.
5721 		 */
5722 		if ((ip->i_mode & IFMT) == IFDIR)
5723 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5724 			    &pagedep);
5725 	}
5726 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5727 		panic("softdep_setup_allocdirect: lost block");
5728 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5729 	    ("softdep_setup_allocdirect: newblk already initialized"));
5730 	/*
5731 	 * Convert the newblk to an allocdirect.
5732 	 */
5733 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5734 	adp = (struct allocdirect *)newblk;
5735 	newblk->nb_freefrag = freefrag;
5736 	adp->ad_offset = off;
5737 	adp->ad_oldblkno = oldblkno;
5738 	adp->ad_newsize = newsize;
5739 	adp->ad_oldsize = oldsize;
5740 
5741 	/*
5742 	 * Finish initializing the journal.
5743 	 */
5744 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5745 		jnewblk->jn_ino = ip->i_number;
5746 		jnewblk->jn_lbn = lbn;
5747 		add_to_journal(&jnewblk->jn_list);
5748 	}
5749 	if (freefrag && freefrag->ff_jdep != NULL &&
5750 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5751 		add_to_journal(freefrag->ff_jdep);
5752 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5753 	adp->ad_inodedep = inodedep;
5754 
5755 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5756 	/*
5757 	 * The list of allocdirects must be kept in sorted and ascending
5758 	 * order so that the rollback routines can quickly determine the
5759 	 * first uncommitted block (the size of the file stored on disk
5760 	 * ends at the end of the lowest committed fragment, or if there
5761 	 * are no fragments, at the end of the highest committed block).
5762 	 * Since files generally grow, the typical case is that the new
5763 	 * block is to be added at the end of the list. We speed this
5764 	 * special case by checking against the last allocdirect in the
5765 	 * list before laboriously traversing the list looking for the
5766 	 * insertion point.
5767 	 */
5768 	adphead = &inodedep->id_newinoupdt;
5769 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5770 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5771 		/* insert at end of list */
5772 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5773 		if (oldadp != NULL && oldadp->ad_offset == off)
5774 			allocdirect_merge(adphead, adp, oldadp);
5775 		FREE_LOCK(ITOUMP(ip));
5776 		return;
5777 	}
5778 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5779 		if (oldadp->ad_offset >= off)
5780 			break;
5781 	}
5782 	if (oldadp == NULL)
5783 		panic("softdep_setup_allocdirect: lost entry");
5784 	/* insert in middle of list */
5785 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5786 	if (oldadp->ad_offset == off)
5787 		allocdirect_merge(adphead, adp, oldadp);
5788 
5789 	FREE_LOCK(ITOUMP(ip));
5790 }
5791 
5792 /*
5793  * Merge a newer and older journal record to be stored either in a
5794  * newblock or freefrag.  This handles aggregating journal records for
5795  * fragment allocation into a second record as well as replacing a
5796  * journal free with an aborted journal allocation.  A segment for the
5797  * oldest record will be placed on wkhd if it has been written.  If not
5798  * the segment for the newer record will suffice.
5799  */
5800 static struct worklist *
5801 jnewblk_merge(new, old, wkhd)
5802 	struct worklist *new;
5803 	struct worklist *old;
5804 	struct workhead *wkhd;
5805 {
5806 	struct jnewblk *njnewblk;
5807 	struct jnewblk *jnewblk;
5808 
5809 	/* Handle NULLs to simplify callers. */
5810 	if (new == NULL)
5811 		return (old);
5812 	if (old == NULL)
5813 		return (new);
5814 	/* Replace a jfreefrag with a jnewblk. */
5815 	if (new->wk_type == D_JFREEFRAG) {
5816 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5817 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5818 			    old, new);
5819 		cancel_jfreefrag(WK_JFREEFRAG(new));
5820 		return (old);
5821 	}
5822 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5823 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5824 		    old->wk_type, new->wk_type);
5825 	/*
5826 	 * Handle merging of two jnewblk records that describe
5827 	 * different sets of fragments in the same block.
5828 	 */
5829 	jnewblk = WK_JNEWBLK(old);
5830 	njnewblk = WK_JNEWBLK(new);
5831 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5832 		panic("jnewblk_merge: Merging disparate blocks.");
5833 	/*
5834 	 * The record may be rolled back in the cg.
5835 	 */
5836 	if (jnewblk->jn_state & UNDONE) {
5837 		jnewblk->jn_state &= ~UNDONE;
5838 		njnewblk->jn_state |= UNDONE;
5839 		njnewblk->jn_state &= ~ATTACHED;
5840 	}
5841 	/*
5842 	 * We modify the newer addref and free the older so that if neither
5843 	 * has been written the most up-to-date copy will be on disk.  If
5844 	 * both have been written but rolled back we only temporarily need
5845 	 * one of them to fix the bits when the cg write completes.
5846 	 */
5847 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5848 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5849 	cancel_jnewblk(jnewblk, wkhd);
5850 	WORKLIST_REMOVE(&jnewblk->jn_list);
5851 	free_jnewblk(jnewblk);
5852 	return (new);
5853 }
5854 
5855 /*
5856  * Replace an old allocdirect dependency with a newer one.
5857  */
5858 static void
5859 allocdirect_merge(adphead, newadp, oldadp)
5860 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5861 	struct allocdirect *newadp;	/* allocdirect being added */
5862 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5863 {
5864 	struct worklist *wk;
5865 	struct freefrag *freefrag;
5866 
5867 	freefrag = NULL;
5868 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5869 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5870 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5871 	    newadp->ad_offset >= UFS_NDADDR)
5872 		panic("%s %jd != new %jd || old size %ld != new %ld",
5873 		    "allocdirect_merge: old blkno",
5874 		    (intmax_t)newadp->ad_oldblkno,
5875 		    (intmax_t)oldadp->ad_newblkno,
5876 		    newadp->ad_oldsize, oldadp->ad_newsize);
5877 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5878 	newadp->ad_oldsize = oldadp->ad_oldsize;
5879 	/*
5880 	 * If the old dependency had a fragment to free or had never
5881 	 * previously had a block allocated, then the new dependency
5882 	 * can immediately post its freefrag and adopt the old freefrag.
5883 	 * This action is done by swapping the freefrag dependencies.
5884 	 * The new dependency gains the old one's freefrag, and the
5885 	 * old one gets the new one and then immediately puts it on
5886 	 * the worklist when it is freed by free_newblk. It is
5887 	 * not possible to do this swap when the old dependency had a
5888 	 * non-zero size but no previous fragment to free. This condition
5889 	 * arises when the new block is an extension of the old block.
5890 	 * Here, the first part of the fragment allocated to the new
5891 	 * dependency is part of the block currently claimed on disk by
5892 	 * the old dependency, so cannot legitimately be freed until the
5893 	 * conditions for the new dependency are fulfilled.
5894 	 */
5895 	freefrag = newadp->ad_freefrag;
5896 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5897 		newadp->ad_freefrag = oldadp->ad_freefrag;
5898 		oldadp->ad_freefrag = freefrag;
5899 	}
5900 	/*
5901 	 * If we are tracking a new directory-block allocation,
5902 	 * move it from the old allocdirect to the new allocdirect.
5903 	 */
5904 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5905 		WORKLIST_REMOVE(wk);
5906 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5907 			panic("allocdirect_merge: extra newdirblk");
5908 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5909 	}
5910 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5911 	/*
5912 	 * We need to move any journal dependencies over to the freefrag
5913 	 * that releases this block if it exists.  Otherwise we are
5914 	 * extending an existing block and we'll wait until that is
5915 	 * complete to release the journal space and extend the
5916 	 * new journal to cover this old space as well.
5917 	 */
5918 	if (freefrag == NULL) {
5919 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5920 			panic("allocdirect_merge: %jd != %jd",
5921 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5922 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5923 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5924 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5925 		    &newadp->ad_block.nb_jwork);
5926 		oldadp->ad_block.nb_jnewblk = NULL;
5927 		cancel_newblk(&oldadp->ad_block, NULL,
5928 		    &newadp->ad_block.nb_jwork);
5929 	} else {
5930 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5931 		    &freefrag->ff_list, &freefrag->ff_jwork);
5932 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5933 		    &freefrag->ff_jwork);
5934 	}
5935 	free_newblk(&oldadp->ad_block);
5936 }
5937 
5938 /*
5939  * Allocate a jfreefrag structure to journal a single block free.
5940  */
5941 static struct jfreefrag *
5942 newjfreefrag(freefrag, ip, blkno, size, lbn)
5943 	struct freefrag *freefrag;
5944 	struct inode *ip;
5945 	ufs2_daddr_t blkno;
5946 	long size;
5947 	ufs_lbn_t lbn;
5948 {
5949 	struct jfreefrag *jfreefrag;
5950 	struct fs *fs;
5951 
5952 	fs = ITOFS(ip);
5953 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5954 	    M_SOFTDEP_FLAGS);
5955 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5956 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5957 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5958 	jfreefrag->fr_ino = ip->i_number;
5959 	jfreefrag->fr_lbn = lbn;
5960 	jfreefrag->fr_blkno = blkno;
5961 	jfreefrag->fr_frags = numfrags(fs, size);
5962 	jfreefrag->fr_freefrag = freefrag;
5963 
5964 	return (jfreefrag);
5965 }
5966 
5967 /*
5968  * Allocate a new freefrag structure.
5969  */
5970 static struct freefrag *
5971 newfreefrag(ip, blkno, size, lbn, key)
5972 	struct inode *ip;
5973 	ufs2_daddr_t blkno;
5974 	long size;
5975 	ufs_lbn_t lbn;
5976 	u_long key;
5977 {
5978 	struct freefrag *freefrag;
5979 	struct ufsmount *ump;
5980 	struct fs *fs;
5981 
5982 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5983 	    ip->i_number, blkno, size, lbn);
5984 	ump = ITOUMP(ip);
5985 	fs = ump->um_fs;
5986 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5987 		panic("newfreefrag: frag size");
5988 	freefrag = malloc(sizeof(struct freefrag),
5989 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5990 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5991 	freefrag->ff_state = ATTACHED;
5992 	LIST_INIT(&freefrag->ff_jwork);
5993 	freefrag->ff_inum = ip->i_number;
5994 	freefrag->ff_vtype = ITOV(ip)->v_type;
5995 	freefrag->ff_blkno = blkno;
5996 	freefrag->ff_fragsize = size;
5997 	freefrag->ff_key = key;
5998 
5999 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
6000 		freefrag->ff_jdep = (struct worklist *)
6001 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
6002 	} else {
6003 		freefrag->ff_state |= DEPCOMPLETE;
6004 		freefrag->ff_jdep = NULL;
6005 	}
6006 
6007 	return (freefrag);
6008 }
6009 
6010 /*
6011  * This workitem de-allocates fragments that were replaced during
6012  * file block allocation.
6013  */
6014 static void
6015 handle_workitem_freefrag(freefrag)
6016 	struct freefrag *freefrag;
6017 {
6018 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
6019 	struct workhead wkhd;
6020 
6021 	CTR3(KTR_SUJ,
6022 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
6023 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
6024 	/*
6025 	 * It would be illegal to add new completion items to the
6026 	 * freefrag after it was schedule to be done so it must be
6027 	 * safe to modify the list head here.
6028 	 */
6029 	LIST_INIT(&wkhd);
6030 	ACQUIRE_LOCK(ump);
6031 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
6032 	/*
6033 	 * If the journal has not been written we must cancel it here.
6034 	 */
6035 	if (freefrag->ff_jdep) {
6036 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
6037 			panic("handle_workitem_freefrag: Unexpected type %d\n",
6038 			    freefrag->ff_jdep->wk_type);
6039 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
6040 	}
6041 	FREE_LOCK(ump);
6042 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
6043 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
6044 	   &wkhd, freefrag->ff_key);
6045 	ACQUIRE_LOCK(ump);
6046 	WORKITEM_FREE(freefrag, D_FREEFRAG);
6047 	FREE_LOCK(ump);
6048 }
6049 
6050 /*
6051  * Set up a dependency structure for an external attributes data block.
6052  * This routine follows much of the structure of softdep_setup_allocdirect.
6053  * See the description of softdep_setup_allocdirect above for details.
6054  */
6055 void
6056 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
6057 	struct inode *ip;
6058 	ufs_lbn_t off;
6059 	ufs2_daddr_t newblkno;
6060 	ufs2_daddr_t oldblkno;
6061 	long newsize;
6062 	long oldsize;
6063 	struct buf *bp;
6064 {
6065 	struct allocdirect *adp, *oldadp;
6066 	struct allocdirectlst *adphead;
6067 	struct freefrag *freefrag;
6068 	struct inodedep *inodedep;
6069 	struct jnewblk *jnewblk;
6070 	struct newblk *newblk;
6071 	struct mount *mp;
6072 	struct ufsmount *ump;
6073 	ufs_lbn_t lbn;
6074 
6075 	mp = ITOVFS(ip);
6076 	ump = VFSTOUFS(mp);
6077 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6078 	    ("softdep_setup_allocext called on non-softdep filesystem"));
6079 	KASSERT(off < UFS_NXADDR,
6080 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
6081 
6082 	lbn = bp->b_lblkno;
6083 	if (oldblkno && oldblkno != newblkno)
6084 		/*
6085 		 * The usual case is that a smaller fragment that
6086 		 * was just allocated has been replaced with a bigger
6087 		 * fragment or a full-size block. If it is marked as
6088 		 * B_DELWRI, the current contents have not been written
6089 		 * to disk. It is possible that the block was written
6090 		 * earlier, but very uncommon. If the block has never
6091 		 * been written, there is no need to send a BIO_DELETE
6092 		 * for it when it is freed. The gain from avoiding the
6093 		 * TRIMs for the common case of unwritten blocks far
6094 		 * exceeds the cost of the write amplification for the
6095 		 * uncommon case of failing to send a TRIM for a block
6096 		 * that had been written.
6097 		 */
6098 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
6099 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
6100 	else
6101 		freefrag = NULL;
6102 
6103 	ACQUIRE_LOCK(ump);
6104 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
6105 		panic("softdep_setup_allocext: lost block");
6106 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6107 	    ("softdep_setup_allocext: newblk already initialized"));
6108 	/*
6109 	 * Convert the newblk to an allocdirect.
6110 	 */
6111 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
6112 	adp = (struct allocdirect *)newblk;
6113 	newblk->nb_freefrag = freefrag;
6114 	adp->ad_offset = off;
6115 	adp->ad_oldblkno = oldblkno;
6116 	adp->ad_newsize = newsize;
6117 	adp->ad_oldsize = oldsize;
6118 	adp->ad_state |=  EXTDATA;
6119 
6120 	/*
6121 	 * Finish initializing the journal.
6122 	 */
6123 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6124 		jnewblk->jn_ino = ip->i_number;
6125 		jnewblk->jn_lbn = lbn;
6126 		add_to_journal(&jnewblk->jn_list);
6127 	}
6128 	if (freefrag && freefrag->ff_jdep != NULL &&
6129 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6130 		add_to_journal(freefrag->ff_jdep);
6131 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6132 	adp->ad_inodedep = inodedep;
6133 
6134 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
6135 	/*
6136 	 * The list of allocdirects must be kept in sorted and ascending
6137 	 * order so that the rollback routines can quickly determine the
6138 	 * first uncommitted block (the size of the file stored on disk
6139 	 * ends at the end of the lowest committed fragment, or if there
6140 	 * are no fragments, at the end of the highest committed block).
6141 	 * Since files generally grow, the typical case is that the new
6142 	 * block is to be added at the end of the list. We speed this
6143 	 * special case by checking against the last allocdirect in the
6144 	 * list before laboriously traversing the list looking for the
6145 	 * insertion point.
6146 	 */
6147 	adphead = &inodedep->id_newextupdt;
6148 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
6149 	if (oldadp == NULL || oldadp->ad_offset <= off) {
6150 		/* insert at end of list */
6151 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
6152 		if (oldadp != NULL && oldadp->ad_offset == off)
6153 			allocdirect_merge(adphead, adp, oldadp);
6154 		FREE_LOCK(ump);
6155 		return;
6156 	}
6157 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
6158 		if (oldadp->ad_offset >= off)
6159 			break;
6160 	}
6161 	if (oldadp == NULL)
6162 		panic("softdep_setup_allocext: lost entry");
6163 	/* insert in middle of list */
6164 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
6165 	if (oldadp->ad_offset == off)
6166 		allocdirect_merge(adphead, adp, oldadp);
6167 	FREE_LOCK(ump);
6168 }
6169 
6170 /*
6171  * Indirect block allocation dependencies.
6172  *
6173  * The same dependencies that exist for a direct block also exist when
6174  * a new block is allocated and pointed to by an entry in a block of
6175  * indirect pointers. The undo/redo states described above are also
6176  * used here. Because an indirect block contains many pointers that
6177  * may have dependencies, a second copy of the entire in-memory indirect
6178  * block is kept. The buffer cache copy is always completely up-to-date.
6179  * The second copy, which is used only as a source for disk writes,
6180  * contains only the safe pointers (i.e., those that have no remaining
6181  * update dependencies). The second copy is freed when all pointers
6182  * are safe. The cache is not allowed to replace indirect blocks with
6183  * pending update dependencies. If a buffer containing an indirect
6184  * block with dependencies is written, these routines will mark it
6185  * dirty again. It can only be successfully written once all the
6186  * dependencies are removed. The ffs_fsync routine in conjunction with
6187  * softdep_sync_metadata work together to get all the dependencies
6188  * removed so that a file can be successfully written to disk. Three
6189  * procedures are used when setting up indirect block pointer
6190  * dependencies. The division is necessary because of the organization
6191  * of the "balloc" routine and because of the distinction between file
6192  * pages and file metadata blocks.
6193  */
6194 
6195 /*
6196  * Allocate a new allocindir structure.
6197  */
6198 static struct allocindir *
6199 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
6200 	struct inode *ip;	/* inode for file being extended */
6201 	int ptrno;		/* offset of pointer in indirect block */
6202 	ufs2_daddr_t newblkno;	/* disk block number being added */
6203 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
6204 	ufs_lbn_t lbn;
6205 {
6206 	struct newblk *newblk;
6207 	struct allocindir *aip;
6208 	struct freefrag *freefrag;
6209 	struct jnewblk *jnewblk;
6210 
6211 	if (oldblkno)
6212 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
6213 		    SINGLETON_KEY);
6214 	else
6215 		freefrag = NULL;
6216 	ACQUIRE_LOCK(ITOUMP(ip));
6217 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
6218 		panic("new_allocindir: lost block");
6219 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6220 	    ("newallocindir: newblk already initialized"));
6221 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
6222 	newblk->nb_freefrag = freefrag;
6223 	aip = (struct allocindir *)newblk;
6224 	aip->ai_offset = ptrno;
6225 	aip->ai_oldblkno = oldblkno;
6226 	aip->ai_lbn = lbn;
6227 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6228 		jnewblk->jn_ino = ip->i_number;
6229 		jnewblk->jn_lbn = lbn;
6230 		add_to_journal(&jnewblk->jn_list);
6231 	}
6232 	if (freefrag && freefrag->ff_jdep != NULL &&
6233 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6234 		add_to_journal(freefrag->ff_jdep);
6235 	return (aip);
6236 }
6237 
6238 /*
6239  * Called just before setting an indirect block pointer
6240  * to a newly allocated file page.
6241  */
6242 void
6243 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
6244 	struct inode *ip;	/* inode for file being extended */
6245 	ufs_lbn_t lbn;		/* allocated block number within file */
6246 	struct buf *bp;		/* buffer with indirect blk referencing page */
6247 	int ptrno;		/* offset of pointer in indirect block */
6248 	ufs2_daddr_t newblkno;	/* disk block number being added */
6249 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
6250 	struct buf *nbp;	/* buffer holding allocated page */
6251 {
6252 	struct inodedep *inodedep;
6253 	struct freefrag *freefrag;
6254 	struct allocindir *aip;
6255 	struct pagedep *pagedep;
6256 	struct mount *mp;
6257 	struct ufsmount *ump;
6258 
6259 	mp = ITOVFS(ip);
6260 	ump = VFSTOUFS(mp);
6261 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6262 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
6263 	KASSERT(lbn == nbp->b_lblkno,
6264 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
6265 	    lbn, bp->b_lblkno));
6266 	CTR4(KTR_SUJ,
6267 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
6268 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
6269 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
6270 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
6271 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6272 	/*
6273 	 * If we are allocating a directory page, then we must
6274 	 * allocate an associated pagedep to track additions and
6275 	 * deletions.
6276 	 */
6277 	if ((ip->i_mode & IFMT) == IFDIR)
6278 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
6279 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6280 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
6281 	FREE_LOCK(ump);
6282 	if (freefrag)
6283 		handle_workitem_freefrag(freefrag);
6284 }
6285 
6286 /*
6287  * Called just before setting an indirect block pointer to a
6288  * newly allocated indirect block.
6289  */
6290 void
6291 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
6292 	struct buf *nbp;	/* newly allocated indirect block */
6293 	struct inode *ip;	/* inode for file being extended */
6294 	struct buf *bp;		/* indirect block referencing allocated block */
6295 	int ptrno;		/* offset of pointer in indirect block */
6296 	ufs2_daddr_t newblkno;	/* disk block number being added */
6297 {
6298 	struct inodedep *inodedep;
6299 	struct allocindir *aip;
6300 	struct ufsmount *ump;
6301 	ufs_lbn_t lbn;
6302 
6303 	ump = ITOUMP(ip);
6304 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6305 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
6306 	CTR3(KTR_SUJ,
6307 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
6308 	    ip->i_number, newblkno, ptrno);
6309 	lbn = nbp->b_lblkno;
6310 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
6311 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
6312 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
6313 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6314 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
6315 		panic("softdep_setup_allocindir_meta: Block already existed");
6316 	FREE_LOCK(ump);
6317 }
6318 
6319 static void
6320 indirdep_complete(indirdep)
6321 	struct indirdep *indirdep;
6322 {
6323 	struct allocindir *aip;
6324 
6325 	LIST_REMOVE(indirdep, ir_next);
6326 	indirdep->ir_state |= DEPCOMPLETE;
6327 
6328 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
6329 		LIST_REMOVE(aip, ai_next);
6330 		free_newblk(&aip->ai_block);
6331 	}
6332 	/*
6333 	 * If this indirdep is not attached to a buf it was simply waiting
6334 	 * on completion to clear completehd.  free_indirdep() asserts
6335 	 * that nothing is dangling.
6336 	 */
6337 	if ((indirdep->ir_state & ONWORKLIST) == 0)
6338 		free_indirdep(indirdep);
6339 }
6340 
6341 static struct indirdep *
6342 indirdep_lookup(mp, ip, bp)
6343 	struct mount *mp;
6344 	struct inode *ip;
6345 	struct buf *bp;
6346 {
6347 	struct indirdep *indirdep, *newindirdep;
6348 	struct newblk *newblk;
6349 	struct ufsmount *ump;
6350 	struct worklist *wk;
6351 	struct fs *fs;
6352 	ufs2_daddr_t blkno;
6353 
6354 	ump = VFSTOUFS(mp);
6355 	LOCK_OWNED(ump);
6356 	indirdep = NULL;
6357 	newindirdep = NULL;
6358 	fs = ump->um_fs;
6359 	for (;;) {
6360 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6361 			if (wk->wk_type != D_INDIRDEP)
6362 				continue;
6363 			indirdep = WK_INDIRDEP(wk);
6364 			break;
6365 		}
6366 		/* Found on the buffer worklist, no new structure to free. */
6367 		if (indirdep != NULL && newindirdep == NULL)
6368 			return (indirdep);
6369 		if (indirdep != NULL && newindirdep != NULL)
6370 			panic("indirdep_lookup: simultaneous create");
6371 		/* None found on the buffer and a new structure is ready. */
6372 		if (indirdep == NULL && newindirdep != NULL)
6373 			break;
6374 		/* None found and no new structure available. */
6375 		FREE_LOCK(ump);
6376 		newindirdep = malloc(sizeof(struct indirdep),
6377 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
6378 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6379 		newindirdep->ir_state = ATTACHED;
6380 		if (I_IS_UFS1(ip))
6381 			newindirdep->ir_state |= UFS1FMT;
6382 		TAILQ_INIT(&newindirdep->ir_trunc);
6383 		newindirdep->ir_saveddata = NULL;
6384 		LIST_INIT(&newindirdep->ir_deplisthd);
6385 		LIST_INIT(&newindirdep->ir_donehd);
6386 		LIST_INIT(&newindirdep->ir_writehd);
6387 		LIST_INIT(&newindirdep->ir_completehd);
6388 		if (bp->b_blkno == bp->b_lblkno) {
6389 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6390 			    NULL, NULL);
6391 			bp->b_blkno = blkno;
6392 		}
6393 		newindirdep->ir_freeblks = NULL;
6394 		newindirdep->ir_savebp =
6395 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6396 		newindirdep->ir_bp = bp;
6397 		BUF_KERNPROC(newindirdep->ir_savebp);
6398 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6399 		ACQUIRE_LOCK(ump);
6400 	}
6401 	indirdep = newindirdep;
6402 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6403 	/*
6404 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6405 	 * that we don't free dependencies until the pointers are valid.
6406 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6407 	 * than using the hash.
6408 	 */
6409 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6410 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6411 	else
6412 		indirdep->ir_state |= DEPCOMPLETE;
6413 	return (indirdep);
6414 }
6415 
6416 /*
6417  * Called to finish the allocation of the "aip" allocated
6418  * by one of the two routines above.
6419  */
6420 static struct freefrag *
6421 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6422 	struct buf *bp;		/* in-memory copy of the indirect block */
6423 	struct inode *ip;	/* inode for file being extended */
6424 	struct inodedep *inodedep; /* Inodedep for ip */
6425 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6426 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6427 {
6428 	struct fs *fs;
6429 	struct indirdep *indirdep;
6430 	struct allocindir *oldaip;
6431 	struct freefrag *freefrag;
6432 	struct mount *mp;
6433 	struct ufsmount *ump;
6434 
6435 	mp = ITOVFS(ip);
6436 	ump = VFSTOUFS(mp);
6437 	LOCK_OWNED(ump);
6438 	fs = ump->um_fs;
6439 	if (bp->b_lblkno >= 0)
6440 		panic("setup_allocindir_phase2: not indir blk");
6441 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6442 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6443 	indirdep = indirdep_lookup(mp, ip, bp);
6444 	KASSERT(indirdep->ir_savebp != NULL,
6445 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6446 	aip->ai_indirdep = indirdep;
6447 	/*
6448 	 * Check for an unwritten dependency for this indirect offset.  If
6449 	 * there is, merge the old dependency into the new one.  This happens
6450 	 * as a result of reallocblk only.
6451 	 */
6452 	freefrag = NULL;
6453 	if (aip->ai_oldblkno != 0) {
6454 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6455 			if (oldaip->ai_offset == aip->ai_offset) {
6456 				freefrag = allocindir_merge(aip, oldaip);
6457 				goto done;
6458 			}
6459 		}
6460 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6461 			if (oldaip->ai_offset == aip->ai_offset) {
6462 				freefrag = allocindir_merge(aip, oldaip);
6463 				goto done;
6464 			}
6465 		}
6466 	}
6467 done:
6468 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6469 	return (freefrag);
6470 }
6471 
6472 /*
6473  * Merge two allocindirs which refer to the same block.  Move newblock
6474  * dependencies and setup the freefrags appropriately.
6475  */
6476 static struct freefrag *
6477 allocindir_merge(aip, oldaip)
6478 	struct allocindir *aip;
6479 	struct allocindir *oldaip;
6480 {
6481 	struct freefrag *freefrag;
6482 	struct worklist *wk;
6483 
6484 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6485 		panic("allocindir_merge: blkno");
6486 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6487 	freefrag = aip->ai_freefrag;
6488 	aip->ai_freefrag = oldaip->ai_freefrag;
6489 	oldaip->ai_freefrag = NULL;
6490 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6491 	/*
6492 	 * If we are tracking a new directory-block allocation,
6493 	 * move it from the old allocindir to the new allocindir.
6494 	 */
6495 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6496 		WORKLIST_REMOVE(wk);
6497 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6498 			panic("allocindir_merge: extra newdirblk");
6499 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6500 	}
6501 	/*
6502 	 * We can skip journaling for this freefrag and just complete
6503 	 * any pending journal work for the allocindir that is being
6504 	 * removed after the freefrag completes.
6505 	 */
6506 	if (freefrag->ff_jdep)
6507 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6508 	LIST_REMOVE(oldaip, ai_next);
6509 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6510 	    &freefrag->ff_list, &freefrag->ff_jwork);
6511 	free_newblk(&oldaip->ai_block);
6512 
6513 	return (freefrag);
6514 }
6515 
6516 static inline void
6517 setup_freedirect(freeblks, ip, i, needj)
6518 	struct freeblks *freeblks;
6519 	struct inode *ip;
6520 	int i;
6521 	int needj;
6522 {
6523 	struct ufsmount *ump;
6524 	ufs2_daddr_t blkno;
6525 	int frags;
6526 
6527 	blkno = DIP(ip, i_db[i]);
6528 	if (blkno == 0)
6529 		return;
6530 	DIP_SET(ip, i_db[i], 0);
6531 	ump = ITOUMP(ip);
6532 	frags = sblksize(ump->um_fs, ip->i_size, i);
6533 	frags = numfrags(ump->um_fs, frags);
6534 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6535 }
6536 
6537 static inline void
6538 setup_freeext(freeblks, ip, i, needj)
6539 	struct freeblks *freeblks;
6540 	struct inode *ip;
6541 	int i;
6542 	int needj;
6543 {
6544 	struct ufsmount *ump;
6545 	ufs2_daddr_t blkno;
6546 	int frags;
6547 
6548 	blkno = ip->i_din2->di_extb[i];
6549 	if (blkno == 0)
6550 		return;
6551 	ip->i_din2->di_extb[i] = 0;
6552 	ump = ITOUMP(ip);
6553 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6554 	frags = numfrags(ump->um_fs, frags);
6555 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6556 }
6557 
6558 static inline void
6559 setup_freeindir(freeblks, ip, i, lbn, needj)
6560 	struct freeblks *freeblks;
6561 	struct inode *ip;
6562 	int i;
6563 	ufs_lbn_t lbn;
6564 	int needj;
6565 {
6566 	struct ufsmount *ump;
6567 	ufs2_daddr_t blkno;
6568 
6569 	blkno = DIP(ip, i_ib[i]);
6570 	if (blkno == 0)
6571 		return;
6572 	DIP_SET(ip, i_ib[i], 0);
6573 	ump = ITOUMP(ip);
6574 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6575 	    0, needj);
6576 }
6577 
6578 static inline struct freeblks *
6579 newfreeblks(mp, ip)
6580 	struct mount *mp;
6581 	struct inode *ip;
6582 {
6583 	struct freeblks *freeblks;
6584 
6585 	freeblks = malloc(sizeof(struct freeblks),
6586 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6587 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6588 	LIST_INIT(&freeblks->fb_jblkdephd);
6589 	LIST_INIT(&freeblks->fb_jwork);
6590 	freeblks->fb_ref = 0;
6591 	freeblks->fb_cgwait = 0;
6592 	freeblks->fb_state = ATTACHED;
6593 	freeblks->fb_uid = ip->i_uid;
6594 	freeblks->fb_inum = ip->i_number;
6595 	freeblks->fb_vtype = ITOV(ip)->v_type;
6596 	freeblks->fb_modrev = DIP(ip, i_modrev);
6597 	freeblks->fb_devvp = ITODEVVP(ip);
6598 	freeblks->fb_chkcnt = 0;
6599 	freeblks->fb_len = 0;
6600 
6601 	return (freeblks);
6602 }
6603 
6604 static void
6605 trunc_indirdep(indirdep, freeblks, bp, off)
6606 	struct indirdep *indirdep;
6607 	struct freeblks *freeblks;
6608 	struct buf *bp;
6609 	int off;
6610 {
6611 	struct allocindir *aip, *aipn;
6612 
6613 	/*
6614 	 * The first set of allocindirs won't be in savedbp.
6615 	 */
6616 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6617 		if (aip->ai_offset > off)
6618 			cancel_allocindir(aip, bp, freeblks, 1);
6619 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6620 		if (aip->ai_offset > off)
6621 			cancel_allocindir(aip, bp, freeblks, 1);
6622 	/*
6623 	 * These will exist in savedbp.
6624 	 */
6625 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6626 		if (aip->ai_offset > off)
6627 			cancel_allocindir(aip, NULL, freeblks, 0);
6628 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6629 		if (aip->ai_offset > off)
6630 			cancel_allocindir(aip, NULL, freeblks, 0);
6631 }
6632 
6633 /*
6634  * Follow the chain of indirects down to lastlbn creating a freework
6635  * structure for each.  This will be used to start indir_trunc() at
6636  * the right offset and create the journal records for the parrtial
6637  * truncation.  A second step will handle the truncated dependencies.
6638  */
6639 static int
6640 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6641 	struct freeblks *freeblks;
6642 	struct inode *ip;
6643 	ufs_lbn_t lbn;
6644 	ufs_lbn_t lastlbn;
6645 	ufs2_daddr_t blkno;
6646 {
6647 	struct indirdep *indirdep;
6648 	struct indirdep *indirn;
6649 	struct freework *freework;
6650 	struct newblk *newblk;
6651 	struct mount *mp;
6652 	struct ufsmount *ump;
6653 	struct buf *bp;
6654 	uint8_t *start;
6655 	uint8_t *end;
6656 	ufs_lbn_t lbnadd;
6657 	int level;
6658 	int error;
6659 	int off;
6660 
6661 	freework = NULL;
6662 	if (blkno == 0)
6663 		return (0);
6664 	mp = freeblks->fb_list.wk_mp;
6665 	ump = VFSTOUFS(mp);
6666 	/*
6667 	 * Here, calls to VOP_BMAP() will fail.  However, we already have
6668 	 * the on-disk address, so we just pass it to bread() instead of
6669 	 * having bread() attempt to calculate it using VOP_BMAP().
6670 	 */
6671 	error = ffs_breadz(ump, ITOV(ip), lbn, blkptrtodb(ump, blkno),
6672 	    (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6673 	if (error)
6674 		return (error);
6675 	level = lbn_level(lbn);
6676 	lbnadd = lbn_offset(ump->um_fs, level);
6677 	/*
6678 	 * Compute the offset of the last block we want to keep.  Store
6679 	 * in the freework the first block we want to completely free.
6680 	 */
6681 	off = (lastlbn - -(lbn + level)) / lbnadd;
6682 	if (off + 1 == NINDIR(ump->um_fs))
6683 		goto nowork;
6684 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6685 	/*
6686 	 * Link the freework into the indirdep.  This will prevent any new
6687 	 * allocations from proceeding until we are finished with the
6688 	 * truncate and the block is written.
6689 	 */
6690 	ACQUIRE_LOCK(ump);
6691 	indirdep = indirdep_lookup(mp, ip, bp);
6692 	if (indirdep->ir_freeblks)
6693 		panic("setup_trunc_indir: indirdep already truncated.");
6694 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6695 	freework->fw_indir = indirdep;
6696 	/*
6697 	 * Cancel any allocindirs that will not make it to disk.
6698 	 * We have to do this for all copies of the indirdep that
6699 	 * live on this newblk.
6700 	 */
6701 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6702 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6703 		    &newblk) == 0)
6704 			panic("setup_trunc_indir: lost block");
6705 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6706 			trunc_indirdep(indirn, freeblks, bp, off);
6707 	} else
6708 		trunc_indirdep(indirdep, freeblks, bp, off);
6709 	FREE_LOCK(ump);
6710 	/*
6711 	 * Creation is protected by the buf lock. The saveddata is only
6712 	 * needed if a full truncation follows a partial truncation but it
6713 	 * is difficult to allocate in that case so we fetch it anyway.
6714 	 */
6715 	if (indirdep->ir_saveddata == NULL)
6716 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6717 		    M_SOFTDEP_FLAGS);
6718 nowork:
6719 	/* Fetch the blkno of the child and the zero start offset. */
6720 	if (I_IS_UFS1(ip)) {
6721 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6722 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6723 	} else {
6724 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6725 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6726 	}
6727 	if (freework) {
6728 		/* Zero the truncated pointers. */
6729 		end = bp->b_data + bp->b_bcount;
6730 		bzero(start, end - start);
6731 		bdwrite(bp);
6732 	} else
6733 		bqrelse(bp);
6734 	if (level == 0)
6735 		return (0);
6736 	lbn++; /* adjust level */
6737 	lbn -= (off * lbnadd);
6738 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6739 }
6740 
6741 /*
6742  * Complete the partial truncation of an indirect block setup by
6743  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6744  * copy and writes them to disk before the freeblks is allowed to complete.
6745  */
6746 static void
6747 complete_trunc_indir(freework)
6748 	struct freework *freework;
6749 {
6750 	struct freework *fwn;
6751 	struct indirdep *indirdep;
6752 	struct ufsmount *ump;
6753 	struct buf *bp;
6754 	uintptr_t start;
6755 	int count;
6756 
6757 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6758 	LOCK_OWNED(ump);
6759 	indirdep = freework->fw_indir;
6760 	for (;;) {
6761 		bp = indirdep->ir_bp;
6762 		/* See if the block was discarded. */
6763 		if (bp == NULL)
6764 			break;
6765 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6766 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6767 			break;
6768 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6769 		    LOCK_PTR(ump)) == 0)
6770 			BUF_UNLOCK(bp);
6771 		ACQUIRE_LOCK(ump);
6772 	}
6773 	freework->fw_state |= DEPCOMPLETE;
6774 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6775 	/*
6776 	 * Zero the pointers in the saved copy.
6777 	 */
6778 	if (indirdep->ir_state & UFS1FMT)
6779 		start = sizeof(ufs1_daddr_t);
6780 	else
6781 		start = sizeof(ufs2_daddr_t);
6782 	start *= freework->fw_start;
6783 	count = indirdep->ir_savebp->b_bcount - start;
6784 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6785 	bzero((char *)start, count);
6786 	/*
6787 	 * We need to start the next truncation in the list if it has not
6788 	 * been started yet.
6789 	 */
6790 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6791 	if (fwn != NULL) {
6792 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6793 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6794 		if ((fwn->fw_state & ONWORKLIST) == 0)
6795 			freework_enqueue(fwn);
6796 	}
6797 	/*
6798 	 * If bp is NULL the block was fully truncated, restore
6799 	 * the saved block list otherwise free it if it is no
6800 	 * longer needed.
6801 	 */
6802 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6803 		if (bp == NULL)
6804 			bcopy(indirdep->ir_saveddata,
6805 			    indirdep->ir_savebp->b_data,
6806 			    indirdep->ir_savebp->b_bcount);
6807 		free(indirdep->ir_saveddata, M_INDIRDEP);
6808 		indirdep->ir_saveddata = NULL;
6809 	}
6810 	/*
6811 	 * When bp is NULL there is a full truncation pending.  We
6812 	 * must wait for this full truncation to be journaled before
6813 	 * we can release this freework because the disk pointers will
6814 	 * never be written as zero.
6815 	 */
6816 	if (bp == NULL)  {
6817 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6818 			handle_written_freework(freework);
6819 		else
6820 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6821 			   &freework->fw_list);
6822 		if (fwn == NULL) {
6823 			freework->fw_indir = (void *)0x0000deadbeef0000;
6824 			bp = indirdep->ir_savebp;
6825 			indirdep->ir_savebp = NULL;
6826 			free_indirdep(indirdep);
6827 			FREE_LOCK(ump);
6828 			brelse(bp);
6829 			ACQUIRE_LOCK(ump);
6830 		}
6831 	} else {
6832 		/* Complete when the real copy is written. */
6833 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6834 		BUF_UNLOCK(bp);
6835 	}
6836 }
6837 
6838 /*
6839  * Calculate the number of blocks we are going to release where datablocks
6840  * is the current total and length is the new file size.
6841  */
6842 static ufs2_daddr_t
6843 blkcount(fs, datablocks, length)
6844 	struct fs *fs;
6845 	ufs2_daddr_t datablocks;
6846 	off_t length;
6847 {
6848 	off_t totblks, numblks;
6849 
6850 	totblks = 0;
6851 	numblks = howmany(length, fs->fs_bsize);
6852 	if (numblks <= UFS_NDADDR) {
6853 		totblks = howmany(length, fs->fs_fsize);
6854 		goto out;
6855 	}
6856         totblks = blkstofrags(fs, numblks);
6857 	numblks -= UFS_NDADDR;
6858 	/*
6859 	 * Count all single, then double, then triple indirects required.
6860 	 * Subtracting one indirects worth of blocks for each pass
6861 	 * acknowledges one of each pointed to by the inode.
6862 	 */
6863 	for (;;) {
6864 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6865 		numblks -= NINDIR(fs);
6866 		if (numblks <= 0)
6867 			break;
6868 		numblks = howmany(numblks, NINDIR(fs));
6869 	}
6870 out:
6871 	totblks = fsbtodb(fs, totblks);
6872 	/*
6873 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6874 	 * references.  We will correct it later in handle_complete_freeblks()
6875 	 * when we know the real count.
6876 	 */
6877 	if (totblks > datablocks)
6878 		return (0);
6879 	return (datablocks - totblks);
6880 }
6881 
6882 /*
6883  * Handle freeblocks for journaled softupdate filesystems.
6884  *
6885  * Contrary to normal softupdates, we must preserve the block pointers in
6886  * indirects until their subordinates are free.  This is to avoid journaling
6887  * every block that is freed which may consume more space than the journal
6888  * itself.  The recovery program will see the free block journals at the
6889  * base of the truncated area and traverse them to reclaim space.  The
6890  * pointers in the inode may be cleared immediately after the journal
6891  * records are written because each direct and indirect pointer in the
6892  * inode is recorded in a journal.  This permits full truncation to proceed
6893  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6894  *
6895  * The algorithm is as follows:
6896  * 1) Traverse the in-memory state and create journal entries to release
6897  *    the relevant blocks and full indirect trees.
6898  * 2) Traverse the indirect block chain adding partial truncation freework
6899  *    records to indirects in the path to lastlbn.  The freework will
6900  *    prevent new allocation dependencies from being satisfied in this
6901  *    indirect until the truncation completes.
6902  * 3) Read and lock the inode block, performing an update with the new size
6903  *    and pointers.  This prevents truncated data from becoming valid on
6904  *    disk through step 4.
6905  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6906  *    eliminate journal work for those records that do not require it.
6907  * 5) Schedule the journal records to be written followed by the inode block.
6908  * 6) Allocate any necessary frags for the end of file.
6909  * 7) Zero any partially truncated blocks.
6910  *
6911  * From this truncation proceeds asynchronously using the freework and
6912  * indir_trunc machinery.  The file will not be extended again into a
6913  * partially truncated indirect block until all work is completed but
6914  * the normal dependency mechanism ensures that it is rolled back/forward
6915  * as appropriate.  Further truncation may occur without delay and is
6916  * serialized in indir_trunc().
6917  */
6918 void
6919 softdep_journal_freeblocks(ip, cred, length, flags)
6920 	struct inode *ip;	/* The inode whose length is to be reduced */
6921 	struct ucred *cred;
6922 	off_t length;		/* The new length for the file */
6923 	int flags;		/* IO_EXT and/or IO_NORMAL */
6924 {
6925 	struct freeblks *freeblks, *fbn;
6926 	struct worklist *wk, *wkn;
6927 	struct inodedep *inodedep;
6928 	struct jblkdep *jblkdep;
6929 	struct allocdirect *adp, *adpn;
6930 	struct ufsmount *ump;
6931 	struct fs *fs;
6932 	struct buf *bp;
6933 	struct vnode *vp;
6934 	struct mount *mp;
6935 	daddr_t dbn;
6936 	ufs2_daddr_t extblocks, datablocks;
6937 	ufs_lbn_t tmpval, lbn, lastlbn;
6938 	int frags, lastoff, iboff, allocblock, needj, error, i;
6939 
6940 	ump = ITOUMP(ip);
6941 	mp = UFSTOVFS(ump);
6942 	fs = ump->um_fs;
6943 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6944 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6945 	vp = ITOV(ip);
6946 	needj = 1;
6947 	iboff = -1;
6948 	allocblock = 0;
6949 	extblocks = 0;
6950 	datablocks = 0;
6951 	frags = 0;
6952 	freeblks = newfreeblks(mp, ip);
6953 	ACQUIRE_LOCK(ump);
6954 	/*
6955 	 * If we're truncating a removed file that will never be written
6956 	 * we don't need to journal the block frees.  The canceled journals
6957 	 * for the allocations will suffice.
6958 	 */
6959 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6960 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6961 	    length == 0)
6962 		needj = 0;
6963 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6964 	    ip->i_number, length, needj);
6965 	FREE_LOCK(ump);
6966 	/*
6967 	 * Calculate the lbn that we are truncating to.  This results in -1
6968 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6969 	 * to keep, not the first lbn we want to truncate.
6970 	 */
6971 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6972 	lastoff = blkoff(fs, length);
6973 	/*
6974 	 * Compute frags we are keeping in lastlbn.  0 means all.
6975 	 */
6976 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6977 		frags = fragroundup(fs, lastoff);
6978 		/* adp offset of last valid allocdirect. */
6979 		iboff = lastlbn;
6980 	} else if (lastlbn > 0)
6981 		iboff = UFS_NDADDR;
6982 	if (fs->fs_magic == FS_UFS2_MAGIC)
6983 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6984 	/*
6985 	 * Handle normal data blocks and indirects.  This section saves
6986 	 * values used after the inode update to complete frag and indirect
6987 	 * truncation.
6988 	 */
6989 	if ((flags & IO_NORMAL) != 0) {
6990 		/*
6991 		 * Handle truncation of whole direct and indirect blocks.
6992 		 */
6993 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6994 			setup_freedirect(freeblks, ip, i, needj);
6995 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6996 		    i < UFS_NIADDR;
6997 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6998 			/* Release a whole indirect tree. */
6999 			if (lbn > lastlbn) {
7000 				setup_freeindir(freeblks, ip, i, -lbn -i,
7001 				    needj);
7002 				continue;
7003 			}
7004 			iboff = i + UFS_NDADDR;
7005 			/*
7006 			 * Traverse partially truncated indirect tree.
7007 			 */
7008 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
7009 				setup_trunc_indir(freeblks, ip, -lbn - i,
7010 				    lastlbn, DIP(ip, i_ib[i]));
7011 		}
7012 		/*
7013 		 * Handle partial truncation to a frag boundary.
7014 		 */
7015 		if (frags) {
7016 			ufs2_daddr_t blkno;
7017 			long oldfrags;
7018 
7019 			oldfrags = blksize(fs, ip, lastlbn);
7020 			blkno = DIP(ip, i_db[lastlbn]);
7021 			if (blkno && oldfrags != frags) {
7022 				oldfrags -= frags;
7023 				oldfrags = numfrags(fs, oldfrags);
7024 				blkno += numfrags(fs, frags);
7025 				newfreework(ump, freeblks, NULL, lastlbn,
7026 				    blkno, oldfrags, 0, needj);
7027 				if (needj)
7028 					adjust_newfreework(freeblks,
7029 					    numfrags(fs, frags));
7030 			} else if (blkno == 0)
7031 				allocblock = 1;
7032 		}
7033 		/*
7034 		 * Add a journal record for partial truncate if we are
7035 		 * handling indirect blocks.  Non-indirects need no extra
7036 		 * journaling.
7037 		 */
7038 		if (length != 0 && lastlbn >= UFS_NDADDR) {
7039 			UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
7040 			newjtrunc(freeblks, length, 0);
7041 		}
7042 		ip->i_size = length;
7043 		DIP_SET(ip, i_size, ip->i_size);
7044 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7045 		datablocks = DIP(ip, i_blocks) - extblocks;
7046 		if (length != 0)
7047 			datablocks = blkcount(fs, datablocks, length);
7048 		freeblks->fb_len = length;
7049 	}
7050 	if ((flags & IO_EXT) != 0) {
7051 		for (i = 0; i < UFS_NXADDR; i++)
7052 			setup_freeext(freeblks, ip, i, needj);
7053 		ip->i_din2->di_extsize = 0;
7054 		datablocks += extblocks;
7055 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7056 	}
7057 #ifdef QUOTA
7058 	/* Reference the quotas in case the block count is wrong in the end. */
7059 	quotaref(vp, freeblks->fb_quota);
7060 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7061 #endif
7062 	freeblks->fb_chkcnt = -datablocks;
7063 	UFS_LOCK(ump);
7064 	fs->fs_pendingblocks += datablocks;
7065 	UFS_UNLOCK(ump);
7066 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7067 	/*
7068 	 * Handle truncation of incomplete alloc direct dependencies.  We
7069 	 * hold the inode block locked to prevent incomplete dependencies
7070 	 * from reaching the disk while we are eliminating those that
7071 	 * have been truncated.  This is a partially inlined ffs_update().
7072 	 */
7073 	ufs_itimes(vp);
7074 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
7075 	dbn = fsbtodb(fs, ino_to_fsba(fs, ip->i_number));
7076 	error = ffs_breadz(ump, ump->um_devvp, dbn, dbn, (int)fs->fs_bsize,
7077 	    NULL, NULL, 0, cred, 0, NULL, &bp);
7078 	if (error) {
7079 		softdep_error("softdep_journal_freeblocks", error);
7080 		return;
7081 	}
7082 	if (bp->b_bufsize == fs->fs_bsize)
7083 		bp->b_flags |= B_CLUSTEROK;
7084 	softdep_update_inodeblock(ip, bp, 0);
7085 	if (ump->um_fstype == UFS1) {
7086 		*((struct ufs1_dinode *)bp->b_data +
7087 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
7088 	} else {
7089 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7090 		*((struct ufs2_dinode *)bp->b_data +
7091 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
7092 	}
7093 	ACQUIRE_LOCK(ump);
7094 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7095 	if ((inodedep->id_state & IOSTARTED) != 0)
7096 		panic("softdep_setup_freeblocks: inode busy");
7097 	/*
7098 	 * Add the freeblks structure to the list of operations that
7099 	 * must await the zero'ed inode being written to disk. If we
7100 	 * still have a bitmap dependency (needj), then the inode
7101 	 * has never been written to disk, so we can process the
7102 	 * freeblks below once we have deleted the dependencies.
7103 	 */
7104 	if (needj)
7105 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7106 	else
7107 		freeblks->fb_state |= COMPLETE;
7108 	if ((flags & IO_NORMAL) != 0) {
7109 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
7110 			if (adp->ad_offset > iboff)
7111 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
7112 				    freeblks);
7113 			/*
7114 			 * Truncate the allocdirect.  We could eliminate
7115 			 * or modify journal records as well.
7116 			 */
7117 			else if (adp->ad_offset == iboff && frags)
7118 				adp->ad_newsize = frags;
7119 		}
7120 	}
7121 	if ((flags & IO_EXT) != 0)
7122 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7123 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7124 			    freeblks);
7125 	/*
7126 	 * Scan the bufwait list for newblock dependencies that will never
7127 	 * make it to disk.
7128 	 */
7129 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
7130 		if (wk->wk_type != D_ALLOCDIRECT)
7131 			continue;
7132 		adp = WK_ALLOCDIRECT(wk);
7133 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
7134 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
7135 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
7136 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
7137 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7138 		}
7139 	}
7140 	/*
7141 	 * Add journal work.
7142 	 */
7143 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
7144 		add_to_journal(&jblkdep->jb_list);
7145 	FREE_LOCK(ump);
7146 	bdwrite(bp);
7147 	/*
7148 	 * Truncate dependency structures beyond length.
7149 	 */
7150 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
7151 	/*
7152 	 * This is only set when we need to allocate a fragment because
7153 	 * none existed at the end of a frag-sized file.  It handles only
7154 	 * allocating a new, zero filled block.
7155 	 */
7156 	if (allocblock) {
7157 		ip->i_size = length - lastoff;
7158 		DIP_SET(ip, i_size, ip->i_size);
7159 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
7160 		if (error != 0) {
7161 			softdep_error("softdep_journal_freeblks", error);
7162 			return;
7163 		}
7164 		ip->i_size = length;
7165 		DIP_SET(ip, i_size, length);
7166 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
7167 		allocbuf(bp, frags);
7168 		ffs_update(vp, 0);
7169 		bawrite(bp);
7170 	} else if (lastoff != 0 && vp->v_type != VDIR) {
7171 		int size;
7172 
7173 		/*
7174 		 * Zero the end of a truncated frag or block.
7175 		 */
7176 		size = sblksize(fs, length, lastlbn);
7177 		error = bread(vp, lastlbn, size, cred, &bp);
7178 		if (error == 0) {
7179 			bzero((char *)bp->b_data + lastoff, size - lastoff);
7180 			bawrite(bp);
7181 		} else if (!ffs_fsfail_cleanup(ump, error)) {
7182 			softdep_error("softdep_journal_freeblks", error);
7183 			return;
7184 		}
7185 	}
7186 	ACQUIRE_LOCK(ump);
7187 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7188 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
7189 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
7190 	/*
7191 	 * We zero earlier truncations so they don't erroneously
7192 	 * update i_blocks.
7193 	 */
7194 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
7195 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
7196 			fbn->fb_len = 0;
7197 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
7198 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7199 		freeblks->fb_state |= INPROGRESS;
7200 	else
7201 		freeblks = NULL;
7202 	FREE_LOCK(ump);
7203 	if (freeblks)
7204 		handle_workitem_freeblocks(freeblks, 0);
7205 	trunc_pages(ip, length, extblocks, flags);
7206 
7207 }
7208 
7209 /*
7210  * Flush a JOP_SYNC to the journal.
7211  */
7212 void
7213 softdep_journal_fsync(ip)
7214 	struct inode *ip;
7215 {
7216 	struct jfsync *jfsync;
7217 	struct ufsmount *ump;
7218 
7219 	ump = ITOUMP(ip);
7220 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7221 	    ("softdep_journal_fsync called on non-softdep filesystem"));
7222 	if ((ip->i_flag & IN_TRUNCATED) == 0)
7223 		return;
7224 	ip->i_flag &= ~IN_TRUNCATED;
7225 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
7226 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
7227 	jfsync->jfs_size = ip->i_size;
7228 	jfsync->jfs_ino = ip->i_number;
7229 	ACQUIRE_LOCK(ump);
7230 	add_to_journal(&jfsync->jfs_list);
7231 	jwait(&jfsync->jfs_list, MNT_WAIT);
7232 	FREE_LOCK(ump);
7233 }
7234 
7235 /*
7236  * Block de-allocation dependencies.
7237  *
7238  * When blocks are de-allocated, the on-disk pointers must be nullified before
7239  * the blocks are made available for use by other files.  (The true
7240  * requirement is that old pointers must be nullified before new on-disk
7241  * pointers are set.  We chose this slightly more stringent requirement to
7242  * reduce complexity.) Our implementation handles this dependency by updating
7243  * the inode (or indirect block) appropriately but delaying the actual block
7244  * de-allocation (i.e., freemap and free space count manipulation) until
7245  * after the updated versions reach stable storage.  After the disk is
7246  * updated, the blocks can be safely de-allocated whenever it is convenient.
7247  * This implementation handles only the common case of reducing a file's
7248  * length to zero. Other cases are handled by the conventional synchronous
7249  * write approach.
7250  *
7251  * The ffs implementation with which we worked double-checks
7252  * the state of the block pointers and file size as it reduces
7253  * a file's length.  Some of this code is replicated here in our
7254  * soft updates implementation.  The freeblks->fb_chkcnt field is
7255  * used to transfer a part of this information to the procedure
7256  * that eventually de-allocates the blocks.
7257  *
7258  * This routine should be called from the routine that shortens
7259  * a file's length, before the inode's size or block pointers
7260  * are modified. It will save the block pointer information for
7261  * later release and zero the inode so that the calling routine
7262  * can release it.
7263  */
7264 void
7265 softdep_setup_freeblocks(ip, length, flags)
7266 	struct inode *ip;	/* The inode whose length is to be reduced */
7267 	off_t length;		/* The new length for the file */
7268 	int flags;		/* IO_EXT and/or IO_NORMAL */
7269 {
7270 	struct ufs1_dinode *dp1;
7271 	struct ufs2_dinode *dp2;
7272 	struct freeblks *freeblks;
7273 	struct inodedep *inodedep;
7274 	struct allocdirect *adp;
7275 	struct ufsmount *ump;
7276 	struct buf *bp;
7277 	struct fs *fs;
7278 	ufs2_daddr_t extblocks, datablocks;
7279 	struct mount *mp;
7280 	int i, delay, error;
7281 	ufs_lbn_t tmpval;
7282 	ufs_lbn_t lbn;
7283 
7284 	ump = ITOUMP(ip);
7285 	mp = UFSTOVFS(ump);
7286 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
7287 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
7288 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
7289 	    ip->i_number, length);
7290 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
7291 	fs = ump->um_fs;
7292 	if ((error = bread(ump->um_devvp,
7293 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
7294 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
7295 		if (!ffs_fsfail_cleanup(ump, error))
7296 			softdep_error("softdep_setup_freeblocks", error);
7297 		return;
7298 	}
7299 	freeblks = newfreeblks(mp, ip);
7300 	extblocks = 0;
7301 	datablocks = 0;
7302 	if (fs->fs_magic == FS_UFS2_MAGIC)
7303 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
7304 	if ((flags & IO_NORMAL) != 0) {
7305 		for (i = 0; i < UFS_NDADDR; i++)
7306 			setup_freedirect(freeblks, ip, i, 0);
7307 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
7308 		    i < UFS_NIADDR;
7309 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
7310 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
7311 		ip->i_size = 0;
7312 		DIP_SET(ip, i_size, 0);
7313 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7314 		datablocks = DIP(ip, i_blocks) - extblocks;
7315 	}
7316 	if ((flags & IO_EXT) != 0) {
7317 		for (i = 0; i < UFS_NXADDR; i++)
7318 			setup_freeext(freeblks, ip, i, 0);
7319 		ip->i_din2->di_extsize = 0;
7320 		datablocks += extblocks;
7321 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7322 	}
7323 #ifdef QUOTA
7324 	/* Reference the quotas in case the block count is wrong in the end. */
7325 	quotaref(ITOV(ip), freeblks->fb_quota);
7326 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7327 #endif
7328 	freeblks->fb_chkcnt = -datablocks;
7329 	UFS_LOCK(ump);
7330 	fs->fs_pendingblocks += datablocks;
7331 	UFS_UNLOCK(ump);
7332 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7333 	/*
7334 	 * Push the zero'ed inode to its disk buffer so that we are free
7335 	 * to delete its dependencies below. Once the dependencies are gone
7336 	 * the buffer can be safely released.
7337 	 */
7338 	if (ump->um_fstype == UFS1) {
7339 		dp1 = ((struct ufs1_dinode *)bp->b_data +
7340 		    ino_to_fsbo(fs, ip->i_number));
7341 		ip->i_din1->di_freelink = dp1->di_freelink;
7342 		*dp1 = *ip->i_din1;
7343 	} else {
7344 		dp2 = ((struct ufs2_dinode *)bp->b_data +
7345 		    ino_to_fsbo(fs, ip->i_number));
7346 		ip->i_din2->di_freelink = dp2->di_freelink;
7347 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7348 		*dp2 = *ip->i_din2;
7349 	}
7350 	/*
7351 	 * Find and eliminate any inode dependencies.
7352 	 */
7353 	ACQUIRE_LOCK(ump);
7354 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7355 	if ((inodedep->id_state & IOSTARTED) != 0)
7356 		panic("softdep_setup_freeblocks: inode busy");
7357 	/*
7358 	 * Add the freeblks structure to the list of operations that
7359 	 * must await the zero'ed inode being written to disk. If we
7360 	 * still have a bitmap dependency (delay == 0), then the inode
7361 	 * has never been written to disk, so we can process the
7362 	 * freeblks below once we have deleted the dependencies.
7363 	 */
7364 	delay = (inodedep->id_state & DEPCOMPLETE);
7365 	if (delay)
7366 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7367 	else
7368 		freeblks->fb_state |= COMPLETE;
7369 	/*
7370 	 * Because the file length has been truncated to zero, any
7371 	 * pending block allocation dependency structures associated
7372 	 * with this inode are obsolete and can simply be de-allocated.
7373 	 * We must first merge the two dependency lists to get rid of
7374 	 * any duplicate freefrag structures, then purge the merged list.
7375 	 * If we still have a bitmap dependency, then the inode has never
7376 	 * been written to disk, so we can free any fragments without delay.
7377 	 */
7378 	if (flags & IO_NORMAL) {
7379 		merge_inode_lists(&inodedep->id_newinoupdt,
7380 		    &inodedep->id_inoupdt);
7381 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7382 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7383 			    freeblks);
7384 	}
7385 	if (flags & IO_EXT) {
7386 		merge_inode_lists(&inodedep->id_newextupdt,
7387 		    &inodedep->id_extupdt);
7388 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7389 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7390 			    freeblks);
7391 	}
7392 	FREE_LOCK(ump);
7393 	bdwrite(bp);
7394 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7395 	ACQUIRE_LOCK(ump);
7396 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7397 		(void) free_inodedep(inodedep);
7398 	freeblks->fb_state |= DEPCOMPLETE;
7399 	/*
7400 	 * If the inode with zeroed block pointers is now on disk
7401 	 * we can start freeing blocks.
7402 	 */
7403 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7404 		freeblks->fb_state |= INPROGRESS;
7405 	else
7406 		freeblks = NULL;
7407 	FREE_LOCK(ump);
7408 	if (freeblks)
7409 		handle_workitem_freeblocks(freeblks, 0);
7410 	trunc_pages(ip, length, extblocks, flags);
7411 }
7412 
7413 /*
7414  * Eliminate pages from the page cache that back parts of this inode and
7415  * adjust the vnode pager's idea of our size.  This prevents stale data
7416  * from hanging around in the page cache.
7417  */
7418 static void
7419 trunc_pages(ip, length, extblocks, flags)
7420 	struct inode *ip;
7421 	off_t length;
7422 	ufs2_daddr_t extblocks;
7423 	int flags;
7424 {
7425 	struct vnode *vp;
7426 	struct fs *fs;
7427 	ufs_lbn_t lbn;
7428 	off_t end, extend;
7429 
7430 	vp = ITOV(ip);
7431 	fs = ITOFS(ip);
7432 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7433 	if ((flags & IO_EXT) != 0)
7434 		vn_pages_remove(vp, extend, 0);
7435 	if ((flags & IO_NORMAL) == 0)
7436 		return;
7437 	BO_LOCK(&vp->v_bufobj);
7438 	drain_output(vp);
7439 	BO_UNLOCK(&vp->v_bufobj);
7440 	/*
7441 	 * The vnode pager eliminates file pages we eliminate indirects
7442 	 * below.
7443 	 */
7444 	vnode_pager_setsize(vp, length);
7445 	/*
7446 	 * Calculate the end based on the last indirect we want to keep.  If
7447 	 * the block extends into indirects we can just use the negative of
7448 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7449 	 * be careful not to remove those, if they exist.  double and triple
7450 	 * indirect lbns do not overlap with others so it is not important
7451 	 * to verify how many levels are required.
7452 	 */
7453 	lbn = lblkno(fs, length);
7454 	if (lbn >= UFS_NDADDR) {
7455 		/* Calculate the virtual lbn of the triple indirect. */
7456 		lbn = -lbn - (UFS_NIADDR - 1);
7457 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7458 	} else
7459 		end = extend;
7460 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7461 }
7462 
7463 /*
7464  * See if the buf bp is in the range eliminated by truncation.
7465  */
7466 static int
7467 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7468 	struct buf *bp;
7469 	int *blkoffp;
7470 	ufs_lbn_t lastlbn;
7471 	int lastoff;
7472 	int flags;
7473 {
7474 	ufs_lbn_t lbn;
7475 
7476 	*blkoffp = 0;
7477 	/* Only match ext/normal blocks as appropriate. */
7478 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7479 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7480 		return (0);
7481 	/* ALTDATA is always a full truncation. */
7482 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7483 		return (1);
7484 	/* -1 is full truncation. */
7485 	if (lastlbn == -1)
7486 		return (1);
7487 	/*
7488 	 * If this is a partial truncate we only want those
7489 	 * blocks and indirect blocks that cover the range
7490 	 * we're after.
7491 	 */
7492 	lbn = bp->b_lblkno;
7493 	if (lbn < 0)
7494 		lbn = -(lbn + lbn_level(lbn));
7495 	if (lbn < lastlbn)
7496 		return (0);
7497 	/* Here we only truncate lblkno if it's partial. */
7498 	if (lbn == lastlbn) {
7499 		if (lastoff == 0)
7500 			return (0);
7501 		*blkoffp = lastoff;
7502 	}
7503 	return (1);
7504 }
7505 
7506 /*
7507  * Eliminate any dependencies that exist in memory beyond lblkno:off
7508  */
7509 static void
7510 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7511 	struct inode *ip;
7512 	struct freeblks *freeblks;
7513 	ufs_lbn_t lastlbn;
7514 	int lastoff;
7515 	int flags;
7516 {
7517 	struct bufobj *bo;
7518 	struct vnode *vp;
7519 	struct buf *bp;
7520 	int blkoff;
7521 
7522 	/*
7523 	 * We must wait for any I/O in progress to finish so that
7524 	 * all potential buffers on the dirty list will be visible.
7525 	 * Once they are all there, walk the list and get rid of
7526 	 * any dependencies.
7527 	 */
7528 	vp = ITOV(ip);
7529 	bo = &vp->v_bufobj;
7530 	BO_LOCK(bo);
7531 	drain_output(vp);
7532 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7533 		bp->b_vflags &= ~BV_SCANNED;
7534 restart:
7535 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7536 		if (bp->b_vflags & BV_SCANNED)
7537 			continue;
7538 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7539 			bp->b_vflags |= BV_SCANNED;
7540 			continue;
7541 		}
7542 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7543 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7544 			goto restart;
7545 		BO_UNLOCK(bo);
7546 		if (deallocate_dependencies(bp, freeblks, blkoff))
7547 			bqrelse(bp);
7548 		else
7549 			brelse(bp);
7550 		BO_LOCK(bo);
7551 		goto restart;
7552 	}
7553 	/*
7554 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7555 	 */
7556 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7557 		bp->b_vflags &= ~BV_SCANNED;
7558 cleanrestart:
7559 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7560 		if (bp->b_vflags & BV_SCANNED)
7561 			continue;
7562 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7563 			bp->b_vflags |= BV_SCANNED;
7564 			continue;
7565 		}
7566 		if (BUF_LOCK(bp,
7567 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7568 		    BO_LOCKPTR(bo)) == ENOLCK) {
7569 			BO_LOCK(bo);
7570 			goto cleanrestart;
7571 		}
7572 		BO_LOCK(bo);
7573 		bp->b_vflags |= BV_SCANNED;
7574 		BO_UNLOCK(bo);
7575 		bremfree(bp);
7576 		if (blkoff != 0) {
7577 			allocbuf(bp, blkoff);
7578 			bqrelse(bp);
7579 		} else {
7580 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7581 			brelse(bp);
7582 		}
7583 		BO_LOCK(bo);
7584 		goto cleanrestart;
7585 	}
7586 	drain_output(vp);
7587 	BO_UNLOCK(bo);
7588 }
7589 
7590 static int
7591 cancel_pagedep(pagedep, freeblks, blkoff)
7592 	struct pagedep *pagedep;
7593 	struct freeblks *freeblks;
7594 	int blkoff;
7595 {
7596 	struct jremref *jremref;
7597 	struct jmvref *jmvref;
7598 	struct dirrem *dirrem, *tmp;
7599 	int i;
7600 
7601 	/*
7602 	 * Copy any directory remove dependencies to the list
7603 	 * to be processed after the freeblks proceeds.  If
7604 	 * directory entry never made it to disk they
7605 	 * can be dumped directly onto the work list.
7606 	 */
7607 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7608 		/* Skip this directory removal if it is intended to remain. */
7609 		if (dirrem->dm_offset < blkoff)
7610 			continue;
7611 		/*
7612 		 * If there are any dirrems we wait for the journal write
7613 		 * to complete and then restart the buf scan as the lock
7614 		 * has been dropped.
7615 		 */
7616 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7617 			jwait(&jremref->jr_list, MNT_WAIT);
7618 			return (ERESTART);
7619 		}
7620 		LIST_REMOVE(dirrem, dm_next);
7621 		dirrem->dm_dirinum = pagedep->pd_ino;
7622 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7623 	}
7624 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7625 		jwait(&jmvref->jm_list, MNT_WAIT);
7626 		return (ERESTART);
7627 	}
7628 	/*
7629 	 * When we're partially truncating a pagedep we just want to flush
7630 	 * journal entries and return.  There can not be any adds in the
7631 	 * truncated portion of the directory and newblk must remain if
7632 	 * part of the block remains.
7633 	 */
7634 	if (blkoff != 0) {
7635 		struct diradd *dap;
7636 
7637 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7638 			if (dap->da_offset > blkoff)
7639 				panic("cancel_pagedep: diradd %p off %d > %d",
7640 				    dap, dap->da_offset, blkoff);
7641 		for (i = 0; i < DAHASHSZ; i++)
7642 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7643 				if (dap->da_offset > blkoff)
7644 					panic("cancel_pagedep: diradd %p off %d > %d",
7645 					    dap, dap->da_offset, blkoff);
7646 		return (0);
7647 	}
7648 	/*
7649 	 * There should be no directory add dependencies present
7650 	 * as the directory could not be truncated until all
7651 	 * children were removed.
7652 	 */
7653 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7654 	    ("deallocate_dependencies: pendinghd != NULL"));
7655 	for (i = 0; i < DAHASHSZ; i++)
7656 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7657 		    ("deallocate_dependencies: diraddhd != NULL"));
7658 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7659 		free_newdirblk(pagedep->pd_newdirblk);
7660 	if (free_pagedep(pagedep) == 0)
7661 		panic("Failed to free pagedep %p", pagedep);
7662 	return (0);
7663 }
7664 
7665 /*
7666  * Reclaim any dependency structures from a buffer that is about to
7667  * be reallocated to a new vnode. The buffer must be locked, thus,
7668  * no I/O completion operations can occur while we are manipulating
7669  * its associated dependencies. The mutex is held so that other I/O's
7670  * associated with related dependencies do not occur.
7671  */
7672 static int
7673 deallocate_dependencies(bp, freeblks, off)
7674 	struct buf *bp;
7675 	struct freeblks *freeblks;
7676 	int off;
7677 {
7678 	struct indirdep *indirdep;
7679 	struct pagedep *pagedep;
7680 	struct worklist *wk, *wkn;
7681 	struct ufsmount *ump;
7682 
7683 	ump = softdep_bp_to_mp(bp);
7684 	if (ump == NULL)
7685 		goto done;
7686 	ACQUIRE_LOCK(ump);
7687 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7688 		switch (wk->wk_type) {
7689 		case D_INDIRDEP:
7690 			indirdep = WK_INDIRDEP(wk);
7691 			if (bp->b_lblkno >= 0 ||
7692 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7693 				panic("deallocate_dependencies: not indir");
7694 			cancel_indirdep(indirdep, bp, freeblks);
7695 			continue;
7696 
7697 		case D_PAGEDEP:
7698 			pagedep = WK_PAGEDEP(wk);
7699 			if (cancel_pagedep(pagedep, freeblks, off)) {
7700 				FREE_LOCK(ump);
7701 				return (ERESTART);
7702 			}
7703 			continue;
7704 
7705 		case D_ALLOCINDIR:
7706 			/*
7707 			 * Simply remove the allocindir, we'll find it via
7708 			 * the indirdep where we can clear pointers if
7709 			 * needed.
7710 			 */
7711 			WORKLIST_REMOVE(wk);
7712 			continue;
7713 
7714 		case D_FREEWORK:
7715 			/*
7716 			 * A truncation is waiting for the zero'd pointers
7717 			 * to be written.  It can be freed when the freeblks
7718 			 * is journaled.
7719 			 */
7720 			WORKLIST_REMOVE(wk);
7721 			wk->wk_state |= ONDEPLIST;
7722 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7723 			break;
7724 
7725 		case D_ALLOCDIRECT:
7726 			if (off != 0)
7727 				continue;
7728 			/* FALLTHROUGH */
7729 		default:
7730 			panic("deallocate_dependencies: Unexpected type %s",
7731 			    TYPENAME(wk->wk_type));
7732 			/* NOTREACHED */
7733 		}
7734 	}
7735 	FREE_LOCK(ump);
7736 done:
7737 	/*
7738 	 * Don't throw away this buf, we were partially truncating and
7739 	 * some deps may always remain.
7740 	 */
7741 	if (off) {
7742 		allocbuf(bp, off);
7743 		bp->b_vflags |= BV_SCANNED;
7744 		return (EBUSY);
7745 	}
7746 	bp->b_flags |= B_INVAL | B_NOCACHE;
7747 
7748 	return (0);
7749 }
7750 
7751 /*
7752  * An allocdirect is being canceled due to a truncate.  We must make sure
7753  * the journal entry is released in concert with the blkfree that releases
7754  * the storage.  Completed journal entries must not be released until the
7755  * space is no longer pointed to by the inode or in the bitmap.
7756  */
7757 static void
7758 cancel_allocdirect(adphead, adp, freeblks)
7759 	struct allocdirectlst *adphead;
7760 	struct allocdirect *adp;
7761 	struct freeblks *freeblks;
7762 {
7763 	struct freework *freework;
7764 	struct newblk *newblk;
7765 	struct worklist *wk;
7766 
7767 	TAILQ_REMOVE(adphead, adp, ad_next);
7768 	newblk = (struct newblk *)adp;
7769 	freework = NULL;
7770 	/*
7771 	 * Find the correct freework structure.
7772 	 */
7773 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7774 		if (wk->wk_type != D_FREEWORK)
7775 			continue;
7776 		freework = WK_FREEWORK(wk);
7777 		if (freework->fw_blkno == newblk->nb_newblkno)
7778 			break;
7779 	}
7780 	if (freework == NULL)
7781 		panic("cancel_allocdirect: Freework not found");
7782 	/*
7783 	 * If a newblk exists at all we still have the journal entry that
7784 	 * initiated the allocation so we do not need to journal the free.
7785 	 */
7786 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7787 	/*
7788 	 * If the journal hasn't been written the jnewblk must be passed
7789 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7790 	 * this by linking the journal dependency into the freework to be
7791 	 * freed when freework_freeblock() is called.  If the journal has
7792 	 * been written we can simply reclaim the journal space when the
7793 	 * freeblks work is complete.
7794 	 */
7795 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7796 	    &freeblks->fb_jwork);
7797 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7798 }
7799 
7800 /*
7801  * Cancel a new block allocation.  May be an indirect or direct block.  We
7802  * remove it from various lists and return any journal record that needs to
7803  * be resolved by the caller.
7804  *
7805  * A special consideration is made for indirects which were never pointed
7806  * at on disk and will never be found once this block is released.
7807  */
7808 static struct jnewblk *
7809 cancel_newblk(newblk, wk, wkhd)
7810 	struct newblk *newblk;
7811 	struct worklist *wk;
7812 	struct workhead *wkhd;
7813 {
7814 	struct jnewblk *jnewblk;
7815 
7816 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7817 
7818 	newblk->nb_state |= GOINGAWAY;
7819 	/*
7820 	 * Previously we traversed the completedhd on each indirdep
7821 	 * attached to this newblk to cancel them and gather journal
7822 	 * work.  Since we need only the oldest journal segment and
7823 	 * the lowest point on the tree will always have the oldest
7824 	 * journal segment we are free to release the segments
7825 	 * of any subordinates and may leave the indirdep list to
7826 	 * indirdep_complete() when this newblk is freed.
7827 	 */
7828 	if (newblk->nb_state & ONDEPLIST) {
7829 		newblk->nb_state &= ~ONDEPLIST;
7830 		LIST_REMOVE(newblk, nb_deps);
7831 	}
7832 	if (newblk->nb_state & ONWORKLIST)
7833 		WORKLIST_REMOVE(&newblk->nb_list);
7834 	/*
7835 	 * If the journal entry hasn't been written we save a pointer to
7836 	 * the dependency that frees it until it is written or the
7837 	 * superseding operation completes.
7838 	 */
7839 	jnewblk = newblk->nb_jnewblk;
7840 	if (jnewblk != NULL && wk != NULL) {
7841 		newblk->nb_jnewblk = NULL;
7842 		jnewblk->jn_dep = wk;
7843 	}
7844 	if (!LIST_EMPTY(&newblk->nb_jwork))
7845 		jwork_move(wkhd, &newblk->nb_jwork);
7846 	/*
7847 	 * When truncating we must free the newdirblk early to remove
7848 	 * the pagedep from the hash before returning.
7849 	 */
7850 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7851 		free_newdirblk(WK_NEWDIRBLK(wk));
7852 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7853 		panic("cancel_newblk: extra newdirblk");
7854 
7855 	return (jnewblk);
7856 }
7857 
7858 /*
7859  * Schedule the freefrag associated with a newblk to be released once
7860  * the pointers are written and the previous block is no longer needed.
7861  */
7862 static void
7863 newblk_freefrag(newblk)
7864 	struct newblk *newblk;
7865 {
7866 	struct freefrag *freefrag;
7867 
7868 	if (newblk->nb_freefrag == NULL)
7869 		return;
7870 	freefrag = newblk->nb_freefrag;
7871 	newblk->nb_freefrag = NULL;
7872 	freefrag->ff_state |= COMPLETE;
7873 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7874 		add_to_worklist(&freefrag->ff_list, 0);
7875 }
7876 
7877 /*
7878  * Free a newblk. Generate a new freefrag work request if appropriate.
7879  * This must be called after the inode pointer and any direct block pointers
7880  * are valid or fully removed via truncate or frag extension.
7881  */
7882 static void
7883 free_newblk(newblk)
7884 	struct newblk *newblk;
7885 {
7886 	struct indirdep *indirdep;
7887 	struct worklist *wk;
7888 
7889 	KASSERT(newblk->nb_jnewblk == NULL,
7890 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7891 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7892 	    ("free_newblk: unclaimed newblk"));
7893 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7894 	newblk_freefrag(newblk);
7895 	if (newblk->nb_state & ONDEPLIST)
7896 		LIST_REMOVE(newblk, nb_deps);
7897 	if (newblk->nb_state & ONWORKLIST)
7898 		WORKLIST_REMOVE(&newblk->nb_list);
7899 	LIST_REMOVE(newblk, nb_hash);
7900 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7901 		free_newdirblk(WK_NEWDIRBLK(wk));
7902 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7903 		panic("free_newblk: extra newdirblk");
7904 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7905 		indirdep_complete(indirdep);
7906 	handle_jwork(&newblk->nb_jwork);
7907 	WORKITEM_FREE(newblk, D_NEWBLK);
7908 }
7909 
7910 /*
7911  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7912  */
7913 static void
7914 free_newdirblk(newdirblk)
7915 	struct newdirblk *newdirblk;
7916 {
7917 	struct pagedep *pagedep;
7918 	struct diradd *dap;
7919 	struct worklist *wk;
7920 
7921 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7922 	WORKLIST_REMOVE(&newdirblk->db_list);
7923 	/*
7924 	 * If the pagedep is still linked onto the directory buffer
7925 	 * dependency chain, then some of the entries on the
7926 	 * pd_pendinghd list may not be committed to disk yet. In
7927 	 * this case, we will simply clear the NEWBLOCK flag and
7928 	 * let the pd_pendinghd list be processed when the pagedep
7929 	 * is next written. If the pagedep is no longer on the buffer
7930 	 * dependency chain, then all the entries on the pd_pending
7931 	 * list are committed to disk and we can free them here.
7932 	 */
7933 	pagedep = newdirblk->db_pagedep;
7934 	pagedep->pd_state &= ~NEWBLOCK;
7935 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7936 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7937 			free_diradd(dap, NULL);
7938 		/*
7939 		 * If no dependencies remain, the pagedep will be freed.
7940 		 */
7941 		free_pagedep(pagedep);
7942 	}
7943 	/* Should only ever be one item in the list. */
7944 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7945 		WORKLIST_REMOVE(wk);
7946 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7947 	}
7948 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7949 }
7950 
7951 /*
7952  * Prepare an inode to be freed. The actual free operation is not
7953  * done until the zero'ed inode has been written to disk.
7954  */
7955 void
7956 softdep_freefile(pvp, ino, mode)
7957 	struct vnode *pvp;
7958 	ino_t ino;
7959 	int mode;
7960 {
7961 	struct inode *ip = VTOI(pvp);
7962 	struct inodedep *inodedep;
7963 	struct freefile *freefile;
7964 	struct freeblks *freeblks;
7965 	struct ufsmount *ump;
7966 
7967 	ump = ITOUMP(ip);
7968 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7969 	    ("softdep_freefile called on non-softdep filesystem"));
7970 	/*
7971 	 * This sets up the inode de-allocation dependency.
7972 	 */
7973 	freefile = malloc(sizeof(struct freefile),
7974 		M_FREEFILE, M_SOFTDEP_FLAGS);
7975 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7976 	freefile->fx_mode = mode;
7977 	freefile->fx_oldinum = ino;
7978 	freefile->fx_devvp = ump->um_devvp;
7979 	LIST_INIT(&freefile->fx_jwork);
7980 	UFS_LOCK(ump);
7981 	ump->um_fs->fs_pendinginodes += 1;
7982 	UFS_UNLOCK(ump);
7983 
7984 	/*
7985 	 * If the inodedep does not exist, then the zero'ed inode has
7986 	 * been written to disk. If the allocated inode has never been
7987 	 * written to disk, then the on-disk inode is zero'ed. In either
7988 	 * case we can free the file immediately.  If the journal was
7989 	 * canceled before being written the inode will never make it to
7990 	 * disk and we must send the canceled journal entrys to
7991 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7992 	 * Any blocks waiting on the inode to write can be safely freed
7993 	 * here as it will never been written.
7994 	 */
7995 	ACQUIRE_LOCK(ump);
7996 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7997 	if (inodedep) {
7998 		/*
7999 		 * Clear out freeblks that no longer need to reference
8000 		 * this inode.
8001 		 */
8002 		while ((freeblks =
8003 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
8004 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
8005 			    fb_next);
8006 			freeblks->fb_state &= ~ONDEPLIST;
8007 		}
8008 		/*
8009 		 * Remove this inode from the unlinked list.
8010 		 */
8011 		if (inodedep->id_state & UNLINKED) {
8012 			/*
8013 			 * Save the journal work to be freed with the bitmap
8014 			 * before we clear UNLINKED.  Otherwise it can be lost
8015 			 * if the inode block is written.
8016 			 */
8017 			handle_bufwait(inodedep, &freefile->fx_jwork);
8018 			clear_unlinked_inodedep(inodedep);
8019 			/*
8020 			 * Re-acquire inodedep as we've dropped the
8021 			 * per-filesystem lock in clear_unlinked_inodedep().
8022 			 */
8023 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
8024 		}
8025 	}
8026 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
8027 		FREE_LOCK(ump);
8028 		handle_workitem_freefile(freefile);
8029 		return;
8030 	}
8031 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
8032 		inodedep->id_state |= GOINGAWAY;
8033 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
8034 	FREE_LOCK(ump);
8035 	if (ip->i_number == ino)
8036 		UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
8037 }
8038 
8039 /*
8040  * Check to see if an inode has never been written to disk. If
8041  * so free the inodedep and return success, otherwise return failure.
8042  *
8043  * If we still have a bitmap dependency, then the inode has never
8044  * been written to disk. Drop the dependency as it is no longer
8045  * necessary since the inode is being deallocated. We set the
8046  * ALLCOMPLETE flags since the bitmap now properly shows that the
8047  * inode is not allocated. Even if the inode is actively being
8048  * written, it has been rolled back to its zero'ed state, so we
8049  * are ensured that a zero inode is what is on the disk. For short
8050  * lived files, this change will usually result in removing all the
8051  * dependencies from the inode so that it can be freed immediately.
8052  */
8053 static int
8054 check_inode_unwritten(inodedep)
8055 	struct inodedep *inodedep;
8056 {
8057 
8058 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8059 
8060 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
8061 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
8062 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
8063 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
8064 	    !LIST_EMPTY(&inodedep->id_inowait) ||
8065 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
8066 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
8067 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
8068 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
8069 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
8070 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
8071 	    inodedep->id_mkdiradd != NULL ||
8072 	    inodedep->id_nlinkdelta != 0)
8073 		return (0);
8074 	/*
8075 	 * Another process might be in initiate_write_inodeblock_ufs[12]
8076 	 * trying to allocate memory without holding "Softdep Lock".
8077 	 */
8078 	if ((inodedep->id_state & IOSTARTED) != 0 &&
8079 	    inodedep->id_savedino1 == NULL)
8080 		return (0);
8081 
8082 	if (inodedep->id_state & ONDEPLIST)
8083 		LIST_REMOVE(inodedep, id_deps);
8084 	inodedep->id_state &= ~ONDEPLIST;
8085 	inodedep->id_state |= ALLCOMPLETE;
8086 	inodedep->id_bmsafemap = NULL;
8087 	if (inodedep->id_state & ONWORKLIST)
8088 		WORKLIST_REMOVE(&inodedep->id_list);
8089 	if (inodedep->id_savedino1 != NULL) {
8090 		free(inodedep->id_savedino1, M_SAVEDINO);
8091 		inodedep->id_savedino1 = NULL;
8092 	}
8093 	if (free_inodedep(inodedep) == 0)
8094 		panic("check_inode_unwritten: busy inode");
8095 	return (1);
8096 }
8097 
8098 static int
8099 check_inodedep_free(inodedep)
8100 	struct inodedep *inodedep;
8101 {
8102 
8103 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8104 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
8105 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
8106 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
8107 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
8108 	    !LIST_EMPTY(&inodedep->id_inowait) ||
8109 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
8110 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
8111 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
8112 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
8113 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
8114 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
8115 	    inodedep->id_mkdiradd != NULL ||
8116 	    inodedep->id_nlinkdelta != 0 ||
8117 	    inodedep->id_savedino1 != NULL)
8118 		return (0);
8119 	return (1);
8120 }
8121 
8122 /*
8123  * Try to free an inodedep structure. Return 1 if it could be freed.
8124  */
8125 static int
8126 free_inodedep(inodedep)
8127 	struct inodedep *inodedep;
8128 {
8129 
8130 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8131 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
8132 	    !check_inodedep_free(inodedep))
8133 		return (0);
8134 	if (inodedep->id_state & ONDEPLIST)
8135 		LIST_REMOVE(inodedep, id_deps);
8136 	LIST_REMOVE(inodedep, id_hash);
8137 	WORKITEM_FREE(inodedep, D_INODEDEP);
8138 	return (1);
8139 }
8140 
8141 /*
8142  * Free the block referenced by a freework structure.  The parent freeblks
8143  * structure is released and completed when the final cg bitmap reaches
8144  * the disk.  This routine may be freeing a jnewblk which never made it to
8145  * disk in which case we do not have to wait as the operation is undone
8146  * in memory immediately.
8147  */
8148 static void
8149 freework_freeblock(freework, key)
8150 	struct freework *freework;
8151 	u_long key;
8152 {
8153 	struct freeblks *freeblks;
8154 	struct jnewblk *jnewblk;
8155 	struct ufsmount *ump;
8156 	struct workhead wkhd;
8157 	struct fs *fs;
8158 	int bsize;
8159 	int needj;
8160 
8161 	ump = VFSTOUFS(freework->fw_list.wk_mp);
8162 	LOCK_OWNED(ump);
8163 	/*
8164 	 * Handle partial truncate separately.
8165 	 */
8166 	if (freework->fw_indir) {
8167 		complete_trunc_indir(freework);
8168 		return;
8169 	}
8170 	freeblks = freework->fw_freeblks;
8171 	fs = ump->um_fs;
8172 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
8173 	bsize = lfragtosize(fs, freework->fw_frags);
8174 	LIST_INIT(&wkhd);
8175 	/*
8176 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
8177 	 * on the indirblk hashtable and prevents premature freeing.
8178 	 */
8179 	freework->fw_state |= DEPCOMPLETE;
8180 	/*
8181 	 * SUJ needs to wait for the segment referencing freed indirect
8182 	 * blocks to expire so that we know the checker will not confuse
8183 	 * a re-allocated indirect block with its old contents.
8184 	 */
8185 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
8186 		indirblk_insert(freework);
8187 	/*
8188 	 * If we are canceling an existing jnewblk pass it to the free
8189 	 * routine, otherwise pass the freeblk which will ultimately
8190 	 * release the freeblks.  If we're not journaling, we can just
8191 	 * free the freeblks immediately.
8192 	 */
8193 	jnewblk = freework->fw_jnewblk;
8194 	if (jnewblk != NULL) {
8195 		cancel_jnewblk(jnewblk, &wkhd);
8196 		needj = 0;
8197 	} else if (needj) {
8198 		freework->fw_state |= DELAYEDFREE;
8199 		freeblks->fb_cgwait++;
8200 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
8201 	}
8202 	FREE_LOCK(ump);
8203 	freeblks_free(ump, freeblks, btodb(bsize));
8204 	CTR4(KTR_SUJ,
8205 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
8206 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
8207 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
8208 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
8209 	ACQUIRE_LOCK(ump);
8210 	/*
8211 	 * The jnewblk will be discarded and the bits in the map never
8212 	 * made it to disk.  We can immediately free the freeblk.
8213 	 */
8214 	if (needj == 0)
8215 		handle_written_freework(freework);
8216 }
8217 
8218 /*
8219  * We enqueue freework items that need processing back on the freeblks and
8220  * add the freeblks to the worklist.  This makes it easier to find all work
8221  * required to flush a truncation in process_truncates().
8222  */
8223 static void
8224 freework_enqueue(freework)
8225 	struct freework *freework;
8226 {
8227 	struct freeblks *freeblks;
8228 
8229 	freeblks = freework->fw_freeblks;
8230 	if ((freework->fw_state & INPROGRESS) == 0)
8231 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
8232 	if ((freeblks->fb_state &
8233 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
8234 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
8235 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8236 }
8237 
8238 /*
8239  * Start, continue, or finish the process of freeing an indirect block tree.
8240  * The free operation may be paused at any point with fw_off containing the
8241  * offset to restart from.  This enables us to implement some flow control
8242  * for large truncates which may fan out and generate a huge number of
8243  * dependencies.
8244  */
8245 static void
8246 handle_workitem_indirblk(freework)
8247 	struct freework *freework;
8248 {
8249 	struct freeblks *freeblks;
8250 	struct ufsmount *ump;
8251 	struct fs *fs;
8252 
8253 	freeblks = freework->fw_freeblks;
8254 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8255 	fs = ump->um_fs;
8256 	if (freework->fw_state & DEPCOMPLETE) {
8257 		handle_written_freework(freework);
8258 		return;
8259 	}
8260 	if (freework->fw_off == NINDIR(fs)) {
8261 		freework_freeblock(freework, SINGLETON_KEY);
8262 		return;
8263 	}
8264 	freework->fw_state |= INPROGRESS;
8265 	FREE_LOCK(ump);
8266 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
8267 	    freework->fw_lbn);
8268 	ACQUIRE_LOCK(ump);
8269 }
8270 
8271 /*
8272  * Called when a freework structure attached to a cg buf is written.  The
8273  * ref on either the parent or the freeblks structure is released and
8274  * the freeblks is added back to the worklist if there is more work to do.
8275  */
8276 static void
8277 handle_written_freework(freework)
8278 	struct freework *freework;
8279 {
8280 	struct freeblks *freeblks;
8281 	struct freework *parent;
8282 
8283 	freeblks = freework->fw_freeblks;
8284 	parent = freework->fw_parent;
8285 	if (freework->fw_state & DELAYEDFREE)
8286 		freeblks->fb_cgwait--;
8287 	freework->fw_state |= COMPLETE;
8288 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
8289 		WORKITEM_FREE(freework, D_FREEWORK);
8290 	if (parent) {
8291 		if (--parent->fw_ref == 0)
8292 			freework_enqueue(parent);
8293 		return;
8294 	}
8295 	if (--freeblks->fb_ref != 0)
8296 		return;
8297 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
8298 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
8299 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8300 }
8301 
8302 /*
8303  * This workitem routine performs the block de-allocation.
8304  * The workitem is added to the pending list after the updated
8305  * inode block has been written to disk.  As mentioned above,
8306  * checks regarding the number of blocks de-allocated (compared
8307  * to the number of blocks allocated for the file) are also
8308  * performed in this function.
8309  */
8310 static int
8311 handle_workitem_freeblocks(freeblks, flags)
8312 	struct freeblks *freeblks;
8313 	int flags;
8314 {
8315 	struct freework *freework;
8316 	struct newblk *newblk;
8317 	struct allocindir *aip;
8318 	struct ufsmount *ump;
8319 	struct worklist *wk;
8320 	u_long key;
8321 
8322 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
8323 	    ("handle_workitem_freeblocks: Journal entries not written."));
8324 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8325 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8326 	ACQUIRE_LOCK(ump);
8327 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
8328 		WORKLIST_REMOVE(wk);
8329 		switch (wk->wk_type) {
8330 		case D_DIRREM:
8331 			wk->wk_state |= COMPLETE;
8332 			add_to_worklist(wk, 0);
8333 			continue;
8334 
8335 		case D_ALLOCDIRECT:
8336 			free_newblk(WK_NEWBLK(wk));
8337 			continue;
8338 
8339 		case D_ALLOCINDIR:
8340 			aip = WK_ALLOCINDIR(wk);
8341 			freework = NULL;
8342 			if (aip->ai_state & DELAYEDFREE) {
8343 				FREE_LOCK(ump);
8344 				freework = newfreework(ump, freeblks, NULL,
8345 				    aip->ai_lbn, aip->ai_newblkno,
8346 				    ump->um_fs->fs_frag, 0, 0);
8347 				ACQUIRE_LOCK(ump);
8348 			}
8349 			newblk = WK_NEWBLK(wk);
8350 			if (newblk->nb_jnewblk) {
8351 				freework->fw_jnewblk = newblk->nb_jnewblk;
8352 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
8353 				newblk->nb_jnewblk = NULL;
8354 			}
8355 			free_newblk(newblk);
8356 			continue;
8357 
8358 		case D_FREEWORK:
8359 			freework = WK_FREEWORK(wk);
8360 			if (freework->fw_lbn <= -UFS_NDADDR)
8361 				handle_workitem_indirblk(freework);
8362 			else
8363 				freework_freeblock(freework, key);
8364 			continue;
8365 		default:
8366 			panic("handle_workitem_freeblocks: Unknown type %s",
8367 			    TYPENAME(wk->wk_type));
8368 		}
8369 	}
8370 	if (freeblks->fb_ref != 0) {
8371 		freeblks->fb_state &= ~INPROGRESS;
8372 		wake_worklist(&freeblks->fb_list);
8373 		freeblks = NULL;
8374 	}
8375 	FREE_LOCK(ump);
8376 	ffs_blkrelease_finish(ump, key);
8377 	if (freeblks)
8378 		return handle_complete_freeblocks(freeblks, flags);
8379 	return (0);
8380 }
8381 
8382 /*
8383  * Handle completion of block free via truncate.  This allows fs_pending
8384  * to track the actual free block count more closely than if we only updated
8385  * it at the end.  We must be careful to handle cases where the block count
8386  * on free was incorrect.
8387  */
8388 static void
8389 freeblks_free(ump, freeblks, blocks)
8390 	struct ufsmount *ump;
8391 	struct freeblks *freeblks;
8392 	int blocks;
8393 {
8394 	struct fs *fs;
8395 	ufs2_daddr_t remain;
8396 
8397 	UFS_LOCK(ump);
8398 	remain = -freeblks->fb_chkcnt;
8399 	freeblks->fb_chkcnt += blocks;
8400 	if (remain > 0) {
8401 		if (remain < blocks)
8402 			blocks = remain;
8403 		fs = ump->um_fs;
8404 		fs->fs_pendingblocks -= blocks;
8405 	}
8406 	UFS_UNLOCK(ump);
8407 }
8408 
8409 /*
8410  * Once all of the freework workitems are complete we can retire the
8411  * freeblocks dependency and any journal work awaiting completion.  This
8412  * can not be called until all other dependencies are stable on disk.
8413  */
8414 static int
8415 handle_complete_freeblocks(freeblks, flags)
8416 	struct freeblks *freeblks;
8417 	int flags;
8418 {
8419 	struct inodedep *inodedep;
8420 	struct inode *ip;
8421 	struct vnode *vp;
8422 	struct fs *fs;
8423 	struct ufsmount *ump;
8424 	ufs2_daddr_t spare;
8425 
8426 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8427 	fs = ump->um_fs;
8428 	flags = LK_EXCLUSIVE | flags;
8429 	spare = freeblks->fb_chkcnt;
8430 
8431 	/*
8432 	 * If we did not release the expected number of blocks we may have
8433 	 * to adjust the inode block count here.  Only do so if it wasn't
8434 	 * a truncation to zero and the modrev still matches.
8435 	 */
8436 	if (spare && freeblks->fb_len != 0) {
8437 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8438 		    flags, &vp, FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP) != 0)
8439 			return (EBUSY);
8440 		ip = VTOI(vp);
8441 		if (ip->i_mode == 0) {
8442 			vgone(vp);
8443 		} else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8444 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8445 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8446 			/*
8447 			 * We must wait so this happens before the
8448 			 * journal is reclaimed.
8449 			 */
8450 			ffs_update(vp, 1);
8451 		}
8452 		vput(vp);
8453 	}
8454 	if (spare < 0) {
8455 		UFS_LOCK(ump);
8456 		fs->fs_pendingblocks += spare;
8457 		UFS_UNLOCK(ump);
8458 	}
8459 #ifdef QUOTA
8460 	/* Handle spare. */
8461 	if (spare)
8462 		quotaadj(freeblks->fb_quota, ump, -spare);
8463 	quotarele(freeblks->fb_quota);
8464 #endif
8465 	ACQUIRE_LOCK(ump);
8466 	if (freeblks->fb_state & ONDEPLIST) {
8467 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8468 		    0, &inodedep);
8469 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8470 		freeblks->fb_state &= ~ONDEPLIST;
8471 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8472 			free_inodedep(inodedep);
8473 	}
8474 	/*
8475 	 * All of the freeblock deps must be complete prior to this call
8476 	 * so it's now safe to complete earlier outstanding journal entries.
8477 	 */
8478 	handle_jwork(&freeblks->fb_jwork);
8479 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8480 	FREE_LOCK(ump);
8481 	return (0);
8482 }
8483 
8484 /*
8485  * Release blocks associated with the freeblks and stored in the indirect
8486  * block dbn. If level is greater than SINGLE, the block is an indirect block
8487  * and recursive calls to indirtrunc must be used to cleanse other indirect
8488  * blocks.
8489  *
8490  * This handles partial and complete truncation of blocks.  Partial is noted
8491  * with goingaway == 0.  In this case the freework is completed after the
8492  * zero'd indirects are written to disk.  For full truncation the freework
8493  * is completed after the block is freed.
8494  */
8495 static void
8496 indir_trunc(freework, dbn, lbn)
8497 	struct freework *freework;
8498 	ufs2_daddr_t dbn;
8499 	ufs_lbn_t lbn;
8500 {
8501 	struct freework *nfreework;
8502 	struct workhead wkhd;
8503 	struct freeblks *freeblks;
8504 	struct buf *bp;
8505 	struct fs *fs;
8506 	struct indirdep *indirdep;
8507 	struct mount *mp;
8508 	struct ufsmount *ump;
8509 	ufs1_daddr_t *bap1;
8510 	ufs2_daddr_t nb, nnb, *bap2;
8511 	ufs_lbn_t lbnadd, nlbn;
8512 	u_long key;
8513 	int nblocks, ufs1fmt, freedblocks;
8514 	int goingaway, freedeps, needj, level, cnt, i, error;
8515 
8516 	freeblks = freework->fw_freeblks;
8517 	mp = freeblks->fb_list.wk_mp;
8518 	ump = VFSTOUFS(mp);
8519 	fs = ump->um_fs;
8520 	/*
8521 	 * Get buffer of block pointers to be freed.  There are three cases:
8522 	 *
8523 	 * 1) Partial truncate caches the indirdep pointer in the freework
8524 	 *    which provides us a back copy to the save bp which holds the
8525 	 *    pointers we want to clear.  When this completes the zero
8526 	 *    pointers are written to the real copy.
8527 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8528 	 *    eliminated the real copy and placed the indirdep on the saved
8529 	 *    copy.  The indirdep and buf are discarded when this completes.
8530 	 * 3) The indirect was not in memory, we read a copy off of the disk
8531 	 *    using the devvp and drop and invalidate the buffer when we're
8532 	 *    done.
8533 	 */
8534 	goingaway = 1;
8535 	indirdep = NULL;
8536 	if (freework->fw_indir != NULL) {
8537 		goingaway = 0;
8538 		indirdep = freework->fw_indir;
8539 		bp = indirdep->ir_savebp;
8540 		if (bp == NULL || bp->b_blkno != dbn)
8541 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8542 			    bp, (intmax_t)dbn);
8543 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8544 		/*
8545 		 * The lock prevents the buf dep list from changing and
8546 	 	 * indirects on devvp should only ever have one dependency.
8547 		 */
8548 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8549 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8550 			panic("indir_trunc: Bad indirdep %p from buf %p",
8551 			    indirdep, bp);
8552 	} else {
8553 		error = ffs_breadz(ump, freeblks->fb_devvp, dbn, dbn,
8554 		    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
8555 		if (error)
8556 			return;
8557 	}
8558 	ACQUIRE_LOCK(ump);
8559 	/* Protects against a race with complete_trunc_indir(). */
8560 	freework->fw_state &= ~INPROGRESS;
8561 	/*
8562 	 * If we have an indirdep we need to enforce the truncation order
8563 	 * and discard it when it is complete.
8564 	 */
8565 	if (indirdep) {
8566 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8567 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8568 			/*
8569 			 * Add the complete truncate to the list on the
8570 			 * indirdep to enforce in-order processing.
8571 			 */
8572 			if (freework->fw_indir == NULL)
8573 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8574 				    freework, fw_next);
8575 			FREE_LOCK(ump);
8576 			return;
8577 		}
8578 		/*
8579 		 * If we're goingaway, free the indirdep.  Otherwise it will
8580 		 * linger until the write completes.
8581 		 */
8582 		if (goingaway) {
8583 			KASSERT(indirdep->ir_savebp == bp,
8584 			    ("indir_trunc: losing ir_savebp %p",
8585 			    indirdep->ir_savebp));
8586 			indirdep->ir_savebp = NULL;
8587 			free_indirdep(indirdep);
8588 		}
8589 	}
8590 	FREE_LOCK(ump);
8591 	/* Initialize pointers depending on block size. */
8592 	if (ump->um_fstype == UFS1) {
8593 		bap1 = (ufs1_daddr_t *)bp->b_data;
8594 		nb = bap1[freework->fw_off];
8595 		ufs1fmt = 1;
8596 		bap2 = NULL;
8597 	} else {
8598 		bap2 = (ufs2_daddr_t *)bp->b_data;
8599 		nb = bap2[freework->fw_off];
8600 		ufs1fmt = 0;
8601 		bap1 = NULL;
8602 	}
8603 	level = lbn_level(lbn);
8604 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8605 	lbnadd = lbn_offset(fs, level);
8606 	nblocks = btodb(fs->fs_bsize);
8607 	nfreework = freework;
8608 	freedeps = 0;
8609 	cnt = 0;
8610 	/*
8611 	 * Reclaim blocks.  Traverses into nested indirect levels and
8612 	 * arranges for the current level to be freed when subordinates
8613 	 * are free when journaling.
8614 	 */
8615 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8616 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8617 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8618 		    fs->fs_bsize) != 0)
8619 			nb = 0;
8620 		if (i != NINDIR(fs) - 1) {
8621 			if (ufs1fmt)
8622 				nnb = bap1[i+1];
8623 			else
8624 				nnb = bap2[i+1];
8625 		} else
8626 			nnb = 0;
8627 		if (nb == 0)
8628 			continue;
8629 		cnt++;
8630 		if (level != 0) {
8631 			nlbn = (lbn + 1) - (i * lbnadd);
8632 			if (needj != 0) {
8633 				nfreework = newfreework(ump, freeblks, freework,
8634 				    nlbn, nb, fs->fs_frag, 0, 0);
8635 				freedeps++;
8636 			}
8637 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8638 		} else {
8639 			struct freedep *freedep;
8640 
8641 			/*
8642 			 * Attempt to aggregate freedep dependencies for
8643 			 * all blocks being released to the same CG.
8644 			 */
8645 			LIST_INIT(&wkhd);
8646 			if (needj != 0 &&
8647 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8648 				freedep = newfreedep(freework);
8649 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8650 				    &freedep->fd_list);
8651 				freedeps++;
8652 			}
8653 			CTR3(KTR_SUJ,
8654 			    "indir_trunc: ino %jd blkno %jd size %d",
8655 			    freeblks->fb_inum, nb, fs->fs_bsize);
8656 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8657 			    fs->fs_bsize, freeblks->fb_inum,
8658 			    freeblks->fb_vtype, &wkhd, key);
8659 		}
8660 	}
8661 	ffs_blkrelease_finish(ump, key);
8662 	if (goingaway) {
8663 		bp->b_flags |= B_INVAL | B_NOCACHE;
8664 		brelse(bp);
8665 	}
8666 	freedblocks = 0;
8667 	if (level == 0)
8668 		freedblocks = (nblocks * cnt);
8669 	if (needj == 0)
8670 		freedblocks += nblocks;
8671 	freeblks_free(ump, freeblks, freedblocks);
8672 	/*
8673 	 * If we are journaling set up the ref counts and offset so this
8674 	 * indirect can be completed when its children are free.
8675 	 */
8676 	if (needj) {
8677 		ACQUIRE_LOCK(ump);
8678 		freework->fw_off = i;
8679 		freework->fw_ref += freedeps;
8680 		freework->fw_ref -= NINDIR(fs) + 1;
8681 		if (level == 0)
8682 			freeblks->fb_cgwait += freedeps;
8683 		if (freework->fw_ref == 0)
8684 			freework_freeblock(freework, SINGLETON_KEY);
8685 		FREE_LOCK(ump);
8686 		return;
8687 	}
8688 	/*
8689 	 * If we're not journaling we can free the indirect now.
8690 	 */
8691 	dbn = dbtofsb(fs, dbn);
8692 	CTR3(KTR_SUJ,
8693 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8694 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8695 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8696 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8697 	/* Non SUJ softdep does single-threaded truncations. */
8698 	if (freework->fw_blkno == dbn) {
8699 		freework->fw_state |= ALLCOMPLETE;
8700 		ACQUIRE_LOCK(ump);
8701 		handle_written_freework(freework);
8702 		FREE_LOCK(ump);
8703 	}
8704 	return;
8705 }
8706 
8707 /*
8708  * Cancel an allocindir when it is removed via truncation.  When bp is not
8709  * NULL the indirect never appeared on disk and is scheduled to be freed
8710  * independently of the indir so we can more easily track journal work.
8711  */
8712 static void
8713 cancel_allocindir(aip, bp, freeblks, trunc)
8714 	struct allocindir *aip;
8715 	struct buf *bp;
8716 	struct freeblks *freeblks;
8717 	int trunc;
8718 {
8719 	struct indirdep *indirdep;
8720 	struct freefrag *freefrag;
8721 	struct newblk *newblk;
8722 
8723 	newblk = (struct newblk *)aip;
8724 	LIST_REMOVE(aip, ai_next);
8725 	/*
8726 	 * We must eliminate the pointer in bp if it must be freed on its
8727 	 * own due to partial truncate or pending journal work.
8728 	 */
8729 	if (bp && (trunc || newblk->nb_jnewblk)) {
8730 		/*
8731 		 * Clear the pointer and mark the aip to be freed
8732 		 * directly if it never existed on disk.
8733 		 */
8734 		aip->ai_state |= DELAYEDFREE;
8735 		indirdep = aip->ai_indirdep;
8736 		if (indirdep->ir_state & UFS1FMT)
8737 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8738 		else
8739 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8740 	}
8741 	/*
8742 	 * When truncating the previous pointer will be freed via
8743 	 * savedbp.  Eliminate the freefrag which would dup free.
8744 	 */
8745 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8746 		newblk->nb_freefrag = NULL;
8747 		if (freefrag->ff_jdep)
8748 			cancel_jfreefrag(
8749 			    WK_JFREEFRAG(freefrag->ff_jdep));
8750 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8751 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8752 	}
8753 	/*
8754 	 * If the journal hasn't been written the jnewblk must be passed
8755 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8756 	 * this by leaving the journal dependency on the newblk to be freed
8757 	 * when a freework is created in handle_workitem_freeblocks().
8758 	 */
8759 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8760 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8761 }
8762 
8763 /*
8764  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8765  * in to a newdirblk so any subsequent additions are tracked properly.  The
8766  * caller is responsible for adding the mkdir1 dependency to the journal
8767  * and updating id_mkdiradd.  This function returns with the per-filesystem
8768  * lock held.
8769  */
8770 static struct mkdir *
8771 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8772 	struct diradd *dap;
8773 	ino_t newinum;
8774 	ino_t dinum;
8775 	struct buf *newdirbp;
8776 	struct mkdir **mkdirp;
8777 {
8778 	struct newblk *newblk;
8779 	struct pagedep *pagedep;
8780 	struct inodedep *inodedep;
8781 	struct newdirblk *newdirblk;
8782 	struct mkdir *mkdir1, *mkdir2;
8783 	struct worklist *wk;
8784 	struct jaddref *jaddref;
8785 	struct ufsmount *ump;
8786 	struct mount *mp;
8787 
8788 	mp = dap->da_list.wk_mp;
8789 	ump = VFSTOUFS(mp);
8790 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8791 	    M_SOFTDEP_FLAGS);
8792 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8793 	LIST_INIT(&newdirblk->db_mkdir);
8794 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8795 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8796 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8797 	mkdir1->md_diradd = dap;
8798 	mkdir1->md_jaddref = NULL;
8799 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8800 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8801 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8802 	mkdir2->md_diradd = dap;
8803 	mkdir2->md_jaddref = NULL;
8804 	if (MOUNTEDSUJ(mp) == 0) {
8805 		mkdir1->md_state |= DEPCOMPLETE;
8806 		mkdir2->md_state |= DEPCOMPLETE;
8807 	}
8808 	/*
8809 	 * Dependency on "." and ".." being written to disk.
8810 	 */
8811 	mkdir1->md_buf = newdirbp;
8812 	ACQUIRE_LOCK(VFSTOUFS(mp));
8813 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8814 	/*
8815 	 * We must link the pagedep, allocdirect, and newdirblk for
8816 	 * the initial file page so the pointer to the new directory
8817 	 * is not written until the directory contents are live and
8818 	 * any subsequent additions are not marked live until the
8819 	 * block is reachable via the inode.
8820 	 */
8821 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8822 		panic("setup_newdir: lost pagedep");
8823 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8824 		if (wk->wk_type == D_ALLOCDIRECT)
8825 			break;
8826 	if (wk == NULL)
8827 		panic("setup_newdir: lost allocdirect");
8828 	if (pagedep->pd_state & NEWBLOCK)
8829 		panic("setup_newdir: NEWBLOCK already set");
8830 	newblk = WK_NEWBLK(wk);
8831 	pagedep->pd_state |= NEWBLOCK;
8832 	pagedep->pd_newdirblk = newdirblk;
8833 	newdirblk->db_pagedep = pagedep;
8834 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8835 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8836 	/*
8837 	 * Look up the inodedep for the parent directory so that we
8838 	 * can link mkdir2 into the pending dotdot jaddref or
8839 	 * the inode write if there is none.  If the inode is
8840 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8841 	 * been satisfied and mkdir2 can be freed.
8842 	 */
8843 	inodedep_lookup(mp, dinum, 0, &inodedep);
8844 	if (MOUNTEDSUJ(mp)) {
8845 		if (inodedep == NULL)
8846 			panic("setup_newdir: Lost parent.");
8847 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8848 		    inoreflst);
8849 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8850 		    (jaddref->ja_state & MKDIR_PARENT),
8851 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8852 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8853 		mkdir2->md_jaddref = jaddref;
8854 		jaddref->ja_mkdir = mkdir2;
8855 	} else if (inodedep == NULL ||
8856 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8857 		dap->da_state &= ~MKDIR_PARENT;
8858 		WORKITEM_FREE(mkdir2, D_MKDIR);
8859 		mkdir2 = NULL;
8860 	} else {
8861 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8862 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8863 	}
8864 	*mkdirp = mkdir2;
8865 
8866 	return (mkdir1);
8867 }
8868 
8869 /*
8870  * Directory entry addition dependencies.
8871  *
8872  * When adding a new directory entry, the inode (with its incremented link
8873  * count) must be written to disk before the directory entry's pointer to it.
8874  * Also, if the inode is newly allocated, the corresponding freemap must be
8875  * updated (on disk) before the directory entry's pointer. These requirements
8876  * are met via undo/redo on the directory entry's pointer, which consists
8877  * simply of the inode number.
8878  *
8879  * As directory entries are added and deleted, the free space within a
8880  * directory block can become fragmented.  The ufs filesystem will compact
8881  * a fragmented directory block to make space for a new entry. When this
8882  * occurs, the offsets of previously added entries change. Any "diradd"
8883  * dependency structures corresponding to these entries must be updated with
8884  * the new offsets.
8885  */
8886 
8887 /*
8888  * This routine is called after the in-memory inode's link
8889  * count has been incremented, but before the directory entry's
8890  * pointer to the inode has been set.
8891  */
8892 int
8893 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8894 	struct buf *bp;		/* buffer containing directory block */
8895 	struct inode *dp;	/* inode for directory */
8896 	off_t diroffset;	/* offset of new entry in directory */
8897 	ino_t newinum;		/* inode referenced by new directory entry */
8898 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8899 	int isnewblk;		/* entry is in a newly allocated block */
8900 {
8901 	int offset;		/* offset of new entry within directory block */
8902 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8903 	struct fs *fs;
8904 	struct diradd *dap;
8905 	struct newblk *newblk;
8906 	struct pagedep *pagedep;
8907 	struct inodedep *inodedep;
8908 	struct newdirblk *newdirblk;
8909 	struct mkdir *mkdir1, *mkdir2;
8910 	struct jaddref *jaddref;
8911 	struct ufsmount *ump;
8912 	struct mount *mp;
8913 	int isindir;
8914 
8915 	mp = ITOVFS(dp);
8916 	ump = VFSTOUFS(mp);
8917 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8918 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8919 	/*
8920 	 * Whiteouts have no dependencies.
8921 	 */
8922 	if (newinum == UFS_WINO) {
8923 		if (newdirbp != NULL)
8924 			bdwrite(newdirbp);
8925 		return (0);
8926 	}
8927 	jaddref = NULL;
8928 	mkdir1 = mkdir2 = NULL;
8929 	fs = ump->um_fs;
8930 	lbn = lblkno(fs, diroffset);
8931 	offset = blkoff(fs, diroffset);
8932 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8933 		M_SOFTDEP_FLAGS|M_ZERO);
8934 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8935 	dap->da_offset = offset;
8936 	dap->da_newinum = newinum;
8937 	dap->da_state = ATTACHED;
8938 	LIST_INIT(&dap->da_jwork);
8939 	isindir = bp->b_lblkno >= UFS_NDADDR;
8940 	newdirblk = NULL;
8941 	if (isnewblk &&
8942 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8943 		newdirblk = malloc(sizeof(struct newdirblk),
8944 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8945 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8946 		LIST_INIT(&newdirblk->db_mkdir);
8947 	}
8948 	/*
8949 	 * If we're creating a new directory setup the dependencies and set
8950 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8951 	 * we can move on.
8952 	 */
8953 	if (newdirbp == NULL) {
8954 		dap->da_state |= DEPCOMPLETE;
8955 		ACQUIRE_LOCK(ump);
8956 	} else {
8957 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8958 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8959 		    &mkdir2);
8960 	}
8961 	/*
8962 	 * Link into parent directory pagedep to await its being written.
8963 	 */
8964 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8965 #ifdef INVARIANTS
8966 	if (diradd_lookup(pagedep, offset) != NULL)
8967 		panic("softdep_setup_directory_add: %p already at off %d\n",
8968 		    diradd_lookup(pagedep, offset), offset);
8969 #endif
8970 	dap->da_pagedep = pagedep;
8971 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8972 	    da_pdlist);
8973 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8974 	/*
8975 	 * If we're journaling, link the diradd into the jaddref so it
8976 	 * may be completed after the journal entry is written.  Otherwise,
8977 	 * link the diradd into its inodedep.  If the inode is not yet
8978 	 * written place it on the bufwait list, otherwise do the post-inode
8979 	 * write processing to put it on the id_pendinghd list.
8980 	 */
8981 	if (MOUNTEDSUJ(mp)) {
8982 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8983 		    inoreflst);
8984 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8985 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8986 		jaddref->ja_diroff = diroffset;
8987 		jaddref->ja_diradd = dap;
8988 		add_to_journal(&jaddref->ja_list);
8989 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8990 		diradd_inode_written(dap, inodedep);
8991 	else
8992 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8993 	/*
8994 	 * Add the journal entries for . and .. links now that the primary
8995 	 * link is written.
8996 	 */
8997 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8998 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8999 		    inoreflst, if_deps);
9000 		KASSERT(jaddref != NULL &&
9001 		    jaddref->ja_ino == jaddref->ja_parent &&
9002 		    (jaddref->ja_state & MKDIR_BODY),
9003 		    ("softdep_setup_directory_add: bad dot jaddref %p",
9004 		    jaddref));
9005 		mkdir1->md_jaddref = jaddref;
9006 		jaddref->ja_mkdir = mkdir1;
9007 		/*
9008 		 * It is important that the dotdot journal entry
9009 		 * is added prior to the dot entry since dot writes
9010 		 * both the dot and dotdot links.  These both must
9011 		 * be added after the primary link for the journal
9012 		 * to remain consistent.
9013 		 */
9014 		add_to_journal(&mkdir2->md_jaddref->ja_list);
9015 		add_to_journal(&jaddref->ja_list);
9016 	}
9017 	/*
9018 	 * If we are adding a new directory remember this diradd so that if
9019 	 * we rename it we can keep the dot and dotdot dependencies.  If
9020 	 * we are adding a new name for an inode that has a mkdiradd we
9021 	 * must be in rename and we have to move the dot and dotdot
9022 	 * dependencies to this new name.  The old name is being orphaned
9023 	 * soon.
9024 	 */
9025 	if (mkdir1 != NULL) {
9026 		if (inodedep->id_mkdiradd != NULL)
9027 			panic("softdep_setup_directory_add: Existing mkdir");
9028 		inodedep->id_mkdiradd = dap;
9029 	} else if (inodedep->id_mkdiradd)
9030 		merge_diradd(inodedep, dap);
9031 	if (newdirblk != NULL) {
9032 		/*
9033 		 * There is nothing to do if we are already tracking
9034 		 * this block.
9035 		 */
9036 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
9037 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
9038 			FREE_LOCK(ump);
9039 			return (0);
9040 		}
9041 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
9042 		    == 0)
9043 			panic("softdep_setup_directory_add: lost entry");
9044 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
9045 		pagedep->pd_state |= NEWBLOCK;
9046 		pagedep->pd_newdirblk = newdirblk;
9047 		newdirblk->db_pagedep = pagedep;
9048 		FREE_LOCK(ump);
9049 		/*
9050 		 * If we extended into an indirect signal direnter to sync.
9051 		 */
9052 		if (isindir)
9053 			return (1);
9054 		return (0);
9055 	}
9056 	FREE_LOCK(ump);
9057 	return (0);
9058 }
9059 
9060 /*
9061  * This procedure is called to change the offset of a directory
9062  * entry when compacting a directory block which must be owned
9063  * exclusively by the caller. Note that the actual entry movement
9064  * must be done in this procedure to ensure that no I/O completions
9065  * occur while the move is in progress.
9066  */
9067 void
9068 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
9069 	struct buf *bp;		/* Buffer holding directory block. */
9070 	struct inode *dp;	/* inode for directory */
9071 	caddr_t base;		/* address of dp->i_offset */
9072 	caddr_t oldloc;		/* address of old directory location */
9073 	caddr_t newloc;		/* address of new directory location */
9074 	int entrysize;		/* size of directory entry */
9075 {
9076 	int offset, oldoffset, newoffset;
9077 	struct pagedep *pagedep;
9078 	struct jmvref *jmvref;
9079 	struct diradd *dap;
9080 	struct direct *de;
9081 	struct mount *mp;
9082 	struct ufsmount *ump;
9083 	ufs_lbn_t lbn;
9084 	int flags;
9085 
9086 	mp = ITOVFS(dp);
9087 	ump = VFSTOUFS(mp);
9088 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9089 	    ("softdep_change_directoryentry_offset called on "
9090 	     "non-softdep filesystem"));
9091 	de = (struct direct *)oldloc;
9092 	jmvref = NULL;
9093 	flags = 0;
9094 	/*
9095 	 * Moves are always journaled as it would be too complex to
9096 	 * determine if any affected adds or removes are present in the
9097 	 * journal.
9098 	 */
9099 	if (MOUNTEDSUJ(mp)) {
9100 		flags = DEPALLOC;
9101 		jmvref = newjmvref(dp, de->d_ino,
9102 		    I_OFFSET(dp) + (oldloc - base),
9103 		    I_OFFSET(dp) + (newloc - base));
9104 	}
9105 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9106 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9107 	oldoffset = offset + (oldloc - base);
9108 	newoffset = offset + (newloc - base);
9109 	ACQUIRE_LOCK(ump);
9110 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
9111 		goto done;
9112 	dap = diradd_lookup(pagedep, oldoffset);
9113 	if (dap) {
9114 		dap->da_offset = newoffset;
9115 		newoffset = DIRADDHASH(newoffset);
9116 		oldoffset = DIRADDHASH(oldoffset);
9117 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
9118 		    newoffset != oldoffset) {
9119 			LIST_REMOVE(dap, da_pdlist);
9120 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
9121 			    dap, da_pdlist);
9122 		}
9123 	}
9124 done:
9125 	if (jmvref) {
9126 		jmvref->jm_pagedep = pagedep;
9127 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
9128 		add_to_journal(&jmvref->jm_list);
9129 	}
9130 	bcopy(oldloc, newloc, entrysize);
9131 	FREE_LOCK(ump);
9132 }
9133 
9134 /*
9135  * Move the mkdir dependencies and journal work from one diradd to another
9136  * when renaming a directory.  The new name must depend on the mkdir deps
9137  * completing as the old name did.  Directories can only have one valid link
9138  * at a time so one must be canonical.
9139  */
9140 static void
9141 merge_diradd(inodedep, newdap)
9142 	struct inodedep *inodedep;
9143 	struct diradd *newdap;
9144 {
9145 	struct diradd *olddap;
9146 	struct mkdir *mkdir, *nextmd;
9147 	struct ufsmount *ump;
9148 	short state;
9149 
9150 	olddap = inodedep->id_mkdiradd;
9151 	inodedep->id_mkdiradd = newdap;
9152 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9153 		newdap->da_state &= ~DEPCOMPLETE;
9154 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
9155 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9156 		     mkdir = nextmd) {
9157 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9158 			if (mkdir->md_diradd != olddap)
9159 				continue;
9160 			mkdir->md_diradd = newdap;
9161 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
9162 			newdap->da_state |= state;
9163 			olddap->da_state &= ~state;
9164 			if ((olddap->da_state &
9165 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
9166 				break;
9167 		}
9168 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9169 			panic("merge_diradd: unfound ref");
9170 	}
9171 	/*
9172 	 * Any mkdir related journal items are not safe to be freed until
9173 	 * the new name is stable.
9174 	 */
9175 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
9176 	olddap->da_state |= DEPCOMPLETE;
9177 	complete_diradd(olddap);
9178 }
9179 
9180 /*
9181  * Move the diradd to the pending list when all diradd dependencies are
9182  * complete.
9183  */
9184 static void
9185 complete_diradd(dap)
9186 	struct diradd *dap;
9187 {
9188 	struct pagedep *pagedep;
9189 
9190 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
9191 		if (dap->da_state & DIRCHG)
9192 			pagedep = dap->da_previous->dm_pagedep;
9193 		else
9194 			pagedep = dap->da_pagedep;
9195 		LIST_REMOVE(dap, da_pdlist);
9196 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9197 	}
9198 }
9199 
9200 /*
9201  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
9202  * add entries and conditonally journal the remove.
9203  */
9204 static void
9205 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
9206 	struct diradd *dap;
9207 	struct dirrem *dirrem;
9208 	struct jremref *jremref;
9209 	struct jremref *dotremref;
9210 	struct jremref *dotdotremref;
9211 {
9212 	struct inodedep *inodedep;
9213 	struct jaddref *jaddref;
9214 	struct inoref *inoref;
9215 	struct ufsmount *ump;
9216 	struct mkdir *mkdir;
9217 
9218 	/*
9219 	 * If no remove references were allocated we're on a non-journaled
9220 	 * filesystem and can skip the cancel step.
9221 	 */
9222 	if (jremref == NULL) {
9223 		free_diradd(dap, NULL);
9224 		return;
9225 	}
9226 	/*
9227 	 * Cancel the primary name an free it if it does not require
9228 	 * journaling.
9229 	 */
9230 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
9231 	    0, &inodedep) != 0) {
9232 		/* Abort the addref that reference this diradd.  */
9233 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
9234 			if (inoref->if_list.wk_type != D_JADDREF)
9235 				continue;
9236 			jaddref = (struct jaddref *)inoref;
9237 			if (jaddref->ja_diradd != dap)
9238 				continue;
9239 			if (cancel_jaddref(jaddref, inodedep,
9240 			    &dirrem->dm_jwork) == 0) {
9241 				free_jremref(jremref);
9242 				jremref = NULL;
9243 			}
9244 			break;
9245 		}
9246 	}
9247 	/*
9248 	 * Cancel subordinate names and free them if they do not require
9249 	 * journaling.
9250 	 */
9251 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9252 		ump = VFSTOUFS(dap->da_list.wk_mp);
9253 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
9254 			if (mkdir->md_diradd != dap)
9255 				continue;
9256 			if ((jaddref = mkdir->md_jaddref) == NULL)
9257 				continue;
9258 			mkdir->md_jaddref = NULL;
9259 			if (mkdir->md_state & MKDIR_PARENT) {
9260 				if (cancel_jaddref(jaddref, NULL,
9261 				    &dirrem->dm_jwork) == 0) {
9262 					free_jremref(dotdotremref);
9263 					dotdotremref = NULL;
9264 				}
9265 			} else {
9266 				if (cancel_jaddref(jaddref, inodedep,
9267 				    &dirrem->dm_jwork) == 0) {
9268 					free_jremref(dotremref);
9269 					dotremref = NULL;
9270 				}
9271 			}
9272 		}
9273 	}
9274 
9275 	if (jremref)
9276 		journal_jremref(dirrem, jremref, inodedep);
9277 	if (dotremref)
9278 		journal_jremref(dirrem, dotremref, inodedep);
9279 	if (dotdotremref)
9280 		journal_jremref(dirrem, dotdotremref, NULL);
9281 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
9282 	free_diradd(dap, &dirrem->dm_jwork);
9283 }
9284 
9285 /*
9286  * Free a diradd dependency structure.
9287  */
9288 static void
9289 free_diradd(dap, wkhd)
9290 	struct diradd *dap;
9291 	struct workhead *wkhd;
9292 {
9293 	struct dirrem *dirrem;
9294 	struct pagedep *pagedep;
9295 	struct inodedep *inodedep;
9296 	struct mkdir *mkdir, *nextmd;
9297 	struct ufsmount *ump;
9298 
9299 	ump = VFSTOUFS(dap->da_list.wk_mp);
9300 	LOCK_OWNED(ump);
9301 	LIST_REMOVE(dap, da_pdlist);
9302 	if (dap->da_state & ONWORKLIST)
9303 		WORKLIST_REMOVE(&dap->da_list);
9304 	if ((dap->da_state & DIRCHG) == 0) {
9305 		pagedep = dap->da_pagedep;
9306 	} else {
9307 		dirrem = dap->da_previous;
9308 		pagedep = dirrem->dm_pagedep;
9309 		dirrem->dm_dirinum = pagedep->pd_ino;
9310 		dirrem->dm_state |= COMPLETE;
9311 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9312 			add_to_worklist(&dirrem->dm_list, 0);
9313 	}
9314 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
9315 	    0, &inodedep) != 0)
9316 		if (inodedep->id_mkdiradd == dap)
9317 			inodedep->id_mkdiradd = NULL;
9318 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9319 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9320 		     mkdir = nextmd) {
9321 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9322 			if (mkdir->md_diradd != dap)
9323 				continue;
9324 			dap->da_state &=
9325 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
9326 			LIST_REMOVE(mkdir, md_mkdirs);
9327 			if (mkdir->md_state & ONWORKLIST)
9328 				WORKLIST_REMOVE(&mkdir->md_list);
9329 			if (mkdir->md_jaddref != NULL)
9330 				panic("free_diradd: Unexpected jaddref");
9331 			WORKITEM_FREE(mkdir, D_MKDIR);
9332 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
9333 				break;
9334 		}
9335 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9336 			panic("free_diradd: unfound ref");
9337 	}
9338 	if (inodedep)
9339 		free_inodedep(inodedep);
9340 	/*
9341 	 * Free any journal segments waiting for the directory write.
9342 	 */
9343 	handle_jwork(&dap->da_jwork);
9344 	WORKITEM_FREE(dap, D_DIRADD);
9345 }
9346 
9347 /*
9348  * Directory entry removal dependencies.
9349  *
9350  * When removing a directory entry, the entry's inode pointer must be
9351  * zero'ed on disk before the corresponding inode's link count is decremented
9352  * (possibly freeing the inode for re-use). This dependency is handled by
9353  * updating the directory entry but delaying the inode count reduction until
9354  * after the directory block has been written to disk. After this point, the
9355  * inode count can be decremented whenever it is convenient.
9356  */
9357 
9358 /*
9359  * This routine should be called immediately after removing
9360  * a directory entry.  The inode's link count should not be
9361  * decremented by the calling procedure -- the soft updates
9362  * code will do this task when it is safe.
9363  */
9364 void
9365 softdep_setup_remove(bp, dp, ip, isrmdir)
9366 	struct buf *bp;		/* buffer containing directory block */
9367 	struct inode *dp;	/* inode for the directory being modified */
9368 	struct inode *ip;	/* inode for directory entry being removed */
9369 	int isrmdir;		/* indicates if doing RMDIR */
9370 {
9371 	struct dirrem *dirrem, *prevdirrem;
9372 	struct inodedep *inodedep;
9373 	struct ufsmount *ump;
9374 	int direct;
9375 
9376 	ump = ITOUMP(ip);
9377 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9378 	    ("softdep_setup_remove called on non-softdep filesystem"));
9379 	/*
9380 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9381 	 * newdirrem() to setup the full directory remove which requires
9382 	 * isrmdir > 1.
9383 	 */
9384 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9385 	/*
9386 	 * Add the dirrem to the inodedep's pending remove list for quick
9387 	 * discovery later.
9388 	 */
9389 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9390 		panic("softdep_setup_remove: Lost inodedep.");
9391 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9392 	dirrem->dm_state |= ONDEPLIST;
9393 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9394 
9395 	/*
9396 	 * If the COMPLETE flag is clear, then there were no active
9397 	 * entries and we want to roll back to a zeroed entry until
9398 	 * the new inode is committed to disk. If the COMPLETE flag is
9399 	 * set then we have deleted an entry that never made it to
9400 	 * disk. If the entry we deleted resulted from a name change,
9401 	 * then the old name still resides on disk. We cannot delete
9402 	 * its inode (returned to us in prevdirrem) until the zeroed
9403 	 * directory entry gets to disk. The new inode has never been
9404 	 * referenced on the disk, so can be deleted immediately.
9405 	 */
9406 	if ((dirrem->dm_state & COMPLETE) == 0) {
9407 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9408 		    dm_next);
9409 		FREE_LOCK(ump);
9410 	} else {
9411 		if (prevdirrem != NULL)
9412 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9413 			    prevdirrem, dm_next);
9414 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9415 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9416 		FREE_LOCK(ump);
9417 		if (direct)
9418 			handle_workitem_remove(dirrem, 0);
9419 	}
9420 }
9421 
9422 /*
9423  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9424  * pd_pendinghd list of a pagedep.
9425  */
9426 static struct diradd *
9427 diradd_lookup(pagedep, offset)
9428 	struct pagedep *pagedep;
9429 	int offset;
9430 {
9431 	struct diradd *dap;
9432 
9433 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9434 		if (dap->da_offset == offset)
9435 			return (dap);
9436 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9437 		if (dap->da_offset == offset)
9438 			return (dap);
9439 	return (NULL);
9440 }
9441 
9442 /*
9443  * Search for a .. diradd dependency in a directory that is being removed.
9444  * If the directory was renamed to a new parent we have a diradd rather
9445  * than a mkdir for the .. entry.  We need to cancel it now before
9446  * it is found in truncate().
9447  */
9448 static struct jremref *
9449 cancel_diradd_dotdot(ip, dirrem, jremref)
9450 	struct inode *ip;
9451 	struct dirrem *dirrem;
9452 	struct jremref *jremref;
9453 {
9454 	struct pagedep *pagedep;
9455 	struct diradd *dap;
9456 	struct worklist *wk;
9457 
9458 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9459 		return (jremref);
9460 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9461 	if (dap == NULL)
9462 		return (jremref);
9463 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9464 	/*
9465 	 * Mark any journal work as belonging to the parent so it is freed
9466 	 * with the .. reference.
9467 	 */
9468 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9469 		wk->wk_state |= MKDIR_PARENT;
9470 	return (NULL);
9471 }
9472 
9473 /*
9474  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9475  * replace it with a dirrem/diradd pair as a result of re-parenting a
9476  * directory.  This ensures that we don't simultaneously have a mkdir and
9477  * a diradd for the same .. entry.
9478  */
9479 static struct jremref *
9480 cancel_mkdir_dotdot(ip, dirrem, jremref)
9481 	struct inode *ip;
9482 	struct dirrem *dirrem;
9483 	struct jremref *jremref;
9484 {
9485 	struct inodedep *inodedep;
9486 	struct jaddref *jaddref;
9487 	struct ufsmount *ump;
9488 	struct mkdir *mkdir;
9489 	struct diradd *dap;
9490 	struct mount *mp;
9491 
9492 	mp = ITOVFS(ip);
9493 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9494 		return (jremref);
9495 	dap = inodedep->id_mkdiradd;
9496 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9497 		return (jremref);
9498 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9499 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9500 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9501 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9502 			break;
9503 	if (mkdir == NULL)
9504 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9505 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9506 		mkdir->md_jaddref = NULL;
9507 		jaddref->ja_state &= ~MKDIR_PARENT;
9508 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9509 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9510 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9511 			journal_jremref(dirrem, jremref, inodedep);
9512 			jremref = NULL;
9513 		}
9514 	}
9515 	if (mkdir->md_state & ONWORKLIST)
9516 		WORKLIST_REMOVE(&mkdir->md_list);
9517 	mkdir->md_state |= ALLCOMPLETE;
9518 	complete_mkdir(mkdir);
9519 	return (jremref);
9520 }
9521 
9522 static void
9523 journal_jremref(dirrem, jremref, inodedep)
9524 	struct dirrem *dirrem;
9525 	struct jremref *jremref;
9526 	struct inodedep *inodedep;
9527 {
9528 
9529 	if (inodedep == NULL)
9530 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9531 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9532 			panic("journal_jremref: Lost inodedep");
9533 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9534 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9535 	add_to_journal(&jremref->jr_list);
9536 }
9537 
9538 static void
9539 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9540 	struct dirrem *dirrem;
9541 	struct jremref *jremref;
9542 	struct jremref *dotremref;
9543 	struct jremref *dotdotremref;
9544 {
9545 	struct inodedep *inodedep;
9546 
9547 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9548 	    &inodedep) == 0)
9549 		panic("dirrem_journal: Lost inodedep");
9550 	journal_jremref(dirrem, jremref, inodedep);
9551 	if (dotremref)
9552 		journal_jremref(dirrem, dotremref, inodedep);
9553 	if (dotdotremref)
9554 		journal_jremref(dirrem, dotdotremref, NULL);
9555 }
9556 
9557 /*
9558  * Allocate a new dirrem if appropriate and return it along with
9559  * its associated pagedep. Called without a lock, returns with lock.
9560  */
9561 static struct dirrem *
9562 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9563 	struct buf *bp;		/* buffer containing directory block */
9564 	struct inode *dp;	/* inode for the directory being modified */
9565 	struct inode *ip;	/* inode for directory entry being removed */
9566 	int isrmdir;		/* indicates if doing RMDIR */
9567 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9568 {
9569 	int offset;
9570 	ufs_lbn_t lbn;
9571 	struct diradd *dap;
9572 	struct dirrem *dirrem;
9573 	struct pagedep *pagedep;
9574 	struct jremref *jremref;
9575 	struct jremref *dotremref;
9576 	struct jremref *dotdotremref;
9577 	struct vnode *dvp;
9578 	struct ufsmount *ump;
9579 
9580 	/*
9581 	 * Whiteouts have no deletion dependencies.
9582 	 */
9583 	if (ip == NULL)
9584 		panic("newdirrem: whiteout");
9585 	dvp = ITOV(dp);
9586 	ump = ITOUMP(dp);
9587 
9588 	/*
9589 	 * If the system is over its limit and our filesystem is
9590 	 * responsible for more than our share of that usage and
9591 	 * we are not a snapshot, request some inodedep cleanup.
9592 	 * Limiting the number of dirrem structures will also limit
9593 	 * the number of freefile and freeblks structures.
9594 	 */
9595 	ACQUIRE_LOCK(ump);
9596 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9597 		schedule_cleanup(UFSTOVFS(ump));
9598 	else
9599 		FREE_LOCK(ump);
9600 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9601 	    M_ZERO);
9602 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9603 	LIST_INIT(&dirrem->dm_jremrefhd);
9604 	LIST_INIT(&dirrem->dm_jwork);
9605 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9606 	dirrem->dm_oldinum = ip->i_number;
9607 	*prevdirremp = NULL;
9608 	/*
9609 	 * Allocate remove reference structures to track journal write
9610 	 * dependencies.  We will always have one for the link and
9611 	 * when doing directories we will always have one more for dot.
9612 	 * When renaming a directory we skip the dotdot link change so
9613 	 * this is not needed.
9614 	 */
9615 	jremref = dotremref = dotdotremref = NULL;
9616 	if (DOINGSUJ(dvp)) {
9617 		if (isrmdir) {
9618 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9619 			    ip->i_effnlink + 2);
9620 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9621 			    ip->i_effnlink + 1);
9622 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9623 			    dp->i_effnlink + 1);
9624 			dotdotremref->jr_state |= MKDIR_PARENT;
9625 		} else
9626 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9627 			    ip->i_effnlink + 1);
9628 	}
9629 	ACQUIRE_LOCK(ump);
9630 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9631 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9632 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9633 	    &pagedep);
9634 	dirrem->dm_pagedep = pagedep;
9635 	dirrem->dm_offset = offset;
9636 	/*
9637 	 * If we're renaming a .. link to a new directory, cancel any
9638 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9639 	 * the jremref is preserved for any potential diradd in this
9640 	 * location.  This can not coincide with a rmdir.
9641 	 */
9642 	if (I_OFFSET(dp) == DOTDOT_OFFSET) {
9643 		if (isrmdir)
9644 			panic("newdirrem: .. directory change during remove?");
9645 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9646 	}
9647 	/*
9648 	 * If we're removing a directory search for the .. dependency now and
9649 	 * cancel it.  Any pending journal work will be added to the dirrem
9650 	 * to be completed when the workitem remove completes.
9651 	 */
9652 	if (isrmdir)
9653 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9654 	/*
9655 	 * Check for a diradd dependency for the same directory entry.
9656 	 * If present, then both dependencies become obsolete and can
9657 	 * be de-allocated.
9658 	 */
9659 	dap = diradd_lookup(pagedep, offset);
9660 	if (dap == NULL) {
9661 		/*
9662 		 * Link the jremref structures into the dirrem so they are
9663 		 * written prior to the pagedep.
9664 		 */
9665 		if (jremref)
9666 			dirrem_journal(dirrem, jremref, dotremref,
9667 			    dotdotremref);
9668 		return (dirrem);
9669 	}
9670 	/*
9671 	 * Must be ATTACHED at this point.
9672 	 */
9673 	if ((dap->da_state & ATTACHED) == 0)
9674 		panic("newdirrem: not ATTACHED");
9675 	if (dap->da_newinum != ip->i_number)
9676 		panic("newdirrem: inum %ju should be %ju",
9677 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9678 	/*
9679 	 * If we are deleting a changed name that never made it to disk,
9680 	 * then return the dirrem describing the previous inode (which
9681 	 * represents the inode currently referenced from this entry on disk).
9682 	 */
9683 	if ((dap->da_state & DIRCHG) != 0) {
9684 		*prevdirremp = dap->da_previous;
9685 		dap->da_state &= ~DIRCHG;
9686 		dap->da_pagedep = pagedep;
9687 	}
9688 	/*
9689 	 * We are deleting an entry that never made it to disk.
9690 	 * Mark it COMPLETE so we can delete its inode immediately.
9691 	 */
9692 	dirrem->dm_state |= COMPLETE;
9693 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9694 #ifdef INVARIANTS
9695 	if (isrmdir == 0) {
9696 		struct worklist *wk;
9697 
9698 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9699 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9700 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9701 	}
9702 #endif
9703 
9704 	return (dirrem);
9705 }
9706 
9707 /*
9708  * Directory entry change dependencies.
9709  *
9710  * Changing an existing directory entry requires that an add operation
9711  * be completed first followed by a deletion. The semantics for the addition
9712  * are identical to the description of adding a new entry above except
9713  * that the rollback is to the old inode number rather than zero. Once
9714  * the addition dependency is completed, the removal is done as described
9715  * in the removal routine above.
9716  */
9717 
9718 /*
9719  * This routine should be called immediately after changing
9720  * a directory entry.  The inode's link count should not be
9721  * decremented by the calling procedure -- the soft updates
9722  * code will perform this task when it is safe.
9723  */
9724 void
9725 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9726 	struct buf *bp;		/* buffer containing directory block */
9727 	struct inode *dp;	/* inode for the directory being modified */
9728 	struct inode *ip;	/* inode for directory entry being removed */
9729 	ino_t newinum;		/* new inode number for changed entry */
9730 	int isrmdir;		/* indicates if doing RMDIR */
9731 {
9732 	int offset;
9733 	struct diradd *dap = NULL;
9734 	struct dirrem *dirrem, *prevdirrem;
9735 	struct pagedep *pagedep;
9736 	struct inodedep *inodedep;
9737 	struct jaddref *jaddref;
9738 	struct mount *mp;
9739 	struct ufsmount *ump;
9740 
9741 	mp = ITOVFS(dp);
9742 	ump = VFSTOUFS(mp);
9743 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9744 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9745 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9746 
9747 	/*
9748 	 * Whiteouts do not need diradd dependencies.
9749 	 */
9750 	if (newinum != UFS_WINO) {
9751 		dap = malloc(sizeof(struct diradd),
9752 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9753 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9754 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9755 		dap->da_offset = offset;
9756 		dap->da_newinum = newinum;
9757 		LIST_INIT(&dap->da_jwork);
9758 	}
9759 
9760 	/*
9761 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9762 	 */
9763 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9764 	pagedep = dirrem->dm_pagedep;
9765 	/*
9766 	 * The possible values for isrmdir:
9767 	 *	0 - non-directory file rename
9768 	 *	1 - directory rename within same directory
9769 	 *   inum - directory rename to new directory of given inode number
9770 	 * When renaming to a new directory, we are both deleting and
9771 	 * creating a new directory entry, so the link count on the new
9772 	 * directory should not change. Thus we do not need the followup
9773 	 * dirrem which is usually done in handle_workitem_remove. We set
9774 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9775 	 * followup dirrem.
9776 	 */
9777 	if (isrmdir > 1)
9778 		dirrem->dm_state |= DIRCHG;
9779 
9780 	/*
9781 	 * Whiteouts have no additional dependencies,
9782 	 * so just put the dirrem on the correct list.
9783 	 */
9784 	if (newinum == UFS_WINO) {
9785 		if ((dirrem->dm_state & COMPLETE) == 0) {
9786 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9787 			    dm_next);
9788 		} else {
9789 			dirrem->dm_dirinum = pagedep->pd_ino;
9790 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9791 				add_to_worklist(&dirrem->dm_list, 0);
9792 		}
9793 		FREE_LOCK(ump);
9794 		return;
9795 	}
9796 	/*
9797 	 * Add the dirrem to the inodedep's pending remove list for quick
9798 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9799 	 * will not fail.
9800 	 */
9801 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9802 		panic("softdep_setup_directory_change: Lost inodedep.");
9803 	dirrem->dm_state |= ONDEPLIST;
9804 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9805 
9806 	/*
9807 	 * If the COMPLETE flag is clear, then there were no active
9808 	 * entries and we want to roll back to the previous inode until
9809 	 * the new inode is committed to disk. If the COMPLETE flag is
9810 	 * set, then we have deleted an entry that never made it to disk.
9811 	 * If the entry we deleted resulted from a name change, then the old
9812 	 * inode reference still resides on disk. Any rollback that we do
9813 	 * needs to be to that old inode (returned to us in prevdirrem). If
9814 	 * the entry we deleted resulted from a create, then there is
9815 	 * no entry on the disk, so we want to roll back to zero rather
9816 	 * than the uncommitted inode. In either of the COMPLETE cases we
9817 	 * want to immediately free the unwritten and unreferenced inode.
9818 	 */
9819 	if ((dirrem->dm_state & COMPLETE) == 0) {
9820 		dap->da_previous = dirrem;
9821 	} else {
9822 		if (prevdirrem != NULL) {
9823 			dap->da_previous = prevdirrem;
9824 		} else {
9825 			dap->da_state &= ~DIRCHG;
9826 			dap->da_pagedep = pagedep;
9827 		}
9828 		dirrem->dm_dirinum = pagedep->pd_ino;
9829 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9830 			add_to_worklist(&dirrem->dm_list, 0);
9831 	}
9832 	/*
9833 	 * Lookup the jaddref for this journal entry.  We must finish
9834 	 * initializing it and make the diradd write dependent on it.
9835 	 * If we're not journaling, put it on the id_bufwait list if the
9836 	 * inode is not yet written. If it is written, do the post-inode
9837 	 * write processing to put it on the id_pendinghd list.
9838 	 */
9839 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9840 	if (MOUNTEDSUJ(mp)) {
9841 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9842 		    inoreflst);
9843 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9844 		    ("softdep_setup_directory_change: bad jaddref %p",
9845 		    jaddref));
9846 		jaddref->ja_diroff = I_OFFSET(dp);
9847 		jaddref->ja_diradd = dap;
9848 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9849 		    dap, da_pdlist);
9850 		add_to_journal(&jaddref->ja_list);
9851 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9852 		dap->da_state |= COMPLETE;
9853 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9854 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9855 	} else {
9856 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9857 		    dap, da_pdlist);
9858 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9859 	}
9860 	/*
9861 	 * If we're making a new name for a directory that has not been
9862 	 * committed when need to move the dot and dotdot references to
9863 	 * this new name.
9864 	 */
9865 	if (inodedep->id_mkdiradd && I_OFFSET(dp) != DOTDOT_OFFSET)
9866 		merge_diradd(inodedep, dap);
9867 	FREE_LOCK(ump);
9868 }
9869 
9870 /*
9871  * Called whenever the link count on an inode is changed.
9872  * It creates an inode dependency so that the new reference(s)
9873  * to the inode cannot be committed to disk until the updated
9874  * inode has been written.
9875  */
9876 void
9877 softdep_change_linkcnt(ip)
9878 	struct inode *ip;	/* the inode with the increased link count */
9879 {
9880 	struct inodedep *inodedep;
9881 	struct ufsmount *ump;
9882 
9883 	ump = ITOUMP(ip);
9884 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9885 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9886 	ACQUIRE_LOCK(ump);
9887 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9888 	if (ip->i_nlink < ip->i_effnlink)
9889 		panic("softdep_change_linkcnt: bad delta");
9890 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9891 	FREE_LOCK(ump);
9892 }
9893 
9894 /*
9895  * Attach a sbdep dependency to the superblock buf so that we can keep
9896  * track of the head of the linked list of referenced but unlinked inodes.
9897  */
9898 void
9899 softdep_setup_sbupdate(ump, fs, bp)
9900 	struct ufsmount *ump;
9901 	struct fs *fs;
9902 	struct buf *bp;
9903 {
9904 	struct sbdep *sbdep;
9905 	struct worklist *wk;
9906 
9907 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9908 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9909 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9910 		if (wk->wk_type == D_SBDEP)
9911 			break;
9912 	if (wk != NULL)
9913 		return;
9914 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9915 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9916 	sbdep->sb_fs = fs;
9917 	sbdep->sb_ump = ump;
9918 	ACQUIRE_LOCK(ump);
9919 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9920 	FREE_LOCK(ump);
9921 }
9922 
9923 /*
9924  * Return the first unlinked inodedep which is ready to be the head of the
9925  * list.  The inodedep and all those after it must have valid next pointers.
9926  */
9927 static struct inodedep *
9928 first_unlinked_inodedep(ump)
9929 	struct ufsmount *ump;
9930 {
9931 	struct inodedep *inodedep;
9932 	struct inodedep *idp;
9933 
9934 	LOCK_OWNED(ump);
9935 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9936 	    inodedep; inodedep = idp) {
9937 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9938 			return (NULL);
9939 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9940 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9941 			break;
9942 		if ((inodedep->id_state & UNLINKPREV) == 0)
9943 			break;
9944 	}
9945 	return (inodedep);
9946 }
9947 
9948 /*
9949  * Set the sujfree unlinked head pointer prior to writing a superblock.
9950  */
9951 static void
9952 initiate_write_sbdep(sbdep)
9953 	struct sbdep *sbdep;
9954 {
9955 	struct inodedep *inodedep;
9956 	struct fs *bpfs;
9957 	struct fs *fs;
9958 
9959 	bpfs = sbdep->sb_fs;
9960 	fs = sbdep->sb_ump->um_fs;
9961 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9962 	if (inodedep) {
9963 		fs->fs_sujfree = inodedep->id_ino;
9964 		inodedep->id_state |= UNLINKPREV;
9965 	} else
9966 		fs->fs_sujfree = 0;
9967 	bpfs->fs_sujfree = fs->fs_sujfree;
9968 	/*
9969 	 * Because we have made changes to the superblock, we need to
9970 	 * recompute its check-hash.
9971 	 */
9972 	bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9973 }
9974 
9975 /*
9976  * After a superblock is written determine whether it must be written again
9977  * due to a changing unlinked list head.
9978  */
9979 static int
9980 handle_written_sbdep(sbdep, bp)
9981 	struct sbdep *sbdep;
9982 	struct buf *bp;
9983 {
9984 	struct inodedep *inodedep;
9985 	struct fs *fs;
9986 
9987 	LOCK_OWNED(sbdep->sb_ump);
9988 	fs = sbdep->sb_fs;
9989 	/*
9990 	 * If the superblock doesn't match the in-memory list start over.
9991 	 */
9992 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9993 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9994 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9995 		bdirty(bp);
9996 		return (1);
9997 	}
9998 	WORKITEM_FREE(sbdep, D_SBDEP);
9999 	if (fs->fs_sujfree == 0)
10000 		return (0);
10001 	/*
10002 	 * Now that we have a record of this inode in stable store allow it
10003 	 * to be written to free up pending work.  Inodes may see a lot of
10004 	 * write activity after they are unlinked which we must not hold up.
10005 	 */
10006 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
10007 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
10008 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
10009 			    inodedep, inodedep->id_state);
10010 		if (inodedep->id_state & UNLINKONLIST)
10011 			break;
10012 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
10013 	}
10014 
10015 	return (0);
10016 }
10017 
10018 /*
10019  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
10020  */
10021 static void
10022 unlinked_inodedep(mp, inodedep)
10023 	struct mount *mp;
10024 	struct inodedep *inodedep;
10025 {
10026 	struct ufsmount *ump;
10027 
10028 	ump = VFSTOUFS(mp);
10029 	LOCK_OWNED(ump);
10030 	if (MOUNTEDSUJ(mp) == 0)
10031 		return;
10032 	ump->um_fs->fs_fmod = 1;
10033 	if (inodedep->id_state & UNLINKED)
10034 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
10035 	inodedep->id_state |= UNLINKED;
10036 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
10037 }
10038 
10039 /*
10040  * Remove an inodedep from the unlinked inodedep list.  This may require
10041  * disk writes if the inode has made it that far.
10042  */
10043 static void
10044 clear_unlinked_inodedep(inodedep)
10045 	struct inodedep *inodedep;
10046 {
10047 	struct ufs2_dinode *dip;
10048 	struct ufsmount *ump;
10049 	struct inodedep *idp;
10050 	struct inodedep *idn;
10051 	struct fs *fs, *bpfs;
10052 	struct buf *bp;
10053 	daddr_t dbn;
10054 	ino_t ino;
10055 	ino_t nino;
10056 	ino_t pino;
10057 	int error;
10058 
10059 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10060 	fs = ump->um_fs;
10061 	ino = inodedep->id_ino;
10062 	error = 0;
10063 	for (;;) {
10064 		LOCK_OWNED(ump);
10065 		KASSERT((inodedep->id_state & UNLINKED) != 0,
10066 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
10067 		    inodedep));
10068 		/*
10069 		 * If nothing has yet been written simply remove us from
10070 		 * the in memory list and return.  This is the most common
10071 		 * case where handle_workitem_remove() loses the final
10072 		 * reference.
10073 		 */
10074 		if ((inodedep->id_state & UNLINKLINKS) == 0)
10075 			break;
10076 		/*
10077 		 * If we have a NEXT pointer and no PREV pointer we can simply
10078 		 * clear NEXT's PREV and remove ourselves from the list.  Be
10079 		 * careful not to clear PREV if the superblock points at
10080 		 * next as well.
10081 		 */
10082 		idn = TAILQ_NEXT(inodedep, id_unlinked);
10083 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
10084 			if (idn && fs->fs_sujfree != idn->id_ino)
10085 				idn->id_state &= ~UNLINKPREV;
10086 			break;
10087 		}
10088 		/*
10089 		 * Here we have an inodedep which is actually linked into
10090 		 * the list.  We must remove it by forcing a write to the
10091 		 * link before us, whether it be the superblock or an inode.
10092 		 * Unfortunately the list may change while we're waiting
10093 		 * on the buf lock for either resource so we must loop until
10094 		 * we lock the right one.  If both the superblock and an
10095 		 * inode point to this inode we must clear the inode first
10096 		 * followed by the superblock.
10097 		 */
10098 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
10099 		pino = 0;
10100 		if (idp && (idp->id_state & UNLINKNEXT))
10101 			pino = idp->id_ino;
10102 		FREE_LOCK(ump);
10103 		if (pino == 0) {
10104 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
10105 			    (int)fs->fs_sbsize, 0, 0, 0);
10106 		} else {
10107 			dbn = fsbtodb(fs, ino_to_fsba(fs, pino));
10108 			error = ffs_breadz(ump, ump->um_devvp, dbn, dbn,
10109 			    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL,
10110 			    &bp);
10111 		}
10112 		ACQUIRE_LOCK(ump);
10113 		if (error)
10114 			break;
10115 		/* If the list has changed restart the loop. */
10116 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
10117 		nino = 0;
10118 		if (idp && (idp->id_state & UNLINKNEXT))
10119 			nino = idp->id_ino;
10120 		if (nino != pino ||
10121 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
10122 			FREE_LOCK(ump);
10123 			brelse(bp);
10124 			ACQUIRE_LOCK(ump);
10125 			continue;
10126 		}
10127 		nino = 0;
10128 		idn = TAILQ_NEXT(inodedep, id_unlinked);
10129 		if (idn)
10130 			nino = idn->id_ino;
10131 		/*
10132 		 * Remove us from the in memory list.  After this we cannot
10133 		 * access the inodedep.
10134 		 */
10135 		KASSERT((inodedep->id_state & UNLINKED) != 0,
10136 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
10137 		    inodedep));
10138 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
10139 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
10140 		FREE_LOCK(ump);
10141 		/*
10142 		 * The predecessor's next pointer is manually updated here
10143 		 * so that the NEXT flag is never cleared for an element
10144 		 * that is in the list.
10145 		 */
10146 		if (pino == 0) {
10147 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
10148 			bpfs = (struct fs *)bp->b_data;
10149 			ffs_oldfscompat_write(bpfs, ump);
10150 			softdep_setup_sbupdate(ump, bpfs, bp);
10151 			/*
10152 			 * Because we may have made changes to the superblock,
10153 			 * we need to recompute its check-hash.
10154 			 */
10155 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
10156 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
10157 			((struct ufs1_dinode *)bp->b_data +
10158 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
10159 		} else {
10160 			dip = (struct ufs2_dinode *)bp->b_data +
10161 			    ino_to_fsbo(fs, pino);
10162 			dip->di_freelink = nino;
10163 			ffs_update_dinode_ckhash(fs, dip);
10164 		}
10165 		/*
10166 		 * If the bwrite fails we have no recourse to recover.  The
10167 		 * filesystem is corrupted already.
10168 		 */
10169 		bwrite(bp);
10170 		ACQUIRE_LOCK(ump);
10171 		/*
10172 		 * If the superblock pointer still needs to be cleared force
10173 		 * a write here.
10174 		 */
10175 		if (fs->fs_sujfree == ino) {
10176 			FREE_LOCK(ump);
10177 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
10178 			    (int)fs->fs_sbsize, 0, 0, 0);
10179 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
10180 			bpfs = (struct fs *)bp->b_data;
10181 			ffs_oldfscompat_write(bpfs, ump);
10182 			softdep_setup_sbupdate(ump, bpfs, bp);
10183 			/*
10184 			 * Because we may have made changes to the superblock,
10185 			 * we need to recompute its check-hash.
10186 			 */
10187 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
10188 			bwrite(bp);
10189 			ACQUIRE_LOCK(ump);
10190 		}
10191 
10192 		if (fs->fs_sujfree != ino)
10193 			return;
10194 		panic("clear_unlinked_inodedep: Failed to clear free head");
10195 	}
10196 	if (inodedep->id_ino == fs->fs_sujfree)
10197 		panic("clear_unlinked_inodedep: Freeing head of free list");
10198 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
10199 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
10200 	return;
10201 }
10202 
10203 /*
10204  * This workitem decrements the inode's link count.
10205  * If the link count reaches zero, the file is removed.
10206  */
10207 static int
10208 handle_workitem_remove(dirrem, flags)
10209 	struct dirrem *dirrem;
10210 	int flags;
10211 {
10212 	struct inodedep *inodedep;
10213 	struct workhead dotdotwk;
10214 	struct worklist *wk;
10215 	struct ufsmount *ump;
10216 	struct mount *mp;
10217 	struct vnode *vp;
10218 	struct inode *ip;
10219 	ino_t oldinum;
10220 
10221 	if (dirrem->dm_state & ONWORKLIST)
10222 		panic("handle_workitem_remove: dirrem %p still on worklist",
10223 		    dirrem);
10224 	oldinum = dirrem->dm_oldinum;
10225 	mp = dirrem->dm_list.wk_mp;
10226 	ump = VFSTOUFS(mp);
10227 	flags |= LK_EXCLUSIVE;
10228 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ |
10229 	    FFSV_FORCEINODEDEP) != 0)
10230 		return (EBUSY);
10231 	ip = VTOI(vp);
10232 	MPASS(ip->i_mode != 0);
10233 	ACQUIRE_LOCK(ump);
10234 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
10235 		panic("handle_workitem_remove: lost inodedep");
10236 	if (dirrem->dm_state & ONDEPLIST)
10237 		LIST_REMOVE(dirrem, dm_inonext);
10238 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
10239 	    ("handle_workitem_remove:  Journal entries not written."));
10240 
10241 	/*
10242 	 * Move all dependencies waiting on the remove to complete
10243 	 * from the dirrem to the inode inowait list to be completed
10244 	 * after the inode has been updated and written to disk.
10245 	 *
10246 	 * Any marked MKDIR_PARENT are saved to be completed when the
10247 	 * dotdot ref is removed unless DIRCHG is specified.  For
10248 	 * directory change operations there will be no further
10249 	 * directory writes and the jsegdeps need to be moved along
10250 	 * with the rest to be completed when the inode is free or
10251 	 * stable in the inode free list.
10252 	 */
10253 	LIST_INIT(&dotdotwk);
10254 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
10255 		WORKLIST_REMOVE(wk);
10256 		if ((dirrem->dm_state & DIRCHG) == 0 &&
10257 		    wk->wk_state & MKDIR_PARENT) {
10258 			wk->wk_state &= ~MKDIR_PARENT;
10259 			WORKLIST_INSERT(&dotdotwk, wk);
10260 			continue;
10261 		}
10262 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
10263 	}
10264 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
10265 	/*
10266 	 * Normal file deletion.
10267 	 */
10268 	if ((dirrem->dm_state & RMDIR) == 0) {
10269 		ip->i_nlink--;
10270 		KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
10271 		    "%ju negative i_nlink %d", (intmax_t)ip->i_number,
10272 		    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 file delta");
10277 		if (ip->i_nlink == 0)
10278 			unlinked_inodedep(mp, inodedep);
10279 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10280 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10281 		    ("handle_workitem_remove: worklist not empty. %s",
10282 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
10283 		WORKITEM_FREE(dirrem, D_DIRREM);
10284 		FREE_LOCK(ump);
10285 		goto out;
10286 	}
10287 	/*
10288 	 * Directory deletion. Decrement reference count for both the
10289 	 * just deleted parent directory entry and the reference for ".".
10290 	 * Arrange to have the reference count on the parent decremented
10291 	 * to account for the loss of "..".
10292 	 */
10293 	ip->i_nlink -= 2;
10294 	KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
10295 	    "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
10296 	DIP_SET(ip, i_nlink, ip->i_nlink);
10297 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10298 	if (ip->i_nlink < ip->i_effnlink)
10299 		panic("handle_workitem_remove: bad dir delta");
10300 	if (ip->i_nlink == 0)
10301 		unlinked_inodedep(mp, inodedep);
10302 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10303 	/*
10304 	 * Rename a directory to a new parent. Since, we are both deleting
10305 	 * and creating a new directory entry, the link count on the new
10306 	 * directory should not change. Thus we skip the followup dirrem.
10307 	 */
10308 	if (dirrem->dm_state & DIRCHG) {
10309 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10310 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
10311 		WORKITEM_FREE(dirrem, D_DIRREM);
10312 		FREE_LOCK(ump);
10313 		goto out;
10314 	}
10315 	dirrem->dm_state = ONDEPLIST;
10316 	dirrem->dm_oldinum = dirrem->dm_dirinum;
10317 	/*
10318 	 * Place the dirrem on the parent's diremhd list.
10319 	 */
10320 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
10321 		panic("handle_workitem_remove: lost dir inodedep");
10322 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
10323 	/*
10324 	 * If the allocated inode has never been written to disk, then
10325 	 * the on-disk inode is zero'ed and we can remove the file
10326 	 * immediately.  When journaling if the inode has been marked
10327 	 * unlinked and not DEPCOMPLETE we know it can never be written.
10328 	 */
10329 	inodedep_lookup(mp, oldinum, 0, &inodedep);
10330 	if (inodedep == NULL ||
10331 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
10332 	    check_inode_unwritten(inodedep)) {
10333 		FREE_LOCK(ump);
10334 		vput(vp);
10335 		return handle_workitem_remove(dirrem, flags);
10336 	}
10337 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
10338 	FREE_LOCK(ump);
10339 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10340 out:
10341 	ffs_update(vp, 0);
10342 	vput(vp);
10343 	return (0);
10344 }
10345 
10346 /*
10347  * Inode de-allocation dependencies.
10348  *
10349  * When an inode's link count is reduced to zero, it can be de-allocated. We
10350  * found it convenient to postpone de-allocation until after the inode is
10351  * written to disk with its new link count (zero).  At this point, all of the
10352  * on-disk inode's block pointers are nullified and, with careful dependency
10353  * list ordering, all dependencies related to the inode will be satisfied and
10354  * the corresponding dependency structures de-allocated.  So, if/when the
10355  * inode is reused, there will be no mixing of old dependencies with new
10356  * ones.  This artificial dependency is set up by the block de-allocation
10357  * procedure above (softdep_setup_freeblocks) and completed by the
10358  * following procedure.
10359  */
10360 static void
10361 handle_workitem_freefile(freefile)
10362 	struct freefile *freefile;
10363 {
10364 	struct workhead wkhd;
10365 	struct fs *fs;
10366 	struct ufsmount *ump;
10367 	int error;
10368 #ifdef INVARIANTS
10369 	struct inodedep *idp;
10370 #endif
10371 
10372 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
10373 	fs = ump->um_fs;
10374 #ifdef INVARIANTS
10375 	ACQUIRE_LOCK(ump);
10376 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10377 	FREE_LOCK(ump);
10378 	if (error)
10379 		panic("handle_workitem_freefile: inodedep %p survived", idp);
10380 #endif
10381 	UFS_LOCK(ump);
10382 	fs->fs_pendinginodes -= 1;
10383 	UFS_UNLOCK(ump);
10384 	LIST_INIT(&wkhd);
10385 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10386 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10387 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10388 		softdep_error("handle_workitem_freefile", error);
10389 	ACQUIRE_LOCK(ump);
10390 	WORKITEM_FREE(freefile, D_FREEFILE);
10391 	FREE_LOCK(ump);
10392 }
10393 
10394 /*
10395  * Helper function which unlinks marker element from work list and returns
10396  * the next element on the list.
10397  */
10398 static __inline struct worklist *
10399 markernext(struct worklist *marker)
10400 {
10401 	struct worklist *next;
10402 
10403 	next = LIST_NEXT(marker, wk_list);
10404 	LIST_REMOVE(marker, wk_list);
10405 	return next;
10406 }
10407 
10408 /*
10409  * Disk writes.
10410  *
10411  * The dependency structures constructed above are most actively used when file
10412  * system blocks are written to disk.  No constraints are placed on when a
10413  * block can be written, but unsatisfied update dependencies are made safe by
10414  * modifying (or replacing) the source memory for the duration of the disk
10415  * write.  When the disk write completes, the memory block is again brought
10416  * up-to-date.
10417  *
10418  * In-core inode structure reclamation.
10419  *
10420  * Because there are a finite number of "in-core" inode structures, they are
10421  * reused regularly.  By transferring all inode-related dependencies to the
10422  * in-memory inode block and indexing them separately (via "inodedep"s), we
10423  * can allow "in-core" inode structures to be reused at any time and avoid
10424  * any increase in contention.
10425  *
10426  * Called just before entering the device driver to initiate a new disk I/O.
10427  * The buffer must be locked, thus, no I/O completion operations can occur
10428  * while we are manipulating its associated dependencies.
10429  */
10430 static void
10431 softdep_disk_io_initiation(bp)
10432 	struct buf *bp;		/* structure describing disk write to occur */
10433 {
10434 	struct worklist *wk;
10435 	struct worklist marker;
10436 	struct inodedep *inodedep;
10437 	struct freeblks *freeblks;
10438 	struct jblkdep *jblkdep;
10439 	struct newblk *newblk;
10440 	struct ufsmount *ump;
10441 
10442 	/*
10443 	 * We only care about write operations. There should never
10444 	 * be dependencies for reads.
10445 	 */
10446 	if (bp->b_iocmd != BIO_WRITE)
10447 		panic("softdep_disk_io_initiation: not write");
10448 
10449 	if (bp->b_vflags & BV_BKGRDINPROG)
10450 		panic("softdep_disk_io_initiation: Writing buffer with "
10451 		    "background write in progress: %p", bp);
10452 
10453 	ump = softdep_bp_to_mp(bp);
10454 	if (ump == NULL)
10455 		return;
10456 
10457 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10458 	PHOLD(curproc);			/* Don't swap out kernel stack */
10459 	ACQUIRE_LOCK(ump);
10460 	/*
10461 	 * Do any necessary pre-I/O processing.
10462 	 */
10463 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10464 	     wk = markernext(&marker)) {
10465 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10466 		switch (wk->wk_type) {
10467 		case D_PAGEDEP:
10468 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10469 			continue;
10470 
10471 		case D_INODEDEP:
10472 			inodedep = WK_INODEDEP(wk);
10473 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10474 				initiate_write_inodeblock_ufs1(inodedep, bp);
10475 			else
10476 				initiate_write_inodeblock_ufs2(inodedep, bp);
10477 			continue;
10478 
10479 		case D_INDIRDEP:
10480 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10481 			continue;
10482 
10483 		case D_BMSAFEMAP:
10484 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10485 			continue;
10486 
10487 		case D_JSEG:
10488 			WK_JSEG(wk)->js_buf = NULL;
10489 			continue;
10490 
10491 		case D_FREEBLKS:
10492 			freeblks = WK_FREEBLKS(wk);
10493 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10494 			/*
10495 			 * We have to wait for the freeblks to be journaled
10496 			 * before we can write an inodeblock with updated
10497 			 * pointers.  Be careful to arrange the marker so
10498 			 * we revisit the freeblks if it's not removed by
10499 			 * the first jwait().
10500 			 */
10501 			if (jblkdep != NULL) {
10502 				LIST_REMOVE(&marker, wk_list);
10503 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10504 				jwait(&jblkdep->jb_list, MNT_WAIT);
10505 			}
10506 			continue;
10507 		case D_ALLOCDIRECT:
10508 		case D_ALLOCINDIR:
10509 			/*
10510 			 * We have to wait for the jnewblk to be journaled
10511 			 * before we can write to a block if the contents
10512 			 * may be confused with an earlier file's indirect
10513 			 * at recovery time.  Handle the marker as described
10514 			 * above.
10515 			 */
10516 			newblk = WK_NEWBLK(wk);
10517 			if (newblk->nb_jnewblk != NULL &&
10518 			    indirblk_lookup(newblk->nb_list.wk_mp,
10519 			    newblk->nb_newblkno)) {
10520 				LIST_REMOVE(&marker, wk_list);
10521 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10522 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10523 			}
10524 			continue;
10525 
10526 		case D_SBDEP:
10527 			initiate_write_sbdep(WK_SBDEP(wk));
10528 			continue;
10529 
10530 		case D_MKDIR:
10531 		case D_FREEWORK:
10532 		case D_FREEDEP:
10533 		case D_JSEGDEP:
10534 			continue;
10535 
10536 		default:
10537 			panic("handle_disk_io_initiation: Unexpected type %s",
10538 			    TYPENAME(wk->wk_type));
10539 			/* NOTREACHED */
10540 		}
10541 	}
10542 	FREE_LOCK(ump);
10543 	PRELE(curproc);			/* Allow swapout of kernel stack */
10544 }
10545 
10546 /*
10547  * Called from within the procedure above to deal with unsatisfied
10548  * allocation dependencies in a directory. The buffer must be locked,
10549  * thus, no I/O completion operations can occur while we are
10550  * manipulating its associated dependencies.
10551  */
10552 static void
10553 initiate_write_filepage(pagedep, bp)
10554 	struct pagedep *pagedep;
10555 	struct buf *bp;
10556 {
10557 	struct jremref *jremref;
10558 	struct jmvref *jmvref;
10559 	struct dirrem *dirrem;
10560 	struct diradd *dap;
10561 	struct direct *ep;
10562 	int i;
10563 
10564 	if (pagedep->pd_state & IOSTARTED) {
10565 		/*
10566 		 * This can only happen if there is a driver that does not
10567 		 * understand chaining. Here biodone will reissue the call
10568 		 * to strategy for the incomplete buffers.
10569 		 */
10570 		printf("initiate_write_filepage: already started\n");
10571 		return;
10572 	}
10573 	pagedep->pd_state |= IOSTARTED;
10574 	/*
10575 	 * Wait for all journal remove dependencies to hit the disk.
10576 	 * We can not allow any potentially conflicting directory adds
10577 	 * to be visible before removes and rollback is too difficult.
10578 	 * The per-filesystem lock may be dropped and re-acquired, however
10579 	 * we hold the buf locked so the dependency can not go away.
10580 	 */
10581 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10582 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10583 			jwait(&jremref->jr_list, MNT_WAIT);
10584 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10585 		jwait(&jmvref->jm_list, MNT_WAIT);
10586 	for (i = 0; i < DAHASHSZ; i++) {
10587 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10588 			ep = (struct direct *)
10589 			    ((char *)bp->b_data + dap->da_offset);
10590 			if (ep->d_ino != dap->da_newinum)
10591 				panic("%s: dir inum %ju != new %ju",
10592 				    "initiate_write_filepage",
10593 				    (uintmax_t)ep->d_ino,
10594 				    (uintmax_t)dap->da_newinum);
10595 			if (dap->da_state & DIRCHG)
10596 				ep->d_ino = dap->da_previous->dm_oldinum;
10597 			else
10598 				ep->d_ino = 0;
10599 			dap->da_state &= ~ATTACHED;
10600 			dap->da_state |= UNDONE;
10601 		}
10602 	}
10603 }
10604 
10605 /*
10606  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10607  * Note that any bug fixes made to this routine must be done in the
10608  * version found below.
10609  *
10610  * Called from within the procedure above to deal with unsatisfied
10611  * allocation dependencies in an inodeblock. The buffer must be
10612  * locked, thus, no I/O completion operations can occur while we
10613  * are manipulating its associated dependencies.
10614  */
10615 static void
10616 initiate_write_inodeblock_ufs1(inodedep, bp)
10617 	struct inodedep *inodedep;
10618 	struct buf *bp;			/* The inode block */
10619 {
10620 	struct allocdirect *adp, *lastadp;
10621 	struct ufs1_dinode *dp;
10622 	struct ufs1_dinode *sip;
10623 	struct inoref *inoref;
10624 	struct ufsmount *ump;
10625 	struct fs *fs;
10626 	ufs_lbn_t i;
10627 #ifdef INVARIANTS
10628 	ufs_lbn_t prevlbn = 0;
10629 #endif
10630 	int deplist;
10631 
10632 	if (inodedep->id_state & IOSTARTED)
10633 		panic("initiate_write_inodeblock_ufs1: already started");
10634 	inodedep->id_state |= IOSTARTED;
10635 	fs = inodedep->id_fs;
10636 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10637 	LOCK_OWNED(ump);
10638 	dp = (struct ufs1_dinode *)bp->b_data +
10639 	    ino_to_fsbo(fs, inodedep->id_ino);
10640 
10641 	/*
10642 	 * If we're on the unlinked list but have not yet written our
10643 	 * next pointer initialize it here.
10644 	 */
10645 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10646 		struct inodedep *inon;
10647 
10648 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10649 		dp->di_freelink = inon ? inon->id_ino : 0;
10650 	}
10651 	/*
10652 	 * If the bitmap is not yet written, then the allocated
10653 	 * inode cannot be written to disk.
10654 	 */
10655 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10656 		if (inodedep->id_savedino1 != NULL)
10657 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10658 		FREE_LOCK(ump);
10659 		sip = malloc(sizeof(struct ufs1_dinode),
10660 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10661 		ACQUIRE_LOCK(ump);
10662 		inodedep->id_savedino1 = sip;
10663 		*inodedep->id_savedino1 = *dp;
10664 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10665 		dp->di_gen = inodedep->id_savedino1->di_gen;
10666 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10667 		return;
10668 	}
10669 	/*
10670 	 * If no dependencies, then there is nothing to roll back.
10671 	 */
10672 	inodedep->id_savedsize = dp->di_size;
10673 	inodedep->id_savedextsize = 0;
10674 	inodedep->id_savednlink = dp->di_nlink;
10675 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10676 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10677 		return;
10678 	/*
10679 	 * Revert the link count to that of the first unwritten journal entry.
10680 	 */
10681 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10682 	if (inoref)
10683 		dp->di_nlink = inoref->if_nlink;
10684 	/*
10685 	 * Set the dependencies to busy.
10686 	 */
10687 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10688 	     adp = TAILQ_NEXT(adp, ad_next)) {
10689 #ifdef INVARIANTS
10690 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10691 			panic("softdep_write_inodeblock: lbn order");
10692 		prevlbn = adp->ad_offset;
10693 		if (adp->ad_offset < UFS_NDADDR &&
10694 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10695 			panic("initiate_write_inodeblock_ufs1: "
10696 			    "direct pointer #%jd mismatch %d != %jd",
10697 			    (intmax_t)adp->ad_offset,
10698 			    dp->di_db[adp->ad_offset],
10699 			    (intmax_t)adp->ad_newblkno);
10700 		if (adp->ad_offset >= UFS_NDADDR &&
10701 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10702 			panic("initiate_write_inodeblock_ufs1: "
10703 			    "indirect pointer #%jd mismatch %d != %jd",
10704 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10705 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10706 			    (intmax_t)adp->ad_newblkno);
10707 		deplist |= 1 << adp->ad_offset;
10708 		if ((adp->ad_state & ATTACHED) == 0)
10709 			panic("initiate_write_inodeblock_ufs1: "
10710 			    "Unknown state 0x%x", adp->ad_state);
10711 #endif /* INVARIANTS */
10712 		adp->ad_state &= ~ATTACHED;
10713 		adp->ad_state |= UNDONE;
10714 	}
10715 	/*
10716 	 * The on-disk inode cannot claim to be any larger than the last
10717 	 * fragment that has been written. Otherwise, the on-disk inode
10718 	 * might have fragments that were not the last block in the file
10719 	 * which would corrupt the filesystem.
10720 	 */
10721 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10722 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10723 		if (adp->ad_offset >= UFS_NDADDR)
10724 			break;
10725 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10726 		/* keep going until hitting a rollback to a frag */
10727 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10728 			continue;
10729 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10730 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10731 #ifdef INVARIANTS
10732 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10733 				panic("initiate_write_inodeblock_ufs1: "
10734 				    "lost dep1");
10735 #endif /* INVARIANTS */
10736 			dp->di_db[i] = 0;
10737 		}
10738 		for (i = 0; i < UFS_NIADDR; i++) {
10739 #ifdef INVARIANTS
10740 			if (dp->di_ib[i] != 0 &&
10741 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10742 				panic("initiate_write_inodeblock_ufs1: "
10743 				    "lost dep2");
10744 #endif /* INVARIANTS */
10745 			dp->di_ib[i] = 0;
10746 		}
10747 		return;
10748 	}
10749 	/*
10750 	 * If we have zero'ed out the last allocated block of the file,
10751 	 * roll back the size to the last currently allocated block.
10752 	 * We know that this last allocated block is a full-sized as
10753 	 * we already checked for fragments in the loop above.
10754 	 */
10755 	if (lastadp != NULL &&
10756 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10757 		for (i = lastadp->ad_offset; i >= 0; i--)
10758 			if (dp->di_db[i] != 0)
10759 				break;
10760 		dp->di_size = (i + 1) * fs->fs_bsize;
10761 	}
10762 	/*
10763 	 * The only dependencies are for indirect blocks.
10764 	 *
10765 	 * The file size for indirect block additions is not guaranteed.
10766 	 * Such a guarantee would be non-trivial to achieve. The conventional
10767 	 * synchronous write implementation also does not make this guarantee.
10768 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10769 	 * can be over-estimated without destroying integrity when the file
10770 	 * moves into the indirect blocks (i.e., is large). If we want to
10771 	 * postpone fsck, we are stuck with this argument.
10772 	 */
10773 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10774 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10775 }
10776 
10777 /*
10778  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10779  * Note that any bug fixes made to this routine must be done in the
10780  * version found above.
10781  *
10782  * Called from within the procedure above to deal with unsatisfied
10783  * allocation dependencies in an inodeblock. The buffer must be
10784  * locked, thus, no I/O completion operations can occur while we
10785  * are manipulating its associated dependencies.
10786  */
10787 static void
10788 initiate_write_inodeblock_ufs2(inodedep, bp)
10789 	struct inodedep *inodedep;
10790 	struct buf *bp;			/* The inode block */
10791 {
10792 	struct allocdirect *adp, *lastadp;
10793 	struct ufs2_dinode *dp;
10794 	struct ufs2_dinode *sip;
10795 	struct inoref *inoref;
10796 	struct ufsmount *ump;
10797 	struct fs *fs;
10798 	ufs_lbn_t i;
10799 #ifdef INVARIANTS
10800 	ufs_lbn_t prevlbn = 0;
10801 #endif
10802 	int deplist;
10803 
10804 	if (inodedep->id_state & IOSTARTED)
10805 		panic("initiate_write_inodeblock_ufs2: already started");
10806 	inodedep->id_state |= IOSTARTED;
10807 	fs = inodedep->id_fs;
10808 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10809 	LOCK_OWNED(ump);
10810 	dp = (struct ufs2_dinode *)bp->b_data +
10811 	    ino_to_fsbo(fs, inodedep->id_ino);
10812 
10813 	/*
10814 	 * If we're on the unlinked list but have not yet written our
10815 	 * next pointer initialize it here.
10816 	 */
10817 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10818 		struct inodedep *inon;
10819 
10820 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10821 		dp->di_freelink = inon ? inon->id_ino : 0;
10822 		ffs_update_dinode_ckhash(fs, dp);
10823 	}
10824 	/*
10825 	 * If the bitmap is not yet written, then the allocated
10826 	 * inode cannot be written to disk.
10827 	 */
10828 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10829 		if (inodedep->id_savedino2 != NULL)
10830 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10831 		FREE_LOCK(ump);
10832 		sip = malloc(sizeof(struct ufs2_dinode),
10833 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10834 		ACQUIRE_LOCK(ump);
10835 		inodedep->id_savedino2 = sip;
10836 		*inodedep->id_savedino2 = *dp;
10837 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10838 		dp->di_gen = inodedep->id_savedino2->di_gen;
10839 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10840 		return;
10841 	}
10842 	/*
10843 	 * If no dependencies, then there is nothing to roll back.
10844 	 */
10845 	inodedep->id_savedsize = dp->di_size;
10846 	inodedep->id_savedextsize = dp->di_extsize;
10847 	inodedep->id_savednlink = dp->di_nlink;
10848 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10849 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10850 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10851 		return;
10852 	/*
10853 	 * Revert the link count to that of the first unwritten journal entry.
10854 	 */
10855 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10856 	if (inoref)
10857 		dp->di_nlink = inoref->if_nlink;
10858 
10859 	/*
10860 	 * Set the ext data dependencies to busy.
10861 	 */
10862 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10863 	     adp = TAILQ_NEXT(adp, ad_next)) {
10864 #ifdef INVARIANTS
10865 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10866 			panic("initiate_write_inodeblock_ufs2: lbn order");
10867 		prevlbn = adp->ad_offset;
10868 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10869 			panic("initiate_write_inodeblock_ufs2: "
10870 			    "ext pointer #%jd mismatch %jd != %jd",
10871 			    (intmax_t)adp->ad_offset,
10872 			    (intmax_t)dp->di_extb[adp->ad_offset],
10873 			    (intmax_t)adp->ad_newblkno);
10874 		deplist |= 1 << adp->ad_offset;
10875 		if ((adp->ad_state & ATTACHED) == 0)
10876 			panic("initiate_write_inodeblock_ufs2: Unknown "
10877 			    "state 0x%x", adp->ad_state);
10878 #endif /* INVARIANTS */
10879 		adp->ad_state &= ~ATTACHED;
10880 		adp->ad_state |= UNDONE;
10881 	}
10882 	/*
10883 	 * The on-disk inode cannot claim to be any larger than the last
10884 	 * fragment that has been written. Otherwise, the on-disk inode
10885 	 * might have fragments that were not the last block in the ext
10886 	 * data which would corrupt the filesystem.
10887 	 */
10888 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10889 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10890 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10891 		/* keep going until hitting a rollback to a frag */
10892 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10893 			continue;
10894 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10895 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10896 #ifdef INVARIANTS
10897 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10898 				panic("initiate_write_inodeblock_ufs2: "
10899 				    "lost dep1");
10900 #endif /* INVARIANTS */
10901 			dp->di_extb[i] = 0;
10902 		}
10903 		lastadp = NULL;
10904 		break;
10905 	}
10906 	/*
10907 	 * If we have zero'ed out the last allocated block of the ext
10908 	 * data, roll back the size to the last currently allocated block.
10909 	 * We know that this last allocated block is a full-sized as
10910 	 * we already checked for fragments in the loop above.
10911 	 */
10912 	if (lastadp != NULL &&
10913 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10914 		for (i = lastadp->ad_offset; i >= 0; i--)
10915 			if (dp->di_extb[i] != 0)
10916 				break;
10917 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10918 	}
10919 	/*
10920 	 * Set the file data dependencies to busy.
10921 	 */
10922 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10923 	     adp = TAILQ_NEXT(adp, ad_next)) {
10924 #ifdef INVARIANTS
10925 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10926 			panic("softdep_write_inodeblock: lbn order");
10927 		if ((adp->ad_state & ATTACHED) == 0)
10928 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10929 		prevlbn = adp->ad_offset;
10930 		if (!ffs_fsfail_cleanup(ump, 0) &&
10931 		    adp->ad_offset < UFS_NDADDR &&
10932 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10933 			panic("initiate_write_inodeblock_ufs2: "
10934 			    "direct pointer #%jd mismatch %jd != %jd",
10935 			    (intmax_t)adp->ad_offset,
10936 			    (intmax_t)dp->di_db[adp->ad_offset],
10937 			    (intmax_t)adp->ad_newblkno);
10938 		if (!ffs_fsfail_cleanup(ump, 0) &&
10939 		    adp->ad_offset >= UFS_NDADDR &&
10940 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10941 			panic("initiate_write_inodeblock_ufs2: "
10942 			    "indirect pointer #%jd mismatch %jd != %jd",
10943 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10944 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10945 			    (intmax_t)adp->ad_newblkno);
10946 		deplist |= 1 << adp->ad_offset;
10947 		if ((adp->ad_state & ATTACHED) == 0)
10948 			panic("initiate_write_inodeblock_ufs2: Unknown "
10949 			     "state 0x%x", adp->ad_state);
10950 #endif /* INVARIANTS */
10951 		adp->ad_state &= ~ATTACHED;
10952 		adp->ad_state |= UNDONE;
10953 	}
10954 	/*
10955 	 * The on-disk inode cannot claim to be any larger than the last
10956 	 * fragment that has been written. Otherwise, the on-disk inode
10957 	 * might have fragments that were not the last block in the file
10958 	 * which would corrupt the filesystem.
10959 	 */
10960 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10961 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10962 		if (adp->ad_offset >= UFS_NDADDR)
10963 			break;
10964 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10965 		/* keep going until hitting a rollback to a frag */
10966 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10967 			continue;
10968 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10969 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10970 #ifdef INVARIANTS
10971 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10972 				panic("initiate_write_inodeblock_ufs2: "
10973 				    "lost dep2");
10974 #endif /* INVARIANTS */
10975 			dp->di_db[i] = 0;
10976 		}
10977 		for (i = 0; i < UFS_NIADDR; i++) {
10978 #ifdef INVARIANTS
10979 			if (dp->di_ib[i] != 0 &&
10980 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10981 				panic("initiate_write_inodeblock_ufs2: "
10982 				    "lost dep3");
10983 #endif /* INVARIANTS */
10984 			dp->di_ib[i] = 0;
10985 		}
10986 		ffs_update_dinode_ckhash(fs, dp);
10987 		return;
10988 	}
10989 	/*
10990 	 * If we have zero'ed out the last allocated block of the file,
10991 	 * roll back the size to the last currently allocated block.
10992 	 * We know that this last allocated block is a full-sized as
10993 	 * we already checked for fragments in the loop above.
10994 	 */
10995 	if (lastadp != NULL &&
10996 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10997 		for (i = lastadp->ad_offset; i >= 0; i--)
10998 			if (dp->di_db[i] != 0)
10999 				break;
11000 		dp->di_size = (i + 1) * fs->fs_bsize;
11001 	}
11002 	/*
11003 	 * The only dependencies are for indirect blocks.
11004 	 *
11005 	 * The file size for indirect block additions is not guaranteed.
11006 	 * Such a guarantee would be non-trivial to achieve. The conventional
11007 	 * synchronous write implementation also does not make this guarantee.
11008 	 * Fsck should catch and fix discrepancies. Arguably, the file size
11009 	 * can be over-estimated without destroying integrity when the file
11010 	 * moves into the indirect blocks (i.e., is large). If we want to
11011 	 * postpone fsck, we are stuck with this argument.
11012 	 */
11013 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
11014 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
11015 	ffs_update_dinode_ckhash(fs, dp);
11016 }
11017 
11018 /*
11019  * Cancel an indirdep as a result of truncation.  Release all of the
11020  * children allocindirs and place their journal work on the appropriate
11021  * list.
11022  */
11023 static void
11024 cancel_indirdep(indirdep, bp, freeblks)
11025 	struct indirdep *indirdep;
11026 	struct buf *bp;
11027 	struct freeblks *freeblks;
11028 {
11029 	struct allocindir *aip;
11030 
11031 	/*
11032 	 * None of the indirect pointers will ever be visible,
11033 	 * so they can simply be tossed. GOINGAWAY ensures
11034 	 * that allocated pointers will be saved in the buffer
11035 	 * cache until they are freed. Note that they will
11036 	 * only be able to be found by their physical address
11037 	 * since the inode mapping the logical address will
11038 	 * be gone. The save buffer used for the safe copy
11039 	 * was allocated in setup_allocindir_phase2 using
11040 	 * the physical address so it could be used for this
11041 	 * purpose. Hence we swap the safe copy with the real
11042 	 * copy, allowing the safe copy to be freed and holding
11043 	 * on to the real copy for later use in indir_trunc.
11044 	 */
11045 	if (indirdep->ir_state & GOINGAWAY)
11046 		panic("cancel_indirdep: already gone");
11047 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11048 		indirdep->ir_state |= DEPCOMPLETE;
11049 		LIST_REMOVE(indirdep, ir_next);
11050 	}
11051 	indirdep->ir_state |= GOINGAWAY;
11052 	/*
11053 	 * Pass in bp for blocks still have journal writes
11054 	 * pending so we can cancel them on their own.
11055 	 */
11056 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
11057 		cancel_allocindir(aip, bp, freeblks, 0);
11058 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
11059 		cancel_allocindir(aip, NULL, freeblks, 0);
11060 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
11061 		cancel_allocindir(aip, NULL, freeblks, 0);
11062 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
11063 		cancel_allocindir(aip, NULL, freeblks, 0);
11064 	/*
11065 	 * If there are pending partial truncations we need to keep the
11066 	 * old block copy around until they complete.  This is because
11067 	 * the current b_data is not a perfect superset of the available
11068 	 * blocks.
11069 	 */
11070 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
11071 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
11072 	else
11073 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
11074 	WORKLIST_REMOVE(&indirdep->ir_list);
11075 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
11076 	indirdep->ir_bp = NULL;
11077 	indirdep->ir_freeblks = freeblks;
11078 }
11079 
11080 /*
11081  * Free an indirdep once it no longer has new pointers to track.
11082  */
11083 static void
11084 free_indirdep(indirdep)
11085 	struct indirdep *indirdep;
11086 {
11087 
11088 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
11089 	    ("free_indirdep: Indir trunc list not empty."));
11090 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
11091 	    ("free_indirdep: Complete head not empty."));
11092 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
11093 	    ("free_indirdep: write head not empty."));
11094 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
11095 	    ("free_indirdep: done head not empty."));
11096 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
11097 	    ("free_indirdep: deplist head not empty."));
11098 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
11099 	    ("free_indirdep: %p still on newblk list.", indirdep));
11100 	KASSERT(indirdep->ir_saveddata == NULL,
11101 	    ("free_indirdep: %p still has saved data.", indirdep));
11102 	KASSERT(indirdep->ir_savebp == NULL,
11103 	    ("free_indirdep: %p still has savebp buffer.", indirdep));
11104 	if (indirdep->ir_state & ONWORKLIST)
11105 		WORKLIST_REMOVE(&indirdep->ir_list);
11106 	WORKITEM_FREE(indirdep, D_INDIRDEP);
11107 }
11108 
11109 /*
11110  * Called before a write to an indirdep.  This routine is responsible for
11111  * rolling back pointers to a safe state which includes only those
11112  * allocindirs which have been completed.
11113  */
11114 static void
11115 initiate_write_indirdep(indirdep, bp)
11116 	struct indirdep *indirdep;
11117 	struct buf *bp;
11118 {
11119 	struct ufsmount *ump;
11120 
11121 	indirdep->ir_state |= IOSTARTED;
11122 	if (indirdep->ir_state & GOINGAWAY)
11123 		panic("disk_io_initiation: indirdep gone");
11124 	/*
11125 	 * If there are no remaining dependencies, this will be writing
11126 	 * the real pointers.
11127 	 */
11128 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
11129 	    TAILQ_EMPTY(&indirdep->ir_trunc))
11130 		return;
11131 	/*
11132 	 * Replace up-to-date version with safe version.
11133 	 */
11134 	if (indirdep->ir_saveddata == NULL) {
11135 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
11136 		LOCK_OWNED(ump);
11137 		FREE_LOCK(ump);
11138 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
11139 		    M_SOFTDEP_FLAGS);
11140 		ACQUIRE_LOCK(ump);
11141 	}
11142 	indirdep->ir_state &= ~ATTACHED;
11143 	indirdep->ir_state |= UNDONE;
11144 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
11145 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
11146 	    bp->b_bcount);
11147 }
11148 
11149 /*
11150  * Called when an inode has been cleared in a cg bitmap.  This finally
11151  * eliminates any canceled jaddrefs
11152  */
11153 void
11154 softdep_setup_inofree(mp, bp, ino, wkhd)
11155 	struct mount *mp;
11156 	struct buf *bp;
11157 	ino_t ino;
11158 	struct workhead *wkhd;
11159 {
11160 	struct worklist *wk, *wkn;
11161 	struct inodedep *inodedep;
11162 	struct ufsmount *ump;
11163 	uint8_t *inosused;
11164 	struct cg *cgp;
11165 	struct fs *fs;
11166 
11167 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
11168 	    ("softdep_setup_inofree called on non-softdep filesystem"));
11169 	ump = VFSTOUFS(mp);
11170 	ACQUIRE_LOCK(ump);
11171 	if (!ffs_fsfail_cleanup(ump, 0)) {
11172 		fs = ump->um_fs;
11173 		cgp = (struct cg *)bp->b_data;
11174 		inosused = cg_inosused(cgp);
11175 		if (isset(inosused, ino % fs->fs_ipg))
11176 			panic("softdep_setup_inofree: inode %ju not freed.",
11177 			    (uintmax_t)ino);
11178 	}
11179 	if (inodedep_lookup(mp, ino, 0, &inodedep))
11180 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
11181 		    (uintmax_t)ino, inodedep);
11182 	if (wkhd) {
11183 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
11184 			if (wk->wk_type != D_JADDREF)
11185 				continue;
11186 			WORKLIST_REMOVE(wk);
11187 			/*
11188 			 * We can free immediately even if the jaddref
11189 			 * isn't attached in a background write as now
11190 			 * the bitmaps are reconciled.
11191 			 */
11192 			wk->wk_state |= COMPLETE | ATTACHED;
11193 			free_jaddref(WK_JADDREF(wk));
11194 		}
11195 		jwork_move(&bp->b_dep, wkhd);
11196 	}
11197 	FREE_LOCK(ump);
11198 }
11199 
11200 /*
11201  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
11202  * map.  Any dependencies waiting for the write to clear are added to the
11203  * buf's list and any jnewblks that are being canceled are discarded
11204  * immediately.
11205  */
11206 void
11207 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
11208 	struct mount *mp;
11209 	struct buf *bp;
11210 	ufs2_daddr_t blkno;
11211 	int frags;
11212 	struct workhead *wkhd;
11213 {
11214 	struct bmsafemap *bmsafemap;
11215 	struct jnewblk *jnewblk;
11216 	struct ufsmount *ump;
11217 	struct worklist *wk;
11218 	struct fs *fs;
11219 #ifdef INVARIANTS
11220 	uint8_t *blksfree;
11221 	struct cg *cgp;
11222 	ufs2_daddr_t jstart;
11223 	ufs2_daddr_t jend;
11224 	ufs2_daddr_t end;
11225 	long bno;
11226 	int i;
11227 #endif
11228 
11229 	CTR3(KTR_SUJ,
11230 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
11231 	    blkno, frags, wkhd);
11232 
11233 	ump = VFSTOUFS(mp);
11234 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
11235 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
11236 	ACQUIRE_LOCK(ump);
11237 	/* Lookup the bmsafemap so we track when it is dirty. */
11238 	fs = ump->um_fs;
11239 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11240 	/*
11241 	 * Detach any jnewblks which have been canceled.  They must linger
11242 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
11243 	 * an unjournaled allocation from hitting the disk.
11244 	 */
11245 	if (wkhd) {
11246 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
11247 			CTR2(KTR_SUJ,
11248 			    "softdep_setup_blkfree: blkno %jd wk type %d",
11249 			    blkno, wk->wk_type);
11250 			WORKLIST_REMOVE(wk);
11251 			if (wk->wk_type != D_JNEWBLK) {
11252 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
11253 				continue;
11254 			}
11255 			jnewblk = WK_JNEWBLK(wk);
11256 			KASSERT(jnewblk->jn_state & GOINGAWAY,
11257 			    ("softdep_setup_blkfree: jnewblk not canceled."));
11258 #ifdef INVARIANTS
11259 			/*
11260 			 * Assert that this block is free in the bitmap
11261 			 * before we discard the jnewblk.
11262 			 */
11263 			cgp = (struct cg *)bp->b_data;
11264 			blksfree = cg_blksfree(cgp);
11265 			bno = dtogd(fs, jnewblk->jn_blkno);
11266 			for (i = jnewblk->jn_oldfrags;
11267 			    i < jnewblk->jn_frags; i++) {
11268 				if (isset(blksfree, bno + i))
11269 					continue;
11270 				panic("softdep_setup_blkfree: not free");
11271 			}
11272 #endif
11273 			/*
11274 			 * Even if it's not attached we can free immediately
11275 			 * as the new bitmap is correct.
11276 			 */
11277 			wk->wk_state |= COMPLETE | ATTACHED;
11278 			free_jnewblk(jnewblk);
11279 		}
11280 	}
11281 
11282 #ifdef INVARIANTS
11283 	/*
11284 	 * Assert that we are not freeing a block which has an outstanding
11285 	 * allocation dependency.
11286 	 */
11287 	fs = VFSTOUFS(mp)->um_fs;
11288 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11289 	end = blkno + frags;
11290 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11291 		/*
11292 		 * Don't match against blocks that will be freed when the
11293 		 * background write is done.
11294 		 */
11295 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
11296 		    (COMPLETE | DEPCOMPLETE))
11297 			continue;
11298 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
11299 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
11300 		if ((blkno >= jstart && blkno < jend) ||
11301 		    (end > jstart && end <= jend)) {
11302 			printf("state 0x%X %jd - %d %d dep %p\n",
11303 			    jnewblk->jn_state, jnewblk->jn_blkno,
11304 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
11305 			    jnewblk->jn_dep);
11306 			panic("softdep_setup_blkfree: "
11307 			    "%jd-%jd(%d) overlaps with %jd-%jd",
11308 			    blkno, end, frags, jstart, jend);
11309 		}
11310 	}
11311 #endif
11312 	FREE_LOCK(ump);
11313 }
11314 
11315 /*
11316  * Revert a block allocation when the journal record that describes it
11317  * is not yet written.
11318  */
11319 static int
11320 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
11321 	struct jnewblk *jnewblk;
11322 	struct fs *fs;
11323 	struct cg *cgp;
11324 	uint8_t *blksfree;
11325 {
11326 	ufs1_daddr_t fragno;
11327 	long cgbno, bbase;
11328 	int frags, blk;
11329 	int i;
11330 
11331 	frags = 0;
11332 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11333 	/*
11334 	 * We have to test which frags need to be rolled back.  We may
11335 	 * be operating on a stale copy when doing background writes.
11336 	 */
11337 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
11338 		if (isclr(blksfree, cgbno + i))
11339 			frags++;
11340 	if (frags == 0)
11341 		return (0);
11342 	/*
11343 	 * This is mostly ffs_blkfree() sans some validation and
11344 	 * superblock updates.
11345 	 */
11346 	if (frags == fs->fs_frag) {
11347 		fragno = fragstoblks(fs, cgbno);
11348 		ffs_setblock(fs, blksfree, fragno);
11349 		ffs_clusteracct(fs, cgp, fragno, 1);
11350 		cgp->cg_cs.cs_nbfree++;
11351 	} else {
11352 		cgbno += jnewblk->jn_oldfrags;
11353 		bbase = cgbno - fragnum(fs, cgbno);
11354 		/* Decrement the old frags.  */
11355 		blk = blkmap(fs, blksfree, bbase);
11356 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11357 		/* Deallocate the fragment */
11358 		for (i = 0; i < frags; i++)
11359 			setbit(blksfree, cgbno + i);
11360 		cgp->cg_cs.cs_nffree += frags;
11361 		/* Add back in counts associated with the new frags */
11362 		blk = blkmap(fs, blksfree, bbase);
11363 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11364 		/* If a complete block has been reassembled, account for it. */
11365 		fragno = fragstoblks(fs, bbase);
11366 		if (ffs_isblock(fs, blksfree, fragno)) {
11367 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
11368 			ffs_clusteracct(fs, cgp, fragno, 1);
11369 			cgp->cg_cs.cs_nbfree++;
11370 		}
11371 	}
11372 	stat_jnewblk++;
11373 	jnewblk->jn_state &= ~ATTACHED;
11374 	jnewblk->jn_state |= UNDONE;
11375 
11376 	return (frags);
11377 }
11378 
11379 static void
11380 initiate_write_bmsafemap(bmsafemap, bp)
11381 	struct bmsafemap *bmsafemap;
11382 	struct buf *bp;			/* The cg block. */
11383 {
11384 	struct jaddref *jaddref;
11385 	struct jnewblk *jnewblk;
11386 	uint8_t *inosused;
11387 	uint8_t *blksfree;
11388 	struct cg *cgp;
11389 	struct fs *fs;
11390 	ino_t ino;
11391 
11392 	/*
11393 	 * If this is a background write, we did this at the time that
11394 	 * the copy was made, so do not need to do it again.
11395 	 */
11396 	if (bmsafemap->sm_state & IOSTARTED)
11397 		return;
11398 	bmsafemap->sm_state |= IOSTARTED;
11399 	/*
11400 	 * Clear any inode allocations which are pending journal writes.
11401 	 */
11402 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11403 		cgp = (struct cg *)bp->b_data;
11404 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11405 		inosused = cg_inosused(cgp);
11406 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11407 			ino = jaddref->ja_ino % fs->fs_ipg;
11408 			if (isset(inosused, ino)) {
11409 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11410 					cgp->cg_cs.cs_ndir--;
11411 				cgp->cg_cs.cs_nifree++;
11412 				clrbit(inosused, ino);
11413 				jaddref->ja_state &= ~ATTACHED;
11414 				jaddref->ja_state |= UNDONE;
11415 				stat_jaddref++;
11416 			} else
11417 				panic("initiate_write_bmsafemap: inode %ju "
11418 				    "marked free", (uintmax_t)jaddref->ja_ino);
11419 		}
11420 	}
11421 	/*
11422 	 * Clear any block allocations which are pending journal writes.
11423 	 */
11424 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11425 		cgp = (struct cg *)bp->b_data;
11426 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11427 		blksfree = cg_blksfree(cgp);
11428 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11429 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11430 				continue;
11431 			panic("initiate_write_bmsafemap: block %jd "
11432 			    "marked free", jnewblk->jn_blkno);
11433 		}
11434 	}
11435 	/*
11436 	 * Move allocation lists to the written lists so they can be
11437 	 * cleared once the block write is complete.
11438 	 */
11439 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11440 	    inodedep, id_deps);
11441 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11442 	    newblk, nb_deps);
11443 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11444 	    wk_list);
11445 }
11446 
11447 void
11448 softdep_handle_error(struct buf *bp)
11449 {
11450 	struct ufsmount *ump;
11451 
11452 	ump = softdep_bp_to_mp(bp);
11453 	if (ump == NULL)
11454 		return;
11455 
11456 	if (ffs_fsfail_cleanup(ump, bp->b_error)) {
11457 		/*
11458 		 * No future writes will succeed, so the on-disk image is safe.
11459 		 * Pretend that this write succeeded so that the softdep state
11460 		 * will be cleaned up naturally.
11461 		 */
11462 		bp->b_ioflags &= ~BIO_ERROR;
11463 		bp->b_error = 0;
11464 	}
11465 }
11466 
11467 /*
11468  * This routine is called during the completion interrupt
11469  * service routine for a disk write (from the procedure called
11470  * by the device driver to inform the filesystem caches of
11471  * a request completion).  It should be called early in this
11472  * procedure, before the block is made available to other
11473  * processes or other routines are called.
11474  *
11475  */
11476 static void
11477 softdep_disk_write_complete(bp)
11478 	struct buf *bp;		/* describes the completed disk write */
11479 {
11480 	struct worklist *wk;
11481 	struct worklist *owk;
11482 	struct ufsmount *ump;
11483 	struct workhead reattach;
11484 	struct freeblks *freeblks;
11485 	struct buf *sbp;
11486 
11487 	ump = softdep_bp_to_mp(bp);
11488 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11489 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11490 	     "with outstanding dependencies for buffer %p", bp));
11491 	if (ump == NULL)
11492 		return;
11493 	if ((bp->b_ioflags & BIO_ERROR) != 0)
11494 		softdep_handle_error(bp);
11495 	/*
11496 	 * If an error occurred while doing the write, then the data
11497 	 * has not hit the disk and the dependencies cannot be processed.
11498 	 * But we do have to go through and roll forward any dependencies
11499 	 * that were rolled back before the disk write.
11500 	 */
11501 	sbp = NULL;
11502 	ACQUIRE_LOCK(ump);
11503 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11504 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11505 			switch (wk->wk_type) {
11506 			case D_PAGEDEP:
11507 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11508 				continue;
11509 
11510 			case D_INODEDEP:
11511 				handle_written_inodeblock(WK_INODEDEP(wk),
11512 				    bp, 0);
11513 				continue;
11514 
11515 			case D_BMSAFEMAP:
11516 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11517 				    bp, 0);
11518 				continue;
11519 
11520 			case D_INDIRDEP:
11521 				handle_written_indirdep(WK_INDIRDEP(wk),
11522 				    bp, &sbp, 0);
11523 				continue;
11524 			default:
11525 				/* nothing to roll forward */
11526 				continue;
11527 			}
11528 		}
11529 		FREE_LOCK(ump);
11530 		if (sbp)
11531 			brelse(sbp);
11532 		return;
11533 	}
11534 	LIST_INIT(&reattach);
11535 
11536 	/*
11537 	 * Ump SU lock must not be released anywhere in this code segment.
11538 	 */
11539 	owk = NULL;
11540 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11541 		WORKLIST_REMOVE(wk);
11542 		atomic_add_long(&dep_write[wk->wk_type], 1);
11543 		if (wk == owk)
11544 			panic("duplicate worklist: %p\n", wk);
11545 		owk = wk;
11546 		switch (wk->wk_type) {
11547 		case D_PAGEDEP:
11548 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11549 			    WRITESUCCEEDED))
11550 				WORKLIST_INSERT(&reattach, wk);
11551 			continue;
11552 
11553 		case D_INODEDEP:
11554 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11555 			    WRITESUCCEEDED))
11556 				WORKLIST_INSERT(&reattach, wk);
11557 			continue;
11558 
11559 		case D_BMSAFEMAP:
11560 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11561 			    WRITESUCCEEDED))
11562 				WORKLIST_INSERT(&reattach, wk);
11563 			continue;
11564 
11565 		case D_MKDIR:
11566 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11567 			continue;
11568 
11569 		case D_ALLOCDIRECT:
11570 			wk->wk_state |= COMPLETE;
11571 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11572 			continue;
11573 
11574 		case D_ALLOCINDIR:
11575 			wk->wk_state |= COMPLETE;
11576 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11577 			continue;
11578 
11579 		case D_INDIRDEP:
11580 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11581 			    WRITESUCCEEDED))
11582 				WORKLIST_INSERT(&reattach, wk);
11583 			continue;
11584 
11585 		case D_FREEBLKS:
11586 			wk->wk_state |= COMPLETE;
11587 			freeblks = WK_FREEBLKS(wk);
11588 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11589 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11590 				add_to_worklist(wk, WK_NODELAY);
11591 			continue;
11592 
11593 		case D_FREEWORK:
11594 			handle_written_freework(WK_FREEWORK(wk));
11595 			break;
11596 
11597 		case D_JSEGDEP:
11598 			free_jsegdep(WK_JSEGDEP(wk));
11599 			continue;
11600 
11601 		case D_JSEG:
11602 			handle_written_jseg(WK_JSEG(wk), bp);
11603 			continue;
11604 
11605 		case D_SBDEP:
11606 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11607 				WORKLIST_INSERT(&reattach, wk);
11608 			continue;
11609 
11610 		case D_FREEDEP:
11611 			free_freedep(WK_FREEDEP(wk));
11612 			continue;
11613 
11614 		default:
11615 			panic("handle_disk_write_complete: Unknown type %s",
11616 			    TYPENAME(wk->wk_type));
11617 			/* NOTREACHED */
11618 		}
11619 	}
11620 	/*
11621 	 * Reattach any requests that must be redone.
11622 	 */
11623 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11624 		WORKLIST_REMOVE(wk);
11625 		WORKLIST_INSERT(&bp->b_dep, wk);
11626 	}
11627 	FREE_LOCK(ump);
11628 	if (sbp)
11629 		brelse(sbp);
11630 }
11631 
11632 /*
11633  * Called from within softdep_disk_write_complete above.
11634  */
11635 static void
11636 handle_allocdirect_partdone(adp, wkhd)
11637 	struct allocdirect *adp;	/* the completed allocdirect */
11638 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11639 {
11640 	struct allocdirectlst *listhead;
11641 	struct allocdirect *listadp;
11642 	struct inodedep *inodedep;
11643 	long bsize;
11644 
11645 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11646 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11647 		return;
11648 	/*
11649 	 * The on-disk inode cannot claim to be any larger than the last
11650 	 * fragment that has been written. Otherwise, the on-disk inode
11651 	 * might have fragments that were not the last block in the file
11652 	 * which would corrupt the filesystem. Thus, we cannot free any
11653 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11654 	 * these blocks must be rolled back to zero before writing the inode.
11655 	 * We check the currently active set of allocdirects in id_inoupdt
11656 	 * or id_extupdt as appropriate.
11657 	 */
11658 	inodedep = adp->ad_inodedep;
11659 	bsize = inodedep->id_fs->fs_bsize;
11660 	if (adp->ad_state & EXTDATA)
11661 		listhead = &inodedep->id_extupdt;
11662 	else
11663 		listhead = &inodedep->id_inoupdt;
11664 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11665 		/* found our block */
11666 		if (listadp == adp)
11667 			break;
11668 		/* continue if ad_oldlbn is not a fragment */
11669 		if (listadp->ad_oldsize == 0 ||
11670 		    listadp->ad_oldsize == bsize)
11671 			continue;
11672 		/* hit a fragment */
11673 		return;
11674 	}
11675 	/*
11676 	 * If we have reached the end of the current list without
11677 	 * finding the just finished dependency, then it must be
11678 	 * on the future dependency list. Future dependencies cannot
11679 	 * be freed until they are moved to the current list.
11680 	 */
11681 	if (listadp == NULL) {
11682 #ifdef INVARIANTS
11683 		if (adp->ad_state & EXTDATA)
11684 			listhead = &inodedep->id_newextupdt;
11685 		else
11686 			listhead = &inodedep->id_newinoupdt;
11687 		TAILQ_FOREACH(listadp, listhead, ad_next)
11688 			/* found our block */
11689 			if (listadp == adp)
11690 				break;
11691 		if (listadp == NULL)
11692 			panic("handle_allocdirect_partdone: lost dep");
11693 #endif /* INVARIANTS */
11694 		return;
11695 	}
11696 	/*
11697 	 * If we have found the just finished dependency, then queue
11698 	 * it along with anything that follows it that is complete.
11699 	 * Since the pointer has not yet been written in the inode
11700 	 * as the dependency prevents it, place the allocdirect on the
11701 	 * bufwait list where it will be freed once the pointer is
11702 	 * valid.
11703 	 */
11704 	if (wkhd == NULL)
11705 		wkhd = &inodedep->id_bufwait;
11706 	for (; adp; adp = listadp) {
11707 		listadp = TAILQ_NEXT(adp, ad_next);
11708 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11709 			return;
11710 		TAILQ_REMOVE(listhead, adp, ad_next);
11711 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11712 	}
11713 }
11714 
11715 /*
11716  * Called from within softdep_disk_write_complete above.  This routine
11717  * completes successfully written allocindirs.
11718  */
11719 static void
11720 handle_allocindir_partdone(aip)
11721 	struct allocindir *aip;		/* the completed allocindir */
11722 {
11723 	struct indirdep *indirdep;
11724 
11725 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11726 		return;
11727 	indirdep = aip->ai_indirdep;
11728 	LIST_REMOVE(aip, ai_next);
11729 	/*
11730 	 * Don't set a pointer while the buffer is undergoing IO or while
11731 	 * we have active truncations.
11732 	 */
11733 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11734 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11735 		return;
11736 	}
11737 	if (indirdep->ir_state & UFS1FMT)
11738 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11739 		    aip->ai_newblkno;
11740 	else
11741 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11742 		    aip->ai_newblkno;
11743 	/*
11744 	 * Await the pointer write before freeing the allocindir.
11745 	 */
11746 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11747 }
11748 
11749 /*
11750  * Release segments held on a jwork list.
11751  */
11752 static void
11753 handle_jwork(wkhd)
11754 	struct workhead *wkhd;
11755 {
11756 	struct worklist *wk;
11757 
11758 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11759 		WORKLIST_REMOVE(wk);
11760 		switch (wk->wk_type) {
11761 		case D_JSEGDEP:
11762 			free_jsegdep(WK_JSEGDEP(wk));
11763 			continue;
11764 		case D_FREEDEP:
11765 			free_freedep(WK_FREEDEP(wk));
11766 			continue;
11767 		case D_FREEFRAG:
11768 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11769 			WORKITEM_FREE(wk, D_FREEFRAG);
11770 			continue;
11771 		case D_FREEWORK:
11772 			handle_written_freework(WK_FREEWORK(wk));
11773 			continue;
11774 		default:
11775 			panic("handle_jwork: Unknown type %s\n",
11776 			    TYPENAME(wk->wk_type));
11777 		}
11778 	}
11779 }
11780 
11781 /*
11782  * Handle the bufwait list on an inode when it is safe to release items
11783  * held there.  This normally happens after an inode block is written but
11784  * may be delayed and handled later if there are pending journal items that
11785  * are not yet safe to be released.
11786  */
11787 static struct freefile *
11788 handle_bufwait(inodedep, refhd)
11789 	struct inodedep *inodedep;
11790 	struct workhead *refhd;
11791 {
11792 	struct jaddref *jaddref;
11793 	struct freefile *freefile;
11794 	struct worklist *wk;
11795 
11796 	freefile = NULL;
11797 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11798 		WORKLIST_REMOVE(wk);
11799 		switch (wk->wk_type) {
11800 		case D_FREEFILE:
11801 			/*
11802 			 * We defer adding freefile to the worklist
11803 			 * until all other additions have been made to
11804 			 * ensure that it will be done after all the
11805 			 * old blocks have been freed.
11806 			 */
11807 			if (freefile != NULL)
11808 				panic("handle_bufwait: freefile");
11809 			freefile = WK_FREEFILE(wk);
11810 			continue;
11811 
11812 		case D_MKDIR:
11813 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11814 			continue;
11815 
11816 		case D_DIRADD:
11817 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11818 			continue;
11819 
11820 		case D_FREEFRAG:
11821 			wk->wk_state |= COMPLETE;
11822 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11823 				add_to_worklist(wk, 0);
11824 			continue;
11825 
11826 		case D_DIRREM:
11827 			wk->wk_state |= COMPLETE;
11828 			add_to_worklist(wk, 0);
11829 			continue;
11830 
11831 		case D_ALLOCDIRECT:
11832 		case D_ALLOCINDIR:
11833 			free_newblk(WK_NEWBLK(wk));
11834 			continue;
11835 
11836 		case D_JNEWBLK:
11837 			wk->wk_state |= COMPLETE;
11838 			free_jnewblk(WK_JNEWBLK(wk));
11839 			continue;
11840 
11841 		/*
11842 		 * Save freed journal segments and add references on
11843 		 * the supplied list which will delay their release
11844 		 * until the cg bitmap is cleared on disk.
11845 		 */
11846 		case D_JSEGDEP:
11847 			if (refhd == NULL)
11848 				free_jsegdep(WK_JSEGDEP(wk));
11849 			else
11850 				WORKLIST_INSERT(refhd, wk);
11851 			continue;
11852 
11853 		case D_JADDREF:
11854 			jaddref = WK_JADDREF(wk);
11855 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11856 			    if_deps);
11857 			/*
11858 			 * Transfer any jaddrefs to the list to be freed with
11859 			 * the bitmap if we're handling a removed file.
11860 			 */
11861 			if (refhd == NULL) {
11862 				wk->wk_state |= COMPLETE;
11863 				free_jaddref(jaddref);
11864 			} else
11865 				WORKLIST_INSERT(refhd, wk);
11866 			continue;
11867 
11868 		default:
11869 			panic("handle_bufwait: Unknown type %p(%s)",
11870 			    wk, TYPENAME(wk->wk_type));
11871 			/* NOTREACHED */
11872 		}
11873 	}
11874 	return (freefile);
11875 }
11876 /*
11877  * Called from within softdep_disk_write_complete above to restore
11878  * in-memory inode block contents to their most up-to-date state. Note
11879  * that this routine is always called from interrupt level with further
11880  * interrupts from this device blocked.
11881  *
11882  * If the write did not succeed, we will do all the roll-forward
11883  * operations, but we will not take the actions that will allow its
11884  * dependencies to be processed.
11885  */
11886 static int
11887 handle_written_inodeblock(inodedep, bp, flags)
11888 	struct inodedep *inodedep;
11889 	struct buf *bp;		/* buffer containing the inode block */
11890 	int flags;
11891 {
11892 	struct freefile *freefile;
11893 	struct allocdirect *adp, *nextadp;
11894 	struct ufs1_dinode *dp1 = NULL;
11895 	struct ufs2_dinode *dp2 = NULL;
11896 	struct workhead wkhd;
11897 	int hadchanges, fstype;
11898 	ino_t freelink;
11899 
11900 	LIST_INIT(&wkhd);
11901 	hadchanges = 0;
11902 	freefile = NULL;
11903 	if ((inodedep->id_state & IOSTARTED) == 0)
11904 		panic("handle_written_inodeblock: not started");
11905 	inodedep->id_state &= ~IOSTARTED;
11906 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11907 		fstype = UFS1;
11908 		dp1 = (struct ufs1_dinode *)bp->b_data +
11909 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11910 		freelink = dp1->di_freelink;
11911 	} else {
11912 		fstype = UFS2;
11913 		dp2 = (struct ufs2_dinode *)bp->b_data +
11914 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11915 		freelink = dp2->di_freelink;
11916 	}
11917 	/*
11918 	 * Leave this inodeblock dirty until it's in the list.
11919 	 */
11920 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11921 	    (flags & WRITESUCCEEDED)) {
11922 		struct inodedep *inon;
11923 
11924 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11925 		if ((inon == NULL && freelink == 0) ||
11926 		    (inon && inon->id_ino == freelink)) {
11927 			if (inon)
11928 				inon->id_state |= UNLINKPREV;
11929 			inodedep->id_state |= UNLINKNEXT;
11930 		}
11931 		hadchanges = 1;
11932 	}
11933 	/*
11934 	 * If we had to rollback the inode allocation because of
11935 	 * bitmaps being incomplete, then simply restore it.
11936 	 * Keep the block dirty so that it will not be reclaimed until
11937 	 * all associated dependencies have been cleared and the
11938 	 * corresponding updates written to disk.
11939 	 */
11940 	if (inodedep->id_savedino1 != NULL) {
11941 		hadchanges = 1;
11942 		if (fstype == UFS1)
11943 			*dp1 = *inodedep->id_savedino1;
11944 		else
11945 			*dp2 = *inodedep->id_savedino2;
11946 		free(inodedep->id_savedino1, M_SAVEDINO);
11947 		inodedep->id_savedino1 = NULL;
11948 		if ((bp->b_flags & B_DELWRI) == 0)
11949 			stat_inode_bitmap++;
11950 		bdirty(bp);
11951 		/*
11952 		 * If the inode is clear here and GOINGAWAY it will never
11953 		 * be written.  Process the bufwait and clear any pending
11954 		 * work which may include the freefile.
11955 		 */
11956 		if (inodedep->id_state & GOINGAWAY)
11957 			goto bufwait;
11958 		return (1);
11959 	}
11960 	if (flags & WRITESUCCEEDED)
11961 		inodedep->id_state |= COMPLETE;
11962 	/*
11963 	 * Roll forward anything that had to be rolled back before
11964 	 * the inode could be updated.
11965 	 */
11966 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11967 		nextadp = TAILQ_NEXT(adp, ad_next);
11968 		if (adp->ad_state & ATTACHED)
11969 			panic("handle_written_inodeblock: new entry");
11970 		if (fstype == UFS1) {
11971 			if (adp->ad_offset < UFS_NDADDR) {
11972 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11973 					panic("%s %s #%jd mismatch %d != %jd",
11974 					    "handle_written_inodeblock:",
11975 					    "direct pointer",
11976 					    (intmax_t)adp->ad_offset,
11977 					    dp1->di_db[adp->ad_offset],
11978 					    (intmax_t)adp->ad_oldblkno);
11979 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11980 			} else {
11981 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11982 				    0)
11983 					panic("%s: %s #%jd allocated as %d",
11984 					    "handle_written_inodeblock",
11985 					    "indirect pointer",
11986 					    (intmax_t)adp->ad_offset -
11987 					    UFS_NDADDR,
11988 					    dp1->di_ib[adp->ad_offset -
11989 					    UFS_NDADDR]);
11990 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11991 				    adp->ad_newblkno;
11992 			}
11993 		} else {
11994 			if (adp->ad_offset < UFS_NDADDR) {
11995 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11996 					panic("%s: %s #%jd %s %jd != %jd",
11997 					    "handle_written_inodeblock",
11998 					    "direct pointer",
11999 					    (intmax_t)adp->ad_offset, "mismatch",
12000 					    (intmax_t)dp2->di_db[adp->ad_offset],
12001 					    (intmax_t)adp->ad_oldblkno);
12002 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
12003 			} else {
12004 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
12005 				    0)
12006 					panic("%s: %s #%jd allocated as %jd",
12007 					    "handle_written_inodeblock",
12008 					    "indirect pointer",
12009 					    (intmax_t)adp->ad_offset -
12010 					    UFS_NDADDR,
12011 					    (intmax_t)
12012 					    dp2->di_ib[adp->ad_offset -
12013 					    UFS_NDADDR]);
12014 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
12015 				    adp->ad_newblkno;
12016 			}
12017 		}
12018 		adp->ad_state &= ~UNDONE;
12019 		adp->ad_state |= ATTACHED;
12020 		hadchanges = 1;
12021 	}
12022 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
12023 		nextadp = TAILQ_NEXT(adp, ad_next);
12024 		if (adp->ad_state & ATTACHED)
12025 			panic("handle_written_inodeblock: new entry");
12026 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
12027 			panic("%s: direct pointers #%jd %s %jd != %jd",
12028 			    "handle_written_inodeblock",
12029 			    (intmax_t)adp->ad_offset, "mismatch",
12030 			    (intmax_t)dp2->di_extb[adp->ad_offset],
12031 			    (intmax_t)adp->ad_oldblkno);
12032 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
12033 		adp->ad_state &= ~UNDONE;
12034 		adp->ad_state |= ATTACHED;
12035 		hadchanges = 1;
12036 	}
12037 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
12038 		stat_direct_blk_ptrs++;
12039 	/*
12040 	 * Reset the file size to its most up-to-date value.
12041 	 */
12042 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
12043 		panic("handle_written_inodeblock: bad size");
12044 	if (inodedep->id_savednlink > UFS_LINK_MAX)
12045 		panic("handle_written_inodeblock: Invalid link count "
12046 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
12047 		    inodedep);
12048 	if (fstype == UFS1) {
12049 		if (dp1->di_nlink != inodedep->id_savednlink) {
12050 			dp1->di_nlink = inodedep->id_savednlink;
12051 			hadchanges = 1;
12052 		}
12053 		if (dp1->di_size != inodedep->id_savedsize) {
12054 			dp1->di_size = inodedep->id_savedsize;
12055 			hadchanges = 1;
12056 		}
12057 	} else {
12058 		if (dp2->di_nlink != inodedep->id_savednlink) {
12059 			dp2->di_nlink = inodedep->id_savednlink;
12060 			hadchanges = 1;
12061 		}
12062 		if (dp2->di_size != inodedep->id_savedsize) {
12063 			dp2->di_size = inodedep->id_savedsize;
12064 			hadchanges = 1;
12065 		}
12066 		if (dp2->di_extsize != inodedep->id_savedextsize) {
12067 			dp2->di_extsize = inodedep->id_savedextsize;
12068 			hadchanges = 1;
12069 		}
12070 	}
12071 	inodedep->id_savedsize = -1;
12072 	inodedep->id_savedextsize = -1;
12073 	inodedep->id_savednlink = -1;
12074 	/*
12075 	 * If there were any rollbacks in the inode block, then it must be
12076 	 * marked dirty so that its will eventually get written back in
12077 	 * its correct form.
12078 	 */
12079 	if (hadchanges) {
12080 		if (fstype == UFS2)
12081 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
12082 		bdirty(bp);
12083 	}
12084 bufwait:
12085 	/*
12086 	 * If the write did not succeed, we have done all the roll-forward
12087 	 * operations, but we cannot take the actions that will allow its
12088 	 * dependencies to be processed.
12089 	 */
12090 	if ((flags & WRITESUCCEEDED) == 0)
12091 		return (hadchanges);
12092 	/*
12093 	 * Process any allocdirects that completed during the update.
12094 	 */
12095 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
12096 		handle_allocdirect_partdone(adp, &wkhd);
12097 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
12098 		handle_allocdirect_partdone(adp, &wkhd);
12099 	/*
12100 	 * Process deallocations that were held pending until the
12101 	 * inode had been written to disk. Freeing of the inode
12102 	 * is delayed until after all blocks have been freed to
12103 	 * avoid creation of new <vfsid, inum, lbn> triples
12104 	 * before the old ones have been deleted.  Completely
12105 	 * unlinked inodes are not processed until the unlinked
12106 	 * inode list is written or the last reference is removed.
12107 	 */
12108 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
12109 		freefile = handle_bufwait(inodedep, NULL);
12110 		if (freefile && !LIST_EMPTY(&wkhd)) {
12111 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
12112 			freefile = NULL;
12113 		}
12114 	}
12115 	/*
12116 	 * Move rolled forward dependency completions to the bufwait list
12117 	 * now that those that were already written have been processed.
12118 	 */
12119 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
12120 		panic("handle_written_inodeblock: bufwait but no changes");
12121 	jwork_move(&inodedep->id_bufwait, &wkhd);
12122 
12123 	if (freefile != NULL) {
12124 		/*
12125 		 * If the inode is goingaway it was never written.  Fake up
12126 		 * the state here so free_inodedep() can succeed.
12127 		 */
12128 		if (inodedep->id_state & GOINGAWAY)
12129 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
12130 		if (free_inodedep(inodedep) == 0)
12131 			panic("handle_written_inodeblock: live inodedep %p",
12132 			    inodedep);
12133 		add_to_worklist(&freefile->fx_list, 0);
12134 		return (0);
12135 	}
12136 
12137 	/*
12138 	 * If no outstanding dependencies, free it.
12139 	 */
12140 	if (free_inodedep(inodedep) ||
12141 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
12142 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
12143 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
12144 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
12145 		return (0);
12146 	return (hadchanges);
12147 }
12148 
12149 /*
12150  * Perform needed roll-forwards and kick off any dependencies that
12151  * can now be processed.
12152  *
12153  * If the write did not succeed, we will do all the roll-forward
12154  * operations, but we will not take the actions that will allow its
12155  * dependencies to be processed.
12156  */
12157 static int
12158 handle_written_indirdep(indirdep, bp, bpp, flags)
12159 	struct indirdep *indirdep;
12160 	struct buf *bp;
12161 	struct buf **bpp;
12162 	int flags;
12163 {
12164 	struct allocindir *aip;
12165 	struct buf *sbp;
12166 	int chgs;
12167 
12168 	if (indirdep->ir_state & GOINGAWAY)
12169 		panic("handle_written_indirdep: indirdep gone");
12170 	if ((indirdep->ir_state & IOSTARTED) == 0)
12171 		panic("handle_written_indirdep: IO not started");
12172 	chgs = 0;
12173 	/*
12174 	 * If there were rollbacks revert them here.
12175 	 */
12176 	if (indirdep->ir_saveddata) {
12177 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
12178 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
12179 			free(indirdep->ir_saveddata, M_INDIRDEP);
12180 			indirdep->ir_saveddata = NULL;
12181 		}
12182 		chgs = 1;
12183 	}
12184 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
12185 	indirdep->ir_state |= ATTACHED;
12186 	/*
12187 	 * If the write did not succeed, we have done all the roll-forward
12188 	 * operations, but we cannot take the actions that will allow its
12189 	 * dependencies to be processed.
12190 	 */
12191 	if ((flags & WRITESUCCEEDED) == 0) {
12192 		stat_indir_blk_ptrs++;
12193 		bdirty(bp);
12194 		return (1);
12195 	}
12196 	/*
12197 	 * Move allocindirs with written pointers to the completehd if
12198 	 * the indirdep's pointer is not yet written.  Otherwise
12199 	 * free them here.
12200 	 */
12201 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
12202 		LIST_REMOVE(aip, ai_next);
12203 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
12204 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
12205 			    ai_next);
12206 			newblk_freefrag(&aip->ai_block);
12207 			continue;
12208 		}
12209 		free_newblk(&aip->ai_block);
12210 	}
12211 	/*
12212 	 * Move allocindirs that have finished dependency processing from
12213 	 * the done list to the write list after updating the pointers.
12214 	 */
12215 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
12216 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
12217 			handle_allocindir_partdone(aip);
12218 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
12219 				panic("disk_write_complete: not gone");
12220 			chgs = 1;
12221 		}
12222 	}
12223 	/*
12224 	 * Preserve the indirdep if there were any changes or if it is not
12225 	 * yet valid on disk.
12226 	 */
12227 	if (chgs) {
12228 		stat_indir_blk_ptrs++;
12229 		bdirty(bp);
12230 		return (1);
12231 	}
12232 	/*
12233 	 * If there were no changes we can discard the savedbp and detach
12234 	 * ourselves from the buf.  We are only carrying completed pointers
12235 	 * in this case.
12236 	 */
12237 	sbp = indirdep->ir_savebp;
12238 	sbp->b_flags |= B_INVAL | B_NOCACHE;
12239 	indirdep->ir_savebp = NULL;
12240 	indirdep->ir_bp = NULL;
12241 	if (*bpp != NULL)
12242 		panic("handle_written_indirdep: bp already exists.");
12243 	*bpp = sbp;
12244 	/*
12245 	 * The indirdep may not be freed until its parent points at it.
12246 	 */
12247 	if (indirdep->ir_state & DEPCOMPLETE)
12248 		free_indirdep(indirdep);
12249 
12250 	return (0);
12251 }
12252 
12253 /*
12254  * Process a diradd entry after its dependent inode has been written.
12255  */
12256 static void
12257 diradd_inode_written(dap, inodedep)
12258 	struct diradd *dap;
12259 	struct inodedep *inodedep;
12260 {
12261 
12262 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
12263 	dap->da_state |= COMPLETE;
12264 	complete_diradd(dap);
12265 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
12266 }
12267 
12268 /*
12269  * Returns true if the bmsafemap will have rollbacks when written.  Must only
12270  * be called with the per-filesystem lock and the buf lock on the cg held.
12271  */
12272 static int
12273 bmsafemap_backgroundwrite(bmsafemap, bp)
12274 	struct bmsafemap *bmsafemap;
12275 	struct buf *bp;
12276 {
12277 	int dirty;
12278 
12279 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
12280 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
12281 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
12282 	/*
12283 	 * If we're initiating a background write we need to process the
12284 	 * rollbacks as they exist now, not as they exist when IO starts.
12285 	 * No other consumers will look at the contents of the shadowed
12286 	 * buf so this is safe to do here.
12287 	 */
12288 	if (bp->b_xflags & BX_BKGRDMARKER)
12289 		initiate_write_bmsafemap(bmsafemap, bp);
12290 
12291 	return (dirty);
12292 }
12293 
12294 /*
12295  * Re-apply an allocation when a cg write is complete.
12296  */
12297 static int
12298 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
12299 	struct jnewblk *jnewblk;
12300 	struct fs *fs;
12301 	struct cg *cgp;
12302 	uint8_t *blksfree;
12303 {
12304 	ufs1_daddr_t fragno;
12305 	ufs2_daddr_t blkno;
12306 	long cgbno, bbase;
12307 	int frags, blk;
12308 	int i;
12309 
12310 	frags = 0;
12311 	cgbno = dtogd(fs, jnewblk->jn_blkno);
12312 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
12313 		if (isclr(blksfree, cgbno + i))
12314 			panic("jnewblk_rollforward: re-allocated fragment");
12315 		frags++;
12316 	}
12317 	if (frags == fs->fs_frag) {
12318 		blkno = fragstoblks(fs, cgbno);
12319 		ffs_clrblock(fs, blksfree, (long)blkno);
12320 		ffs_clusteracct(fs, cgp, blkno, -1);
12321 		cgp->cg_cs.cs_nbfree--;
12322 	} else {
12323 		bbase = cgbno - fragnum(fs, cgbno);
12324 		cgbno += jnewblk->jn_oldfrags;
12325                 /* If a complete block had been reassembled, account for it. */
12326 		fragno = fragstoblks(fs, bbase);
12327 		if (ffs_isblock(fs, blksfree, fragno)) {
12328 			cgp->cg_cs.cs_nffree += fs->fs_frag;
12329 			ffs_clusteracct(fs, cgp, fragno, -1);
12330 			cgp->cg_cs.cs_nbfree--;
12331 		}
12332 		/* Decrement the old frags.  */
12333 		blk = blkmap(fs, blksfree, bbase);
12334 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
12335 		/* Allocate the fragment */
12336 		for (i = 0; i < frags; i++)
12337 			clrbit(blksfree, cgbno + i);
12338 		cgp->cg_cs.cs_nffree -= frags;
12339 		/* Add back in counts associated with the new frags */
12340 		blk = blkmap(fs, blksfree, bbase);
12341 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
12342 	}
12343 	return (frags);
12344 }
12345 
12346 /*
12347  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
12348  * changes if it's not a background write.  Set all written dependencies
12349  * to DEPCOMPLETE and free the structure if possible.
12350  *
12351  * If the write did not succeed, we will do all the roll-forward
12352  * operations, but we will not take the actions that will allow its
12353  * dependencies to be processed.
12354  */
12355 static int
12356 handle_written_bmsafemap(bmsafemap, bp, flags)
12357 	struct bmsafemap *bmsafemap;
12358 	struct buf *bp;
12359 	int flags;
12360 {
12361 	struct newblk *newblk;
12362 	struct inodedep *inodedep;
12363 	struct jaddref *jaddref, *jatmp;
12364 	struct jnewblk *jnewblk, *jntmp;
12365 	struct ufsmount *ump;
12366 	uint8_t *inosused;
12367 	uint8_t *blksfree;
12368 	struct cg *cgp;
12369 	struct fs *fs;
12370 	ino_t ino;
12371 	int foreground;
12372 	int chgs;
12373 
12374 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
12375 		panic("handle_written_bmsafemap: Not started\n");
12376 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
12377 	chgs = 0;
12378 	bmsafemap->sm_state &= ~IOSTARTED;
12379 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
12380 	/*
12381 	 * If write was successful, release journal work that was waiting
12382 	 * on the write. Otherwise move the work back.
12383 	 */
12384 	if (flags & WRITESUCCEEDED)
12385 		handle_jwork(&bmsafemap->sm_freewr);
12386 	else
12387 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12388 		    worklist, wk_list);
12389 
12390 	/*
12391 	 * Restore unwritten inode allocation pending jaddref writes.
12392 	 */
12393 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
12394 		cgp = (struct cg *)bp->b_data;
12395 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12396 		inosused = cg_inosused(cgp);
12397 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
12398 		    ja_bmdeps, jatmp) {
12399 			if ((jaddref->ja_state & UNDONE) == 0)
12400 				continue;
12401 			ino = jaddref->ja_ino % fs->fs_ipg;
12402 			if (isset(inosused, ino))
12403 				panic("handle_written_bmsafemap: "
12404 				    "re-allocated inode");
12405 			/* Do the roll-forward only if it's a real copy. */
12406 			if (foreground) {
12407 				if ((jaddref->ja_mode & IFMT) == IFDIR)
12408 					cgp->cg_cs.cs_ndir++;
12409 				cgp->cg_cs.cs_nifree--;
12410 				setbit(inosused, ino);
12411 				chgs = 1;
12412 			}
12413 			jaddref->ja_state &= ~UNDONE;
12414 			jaddref->ja_state |= ATTACHED;
12415 			free_jaddref(jaddref);
12416 		}
12417 	}
12418 	/*
12419 	 * Restore any block allocations which are pending journal writes.
12420 	 */
12421 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12422 		cgp = (struct cg *)bp->b_data;
12423 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12424 		blksfree = cg_blksfree(cgp);
12425 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12426 		    jntmp) {
12427 			if ((jnewblk->jn_state & UNDONE) == 0)
12428 				continue;
12429 			/* Do the roll-forward only if it's a real copy. */
12430 			if (foreground &&
12431 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12432 				chgs = 1;
12433 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12434 			jnewblk->jn_state |= ATTACHED;
12435 			free_jnewblk(jnewblk);
12436 		}
12437 	}
12438 	/*
12439 	 * If the write did not succeed, we have done all the roll-forward
12440 	 * operations, but we cannot take the actions that will allow its
12441 	 * dependencies to be processed.
12442 	 */
12443 	if ((flags & WRITESUCCEEDED) == 0) {
12444 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12445 		    newblk, nb_deps);
12446 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12447 		    worklist, wk_list);
12448 		if (foreground)
12449 			bdirty(bp);
12450 		return (1);
12451 	}
12452 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12453 		newblk->nb_state |= DEPCOMPLETE;
12454 		newblk->nb_state &= ~ONDEPLIST;
12455 		newblk->nb_bmsafemap = NULL;
12456 		LIST_REMOVE(newblk, nb_deps);
12457 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12458 			handle_allocdirect_partdone(
12459 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12460 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12461 			handle_allocindir_partdone(
12462 			    WK_ALLOCINDIR(&newblk->nb_list));
12463 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12464 			panic("handle_written_bmsafemap: Unexpected type: %s",
12465 			    TYPENAME(newblk->nb_list.wk_type));
12466 	}
12467 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12468 		inodedep->id_state |= DEPCOMPLETE;
12469 		inodedep->id_state &= ~ONDEPLIST;
12470 		LIST_REMOVE(inodedep, id_deps);
12471 		inodedep->id_bmsafemap = NULL;
12472 	}
12473 	LIST_REMOVE(bmsafemap, sm_next);
12474 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12475 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12476 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12477 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12478 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12479 		LIST_REMOVE(bmsafemap, sm_hash);
12480 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12481 		return (0);
12482 	}
12483 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12484 	if (foreground)
12485 		bdirty(bp);
12486 	return (1);
12487 }
12488 
12489 /*
12490  * Try to free a mkdir dependency.
12491  */
12492 static void
12493 complete_mkdir(mkdir)
12494 	struct mkdir *mkdir;
12495 {
12496 	struct diradd *dap;
12497 
12498 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12499 		return;
12500 	LIST_REMOVE(mkdir, md_mkdirs);
12501 	dap = mkdir->md_diradd;
12502 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12503 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12504 		dap->da_state |= DEPCOMPLETE;
12505 		complete_diradd(dap);
12506 	}
12507 	WORKITEM_FREE(mkdir, D_MKDIR);
12508 }
12509 
12510 /*
12511  * Handle the completion of a mkdir dependency.
12512  */
12513 static void
12514 handle_written_mkdir(mkdir, type)
12515 	struct mkdir *mkdir;
12516 	int type;
12517 {
12518 
12519 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12520 		panic("handle_written_mkdir: bad type");
12521 	mkdir->md_state |= COMPLETE;
12522 	complete_mkdir(mkdir);
12523 }
12524 
12525 static int
12526 free_pagedep(pagedep)
12527 	struct pagedep *pagedep;
12528 {
12529 	int i;
12530 
12531 	if (pagedep->pd_state & NEWBLOCK)
12532 		return (0);
12533 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12534 		return (0);
12535 	for (i = 0; i < DAHASHSZ; i++)
12536 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12537 			return (0);
12538 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12539 		return (0);
12540 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12541 		return (0);
12542 	if (pagedep->pd_state & ONWORKLIST)
12543 		WORKLIST_REMOVE(&pagedep->pd_list);
12544 	LIST_REMOVE(pagedep, pd_hash);
12545 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12546 
12547 	return (1);
12548 }
12549 
12550 /*
12551  * Called from within softdep_disk_write_complete above.
12552  * A write operation was just completed. Removed inodes can
12553  * now be freed and associated block pointers may be committed.
12554  * Note that this routine is always called from interrupt level
12555  * with further interrupts from this device blocked.
12556  *
12557  * If the write did not succeed, we will do all the roll-forward
12558  * operations, but we will not take the actions that will allow its
12559  * dependencies to be processed.
12560  */
12561 static int
12562 handle_written_filepage(pagedep, bp, flags)
12563 	struct pagedep *pagedep;
12564 	struct buf *bp;		/* buffer containing the written page */
12565 	int flags;
12566 {
12567 	struct dirrem *dirrem;
12568 	struct diradd *dap, *nextdap;
12569 	struct direct *ep;
12570 	int i, chgs;
12571 
12572 	if ((pagedep->pd_state & IOSTARTED) == 0)
12573 		panic("handle_written_filepage: not started");
12574 	pagedep->pd_state &= ~IOSTARTED;
12575 	if ((flags & WRITESUCCEEDED) == 0)
12576 		goto rollforward;
12577 	/*
12578 	 * Process any directory removals that have been committed.
12579 	 */
12580 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12581 		LIST_REMOVE(dirrem, dm_next);
12582 		dirrem->dm_state |= COMPLETE;
12583 		dirrem->dm_dirinum = pagedep->pd_ino;
12584 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12585 		    ("handle_written_filepage: Journal entries not written."));
12586 		add_to_worklist(&dirrem->dm_list, 0);
12587 	}
12588 	/*
12589 	 * Free any directory additions that have been committed.
12590 	 * If it is a newly allocated block, we have to wait until
12591 	 * the on-disk directory inode claims the new block.
12592 	 */
12593 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12594 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12595 			free_diradd(dap, NULL);
12596 rollforward:
12597 	/*
12598 	 * Uncommitted directory entries must be restored.
12599 	 */
12600 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12601 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12602 		     dap = nextdap) {
12603 			nextdap = LIST_NEXT(dap, da_pdlist);
12604 			if (dap->da_state & ATTACHED)
12605 				panic("handle_written_filepage: attached");
12606 			ep = (struct direct *)
12607 			    ((char *)bp->b_data + dap->da_offset);
12608 			ep->d_ino = dap->da_newinum;
12609 			dap->da_state &= ~UNDONE;
12610 			dap->da_state |= ATTACHED;
12611 			chgs = 1;
12612 			/*
12613 			 * If the inode referenced by the directory has
12614 			 * been written out, then the dependency can be
12615 			 * moved to the pending list.
12616 			 */
12617 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12618 				LIST_REMOVE(dap, da_pdlist);
12619 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12620 				    da_pdlist);
12621 			}
12622 		}
12623 	}
12624 	/*
12625 	 * If there were any rollbacks in the directory, then it must be
12626 	 * marked dirty so that its will eventually get written back in
12627 	 * its correct form.
12628 	 */
12629 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12630 		if ((bp->b_flags & B_DELWRI) == 0)
12631 			stat_dir_entry++;
12632 		bdirty(bp);
12633 		return (1);
12634 	}
12635 	/*
12636 	 * If we are not waiting for a new directory block to be
12637 	 * claimed by its inode, then the pagedep will be freed.
12638 	 * Otherwise it will remain to track any new entries on
12639 	 * the page in case they are fsync'ed.
12640 	 */
12641 	free_pagedep(pagedep);
12642 	return (0);
12643 }
12644 
12645 /*
12646  * Writing back in-core inode structures.
12647  *
12648  * The filesystem only accesses an inode's contents when it occupies an
12649  * "in-core" inode structure.  These "in-core" structures are separate from
12650  * the page frames used to cache inode blocks.  Only the latter are
12651  * transferred to/from the disk.  So, when the updated contents of the
12652  * "in-core" inode structure are copied to the corresponding in-memory inode
12653  * block, the dependencies are also transferred.  The following procedure is
12654  * called when copying a dirty "in-core" inode to a cached inode block.
12655  */
12656 
12657 /*
12658  * Called when an inode is loaded from disk. If the effective link count
12659  * differed from the actual link count when it was last flushed, then we
12660  * need to ensure that the correct effective link count is put back.
12661  */
12662 void
12663 softdep_load_inodeblock(ip)
12664 	struct inode *ip;	/* the "in_core" copy of the inode */
12665 {
12666 	struct inodedep *inodedep;
12667 	struct ufsmount *ump;
12668 
12669 	ump = ITOUMP(ip);
12670 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12671 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12672 	/*
12673 	 * Check for alternate nlink count.
12674 	 */
12675 	ip->i_effnlink = ip->i_nlink;
12676 	ACQUIRE_LOCK(ump);
12677 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12678 		FREE_LOCK(ump);
12679 		return;
12680 	}
12681 	if (ip->i_nlink != inodedep->id_nlinkwrote &&
12682 	    inodedep->id_nlinkwrote != -1) {
12683 		KASSERT(ip->i_nlink == 0 &&
12684 		    (ump->um_flags & UM_FSFAIL_CLEANUP) != 0,
12685 		    ("read bad i_nlink value"));
12686 		ip->i_effnlink = ip->i_nlink = inodedep->id_nlinkwrote;
12687 	}
12688 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12689 	KASSERT(ip->i_effnlink >= 0,
12690 	    ("softdep_load_inodeblock: negative i_effnlink"));
12691 	FREE_LOCK(ump);
12692 }
12693 
12694 /*
12695  * This routine is called just before the "in-core" inode
12696  * information is to be copied to the in-memory inode block.
12697  * Recall that an inode block contains several inodes. If
12698  * the force flag is set, then the dependencies will be
12699  * cleared so that the update can always be made. Note that
12700  * the buffer is locked when this routine is called, so we
12701  * will never be in the middle of writing the inode block
12702  * to disk.
12703  */
12704 void
12705 softdep_update_inodeblock(ip, bp, waitfor)
12706 	struct inode *ip;	/* the "in_core" copy of the inode */
12707 	struct buf *bp;		/* the buffer containing the inode block */
12708 	int waitfor;		/* nonzero => update must be allowed */
12709 {
12710 	struct inodedep *inodedep;
12711 	struct inoref *inoref;
12712 	struct ufsmount *ump;
12713 	struct worklist *wk;
12714 	struct mount *mp;
12715 	struct buf *ibp;
12716 	struct fs *fs;
12717 	int error;
12718 
12719 	ump = ITOUMP(ip);
12720 	mp = UFSTOVFS(ump);
12721 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12722 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12723 	fs = ump->um_fs;
12724 	/*
12725 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12726 	 * does not have access to the in-core ip so must write directly into
12727 	 * the inode block buffer when setting freelink.
12728 	 */
12729 	if (fs->fs_magic == FS_UFS1_MAGIC)
12730 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12731 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12732 	else
12733 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12734 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12735 	/*
12736 	 * If the effective link count is not equal to the actual link
12737 	 * count, then we must track the difference in an inodedep while
12738 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12739 	 * if there is no existing inodedep, then there are no dependencies
12740 	 * to track.
12741 	 */
12742 	ACQUIRE_LOCK(ump);
12743 again:
12744 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12745 		FREE_LOCK(ump);
12746 		if (ip->i_effnlink != ip->i_nlink)
12747 			panic("softdep_update_inodeblock: bad link count");
12748 		return;
12749 	}
12750 	KASSERT(ip->i_nlink >= inodedep->id_nlinkdelta,
12751 	    ("softdep_update_inodeblock inconsistent ip %p i_nlink %d "
12752 	    "inodedep %p id_nlinkdelta %jd",
12753 	    ip, ip->i_nlink, inodedep, (intmax_t)inodedep->id_nlinkdelta));
12754 	inodedep->id_nlinkwrote = ip->i_nlink;
12755 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12756 		panic("softdep_update_inodeblock: bad delta");
12757 	/*
12758 	 * If we're flushing all dependencies we must also move any waiting
12759 	 * for journal writes onto the bufwait list prior to I/O.
12760 	 */
12761 	if (waitfor) {
12762 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12763 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12764 			    == DEPCOMPLETE) {
12765 				jwait(&inoref->if_list, MNT_WAIT);
12766 				goto again;
12767 			}
12768 		}
12769 	}
12770 	/*
12771 	 * Changes have been initiated. Anything depending on these
12772 	 * changes cannot occur until this inode has been written.
12773 	 */
12774 	inodedep->id_state &= ~COMPLETE;
12775 	if ((inodedep->id_state & ONWORKLIST) == 0)
12776 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12777 	/*
12778 	 * Any new dependencies associated with the incore inode must
12779 	 * now be moved to the list associated with the buffer holding
12780 	 * the in-memory copy of the inode. Once merged process any
12781 	 * allocdirects that are completed by the merger.
12782 	 */
12783 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12784 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12785 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12786 		    NULL);
12787 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12788 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12789 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12790 		    NULL);
12791 	/*
12792 	 * Now that the inode has been pushed into the buffer, the
12793 	 * operations dependent on the inode being written to disk
12794 	 * can be moved to the id_bufwait so that they will be
12795 	 * processed when the buffer I/O completes.
12796 	 */
12797 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12798 		WORKLIST_REMOVE(wk);
12799 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12800 	}
12801 	/*
12802 	 * Newly allocated inodes cannot be written until the bitmap
12803 	 * that allocates them have been written (indicated by
12804 	 * DEPCOMPLETE being set in id_state). If we are doing a
12805 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12806 	 * to be written so that the update can be done.
12807 	 */
12808 	if (waitfor == 0) {
12809 		FREE_LOCK(ump);
12810 		return;
12811 	}
12812 retry:
12813 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12814 		FREE_LOCK(ump);
12815 		return;
12816 	}
12817 	ibp = inodedep->id_bmsafemap->sm_buf;
12818 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12819 	if (ibp == NULL) {
12820 		/*
12821 		 * If ibp came back as NULL, the dependency could have been
12822 		 * freed while we slept.  Look it up again, and check to see
12823 		 * that it has completed.
12824 		 */
12825 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12826 			goto retry;
12827 		FREE_LOCK(ump);
12828 		return;
12829 	}
12830 	FREE_LOCK(ump);
12831 	if ((error = bwrite(ibp)) != 0)
12832 		softdep_error("softdep_update_inodeblock: bwrite", error);
12833 }
12834 
12835 /*
12836  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12837  * old inode dependency list (such as id_inoupdt).
12838  */
12839 static void
12840 merge_inode_lists(newlisthead, oldlisthead)
12841 	struct allocdirectlst *newlisthead;
12842 	struct allocdirectlst *oldlisthead;
12843 {
12844 	struct allocdirect *listadp, *newadp;
12845 
12846 	newadp = TAILQ_FIRST(newlisthead);
12847 	if (newadp != NULL)
12848 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12849 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12850 		if (listadp->ad_offset < newadp->ad_offset) {
12851 			listadp = TAILQ_NEXT(listadp, ad_next);
12852 			continue;
12853 		}
12854 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12855 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12856 		if (listadp->ad_offset == newadp->ad_offset) {
12857 			allocdirect_merge(oldlisthead, newadp,
12858 			    listadp);
12859 			listadp = newadp;
12860 		}
12861 		newadp = TAILQ_FIRST(newlisthead);
12862 	}
12863 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12864 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12865 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12866 	}
12867 }
12868 
12869 /*
12870  * If we are doing an fsync, then we must ensure that any directory
12871  * entries for the inode have been written after the inode gets to disk.
12872  */
12873 int
12874 softdep_fsync(vp)
12875 	struct vnode *vp;	/* the "in_core" copy of the inode */
12876 {
12877 	struct inodedep *inodedep;
12878 	struct pagedep *pagedep;
12879 	struct inoref *inoref;
12880 	struct ufsmount *ump;
12881 	struct worklist *wk;
12882 	struct diradd *dap;
12883 	struct mount *mp;
12884 	struct vnode *pvp;
12885 	struct inode *ip;
12886 	struct buf *bp;
12887 	struct fs *fs;
12888 	struct thread *td = curthread;
12889 	int error, flushparent, pagedep_new_block;
12890 	ino_t parentino;
12891 	ufs_lbn_t lbn;
12892 
12893 	ip = VTOI(vp);
12894 	mp = vp->v_mount;
12895 	ump = VFSTOUFS(mp);
12896 	fs = ump->um_fs;
12897 	if (MOUNTEDSOFTDEP(mp) == 0)
12898 		return (0);
12899 	ACQUIRE_LOCK(ump);
12900 restart:
12901 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12902 		FREE_LOCK(ump);
12903 		return (0);
12904 	}
12905 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12906 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12907 		    == DEPCOMPLETE) {
12908 			jwait(&inoref->if_list, MNT_WAIT);
12909 			goto restart;
12910 		}
12911 	}
12912 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12913 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12914 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12915 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12916 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12917 		panic("softdep_fsync: pending ops %p", inodedep);
12918 	for (error = 0, flushparent = 0; ; ) {
12919 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12920 			break;
12921 		if (wk->wk_type != D_DIRADD)
12922 			panic("softdep_fsync: Unexpected type %s",
12923 			    TYPENAME(wk->wk_type));
12924 		dap = WK_DIRADD(wk);
12925 		/*
12926 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12927 		 * dependency or is contained in a newly allocated block.
12928 		 */
12929 		if (dap->da_state & DIRCHG)
12930 			pagedep = dap->da_previous->dm_pagedep;
12931 		else
12932 			pagedep = dap->da_pagedep;
12933 		parentino = pagedep->pd_ino;
12934 		lbn = pagedep->pd_lbn;
12935 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12936 			panic("softdep_fsync: dirty");
12937 		if ((dap->da_state & MKDIR_PARENT) ||
12938 		    (pagedep->pd_state & NEWBLOCK))
12939 			flushparent = 1;
12940 		else
12941 			flushparent = 0;
12942 		/*
12943 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12944 		 * then we will not be able to release and recover the
12945 		 * vnode below, so we just have to give up on writing its
12946 		 * directory entry out. It will eventually be written, just
12947 		 * not now, but then the user was not asking to have it
12948 		 * written, so we are not breaking any promises.
12949 		 */
12950 		if (VN_IS_DOOMED(vp))
12951 			break;
12952 		/*
12953 		 * We prevent deadlock by always fetching inodes from the
12954 		 * root, moving down the directory tree. Thus, when fetching
12955 		 * our parent directory, we first try to get the lock. If
12956 		 * that fails, we must unlock ourselves before requesting
12957 		 * the lock on our parent. See the comment in ufs_lookup
12958 		 * for details on possible races.
12959 		 */
12960 		FREE_LOCK(ump);
12961 		error = get_parent_vp(vp, mp, parentino, NULL, NULL, NULL,
12962 		    &pvp);
12963 		if (error == ERELOOKUP)
12964 			error = 0;
12965 		if (error != 0)
12966 			return (error);
12967 		/*
12968 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12969 		 * that are contained in direct blocks will be resolved by
12970 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12971 		 * may require a complete sync'ing of the directory. So, we
12972 		 * try the cheap and fast ffs_update first, and if that fails,
12973 		 * then we do the slower ffs_syncvnode of the directory.
12974 		 */
12975 		if (flushparent) {
12976 			int locked;
12977 
12978 			if ((error = ffs_update(pvp, 1)) != 0) {
12979 				vput(pvp);
12980 				return (error);
12981 			}
12982 			ACQUIRE_LOCK(ump);
12983 			locked = 1;
12984 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12985 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12986 					if (wk->wk_type != D_DIRADD)
12987 						panic("softdep_fsync: Unexpected type %s",
12988 						      TYPENAME(wk->wk_type));
12989 					dap = WK_DIRADD(wk);
12990 					if (dap->da_state & DIRCHG)
12991 						pagedep = dap->da_previous->dm_pagedep;
12992 					else
12993 						pagedep = dap->da_pagedep;
12994 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12995 					FREE_LOCK(ump);
12996 					locked = 0;
12997 					if (pagedep_new_block && (error =
12998 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12999 						vput(pvp);
13000 						return (error);
13001 					}
13002 				}
13003 			}
13004 			if (locked)
13005 				FREE_LOCK(ump);
13006 		}
13007 		/*
13008 		 * Flush directory page containing the inode's name.
13009 		 */
13010 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
13011 		    &bp);
13012 		if (error == 0)
13013 			error = bwrite(bp);
13014 		else
13015 			brelse(bp);
13016 		vput(pvp);
13017 		if (!ffs_fsfail_cleanup(ump, error))
13018 			return (error);
13019 		ACQUIRE_LOCK(ump);
13020 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
13021 			break;
13022 	}
13023 	FREE_LOCK(ump);
13024 	return (0);
13025 }
13026 
13027 /*
13028  * Flush all the dirty bitmaps associated with the block device
13029  * before flushing the rest of the dirty blocks so as to reduce
13030  * the number of dependencies that will have to be rolled back.
13031  *
13032  * XXX Unused?
13033  */
13034 void
13035 softdep_fsync_mountdev(vp)
13036 	struct vnode *vp;
13037 {
13038 	struct buf *bp, *nbp;
13039 	struct worklist *wk;
13040 	struct bufobj *bo;
13041 
13042 	if (!vn_isdisk(vp))
13043 		panic("softdep_fsync_mountdev: vnode not a disk");
13044 	bo = &vp->v_bufobj;
13045 restart:
13046 	BO_LOCK(bo);
13047 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
13048 		/*
13049 		 * If it is already scheduled, skip to the next buffer.
13050 		 */
13051 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
13052 			continue;
13053 
13054 		if ((bp->b_flags & B_DELWRI) == 0)
13055 			panic("softdep_fsync_mountdev: not dirty");
13056 		/*
13057 		 * We are only interested in bitmaps with outstanding
13058 		 * dependencies.
13059 		 */
13060 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
13061 		    wk->wk_type != D_BMSAFEMAP ||
13062 		    (bp->b_vflags & BV_BKGRDINPROG)) {
13063 			BUF_UNLOCK(bp);
13064 			continue;
13065 		}
13066 		BO_UNLOCK(bo);
13067 		bremfree(bp);
13068 		(void) bawrite(bp);
13069 		goto restart;
13070 	}
13071 	drain_output(vp);
13072 	BO_UNLOCK(bo);
13073 }
13074 
13075 /*
13076  * Sync all cylinder groups that were dirty at the time this function is
13077  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
13078  * is used to flush freedep activity that may be holding up writes to a
13079  * indirect block.
13080  */
13081 static int
13082 sync_cgs(mp, waitfor)
13083 	struct mount *mp;
13084 	int waitfor;
13085 {
13086 	struct bmsafemap *bmsafemap;
13087 	struct bmsafemap *sentinel;
13088 	struct ufsmount *ump;
13089 	struct buf *bp;
13090 	int error;
13091 
13092 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
13093 	sentinel->sm_cg = -1;
13094 	ump = VFSTOUFS(mp);
13095 	error = 0;
13096 	ACQUIRE_LOCK(ump);
13097 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
13098 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
13099 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
13100 		/* Skip sentinels and cgs with no work to release. */
13101 		if (bmsafemap->sm_cg == -1 ||
13102 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
13103 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
13104 			LIST_REMOVE(sentinel, sm_next);
13105 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
13106 			continue;
13107 		}
13108 		/*
13109 		 * If we don't get the lock and we're waiting try again, if
13110 		 * not move on to the next buf and try to sync it.
13111 		 */
13112 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
13113 		if (bp == NULL && waitfor == MNT_WAIT)
13114 			continue;
13115 		LIST_REMOVE(sentinel, sm_next);
13116 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
13117 		if (bp == NULL)
13118 			continue;
13119 		FREE_LOCK(ump);
13120 		if (waitfor == MNT_NOWAIT)
13121 			bawrite(bp);
13122 		else
13123 			error = bwrite(bp);
13124 		ACQUIRE_LOCK(ump);
13125 		if (error)
13126 			break;
13127 	}
13128 	LIST_REMOVE(sentinel, sm_next);
13129 	FREE_LOCK(ump);
13130 	free(sentinel, M_BMSAFEMAP);
13131 	return (error);
13132 }
13133 
13134 /*
13135  * This routine is called when we are trying to synchronously flush a
13136  * file. This routine must eliminate any filesystem metadata dependencies
13137  * so that the syncing routine can succeed.
13138  */
13139 int
13140 softdep_sync_metadata(struct vnode *vp)
13141 {
13142 	struct inode *ip;
13143 	int error;
13144 
13145 	ip = VTOI(vp);
13146 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13147 	    ("softdep_sync_metadata called on non-softdep filesystem"));
13148 	/*
13149 	 * Ensure that any direct block dependencies have been cleared,
13150 	 * truncations are started, and inode references are journaled.
13151 	 */
13152 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
13153 	/*
13154 	 * Write all journal records to prevent rollbacks on devvp.
13155 	 */
13156 	if (vp->v_type == VCHR)
13157 		softdep_flushjournal(vp->v_mount);
13158 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
13159 	/*
13160 	 * Ensure that all truncates are written so we won't find deps on
13161 	 * indirect blocks.
13162 	 */
13163 	process_truncates(vp);
13164 	FREE_LOCK(VFSTOUFS(vp->v_mount));
13165 
13166 	return (error);
13167 }
13168 
13169 /*
13170  * This routine is called when we are attempting to sync a buf with
13171  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
13172  * other IO it can but returns EBUSY if the buffer is not yet able to
13173  * be written.  Dependencies which will not cause rollbacks will always
13174  * return 0.
13175  */
13176 int
13177 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
13178 {
13179 	struct indirdep *indirdep;
13180 	struct pagedep *pagedep;
13181 	struct allocindir *aip;
13182 	struct newblk *newblk;
13183 	struct ufsmount *ump;
13184 	struct buf *nbp;
13185 	struct worklist *wk;
13186 	int i, error;
13187 
13188 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13189 	    ("softdep_sync_buf called on non-softdep filesystem"));
13190 	/*
13191 	 * For VCHR we just don't want to force flush any dependencies that
13192 	 * will cause rollbacks.
13193 	 */
13194 	if (vp->v_type == VCHR) {
13195 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
13196 			return (EBUSY);
13197 		return (0);
13198 	}
13199 	ump = VFSTOUFS(vp->v_mount);
13200 	ACQUIRE_LOCK(ump);
13201 	/*
13202 	 * As we hold the buffer locked, none of its dependencies
13203 	 * will disappear.
13204 	 */
13205 	error = 0;
13206 top:
13207 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13208 		switch (wk->wk_type) {
13209 		case D_ALLOCDIRECT:
13210 		case D_ALLOCINDIR:
13211 			newblk = WK_NEWBLK(wk);
13212 			if (newblk->nb_jnewblk != NULL) {
13213 				if (waitfor == MNT_NOWAIT) {
13214 					error = EBUSY;
13215 					goto out_unlock;
13216 				}
13217 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
13218 				goto top;
13219 			}
13220 			if (newblk->nb_state & DEPCOMPLETE ||
13221 			    waitfor == MNT_NOWAIT)
13222 				continue;
13223 			nbp = newblk->nb_bmsafemap->sm_buf;
13224 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13225 			if (nbp == NULL)
13226 				goto top;
13227 			FREE_LOCK(ump);
13228 			if ((error = bwrite(nbp)) != 0)
13229 				goto out;
13230 			ACQUIRE_LOCK(ump);
13231 			continue;
13232 
13233 		case D_INDIRDEP:
13234 			indirdep = WK_INDIRDEP(wk);
13235 			if (waitfor == MNT_NOWAIT) {
13236 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
13237 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
13238 					error = EBUSY;
13239 					goto out_unlock;
13240 				}
13241 			}
13242 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
13243 				panic("softdep_sync_buf: truncation pending.");
13244 		restart:
13245 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13246 				newblk = (struct newblk *)aip;
13247 				if (newblk->nb_jnewblk != NULL) {
13248 					jwait(&newblk->nb_jnewblk->jn_list,
13249 					    waitfor);
13250 					goto restart;
13251 				}
13252 				if (newblk->nb_state & DEPCOMPLETE)
13253 					continue;
13254 				nbp = newblk->nb_bmsafemap->sm_buf;
13255 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13256 				if (nbp == NULL)
13257 					goto restart;
13258 				FREE_LOCK(ump);
13259 				if ((error = bwrite(nbp)) != 0)
13260 					goto out;
13261 				ACQUIRE_LOCK(ump);
13262 				goto restart;
13263 			}
13264 			continue;
13265 
13266 		case D_PAGEDEP:
13267 			/*
13268 			 * Only flush directory entries in synchronous passes.
13269 			 */
13270 			if (waitfor != MNT_WAIT) {
13271 				error = EBUSY;
13272 				goto out_unlock;
13273 			}
13274 			/*
13275 			 * While syncing snapshots, we must allow recursive
13276 			 * lookups.
13277 			 */
13278 			BUF_AREC(bp);
13279 			/*
13280 			 * We are trying to sync a directory that may
13281 			 * have dependencies on both its own metadata
13282 			 * and/or dependencies on the inodes of any
13283 			 * recently allocated files. We walk its diradd
13284 			 * lists pushing out the associated inode.
13285 			 */
13286 			pagedep = WK_PAGEDEP(wk);
13287 			for (i = 0; i < DAHASHSZ; i++) {
13288 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
13289 					continue;
13290 				error = flush_pagedep_deps(vp, wk->wk_mp,
13291 				    &pagedep->pd_diraddhd[i], bp);
13292 				if (error != 0) {
13293 					if (error != ERELOOKUP)
13294 						BUF_NOREC(bp);
13295 					goto out_unlock;
13296 				}
13297 			}
13298 			BUF_NOREC(bp);
13299 			continue;
13300 
13301 		case D_FREEWORK:
13302 		case D_FREEDEP:
13303 		case D_JSEGDEP:
13304 		case D_JNEWBLK:
13305 			continue;
13306 
13307 		default:
13308 			panic("softdep_sync_buf: Unknown type %s",
13309 			    TYPENAME(wk->wk_type));
13310 			/* NOTREACHED */
13311 		}
13312 	}
13313 out_unlock:
13314 	FREE_LOCK(ump);
13315 out:
13316 	return (error);
13317 }
13318 
13319 /*
13320  * Flush the dependencies associated with an inodedep.
13321  */
13322 static int
13323 flush_inodedep_deps(vp, mp, ino)
13324 	struct vnode *vp;
13325 	struct mount *mp;
13326 	ino_t ino;
13327 {
13328 	struct inodedep *inodedep;
13329 	struct inoref *inoref;
13330 	struct ufsmount *ump;
13331 	int error, waitfor;
13332 
13333 	/*
13334 	 * This work is done in two passes. The first pass grabs most
13335 	 * of the buffers and begins asynchronously writing them. The
13336 	 * only way to wait for these asynchronous writes is to sleep
13337 	 * on the filesystem vnode which may stay busy for a long time
13338 	 * if the filesystem is active. So, instead, we make a second
13339 	 * pass over the dependencies blocking on each write. In the
13340 	 * usual case we will be blocking against a write that we
13341 	 * initiated, so when it is done the dependency will have been
13342 	 * resolved. Thus the second pass is expected to end quickly.
13343 	 * We give a brief window at the top of the loop to allow
13344 	 * any pending I/O to complete.
13345 	 */
13346 	ump = VFSTOUFS(mp);
13347 	LOCK_OWNED(ump);
13348 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
13349 		if (error)
13350 			return (error);
13351 		FREE_LOCK(ump);
13352 		ACQUIRE_LOCK(ump);
13353 restart:
13354 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13355 			return (0);
13356 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13357 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13358 			    == DEPCOMPLETE) {
13359 				jwait(&inoref->if_list, MNT_WAIT);
13360 				goto restart;
13361 			}
13362 		}
13363 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
13364 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
13365 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
13366 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
13367 			continue;
13368 		/*
13369 		 * If pass2, we are done, otherwise do pass 2.
13370 		 */
13371 		if (waitfor == MNT_WAIT)
13372 			break;
13373 		waitfor = MNT_WAIT;
13374 	}
13375 	/*
13376 	 * Try freeing inodedep in case all dependencies have been removed.
13377 	 */
13378 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
13379 		(void) free_inodedep(inodedep);
13380 	return (0);
13381 }
13382 
13383 /*
13384  * Flush an inode dependency list.
13385  */
13386 static int
13387 flush_deplist(listhead, waitfor, errorp)
13388 	struct allocdirectlst *listhead;
13389 	int waitfor;
13390 	int *errorp;
13391 {
13392 	struct allocdirect *adp;
13393 	struct newblk *newblk;
13394 	struct ufsmount *ump;
13395 	struct buf *bp;
13396 
13397 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
13398 		return (0);
13399 	ump = VFSTOUFS(adp->ad_list.wk_mp);
13400 	LOCK_OWNED(ump);
13401 	TAILQ_FOREACH(adp, listhead, ad_next) {
13402 		newblk = (struct newblk *)adp;
13403 		if (newblk->nb_jnewblk != NULL) {
13404 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13405 			return (1);
13406 		}
13407 		if (newblk->nb_state & DEPCOMPLETE)
13408 			continue;
13409 		bp = newblk->nb_bmsafemap->sm_buf;
13410 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13411 		if (bp == NULL) {
13412 			if (waitfor == MNT_NOWAIT)
13413 				continue;
13414 			return (1);
13415 		}
13416 		FREE_LOCK(ump);
13417 		if (waitfor == MNT_NOWAIT)
13418 			bawrite(bp);
13419 		else
13420 			*errorp = bwrite(bp);
13421 		ACQUIRE_LOCK(ump);
13422 		return (1);
13423 	}
13424 	return (0);
13425 }
13426 
13427 /*
13428  * Flush dependencies associated with an allocdirect block.
13429  */
13430 static int
13431 flush_newblk_dep(vp, mp, lbn)
13432 	struct vnode *vp;
13433 	struct mount *mp;
13434 	ufs_lbn_t lbn;
13435 {
13436 	struct newblk *newblk;
13437 	struct ufsmount *ump;
13438 	struct bufobj *bo;
13439 	struct inode *ip;
13440 	struct buf *bp;
13441 	ufs2_daddr_t blkno;
13442 	int error;
13443 
13444 	error = 0;
13445 	bo = &vp->v_bufobj;
13446 	ip = VTOI(vp);
13447 	blkno = DIP(ip, i_db[lbn]);
13448 	if (blkno == 0)
13449 		panic("flush_newblk_dep: Missing block");
13450 	ump = VFSTOUFS(mp);
13451 	ACQUIRE_LOCK(ump);
13452 	/*
13453 	 * Loop until all dependencies related to this block are satisfied.
13454 	 * We must be careful to restart after each sleep in case a write
13455 	 * completes some part of this process for us.
13456 	 */
13457 	for (;;) {
13458 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13459 			FREE_LOCK(ump);
13460 			break;
13461 		}
13462 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13463 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13464 		/*
13465 		 * Flush the journal.
13466 		 */
13467 		if (newblk->nb_jnewblk != NULL) {
13468 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13469 			continue;
13470 		}
13471 		/*
13472 		 * Write the bitmap dependency.
13473 		 */
13474 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13475 			bp = newblk->nb_bmsafemap->sm_buf;
13476 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13477 			if (bp == NULL)
13478 				continue;
13479 			FREE_LOCK(ump);
13480 			error = bwrite(bp);
13481 			if (error)
13482 				break;
13483 			ACQUIRE_LOCK(ump);
13484 			continue;
13485 		}
13486 		/*
13487 		 * Write the buffer.
13488 		 */
13489 		FREE_LOCK(ump);
13490 		BO_LOCK(bo);
13491 		bp = gbincore(bo, lbn);
13492 		if (bp != NULL) {
13493 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13494 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13495 			if (error == ENOLCK) {
13496 				ACQUIRE_LOCK(ump);
13497 				error = 0;
13498 				continue; /* Slept, retry */
13499 			}
13500 			if (error != 0)
13501 				break;	/* Failed */
13502 			if (bp->b_flags & B_DELWRI) {
13503 				bremfree(bp);
13504 				error = bwrite(bp);
13505 				if (error)
13506 					break;
13507 			} else
13508 				BUF_UNLOCK(bp);
13509 		} else
13510 			BO_UNLOCK(bo);
13511 		/*
13512 		 * We have to wait for the direct pointers to
13513 		 * point at the newdirblk before the dependency
13514 		 * will go away.
13515 		 */
13516 		error = ffs_update(vp, 1);
13517 		if (error)
13518 			break;
13519 		ACQUIRE_LOCK(ump);
13520 	}
13521 	return (error);
13522 }
13523 
13524 /*
13525  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13526  */
13527 static int
13528 flush_pagedep_deps(pvp, mp, diraddhdp, locked_bp)
13529 	struct vnode *pvp;
13530 	struct mount *mp;
13531 	struct diraddhd *diraddhdp;
13532 	struct buf *locked_bp;
13533 {
13534 	struct inodedep *inodedep;
13535 	struct inoref *inoref;
13536 	struct ufsmount *ump;
13537 	struct diradd *dap;
13538 	struct vnode *vp;
13539 	int error = 0;
13540 	struct buf *bp;
13541 	ino_t inum;
13542 	struct diraddhd unfinished;
13543 
13544 	LIST_INIT(&unfinished);
13545 	ump = VFSTOUFS(mp);
13546 	LOCK_OWNED(ump);
13547 restart:
13548 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13549 		/*
13550 		 * Flush ourselves if this directory entry
13551 		 * has a MKDIR_PARENT dependency.
13552 		 */
13553 		if (dap->da_state & MKDIR_PARENT) {
13554 			FREE_LOCK(ump);
13555 			if ((error = ffs_update(pvp, 1)) != 0)
13556 				break;
13557 			ACQUIRE_LOCK(ump);
13558 			/*
13559 			 * If that cleared dependencies, go on to next.
13560 			 */
13561 			if (dap != LIST_FIRST(diraddhdp))
13562 				continue;
13563 			/*
13564 			 * All MKDIR_PARENT dependencies and all the
13565 			 * NEWBLOCK pagedeps that are contained in direct
13566 			 * blocks were resolved by doing above ffs_update.
13567 			 * Pagedeps contained in indirect blocks may
13568 			 * require a complete sync'ing of the directory.
13569 			 * We are in the midst of doing a complete sync,
13570 			 * so if they are not resolved in this pass we
13571 			 * defer them for now as they will be sync'ed by
13572 			 * our caller shortly.
13573 			 */
13574 			LIST_REMOVE(dap, da_pdlist);
13575 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13576 			continue;
13577 		}
13578 		/*
13579 		 * A newly allocated directory must have its "." and
13580 		 * ".." entries written out before its name can be
13581 		 * committed in its parent.
13582 		 */
13583 		inum = dap->da_newinum;
13584 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13585 			panic("flush_pagedep_deps: lost inode1");
13586 		/*
13587 		 * Wait for any pending journal adds to complete so we don't
13588 		 * cause rollbacks while syncing.
13589 		 */
13590 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13591 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13592 			    == DEPCOMPLETE) {
13593 				jwait(&inoref->if_list, MNT_WAIT);
13594 				goto restart;
13595 			}
13596 		}
13597 		if (dap->da_state & MKDIR_BODY) {
13598 			FREE_LOCK(ump);
13599 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13600 			    diraddhdp, &unfinished, &vp);
13601 			if (error != 0)
13602 				break;
13603 			error = flush_newblk_dep(vp, mp, 0);
13604 			/*
13605 			 * If we still have the dependency we might need to
13606 			 * update the vnode to sync the new link count to
13607 			 * disk.
13608 			 */
13609 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13610 				error = ffs_update(vp, 1);
13611 			vput(vp);
13612 			if (error != 0)
13613 				break;
13614 			ACQUIRE_LOCK(ump);
13615 			/*
13616 			 * If that cleared dependencies, go on to next.
13617 			 */
13618 			if (dap != LIST_FIRST(diraddhdp))
13619 				continue;
13620 			if (dap->da_state & MKDIR_BODY) {
13621 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13622 				    &inodedep);
13623 				panic("flush_pagedep_deps: MKDIR_BODY "
13624 				    "inodedep %p dap %p vp %p",
13625 				    inodedep, dap, vp);
13626 			}
13627 		}
13628 		/*
13629 		 * Flush the inode on which the directory entry depends.
13630 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13631 		 * the only remaining dependency is that the updated inode
13632 		 * count must get pushed to disk. The inode has already
13633 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13634 		 * the time of the reference count change. So we need only
13635 		 * locate that buffer, ensure that there will be no rollback
13636 		 * caused by a bitmap dependency, then write the inode buffer.
13637 		 */
13638 retry:
13639 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13640 			panic("flush_pagedep_deps: lost inode");
13641 		/*
13642 		 * If the inode still has bitmap dependencies,
13643 		 * push them to disk.
13644 		 */
13645 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13646 			bp = inodedep->id_bmsafemap->sm_buf;
13647 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13648 			if (bp == NULL)
13649 				goto retry;
13650 			FREE_LOCK(ump);
13651 			if ((error = bwrite(bp)) != 0)
13652 				break;
13653 			ACQUIRE_LOCK(ump);
13654 			if (dap != LIST_FIRST(diraddhdp))
13655 				continue;
13656 		}
13657 		/*
13658 		 * If the inode is still sitting in a buffer waiting
13659 		 * to be written or waiting for the link count to be
13660 		 * adjusted update it here to flush it to disk.
13661 		 */
13662 		if (dap == LIST_FIRST(diraddhdp)) {
13663 			FREE_LOCK(ump);
13664 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13665 			    diraddhdp, &unfinished, &vp);
13666 			if (error != 0)
13667 				break;
13668 			error = ffs_update(vp, 1);
13669 			vput(vp);
13670 			if (error)
13671 				break;
13672 			ACQUIRE_LOCK(ump);
13673 		}
13674 		/*
13675 		 * If we have failed to get rid of all the dependencies
13676 		 * then something is seriously wrong.
13677 		 */
13678 		if (dap == LIST_FIRST(diraddhdp)) {
13679 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13680 			panic("flush_pagedep_deps: failed to flush "
13681 			    "inodedep %p ino %ju dap %p",
13682 			    inodedep, (uintmax_t)inum, dap);
13683 		}
13684 	}
13685 	if (error)
13686 		ACQUIRE_LOCK(ump);
13687 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13688 		LIST_REMOVE(dap, da_pdlist);
13689 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13690 	}
13691 	return (error);
13692 }
13693 
13694 /*
13695  * A large burst of file addition or deletion activity can drive the
13696  * memory load excessively high. First attempt to slow things down
13697  * using the techniques below. If that fails, this routine requests
13698  * the offending operations to fall back to running synchronously
13699  * until the memory load returns to a reasonable level.
13700  */
13701 int
13702 softdep_slowdown(vp)
13703 	struct vnode *vp;
13704 {
13705 	struct ufsmount *ump;
13706 	int jlow;
13707 	int max_softdeps_hard;
13708 
13709 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13710 	    ("softdep_slowdown called on non-softdep filesystem"));
13711 	ump = VFSTOUFS(vp->v_mount);
13712 	ACQUIRE_LOCK(ump);
13713 	jlow = 0;
13714 	/*
13715 	 * Check for journal space if needed.
13716 	 */
13717 	if (DOINGSUJ(vp)) {
13718 		if (journal_space(ump, 0) == 0)
13719 			jlow = 1;
13720 	}
13721 	/*
13722 	 * If the system is under its limits and our filesystem is
13723 	 * not responsible for more than our share of the usage and
13724 	 * we are not low on journal space, then no need to slow down.
13725 	 */
13726 	max_softdeps_hard = max_softdeps * 11 / 10;
13727 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13728 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13729 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13730 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13731 	    ump->softdep_curdeps[D_DIRREM] <
13732 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13733 	    ump->softdep_curdeps[D_INODEDEP] <
13734 	    max_softdeps_hard / stat_flush_threads &&
13735 	    ump->softdep_curdeps[D_INDIRDEP] <
13736 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13737 	    ump->softdep_curdeps[D_FREEBLKS] <
13738 	    max_softdeps_hard / stat_flush_threads) {
13739 		FREE_LOCK(ump);
13740   		return (0);
13741 	}
13742 	/*
13743 	 * If the journal is low or our filesystem is over its limit
13744 	 * then speedup the cleanup.
13745 	 */
13746 	if (ump->softdep_curdeps[D_INDIRDEP] <
13747 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13748 		softdep_speedup(ump);
13749 	stat_sync_limit_hit += 1;
13750 	FREE_LOCK(ump);
13751 	/*
13752 	 * We only slow down the rate at which new dependencies are
13753 	 * generated if we are not using journaling. With journaling,
13754 	 * the cleanup should always be sufficient to keep things
13755 	 * under control.
13756 	 */
13757 	if (DOINGSUJ(vp))
13758 		return (0);
13759 	return (1);
13760 }
13761 
13762 static int
13763 softdep_request_cleanup_filter(struct vnode *vp, void *arg __unused)
13764 {
13765 	return ((vp->v_iflag & VI_OWEINACT) != 0 && vp->v_usecount == 0 &&
13766 	    ((vp->v_vflag & VV_NOSYNC) != 0 || VTOI(vp)->i_effnlink == 0));
13767 }
13768 
13769 static void
13770 softdep_request_cleanup_inactivate(struct mount *mp)
13771 {
13772 	struct vnode *vp, *mvp;
13773 	int error;
13774 
13775 	MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, softdep_request_cleanup_filter,
13776 	    NULL) {
13777 		vholdl(vp);
13778 		vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
13779 		VI_LOCK(vp);
13780 		if (vp->v_data != NULL && vp->v_usecount == 0) {
13781 			while ((vp->v_iflag & VI_OWEINACT) != 0) {
13782 				error = vinactive(vp);
13783 				if (error != 0 && error != ERELOOKUP)
13784 					break;
13785 			}
13786 			atomic_add_int(&stat_delayed_inact, 1);
13787 		}
13788 		VOP_UNLOCK(vp);
13789 		vdropl(vp);
13790 	}
13791 }
13792 
13793 /*
13794  * Called by the allocation routines when they are about to fail
13795  * in the hope that we can free up the requested resource (inodes
13796  * or disk space).
13797  *
13798  * First check to see if the work list has anything on it. If it has,
13799  * clean up entries until we successfully free the requested resource.
13800  * Because this process holds inodes locked, we cannot handle any remove
13801  * requests that might block on a locked inode as that could lead to
13802  * deadlock. If the worklist yields none of the requested resource,
13803  * start syncing out vnodes to free up the needed space.
13804  */
13805 int
13806 softdep_request_cleanup(fs, vp, cred, resource)
13807 	struct fs *fs;
13808 	struct vnode *vp;
13809 	struct ucred *cred;
13810 	int resource;
13811 {
13812 	struct ufsmount *ump;
13813 	struct mount *mp;
13814 	long starttime;
13815 	ufs2_daddr_t needed;
13816 	int error, failed_vnode;
13817 
13818 	/*
13819 	 * If we are being called because of a process doing a
13820 	 * copy-on-write, then it is not safe to process any
13821 	 * worklist items as we will recurse into the copyonwrite
13822 	 * routine.  This will result in an incoherent snapshot.
13823 	 * If the vnode that we hold is a snapshot, we must avoid
13824 	 * handling other resources that could cause deadlock.
13825 	 */
13826 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13827 		return (0);
13828 
13829 	if (resource == FLUSH_BLOCKS_WAIT)
13830 		stat_cleanup_blkrequests += 1;
13831 	else
13832 		stat_cleanup_inorequests += 1;
13833 
13834 	mp = vp->v_mount;
13835 	ump = VFSTOUFS(mp);
13836 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13837 	UFS_UNLOCK(ump);
13838 	error = ffs_update(vp, 1);
13839 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13840 		UFS_LOCK(ump);
13841 		return (0);
13842 	}
13843 	/*
13844 	 * If we are in need of resources, start by cleaning up
13845 	 * any block removals associated with our inode.
13846 	 */
13847 	ACQUIRE_LOCK(ump);
13848 	process_removes(vp);
13849 	process_truncates(vp);
13850 	FREE_LOCK(ump);
13851 	/*
13852 	 * Now clean up at least as many resources as we will need.
13853 	 *
13854 	 * When requested to clean up inodes, the number that are needed
13855 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13856 	 * plus a bit of slop (2) in case some more writers show up while
13857 	 * we are cleaning.
13858 	 *
13859 	 * When requested to free up space, the amount of space that
13860 	 * we need is enough blocks to allocate a full-sized segment
13861 	 * (fs_contigsumsize). The number of such segments that will
13862 	 * be needed is set by the number of simultaneous writers
13863 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13864 	 * writers show up while we are cleaning.
13865 	 *
13866 	 * Additionally, if we are unpriviledged and allocating space,
13867 	 * we need to ensure that we clean up enough blocks to get the
13868 	 * needed number of blocks over the threshold of the minimum
13869 	 * number of blocks required to be kept free by the filesystem
13870 	 * (fs_minfree).
13871 	 */
13872 	if (resource == FLUSH_INODES_WAIT) {
13873 		needed = vfs_mount_fetch_counter(vp->v_mount,
13874 		    MNT_COUNT_WRITEOPCOUNT) + 2;
13875 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13876 		needed = (vfs_mount_fetch_counter(vp->v_mount,
13877 		    MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13878 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13879 			needed += fragstoblks(fs,
13880 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13881 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13882 	} else {
13883 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13884 		    resource);
13885 		UFS_LOCK(ump);
13886 		return (0);
13887 	}
13888 	starttime = time_second;
13889 retry:
13890 	if (resource == FLUSH_BLOCKS_WAIT &&
13891 	    fs->fs_cstotal.cs_nbfree <= needed)
13892 		softdep_send_speedup(ump, needed * fs->fs_bsize,
13893 		    BIO_SPEEDUP_TRIM);
13894 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13895 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13896 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13897 	    fs->fs_cstotal.cs_nifree <= needed)) {
13898 		ACQUIRE_LOCK(ump);
13899 		if (ump->softdep_on_worklist > 0 &&
13900 		    process_worklist_item(UFSTOVFS(ump),
13901 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13902 			stat_worklist_push += 1;
13903 		FREE_LOCK(ump);
13904 	}
13905 
13906 	/*
13907 	 * Check that there are vnodes pending inactivation.  As they
13908 	 * have been unlinked, inactivating them will free up their
13909 	 * inodes.
13910 	 */
13911 	ACQUIRE_LOCK(ump);
13912 	if (resource == FLUSH_INODES_WAIT &&
13913 	    fs->fs_cstotal.cs_nifree <= needed &&
13914 	    fs->fs_pendinginodes <= needed) {
13915 		if ((ump->um_softdep->sd_flags & FLUSH_DI_ACTIVE) == 0) {
13916 			ump->um_softdep->sd_flags |= FLUSH_DI_ACTIVE;
13917 			FREE_LOCK(ump);
13918 			softdep_request_cleanup_inactivate(mp);
13919 			ACQUIRE_LOCK(ump);
13920 			ump->um_softdep->sd_flags &= ~FLUSH_DI_ACTIVE;
13921 			wakeup(&ump->um_softdep->sd_flags);
13922 		} else {
13923 			while ((ump->um_softdep->sd_flags &
13924 			    FLUSH_DI_ACTIVE) != 0) {
13925 				msleep(&ump->um_softdep->sd_flags,
13926 				    LOCK_PTR(ump), PVM, "ffsvina", hz);
13927 			}
13928 		}
13929 	}
13930 	FREE_LOCK(ump);
13931 
13932 	/*
13933 	 * If we still need resources and there are no more worklist
13934 	 * entries to process to obtain them, we have to start flushing
13935 	 * the dirty vnodes to force the release of additional requests
13936 	 * to the worklist that we can then process to reap addition
13937 	 * resources. We walk the vnodes associated with the mount point
13938 	 * until we get the needed worklist requests that we can reap.
13939 	 *
13940 	 * If there are several threads all needing to clean the same
13941 	 * mount point, only one is allowed to walk the mount list.
13942 	 * When several threads all try to walk the same mount list,
13943 	 * they end up competing with each other and often end up in
13944 	 * livelock. This approach ensures that forward progress is
13945 	 * made at the cost of occational ENOSPC errors being returned
13946 	 * that might otherwise have been avoided.
13947 	 */
13948 	error = 1;
13949 	if ((resource == FLUSH_BLOCKS_WAIT &&
13950 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13951 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13952 	     fs->fs_cstotal.cs_nifree <= needed)) {
13953 		ACQUIRE_LOCK(ump);
13954 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13955 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13956 			FREE_LOCK(ump);
13957 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13958 			ACQUIRE_LOCK(ump);
13959 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13960 			wakeup(&ump->um_softdep->sd_flags);
13961 			FREE_LOCK(ump);
13962 			if (ump->softdep_on_worklist > 0) {
13963 				stat_cleanup_retries += 1;
13964 				if (!failed_vnode)
13965 					goto retry;
13966 			}
13967 		} else {
13968 			while ((ump->um_softdep->sd_flags &
13969 			    FLUSH_RC_ACTIVE) != 0) {
13970 				msleep(&ump->um_softdep->sd_flags,
13971 				    LOCK_PTR(ump), PVM, "ffsrca", hz);
13972 			}
13973 			FREE_LOCK(ump);
13974 			error = 0;
13975 		}
13976 		stat_cleanup_failures += 1;
13977 	}
13978 	if (time_second - starttime > stat_cleanup_high_delay)
13979 		stat_cleanup_high_delay = time_second - starttime;
13980 	UFS_LOCK(ump);
13981 	return (error);
13982 }
13983 
13984 /*
13985  * Scan the vnodes for the specified mount point flushing out any
13986  * vnodes that can be locked without waiting. Finally, try to flush
13987  * the device associated with the mount point if it can be locked
13988  * without waiting.
13989  *
13990  * We return 0 if we were able to lock every vnode in our scan.
13991  * If we had to skip one or more vnodes, we return 1.
13992  */
13993 static int
13994 softdep_request_cleanup_flush(mp, ump)
13995 	struct mount *mp;
13996 	struct ufsmount *ump;
13997 {
13998 	struct thread *td;
13999 	struct vnode *lvp, *mvp;
14000 	int failed_vnode;
14001 
14002 	failed_vnode = 0;
14003 	td = curthread;
14004 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
14005 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
14006 			VI_UNLOCK(lvp);
14007 			continue;
14008 		}
14009 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT) != 0) {
14010 			failed_vnode = 1;
14011 			continue;
14012 		}
14013 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
14014 			vput(lvp);
14015 			continue;
14016 		}
14017 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
14018 		vput(lvp);
14019 	}
14020 	lvp = ump->um_devvp;
14021 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
14022 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
14023 		VOP_UNLOCK(lvp);
14024 	}
14025 	return (failed_vnode);
14026 }
14027 
14028 static bool
14029 softdep_excess_items(struct ufsmount *ump, int item)
14030 {
14031 
14032 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
14033 	return (dep_current[item] > max_softdeps &&
14034 	    ump->softdep_curdeps[item] > max_softdeps /
14035 	    stat_flush_threads);
14036 }
14037 
14038 static void
14039 schedule_cleanup(struct mount *mp)
14040 {
14041 	struct ufsmount *ump;
14042 	struct thread *td;
14043 
14044 	ump = VFSTOUFS(mp);
14045 	LOCK_OWNED(ump);
14046 	FREE_LOCK(ump);
14047 	td = curthread;
14048 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
14049 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
14050 		/*
14051 		 * No ast is delivered to kernel threads, so nobody
14052 		 * would deref the mp.  Some kernel threads
14053 		 * explicitely check for AST, e.g. NFS daemon does
14054 		 * this in the serving loop.
14055 		 */
14056 		return;
14057 	}
14058 	if (td->td_su != NULL)
14059 		vfs_rel(td->td_su);
14060 	vfs_ref(mp);
14061 	td->td_su = mp;
14062 	thread_lock(td);
14063 	td->td_flags |= TDF_ASTPENDING;
14064 	thread_unlock(td);
14065 }
14066 
14067 static void
14068 softdep_ast_cleanup_proc(struct thread *td)
14069 {
14070 	struct mount *mp;
14071 	struct ufsmount *ump;
14072 	int error;
14073 	bool req;
14074 
14075 	while ((mp = td->td_su) != NULL) {
14076 		td->td_su = NULL;
14077 		error = vfs_busy(mp, MBF_NOWAIT);
14078 		vfs_rel(mp);
14079 		if (error != 0)
14080 			return;
14081 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
14082 			ump = VFSTOUFS(mp);
14083 			for (;;) {
14084 				req = false;
14085 				ACQUIRE_LOCK(ump);
14086 				if (softdep_excess_items(ump, D_INODEDEP)) {
14087 					req = true;
14088 					request_cleanup(mp, FLUSH_INODES);
14089 				}
14090 				if (softdep_excess_items(ump, D_DIRREM)) {
14091 					req = true;
14092 					request_cleanup(mp, FLUSH_BLOCKS);
14093 				}
14094 				FREE_LOCK(ump);
14095 				if (softdep_excess_items(ump, D_NEWBLK) ||
14096 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
14097 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
14098 					error = vn_start_write(NULL, &mp,
14099 					    V_WAIT);
14100 					if (error == 0) {
14101 						req = true;
14102 						VFS_SYNC(mp, MNT_WAIT);
14103 						vn_finished_write(mp);
14104 					}
14105 				}
14106 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
14107 					break;
14108 			}
14109 		}
14110 		vfs_unbusy(mp);
14111 	}
14112 	if ((mp = td->td_su) != NULL) {
14113 		td->td_su = NULL;
14114 		vfs_rel(mp);
14115 	}
14116 }
14117 
14118 /*
14119  * If memory utilization has gotten too high, deliberately slow things
14120  * down and speed up the I/O processing.
14121  */
14122 static int
14123 request_cleanup(mp, resource)
14124 	struct mount *mp;
14125 	int resource;
14126 {
14127 	struct thread *td = curthread;
14128 	struct ufsmount *ump;
14129 
14130 	ump = VFSTOUFS(mp);
14131 	LOCK_OWNED(ump);
14132 	/*
14133 	 * We never hold up the filesystem syncer or buf daemon.
14134 	 */
14135 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
14136 		return (0);
14137 	/*
14138 	 * First check to see if the work list has gotten backlogged.
14139 	 * If it has, co-opt this process to help clean up two entries.
14140 	 * Because this process may hold inodes locked, we cannot
14141 	 * handle any remove requests that might block on a locked
14142 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
14143 	 * to avoid recursively processing the worklist.
14144 	 */
14145 	if (ump->softdep_on_worklist > max_softdeps / 10) {
14146 		td->td_pflags |= TDP_SOFTDEP;
14147 		process_worklist_item(mp, 2, LK_NOWAIT);
14148 		td->td_pflags &= ~TDP_SOFTDEP;
14149 		stat_worklist_push += 2;
14150 		return(1);
14151 	}
14152 	/*
14153 	 * Next, we attempt to speed up the syncer process. If that
14154 	 * is successful, then we allow the process to continue.
14155 	 */
14156 	if (softdep_speedup(ump) &&
14157 	    resource != FLUSH_BLOCKS_WAIT &&
14158 	    resource != FLUSH_INODES_WAIT)
14159 		return(0);
14160 	/*
14161 	 * If we are resource constrained on inode dependencies, try
14162 	 * flushing some dirty inodes. Otherwise, we are constrained
14163 	 * by file deletions, so try accelerating flushes of directories
14164 	 * with removal dependencies. We would like to do the cleanup
14165 	 * here, but we probably hold an inode locked at this point and
14166 	 * that might deadlock against one that we try to clean. So,
14167 	 * the best that we can do is request the syncer daemon to do
14168 	 * the cleanup for us.
14169 	 */
14170 	switch (resource) {
14171 	case FLUSH_INODES:
14172 	case FLUSH_INODES_WAIT:
14173 		ACQUIRE_GBLLOCK(&lk);
14174 		stat_ino_limit_push += 1;
14175 		req_clear_inodedeps += 1;
14176 		FREE_GBLLOCK(&lk);
14177 		stat_countp = &stat_ino_limit_hit;
14178 		break;
14179 
14180 	case FLUSH_BLOCKS:
14181 	case FLUSH_BLOCKS_WAIT:
14182 		ACQUIRE_GBLLOCK(&lk);
14183 		stat_blk_limit_push += 1;
14184 		req_clear_remove += 1;
14185 		FREE_GBLLOCK(&lk);
14186 		stat_countp = &stat_blk_limit_hit;
14187 		break;
14188 
14189 	default:
14190 		panic("request_cleanup: unknown type");
14191 	}
14192 	/*
14193 	 * Hopefully the syncer daemon will catch up and awaken us.
14194 	 * We wait at most tickdelay before proceeding in any case.
14195 	 */
14196 	ACQUIRE_GBLLOCK(&lk);
14197 	FREE_LOCK(ump);
14198 	proc_waiting += 1;
14199 	if (callout_pending(&softdep_callout) == FALSE)
14200 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
14201 		    pause_timer, 0);
14202 
14203 	if ((td->td_pflags & TDP_KTHREAD) == 0)
14204 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
14205 	proc_waiting -= 1;
14206 	FREE_GBLLOCK(&lk);
14207 	ACQUIRE_LOCK(ump);
14208 	return (1);
14209 }
14210 
14211 /*
14212  * Awaken processes pausing in request_cleanup and clear proc_waiting
14213  * to indicate that there is no longer a timer running. Pause_timer
14214  * will be called with the global softdep mutex (&lk) locked.
14215  */
14216 static void
14217 pause_timer(arg)
14218 	void *arg;
14219 {
14220 
14221 	GBLLOCK_OWNED(&lk);
14222 	/*
14223 	 * The callout_ API has acquired mtx and will hold it around this
14224 	 * function call.
14225 	 */
14226 	*stat_countp += proc_waiting;
14227 	wakeup(&proc_waiting);
14228 }
14229 
14230 /*
14231  * If requested, try removing inode or removal dependencies.
14232  */
14233 static void
14234 check_clear_deps(mp)
14235 	struct mount *mp;
14236 {
14237 	struct ufsmount *ump;
14238 	bool suj_susp;
14239 
14240 	/*
14241 	 * Tell the lower layers that any TRIM or WRITE transactions that have
14242 	 * been delayed for performance reasons should proceed to help alleviate
14243 	 * the shortage faster. The race between checking req_* and the softdep
14244 	 * mutex (lk) is fine since this is an advisory operation that at most
14245 	 * causes deferred work to be done sooner.
14246 	 */
14247 	ump = VFSTOUFS(mp);
14248 	suj_susp = ump->um_softdep->sd_jblocks != NULL &&
14249 	    ump->softdep_jblocks->jb_suspended;
14250 	if (req_clear_remove || req_clear_inodedeps || suj_susp) {
14251 		FREE_LOCK(ump);
14252 		softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
14253 		ACQUIRE_LOCK(ump);
14254 	}
14255 
14256 	/*
14257 	 * If we are suspended, it may be because of our using
14258 	 * too many inodedeps, so help clear them out.
14259 	 */
14260 	if (suj_susp)
14261 		clear_inodedeps(mp);
14262 
14263 	/*
14264 	 * General requests for cleanup of backed up dependencies
14265 	 */
14266 	ACQUIRE_GBLLOCK(&lk);
14267 	if (req_clear_inodedeps) {
14268 		req_clear_inodedeps -= 1;
14269 		FREE_GBLLOCK(&lk);
14270 		clear_inodedeps(mp);
14271 		ACQUIRE_GBLLOCK(&lk);
14272 		wakeup(&proc_waiting);
14273 	}
14274 	if (req_clear_remove) {
14275 		req_clear_remove -= 1;
14276 		FREE_GBLLOCK(&lk);
14277 		clear_remove(mp);
14278 		ACQUIRE_GBLLOCK(&lk);
14279 		wakeup(&proc_waiting);
14280 	}
14281 	FREE_GBLLOCK(&lk);
14282 }
14283 
14284 /*
14285  * Flush out a directory with at least one removal dependency in an effort to
14286  * reduce the number of dirrem, freefile, and freeblks dependency structures.
14287  */
14288 static void
14289 clear_remove(mp)
14290 	struct mount *mp;
14291 {
14292 	struct pagedep_hashhead *pagedephd;
14293 	struct pagedep *pagedep;
14294 	struct ufsmount *ump;
14295 	struct vnode *vp;
14296 	struct bufobj *bo;
14297 	int error, cnt;
14298 	ino_t ino;
14299 
14300 	ump = VFSTOUFS(mp);
14301 	LOCK_OWNED(ump);
14302 
14303 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
14304 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
14305 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
14306 			ump->pagedep_nextclean = 0;
14307 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
14308 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
14309 				continue;
14310 			ino = pagedep->pd_ino;
14311 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14312 				continue;
14313 			FREE_LOCK(ump);
14314 
14315 			/*
14316 			 * Let unmount clear deps
14317 			 */
14318 			error = vfs_busy(mp, MBF_NOWAIT);
14319 			if (error != 0)
14320 				goto finish_write;
14321 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14322 			     FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
14323 			vfs_unbusy(mp);
14324 			if (error != 0) {
14325 				softdep_error("clear_remove: vget", error);
14326 				goto finish_write;
14327 			}
14328 			MPASS(VTOI(vp)->i_mode != 0);
14329 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14330 				softdep_error("clear_remove: fsync", error);
14331 			bo = &vp->v_bufobj;
14332 			BO_LOCK(bo);
14333 			drain_output(vp);
14334 			BO_UNLOCK(bo);
14335 			vput(vp);
14336 		finish_write:
14337 			vn_finished_write(mp);
14338 			ACQUIRE_LOCK(ump);
14339 			return;
14340 		}
14341 	}
14342 }
14343 
14344 /*
14345  * Clear out a block of dirty inodes in an effort to reduce
14346  * the number of inodedep dependency structures.
14347  */
14348 static void
14349 clear_inodedeps(mp)
14350 	struct mount *mp;
14351 {
14352 	struct inodedep_hashhead *inodedephd;
14353 	struct inodedep *inodedep;
14354 	struct ufsmount *ump;
14355 	struct vnode *vp;
14356 	struct fs *fs;
14357 	int error, cnt;
14358 	ino_t firstino, lastino, ino;
14359 
14360 	ump = VFSTOUFS(mp);
14361 	fs = ump->um_fs;
14362 	LOCK_OWNED(ump);
14363 	/*
14364 	 * Pick a random inode dependency to be cleared.
14365 	 * We will then gather up all the inodes in its block
14366 	 * that have dependencies and flush them out.
14367 	 */
14368 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
14369 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
14370 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
14371 			ump->inodedep_nextclean = 0;
14372 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
14373 			break;
14374 	}
14375 	if (inodedep == NULL)
14376 		return;
14377 	/*
14378 	 * Find the last inode in the block with dependencies.
14379 	 */
14380 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
14381 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
14382 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
14383 			break;
14384 	/*
14385 	 * Asynchronously push all but the last inode with dependencies.
14386 	 * Synchronously push the last inode with dependencies to ensure
14387 	 * that the inode block gets written to free up the inodedeps.
14388 	 */
14389 	for (ino = firstino; ino <= lastino; ino++) {
14390 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
14391 			continue;
14392 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14393 			continue;
14394 		FREE_LOCK(ump);
14395 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
14396 		if (error != 0) {
14397 			vn_finished_write(mp);
14398 			ACQUIRE_LOCK(ump);
14399 			return;
14400 		}
14401 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14402 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP)) != 0) {
14403 			softdep_error("clear_inodedeps: vget", error);
14404 			vfs_unbusy(mp);
14405 			vn_finished_write(mp);
14406 			ACQUIRE_LOCK(ump);
14407 			return;
14408 		}
14409 		vfs_unbusy(mp);
14410 		if (VTOI(vp)->i_mode == 0) {
14411 			vgone(vp);
14412 		} else if (ino == lastino) {
14413 			do {
14414 				error = ffs_syncvnode(vp, MNT_WAIT, 0);
14415 			} while (error == ERELOOKUP);
14416 			if (error != 0)
14417 				softdep_error("clear_inodedeps: fsync1", error);
14418 		} else {
14419 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14420 				softdep_error("clear_inodedeps: fsync2", error);
14421 			BO_LOCK(&vp->v_bufobj);
14422 			drain_output(vp);
14423 			BO_UNLOCK(&vp->v_bufobj);
14424 		}
14425 		vput(vp);
14426 		vn_finished_write(mp);
14427 		ACQUIRE_LOCK(ump);
14428 	}
14429 }
14430 
14431 void
14432 softdep_buf_append(bp, wkhd)
14433 	struct buf *bp;
14434 	struct workhead *wkhd;
14435 {
14436 	struct worklist *wk;
14437 	struct ufsmount *ump;
14438 
14439 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14440 		return;
14441 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14442 	    ("softdep_buf_append called on non-softdep filesystem"));
14443 	ump = VFSTOUFS(wk->wk_mp);
14444 	ACQUIRE_LOCK(ump);
14445 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
14446 		WORKLIST_REMOVE(wk);
14447 		WORKLIST_INSERT(&bp->b_dep, wk);
14448 	}
14449 	FREE_LOCK(ump);
14450 
14451 }
14452 
14453 void
14454 softdep_inode_append(ip, cred, wkhd)
14455 	struct inode *ip;
14456 	struct ucred *cred;
14457 	struct workhead *wkhd;
14458 {
14459 	struct buf *bp;
14460 	struct fs *fs;
14461 	struct ufsmount *ump;
14462 	int error;
14463 
14464 	ump = ITOUMP(ip);
14465 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
14466 	    ("softdep_inode_append called on non-softdep filesystem"));
14467 	fs = ump->um_fs;
14468 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14469 	    (int)fs->fs_bsize, cred, &bp);
14470 	if (error) {
14471 		bqrelse(bp);
14472 		softdep_freework(wkhd);
14473 		return;
14474 	}
14475 	softdep_buf_append(bp, wkhd);
14476 	bqrelse(bp);
14477 }
14478 
14479 void
14480 softdep_freework(wkhd)
14481 	struct workhead *wkhd;
14482 {
14483 	struct worklist *wk;
14484 	struct ufsmount *ump;
14485 
14486 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14487 		return;
14488 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14489 	    ("softdep_freework called on non-softdep filesystem"));
14490 	ump = VFSTOUFS(wk->wk_mp);
14491 	ACQUIRE_LOCK(ump);
14492 	handle_jwork(wkhd);
14493 	FREE_LOCK(ump);
14494 }
14495 
14496 static struct ufsmount *
14497 softdep_bp_to_mp(bp)
14498 	struct buf *bp;
14499 {
14500 	struct mount *mp;
14501 	struct vnode *vp;
14502 
14503 	if (LIST_EMPTY(&bp->b_dep))
14504 		return (NULL);
14505 	vp = bp->b_vp;
14506 	KASSERT(vp != NULL,
14507 	    ("%s, buffer with dependencies lacks vnode", __func__));
14508 
14509 	/*
14510 	 * The ump mount point is stable after we get a correct
14511 	 * pointer, since bp is locked and this prevents unmount from
14512 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
14513 	 * head wk_mp, because we do not yet own SU ump lock and
14514 	 * workitem might be freed while dereferenced.
14515 	 */
14516 retry:
14517 	switch (vp->v_type) {
14518 	case VCHR:
14519 		VI_LOCK(vp);
14520 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14521 		VI_UNLOCK(vp);
14522 		if (mp == NULL)
14523 			goto retry;
14524 		break;
14525 	case VREG:
14526 	case VDIR:
14527 	case VLNK:
14528 	case VFIFO:
14529 	case VSOCK:
14530 		mp = vp->v_mount;
14531 		break;
14532 	case VBLK:
14533 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14534 		/* FALLTHROUGH */
14535 	case VNON:
14536 	case VBAD:
14537 	case VMARKER:
14538 		mp = NULL;
14539 		break;
14540 	default:
14541 		vn_printf(vp, "unknown vnode type");
14542 		mp = NULL;
14543 		break;
14544 	}
14545 	return (VFSTOUFS(mp));
14546 }
14547 
14548 /*
14549  * Function to determine if the buffer has outstanding dependencies
14550  * that will cause a roll-back if the buffer is written. If wantcount
14551  * is set, return number of dependencies, otherwise just yes or no.
14552  */
14553 static int
14554 softdep_count_dependencies(bp, wantcount)
14555 	struct buf *bp;
14556 	int wantcount;
14557 {
14558 	struct worklist *wk;
14559 	struct ufsmount *ump;
14560 	struct bmsafemap *bmsafemap;
14561 	struct freework *freework;
14562 	struct inodedep *inodedep;
14563 	struct indirdep *indirdep;
14564 	struct freeblks *freeblks;
14565 	struct allocindir *aip;
14566 	struct pagedep *pagedep;
14567 	struct dirrem *dirrem;
14568 	struct newblk *newblk;
14569 	struct mkdir *mkdir;
14570 	struct diradd *dap;
14571 	int i, retval;
14572 
14573 	ump = softdep_bp_to_mp(bp);
14574 	if (ump == NULL)
14575 		return (0);
14576 	retval = 0;
14577 	ACQUIRE_LOCK(ump);
14578 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14579 		switch (wk->wk_type) {
14580 		case D_INODEDEP:
14581 			inodedep = WK_INODEDEP(wk);
14582 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14583 				/* bitmap allocation dependency */
14584 				retval += 1;
14585 				if (!wantcount)
14586 					goto out;
14587 			}
14588 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14589 				/* direct block pointer dependency */
14590 				retval += 1;
14591 				if (!wantcount)
14592 					goto out;
14593 			}
14594 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14595 				/* direct block pointer dependency */
14596 				retval += 1;
14597 				if (!wantcount)
14598 					goto out;
14599 			}
14600 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14601 				/* Add reference dependency. */
14602 				retval += 1;
14603 				if (!wantcount)
14604 					goto out;
14605 			}
14606 			continue;
14607 
14608 		case D_INDIRDEP:
14609 			indirdep = WK_INDIRDEP(wk);
14610 
14611 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14612 				/* indirect truncation dependency */
14613 				retval += 1;
14614 				if (!wantcount)
14615 					goto out;
14616 			}
14617 
14618 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14619 				/* indirect block pointer dependency */
14620 				retval += 1;
14621 				if (!wantcount)
14622 					goto out;
14623 			}
14624 			continue;
14625 
14626 		case D_PAGEDEP:
14627 			pagedep = WK_PAGEDEP(wk);
14628 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14629 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14630 					/* Journal remove ref dependency. */
14631 					retval += 1;
14632 					if (!wantcount)
14633 						goto out;
14634 				}
14635 			}
14636 			for (i = 0; i < DAHASHSZ; i++) {
14637 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14638 					/* directory entry dependency */
14639 					retval += 1;
14640 					if (!wantcount)
14641 						goto out;
14642 				}
14643 			}
14644 			continue;
14645 
14646 		case D_BMSAFEMAP:
14647 			bmsafemap = WK_BMSAFEMAP(wk);
14648 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14649 				/* Add reference dependency. */
14650 				retval += 1;
14651 				if (!wantcount)
14652 					goto out;
14653 			}
14654 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14655 				/* Allocate block dependency. */
14656 				retval += 1;
14657 				if (!wantcount)
14658 					goto out;
14659 			}
14660 			continue;
14661 
14662 		case D_FREEBLKS:
14663 			freeblks = WK_FREEBLKS(wk);
14664 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14665 				/* Freeblk journal dependency. */
14666 				retval += 1;
14667 				if (!wantcount)
14668 					goto out;
14669 			}
14670 			continue;
14671 
14672 		case D_ALLOCDIRECT:
14673 		case D_ALLOCINDIR:
14674 			newblk = WK_NEWBLK(wk);
14675 			if (newblk->nb_jnewblk) {
14676 				/* Journal allocate dependency. */
14677 				retval += 1;
14678 				if (!wantcount)
14679 					goto out;
14680 			}
14681 			continue;
14682 
14683 		case D_MKDIR:
14684 			mkdir = WK_MKDIR(wk);
14685 			if (mkdir->md_jaddref) {
14686 				/* Journal reference dependency. */
14687 				retval += 1;
14688 				if (!wantcount)
14689 					goto out;
14690 			}
14691 			continue;
14692 
14693 		case D_FREEWORK:
14694 		case D_FREEDEP:
14695 		case D_JSEGDEP:
14696 		case D_JSEG:
14697 		case D_SBDEP:
14698 			/* never a dependency on these blocks */
14699 			continue;
14700 
14701 		default:
14702 			panic("softdep_count_dependencies: Unexpected type %s",
14703 			    TYPENAME(wk->wk_type));
14704 			/* NOTREACHED */
14705 		}
14706 	}
14707 out:
14708 	FREE_LOCK(ump);
14709 	return (retval);
14710 }
14711 
14712 /*
14713  * Acquire exclusive access to a buffer.
14714  * Must be called with a locked mtx parameter.
14715  * Return acquired buffer or NULL on failure.
14716  */
14717 static struct buf *
14718 getdirtybuf(bp, lock, waitfor)
14719 	struct buf *bp;
14720 	struct rwlock *lock;
14721 	int waitfor;
14722 {
14723 	int error;
14724 
14725 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14726 		if (waitfor != MNT_WAIT)
14727 			return (NULL);
14728 		error = BUF_LOCK(bp,
14729 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14730 		/*
14731 		 * Even if we successfully acquire bp here, we have dropped
14732 		 * lock, which may violates our guarantee.
14733 		 */
14734 		if (error == 0)
14735 			BUF_UNLOCK(bp);
14736 		else if (error != ENOLCK)
14737 			panic("getdirtybuf: inconsistent lock: %d", error);
14738 		rw_wlock(lock);
14739 		return (NULL);
14740 	}
14741 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14742 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14743 			rw_wunlock(lock);
14744 			BO_LOCK(bp->b_bufobj);
14745 			BUF_UNLOCK(bp);
14746 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14747 				bp->b_vflags |= BV_BKGRDWAIT;
14748 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14749 				       PRIBIO | PDROP, "getbuf", 0);
14750 			} else
14751 				BO_UNLOCK(bp->b_bufobj);
14752 			rw_wlock(lock);
14753 			return (NULL);
14754 		}
14755 		BUF_UNLOCK(bp);
14756 		if (waitfor != MNT_WAIT)
14757 			return (NULL);
14758 #ifdef DEBUG_VFS_LOCKS
14759 		if (bp->b_vp->v_type != VCHR)
14760 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14761 #endif
14762 		bp->b_vflags |= BV_BKGRDWAIT;
14763 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14764 		return (NULL);
14765 	}
14766 	if ((bp->b_flags & B_DELWRI) == 0) {
14767 		BUF_UNLOCK(bp);
14768 		return (NULL);
14769 	}
14770 	bremfree(bp);
14771 	return (bp);
14772 }
14773 
14774 /*
14775  * Check if it is safe to suspend the file system now.  On entry,
14776  * the vnode interlock for devvp should be held.  Return 0 with
14777  * the mount interlock held if the file system can be suspended now,
14778  * otherwise return EAGAIN with the mount interlock held.
14779  */
14780 int
14781 softdep_check_suspend(struct mount *mp,
14782 		      struct vnode *devvp,
14783 		      int softdep_depcnt,
14784 		      int softdep_accdepcnt,
14785 		      int secondary_writes,
14786 		      int secondary_accwrites)
14787 {
14788 	struct buf *bp;
14789 	struct bufobj *bo;
14790 	struct ufsmount *ump;
14791 	struct inodedep *inodedep;
14792 	struct indirdep *indirdep;
14793 	struct worklist *wk, *nextwk;
14794 	int error, unlinked;
14795 
14796 	bo = &devvp->v_bufobj;
14797 	ASSERT_BO_WLOCKED(bo);
14798 
14799 	/*
14800 	 * If we are not running with soft updates, then we need only
14801 	 * deal with secondary writes as we try to suspend.
14802 	 */
14803 	if (MOUNTEDSOFTDEP(mp) == 0) {
14804 		MNT_ILOCK(mp);
14805 		while (mp->mnt_secondary_writes != 0) {
14806 			BO_UNLOCK(bo);
14807 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14808 			    (PUSER - 1) | PDROP, "secwr", 0);
14809 			BO_LOCK(bo);
14810 			MNT_ILOCK(mp);
14811 		}
14812 
14813 		/*
14814 		 * Reasons for needing more work before suspend:
14815 		 * - Dirty buffers on devvp.
14816 		 * - Secondary writes occurred after start of vnode sync loop
14817 		 */
14818 		error = 0;
14819 		if (bo->bo_numoutput > 0 ||
14820 		    bo->bo_dirty.bv_cnt > 0 ||
14821 		    secondary_writes != 0 ||
14822 		    mp->mnt_secondary_writes != 0 ||
14823 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14824 			error = EAGAIN;
14825 		BO_UNLOCK(bo);
14826 		return (error);
14827 	}
14828 
14829 	/*
14830 	 * If we are running with soft updates, then we need to coordinate
14831 	 * with them as we try to suspend.
14832 	 */
14833 	ump = VFSTOUFS(mp);
14834 	for (;;) {
14835 		if (!TRY_ACQUIRE_LOCK(ump)) {
14836 			BO_UNLOCK(bo);
14837 			ACQUIRE_LOCK(ump);
14838 			FREE_LOCK(ump);
14839 			BO_LOCK(bo);
14840 			continue;
14841 		}
14842 		MNT_ILOCK(mp);
14843 		if (mp->mnt_secondary_writes != 0) {
14844 			FREE_LOCK(ump);
14845 			BO_UNLOCK(bo);
14846 			msleep(&mp->mnt_secondary_writes,
14847 			       MNT_MTX(mp),
14848 			       (PUSER - 1) | PDROP, "secwr", 0);
14849 			BO_LOCK(bo);
14850 			continue;
14851 		}
14852 		break;
14853 	}
14854 
14855 	unlinked = 0;
14856 	if (MOUNTEDSUJ(mp)) {
14857 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14858 		    inodedep != NULL;
14859 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14860 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14861 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14862 			    UNLINKONLIST) ||
14863 			    !check_inodedep_free(inodedep))
14864 				continue;
14865 			unlinked++;
14866 		}
14867 	}
14868 
14869 	/*
14870 	 * XXX Check for orphaned indirdep dependency structures.
14871 	 *
14872 	 * During forcible unmount after a disk failure there is a
14873 	 * bug that causes one or more indirdep dependency structures
14874 	 * to fail to be deallocated. We check for them here and clean
14875 	 * them up so that the unmount can succeed.
14876 	 */
14877 	if ((ump->um_flags & UM_FSFAIL_CLEANUP) != 0 && ump->softdep_deps > 0 &&
14878 	    ump->softdep_deps == ump->softdep_curdeps[D_INDIRDEP]) {
14879 		LIST_FOREACH_SAFE(wk, &ump->softdep_alldeps[D_INDIRDEP],
14880 		    wk_all, nextwk) {
14881 			indirdep = WK_INDIRDEP(wk);
14882 			if ((indirdep->ir_state & (GOINGAWAY | DEPCOMPLETE)) !=
14883 			    (GOINGAWAY | DEPCOMPLETE) ||
14884 			    !TAILQ_EMPTY(&indirdep->ir_trunc) ||
14885 			    !LIST_EMPTY(&indirdep->ir_completehd) ||
14886 			    !LIST_EMPTY(&indirdep->ir_writehd) ||
14887 			    !LIST_EMPTY(&indirdep->ir_donehd) ||
14888 			    !LIST_EMPTY(&indirdep->ir_deplisthd) ||
14889 			    indirdep->ir_saveddata != NULL ||
14890 			    indirdep->ir_savebp == NULL) {
14891 				printf("%s: skipping orphaned indirdep %p\n",
14892 				    __FUNCTION__, indirdep);
14893 				continue;
14894 			}
14895 			printf("%s: freeing orphaned indirdep %p\n",
14896 			    __FUNCTION__, indirdep);
14897 			bp = indirdep->ir_savebp;
14898 			indirdep->ir_savebp = NULL;
14899 			free_indirdep(indirdep);
14900 			FREE_LOCK(ump);
14901 			brelse(bp);
14902 			while (!TRY_ACQUIRE_LOCK(ump)) {
14903 				BO_UNLOCK(bo);
14904 				ACQUIRE_LOCK(ump);
14905 				FREE_LOCK(ump);
14906 				BO_LOCK(bo);
14907 			}
14908 		}
14909 	}
14910 
14911 	/*
14912 	 * Reasons for needing more work before suspend:
14913 	 * - Dirty buffers on devvp.
14914 	 * - Dependency structures still exist
14915 	 * - Softdep activity occurred after start of vnode sync loop
14916 	 * - Secondary writes occurred after start of vnode sync loop
14917 	 */
14918 	error = 0;
14919 	if (bo->bo_numoutput > 0 ||
14920 	    bo->bo_dirty.bv_cnt > 0 ||
14921 	    softdep_depcnt != unlinked ||
14922 	    ump->softdep_deps != unlinked ||
14923 	    softdep_accdepcnt != ump->softdep_accdeps ||
14924 	    secondary_writes != 0 ||
14925 	    mp->mnt_secondary_writes != 0 ||
14926 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14927 		error = EAGAIN;
14928 	FREE_LOCK(ump);
14929 	BO_UNLOCK(bo);
14930 	return (error);
14931 }
14932 
14933 /*
14934  * Get the number of dependency structures for the file system, both
14935  * the current number and the total number allocated.  These will
14936  * later be used to detect that softdep processing has occurred.
14937  */
14938 void
14939 softdep_get_depcounts(struct mount *mp,
14940 		      int *softdep_depsp,
14941 		      int *softdep_accdepsp)
14942 {
14943 	struct ufsmount *ump;
14944 
14945 	if (MOUNTEDSOFTDEP(mp) == 0) {
14946 		*softdep_depsp = 0;
14947 		*softdep_accdepsp = 0;
14948 		return;
14949 	}
14950 	ump = VFSTOUFS(mp);
14951 	ACQUIRE_LOCK(ump);
14952 	*softdep_depsp = ump->softdep_deps;
14953 	*softdep_accdepsp = ump->softdep_accdeps;
14954 	FREE_LOCK(ump);
14955 }
14956 
14957 /*
14958  * Wait for pending output on a vnode to complete.
14959  */
14960 static void
14961 drain_output(vp)
14962 	struct vnode *vp;
14963 {
14964 
14965 	ASSERT_VOP_LOCKED(vp, "drain_output");
14966 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14967 }
14968 
14969 /*
14970  * Called whenever a buffer that is being invalidated or reallocated
14971  * contains dependencies. This should only happen if an I/O error has
14972  * occurred. The routine is called with the buffer locked.
14973  */
14974 static void
14975 softdep_deallocate_dependencies(bp)
14976 	struct buf *bp;
14977 {
14978 
14979 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14980 		panic("softdep_deallocate_dependencies: dangling deps");
14981 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14982 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14983 	else
14984 		printf("softdep_deallocate_dependencies: "
14985 		    "got error %d while accessing filesystem\n", bp->b_error);
14986 	if (bp->b_error != ENXIO)
14987 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14988 }
14989 
14990 /*
14991  * Function to handle asynchronous write errors in the filesystem.
14992  */
14993 static void
14994 softdep_error(func, error)
14995 	char *func;
14996 	int error;
14997 {
14998 
14999 	/* XXX should do something better! */
15000 	printf("%s: got error %d while accessing filesystem\n", func, error);
15001 }
15002 
15003 #ifdef DDB
15004 
15005 /* exported to ffs_vfsops.c */
15006 extern void db_print_ffs(struct ufsmount *ump);
15007 void
15008 db_print_ffs(struct ufsmount *ump)
15009 {
15010 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
15011 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
15012 	db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
15013 	    ump->um_fs, ump->softdep_on_worklist,
15014 	    ump->softdep_deps, ump->softdep_req);
15015 }
15016 
15017 static void
15018 worklist_print(struct worklist *wk, int verbose)
15019 {
15020 
15021 	if (!verbose) {
15022 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
15023 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
15024 		return;
15025 	}
15026 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
15027 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
15028 	    LIST_NEXT(wk, wk_list));
15029 	db_print_ffs(VFSTOUFS(wk->wk_mp));
15030 }
15031 
15032 static void
15033 inodedep_print(struct inodedep *inodedep, int verbose)
15034 {
15035 
15036 	worklist_print(&inodedep->id_list, 0);
15037 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
15038 	    inodedep->id_fs,
15039 	    (intmax_t)inodedep->id_ino,
15040 	    (intmax_t)fsbtodb(inodedep->id_fs,
15041 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
15042 	    (intmax_t)inodedep->id_nlinkdelta,
15043 	    (intmax_t)inodedep->id_savednlink);
15044 
15045 	if (verbose == 0)
15046 		return;
15047 
15048 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
15049 	    inodedep->id_bmsafemap,
15050 	    inodedep->id_mkdiradd,
15051 	    TAILQ_FIRST(&inodedep->id_inoreflst));
15052 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
15053 	    LIST_FIRST(&inodedep->id_dirremhd),
15054 	    LIST_FIRST(&inodedep->id_pendinghd),
15055 	    LIST_FIRST(&inodedep->id_bufwait));
15056 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
15057 	    LIST_FIRST(&inodedep->id_inowait),
15058 	    TAILQ_FIRST(&inodedep->id_inoupdt),
15059 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
15060 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
15061 	    TAILQ_FIRST(&inodedep->id_extupdt),
15062 	    TAILQ_FIRST(&inodedep->id_newextupdt),
15063 	    TAILQ_FIRST(&inodedep->id_freeblklst));
15064 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
15065 	    inodedep->id_savedino1,
15066 	    (intmax_t)inodedep->id_savedsize,
15067 	    (intmax_t)inodedep->id_savedextsize);
15068 }
15069 
15070 static void
15071 newblk_print(struct newblk *nbp)
15072 {
15073 
15074 	worklist_print(&nbp->nb_list, 0);
15075 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
15076 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
15077 	    &nbp->nb_jnewblk,
15078 	    &nbp->nb_bmsafemap,
15079 	    &nbp->nb_freefrag);
15080 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
15081 	    LIST_FIRST(&nbp->nb_indirdeps),
15082 	    LIST_FIRST(&nbp->nb_newdirblk),
15083 	    LIST_FIRST(&nbp->nb_jwork));
15084 }
15085 
15086 static void
15087 allocdirect_print(struct allocdirect *adp)
15088 {
15089 
15090 	newblk_print(&adp->ad_block);
15091 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
15092 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
15093 	db_printf("    offset %d, inodedep %p\n",
15094 	    adp->ad_offset, adp->ad_inodedep);
15095 }
15096 
15097 static void
15098 allocindir_print(struct allocindir *aip)
15099 {
15100 
15101 	newblk_print(&aip->ai_block);
15102 	db_printf("    oldblkno %jd, lbn %jd\n",
15103 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
15104 	db_printf("    offset %d, indirdep %p\n",
15105 	    aip->ai_offset, aip->ai_indirdep);
15106 }
15107 
15108 static void
15109 mkdir_print(struct mkdir *mkdir)
15110 {
15111 
15112 	worklist_print(&mkdir->md_list, 0);
15113 	db_printf("    diradd %p, jaddref %p, buf %p\n",
15114 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
15115 }
15116 
15117 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
15118 {
15119 
15120 	if (have_addr == 0) {
15121 		db_printf("inodedep address required\n");
15122 		return;
15123 	}
15124 	inodedep_print((struct inodedep*)addr, 1);
15125 }
15126 
15127 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
15128 {
15129 	struct inodedep_hashhead *inodedephd;
15130 	struct inodedep *inodedep;
15131 	struct ufsmount *ump;
15132 	int cnt;
15133 
15134 	if (have_addr == 0) {
15135 		db_printf("ufsmount address required\n");
15136 		return;
15137 	}
15138 	ump = (struct ufsmount *)addr;
15139 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
15140 		inodedephd = &ump->inodedep_hashtbl[cnt];
15141 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
15142 			inodedep_print(inodedep, 0);
15143 		}
15144 	}
15145 }
15146 
15147 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
15148 {
15149 
15150 	if (have_addr == 0) {
15151 		db_printf("worklist address required\n");
15152 		return;
15153 	}
15154 	worklist_print((struct worklist *)addr, 1);
15155 }
15156 
15157 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
15158 {
15159 	struct worklist *wk;
15160 	struct workhead *wkhd;
15161 
15162 	if (have_addr == 0) {
15163 		db_printf("worklist address required "
15164 		    "(for example value in bp->b_dep)\n");
15165 		return;
15166 	}
15167 	/*
15168 	 * We often do not have the address of the worklist head but
15169 	 * instead a pointer to its first entry (e.g., we have the
15170 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
15171 	 * pointer of bp->b_dep will point at the head of the list, so
15172 	 * we cheat and use that instead. If we are in the middle of
15173 	 * a list we will still get the same result, so nothing
15174 	 * unexpected will result.
15175 	 */
15176 	wk = (struct worklist *)addr;
15177 	if (wk == NULL)
15178 		return;
15179 	wkhd = (struct workhead *)wk->wk_list.le_prev;
15180 	LIST_FOREACH(wk, wkhd, wk_list) {
15181 		switch(wk->wk_type) {
15182 		case D_INODEDEP:
15183 			inodedep_print(WK_INODEDEP(wk), 0);
15184 			continue;
15185 		case D_ALLOCDIRECT:
15186 			allocdirect_print(WK_ALLOCDIRECT(wk));
15187 			continue;
15188 		case D_ALLOCINDIR:
15189 			allocindir_print(WK_ALLOCINDIR(wk));
15190 			continue;
15191 		case D_MKDIR:
15192 			mkdir_print(WK_MKDIR(wk));
15193 			continue;
15194 		default:
15195 			worklist_print(wk, 0);
15196 			continue;
15197 		}
15198 	}
15199 }
15200 
15201 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
15202 {
15203 	if (have_addr == 0) {
15204 		db_printf("mkdir address required\n");
15205 		return;
15206 	}
15207 	mkdir_print((struct mkdir *)addr);
15208 }
15209 
15210 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
15211 {
15212 	struct mkdirlist *mkdirlisthd;
15213 	struct mkdir *mkdir;
15214 
15215 	if (have_addr == 0) {
15216 		db_printf("mkdir listhead address required\n");
15217 		return;
15218 	}
15219 	mkdirlisthd = (struct mkdirlist *)addr;
15220 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
15221 		mkdir_print(mkdir);
15222 		if (mkdir->md_diradd != NULL) {
15223 			db_printf("    ");
15224 			worklist_print(&mkdir->md_diradd->da_list, 0);
15225 		}
15226 		if (mkdir->md_jaddref != NULL) {
15227 			db_printf("    ");
15228 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
15229 		}
15230 	}
15231 }
15232 
15233 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
15234 {
15235 	if (have_addr == 0) {
15236 		db_printf("allocdirect address required\n");
15237 		return;
15238 	}
15239 	allocdirect_print((struct allocdirect *)addr);
15240 }
15241 
15242 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
15243 {
15244 	if (have_addr == 0) {
15245 		db_printf("allocindir address required\n");
15246 		return;
15247 	}
15248 	allocindir_print((struct allocindir *)addr);
15249 }
15250 
15251 #endif /* DDB */
15252 
15253 #endif /* SOFTUPDATES */
15254