xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision ec0ea6efa1ad229d75c394c1a9b9cac33af2b1d3)
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_cred = curthread->td_ucred;
2979 	cnp.cn_pnbuf = SUJ_FILE;
2980 	cnp.cn_nameptr = SUJ_FILE;
2981 	cnp.cn_namelen = strlen(SUJ_FILE);
2982 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2983 	vput(dvp);
2984 	if (error != 0)
2985 		return (error);
2986 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2987 	return (error);
2988 }
2989 
2990 /*
2991  * Open and verify the journal file.
2992  */
2993 static int
2994 journal_mount(mp, fs, cred)
2995 	struct mount *mp;
2996 	struct fs *fs;
2997 	struct ucred *cred;
2998 {
2999 	struct jblocks *jblocks;
3000 	struct ufsmount *ump;
3001 	struct vnode *vp;
3002 	struct inode *ip;
3003 	ufs2_daddr_t blkno;
3004 	int bcount;
3005 	int error;
3006 	int i;
3007 
3008 	ump = VFSTOUFS(mp);
3009 	ump->softdep_journal_tail = NULL;
3010 	ump->softdep_on_journal = 0;
3011 	ump->softdep_accdeps = 0;
3012 	ump->softdep_req = 0;
3013 	ump->softdep_jblocks = NULL;
3014 	error = softdep_journal_lookup(mp, &vp);
3015 	if (error != 0) {
3016 		printf("Failed to find journal.  Use tunefs to create one\n");
3017 		return (error);
3018 	}
3019 	ip = VTOI(vp);
3020 	if (ip->i_size < SUJ_MIN) {
3021 		error = ENOSPC;
3022 		goto out;
3023 	}
3024 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
3025 	jblocks = jblocks_create();
3026 	for (i = 0; i < bcount; i++) {
3027 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
3028 		if (error)
3029 			break;
3030 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
3031 	}
3032 	if (error) {
3033 		jblocks_destroy(jblocks);
3034 		goto out;
3035 	}
3036 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
3037 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
3038 	ump->softdep_jblocks = jblocks;
3039 
3040 	MNT_ILOCK(mp);
3041 	mp->mnt_flag |= MNT_SUJ;
3042 	MNT_IUNLOCK(mp);
3043 
3044 	/*
3045 	 * Only validate the journal contents if the
3046 	 * filesystem is clean, otherwise we write the logs
3047 	 * but they'll never be used.  If the filesystem was
3048 	 * still dirty when we mounted it the journal is
3049 	 * invalid and a new journal can only be valid if it
3050 	 * starts from a clean mount.
3051 	 */
3052 	if (fs->fs_clean) {
3053 		DIP_SET(ip, i_modrev, fs->fs_mtime);
3054 		ip->i_flags |= IN_MODIFIED;
3055 		ffs_update(vp, 1);
3056 	}
3057 out:
3058 	vput(vp);
3059 	return (error);
3060 }
3061 
3062 static void
3063 journal_unmount(ump)
3064 	struct ufsmount *ump;
3065 {
3066 
3067 	if (ump->softdep_jblocks)
3068 		jblocks_destroy(ump->softdep_jblocks);
3069 	ump->softdep_jblocks = NULL;
3070 }
3071 
3072 /*
3073  * Called when a journal record is ready to be written.  Space is allocated
3074  * and the journal entry is created when the journal is flushed to stable
3075  * store.
3076  */
3077 static void
3078 add_to_journal(wk)
3079 	struct worklist *wk;
3080 {
3081 	struct ufsmount *ump;
3082 
3083 	ump = VFSTOUFS(wk->wk_mp);
3084 	LOCK_OWNED(ump);
3085 	if (wk->wk_state & ONWORKLIST)
3086 		panic("add_to_journal: %s(0x%X) already on list",
3087 		    TYPENAME(wk->wk_type), wk->wk_state);
3088 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
3089 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
3090 		ump->softdep_jblocks->jb_age = ticks;
3091 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
3092 	} else
3093 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
3094 	ump->softdep_journal_tail = wk;
3095 	ump->softdep_on_journal += 1;
3096 }
3097 
3098 /*
3099  * Remove an arbitrary item for the journal worklist maintain the tail
3100  * pointer.  This happens when a new operation obviates the need to
3101  * journal an old operation.
3102  */
3103 static void
3104 remove_from_journal(wk)
3105 	struct worklist *wk;
3106 {
3107 	struct ufsmount *ump;
3108 
3109 	ump = VFSTOUFS(wk->wk_mp);
3110 	LOCK_OWNED(ump);
3111 #ifdef INVARIANTS
3112 	{
3113 		struct worklist *wkn;
3114 
3115 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
3116 			if (wkn == wk)
3117 				break;
3118 		if (wkn == NULL)
3119 			panic("remove_from_journal: %p is not in journal", wk);
3120 	}
3121 #endif
3122 	/*
3123 	 * We emulate a TAILQ to save space in most structures which do not
3124 	 * require TAILQ semantics.  Here we must update the tail position
3125 	 * when removing the tail which is not the final entry. This works
3126 	 * only if the worklist linkage are at the beginning of the structure.
3127 	 */
3128 	if (ump->softdep_journal_tail == wk)
3129 		ump->softdep_journal_tail =
3130 		    (struct worklist *)wk->wk_list.le_prev;
3131 	WORKLIST_REMOVE(wk);
3132 	ump->softdep_on_journal -= 1;
3133 }
3134 
3135 /*
3136  * Check for journal space as well as dependency limits so the prelink
3137  * code can throttle both journaled and non-journaled filesystems.
3138  * Threshold is 0 for low and 1 for min.
3139  */
3140 static int
3141 journal_space(ump, thresh)
3142 	struct ufsmount *ump;
3143 	int thresh;
3144 {
3145 	struct jblocks *jblocks;
3146 	int limit, avail;
3147 
3148 	jblocks = ump->softdep_jblocks;
3149 	if (jblocks == NULL)
3150 		return (1);
3151 	/*
3152 	 * We use a tighter restriction here to prevent request_cleanup()
3153 	 * running in threads from running into locks we currently hold.
3154 	 * We have to be over the limit and our filesystem has to be
3155 	 * responsible for more than our share of that usage.
3156 	 */
3157 	limit = (max_softdeps / 10) * 9;
3158 	if (dep_current[D_INODEDEP] > limit &&
3159 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
3160 		return (0);
3161 	if (thresh)
3162 		thresh = jblocks->jb_min;
3163 	else
3164 		thresh = jblocks->jb_low;
3165 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
3166 	avail = jblocks->jb_free - avail;
3167 
3168 	return (avail > thresh);
3169 }
3170 
3171 static void
3172 journal_suspend(ump)
3173 	struct ufsmount *ump;
3174 {
3175 	struct jblocks *jblocks;
3176 	struct mount *mp;
3177 	bool set;
3178 
3179 	mp = UFSTOVFS(ump);
3180 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
3181 		return;
3182 
3183 	jblocks = ump->softdep_jblocks;
3184 	vfs_op_enter(mp);
3185 	set = false;
3186 	MNT_ILOCK(mp);
3187 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
3188 		stat_journal_min++;
3189 		mp->mnt_kern_flag |= MNTK_SUSPEND;
3190 		mp->mnt_susp_owner = ump->softdep_flushtd;
3191 		set = true;
3192 	}
3193 	jblocks->jb_suspended = 1;
3194 	MNT_IUNLOCK(mp);
3195 	if (!set)
3196 		vfs_op_exit(mp);
3197 }
3198 
3199 static int
3200 journal_unsuspend(struct ufsmount *ump)
3201 {
3202 	struct jblocks *jblocks;
3203 	struct mount *mp;
3204 
3205 	mp = UFSTOVFS(ump);
3206 	jblocks = ump->softdep_jblocks;
3207 
3208 	if (jblocks != NULL && jblocks->jb_suspended &&
3209 	    journal_space(ump, jblocks->jb_min)) {
3210 		jblocks->jb_suspended = 0;
3211 		FREE_LOCK(ump);
3212 		mp->mnt_susp_owner = curthread;
3213 		vfs_write_resume(mp, 0);
3214 		ACQUIRE_LOCK(ump);
3215 		return (1);
3216 	}
3217 	return (0);
3218 }
3219 
3220 static void
3221 journal_check_space(struct ufsmount *ump)
3222 {
3223 	struct mount *mp;
3224 
3225 	LOCK_OWNED(ump);
3226 
3227 	if (journal_space(ump, 0) == 0) {
3228 		softdep_speedup(ump);
3229 		mp = UFSTOVFS(ump);
3230 		FREE_LOCK(ump);
3231 		VFS_SYNC(mp, MNT_NOWAIT);
3232 		ffs_sbupdate(ump, MNT_WAIT, 0);
3233 		ACQUIRE_LOCK(ump);
3234 		if (journal_space(ump, 1) == 0)
3235 			journal_suspend(ump);
3236 	}
3237 }
3238 
3239 /*
3240  * Called before any allocation function to be certain that there is
3241  * sufficient space in the journal prior to creating any new records.
3242  * Since in the case of block allocation we may have multiple locked
3243  * buffers at the time of the actual allocation we can not block
3244  * when the journal records are created.  Doing so would create a deadlock
3245  * if any of these buffers needed to be flushed to reclaim space.  Instead
3246  * we require a sufficiently large amount of available space such that
3247  * each thread in the system could have passed this allocation check and
3248  * still have sufficient free space.  With 20% of a minimum journal size
3249  * of 1MB we have 6553 records available.
3250  */
3251 int
3252 softdep_prealloc(vp, waitok)
3253 	struct vnode *vp;
3254 	int waitok;
3255 {
3256 	struct ufsmount *ump;
3257 
3258 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3259 	    ("softdep_prealloc called on non-softdep filesystem"));
3260 	/*
3261 	 * Nothing to do if we are not running journaled soft updates.
3262 	 * If we currently hold the snapshot lock, we must avoid
3263 	 * handling other resources that could cause deadlock.  Do not
3264 	 * touch quotas vnode since it is typically recursed with
3265 	 * other vnode locks held.
3266 	 */
3267 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3268 	    (vp->v_vflag & VV_SYSTEM) != 0)
3269 		return (0);
3270 	ump = VFSTOUFS(vp->v_mount);
3271 	ACQUIRE_LOCK(ump);
3272 	if (journal_space(ump, 0)) {
3273 		FREE_LOCK(ump);
3274 		return (0);
3275 	}
3276 	stat_journal_low++;
3277 	FREE_LOCK(ump);
3278 	if (waitok == MNT_NOWAIT)
3279 		return (ENOSPC);
3280 	/*
3281 	 * Attempt to sync this vnode once to flush any journal
3282 	 * work attached to it.
3283 	 */
3284 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3285 		ffs_syncvnode(vp, waitok, 0);
3286 	ACQUIRE_LOCK(ump);
3287 	process_removes(vp);
3288 	process_truncates(vp);
3289 	journal_check_space(ump);
3290 	FREE_LOCK(ump);
3291 
3292 	return (0);
3293 }
3294 
3295 /*
3296  * Try hard to sync all data and metadata for the vnode, and workitems
3297  * flushing which might conflict with the vnode lock.  This is a
3298  * helper for softdep_prerename().
3299  */
3300 static int
3301 softdep_prerename_vnode(ump, vp)
3302 	struct ufsmount *ump;
3303 	struct vnode *vp;
3304 {
3305 	int error;
3306 
3307 	ASSERT_VOP_ELOCKED(vp, "prehandle");
3308 	if (vp->v_data == NULL)
3309 		return (0);
3310 	error = VOP_FSYNC(vp, MNT_WAIT, curthread);
3311 	if (error != 0)
3312 		return (error);
3313 	ACQUIRE_LOCK(ump);
3314 	process_removes(vp);
3315 	process_truncates(vp);
3316 	FREE_LOCK(ump);
3317 	return (0);
3318 }
3319 
3320 /*
3321  * Must be called from VOP_RENAME() after all vnodes are locked.
3322  * Ensures that there is enough journal space for rename.  It is
3323  * sufficiently different from softdep_prelink() by having to handle
3324  * four vnodes.
3325  */
3326 int
3327 softdep_prerename(fdvp, fvp, tdvp, tvp)
3328 	struct vnode *fdvp;
3329 	struct vnode *fvp;
3330 	struct vnode *tdvp;
3331 	struct vnode *tvp;
3332 {
3333 	struct ufsmount *ump;
3334 	int error;
3335 
3336 	ump = VFSTOUFS(fdvp->v_mount);
3337 
3338 	if (journal_space(ump, 0))
3339 		return (0);
3340 
3341 	VOP_UNLOCK(tdvp);
3342 	VOP_UNLOCK(fvp);
3343 	if (tvp != NULL && tvp != tdvp)
3344 		VOP_UNLOCK(tvp);
3345 
3346 	error = softdep_prerename_vnode(ump, fdvp);
3347 	VOP_UNLOCK(fdvp);
3348 	if (error != 0)
3349 		return (error);
3350 
3351 	VOP_LOCK(fvp, LK_EXCLUSIVE | LK_RETRY);
3352 	error = softdep_prerename_vnode(ump, fvp);
3353 	VOP_UNLOCK(fvp);
3354 	if (error != 0)
3355 		return (error);
3356 
3357 	if (tdvp != fdvp) {
3358 		VOP_LOCK(tdvp, LK_EXCLUSIVE | LK_RETRY);
3359 		error = softdep_prerename_vnode(ump, tdvp);
3360 		VOP_UNLOCK(tdvp);
3361 		if (error != 0)
3362 			return (error);
3363 	}
3364 
3365 	if (tvp != fvp && tvp != NULL) {
3366 		VOP_LOCK(tvp, LK_EXCLUSIVE | LK_RETRY);
3367 		error = softdep_prerename_vnode(ump, tvp);
3368 		VOP_UNLOCK(tvp);
3369 		if (error != 0)
3370 			return (error);
3371 	}
3372 
3373 	ACQUIRE_LOCK(ump);
3374 	softdep_speedup(ump);
3375 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3376 	journal_check_space(ump);
3377 	FREE_LOCK(ump);
3378 	return (ERELOOKUP);
3379 }
3380 
3381 /*
3382  * Before adjusting a link count on a vnode verify that we have sufficient
3383  * journal space.  If not, process operations that depend on the currently
3384  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3385  * and softdep flush threads can not acquire these locks to reclaim space.
3386  *
3387  * Returns 0 if all owned locks are still valid and were not dropped
3388  * in the process, in other case it returns either an error from sync,
3389  * or ERELOOKUP if any of the locks were re-acquired.  In the later
3390  * case, the state of the vnodes cannot be relied upon and our VFS
3391  * syscall must be restarted at top level from the lookup.
3392  */
3393 int
3394 softdep_prelink(dvp, vp, cnp)
3395 	struct vnode *dvp;
3396 	struct vnode *vp;
3397 	struct componentname *cnp;
3398 {
3399 	struct ufsmount *ump;
3400 	struct nameidata *ndp;
3401 
3402 	ASSERT_VOP_ELOCKED(dvp, "prelink dvp");
3403 	if (vp != NULL)
3404 		ASSERT_VOP_ELOCKED(vp, "prelink vp");
3405 	ump = VFSTOUFS(dvp->v_mount);
3406 
3407 	/*
3408 	 * Nothing to do if we have sufficient journal space.  We skip
3409 	 * flushing when vp is a snapshot to avoid deadlock where
3410 	 * another thread is trying to update the inodeblock for dvp
3411 	 * and is waiting on snaplk that vp holds.
3412 	 */
3413 	if (journal_space(ump, 0) || (vp != NULL && IS_SNAPSHOT(VTOI(vp))))
3414 		return (0);
3415 
3416 	/*
3417 	 * Check if the journal space consumption can in theory be
3418 	 * accounted on dvp and vp.  If the vnodes metadata was not
3419 	 * changed comparing with the previous round-trip into
3420 	 * softdep_prelink(), as indicated by the seqc generation
3421 	 * recorded in the nameidata, then there is no point in
3422 	 * starting the sync.
3423 	 */
3424 	ndp = __containerof(cnp, struct nameidata, ni_cnd);
3425 	if (!seqc_in_modify(ndp->ni_dvp_seqc) &&
3426 	    vn_seqc_consistent(dvp, ndp->ni_dvp_seqc) &&
3427 	    (vp == NULL || (!seqc_in_modify(ndp->ni_vp_seqc) &&
3428 	    vn_seqc_consistent(vp, ndp->ni_vp_seqc))))
3429 		return (0);
3430 
3431 	stat_journal_low++;
3432 	if (vp != NULL) {
3433 		VOP_UNLOCK(dvp);
3434 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3435 		vn_lock_pair(dvp, false, vp, true);
3436 		if (dvp->v_data == NULL)
3437 			goto out;
3438 	}
3439 	if (vp != NULL)
3440 		VOP_UNLOCK(vp);
3441 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3442 	/* Process vp before dvp as it may create .. removes. */
3443 	if (vp != NULL) {
3444 		VOP_UNLOCK(dvp);
3445 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3446 		if (vp->v_data == NULL) {
3447 			vn_lock_pair(dvp, false, vp, true);
3448 			goto out;
3449 		}
3450 		ACQUIRE_LOCK(ump);
3451 		process_removes(vp);
3452 		process_truncates(vp);
3453 		FREE_LOCK(ump);
3454 		VOP_UNLOCK(vp);
3455 		vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
3456 		if (dvp->v_data == NULL) {
3457 			vn_lock_pair(dvp, true, vp, false);
3458 			goto out;
3459 		}
3460 	}
3461 
3462 	ACQUIRE_LOCK(ump);
3463 	process_removes(dvp);
3464 	process_truncates(dvp);
3465 	VOP_UNLOCK(dvp);
3466 	softdep_speedup(ump);
3467 
3468 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3469 	journal_check_space(ump);
3470 	FREE_LOCK(ump);
3471 
3472 	vn_lock_pair(dvp, false, vp, false);
3473 out:
3474 	ndp->ni_dvp_seqc = vn_seqc_read_any(dvp);
3475 	if (vp != NULL)
3476 		ndp->ni_vp_seqc = vn_seqc_read_any(vp);
3477 	return (ERELOOKUP);
3478 }
3479 
3480 static void
3481 jseg_write(ump, jseg, data)
3482 	struct ufsmount *ump;
3483 	struct jseg *jseg;
3484 	uint8_t *data;
3485 {
3486 	struct jsegrec *rec;
3487 
3488 	rec = (struct jsegrec *)data;
3489 	rec->jsr_seq = jseg->js_seq;
3490 	rec->jsr_oldest = jseg->js_oldseq;
3491 	rec->jsr_cnt = jseg->js_cnt;
3492 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3493 	rec->jsr_crc = 0;
3494 	rec->jsr_time = ump->um_fs->fs_mtime;
3495 }
3496 
3497 static inline void
3498 inoref_write(inoref, jseg, rec)
3499 	struct inoref *inoref;
3500 	struct jseg *jseg;
3501 	struct jrefrec *rec;
3502 {
3503 
3504 	inoref->if_jsegdep->jd_seg = jseg;
3505 	rec->jr_ino = inoref->if_ino;
3506 	rec->jr_parent = inoref->if_parent;
3507 	rec->jr_nlink = inoref->if_nlink;
3508 	rec->jr_mode = inoref->if_mode;
3509 	rec->jr_diroff = inoref->if_diroff;
3510 }
3511 
3512 static void
3513 jaddref_write(jaddref, jseg, data)
3514 	struct jaddref *jaddref;
3515 	struct jseg *jseg;
3516 	uint8_t *data;
3517 {
3518 	struct jrefrec *rec;
3519 
3520 	rec = (struct jrefrec *)data;
3521 	rec->jr_op = JOP_ADDREF;
3522 	inoref_write(&jaddref->ja_ref, jseg, rec);
3523 }
3524 
3525 static void
3526 jremref_write(jremref, jseg, data)
3527 	struct jremref *jremref;
3528 	struct jseg *jseg;
3529 	uint8_t *data;
3530 {
3531 	struct jrefrec *rec;
3532 
3533 	rec = (struct jrefrec *)data;
3534 	rec->jr_op = JOP_REMREF;
3535 	inoref_write(&jremref->jr_ref, jseg, rec);
3536 }
3537 
3538 static void
3539 jmvref_write(jmvref, jseg, data)
3540 	struct jmvref *jmvref;
3541 	struct jseg *jseg;
3542 	uint8_t *data;
3543 {
3544 	struct jmvrec *rec;
3545 
3546 	rec = (struct jmvrec *)data;
3547 	rec->jm_op = JOP_MVREF;
3548 	rec->jm_ino = jmvref->jm_ino;
3549 	rec->jm_parent = jmvref->jm_parent;
3550 	rec->jm_oldoff = jmvref->jm_oldoff;
3551 	rec->jm_newoff = jmvref->jm_newoff;
3552 }
3553 
3554 static void
3555 jnewblk_write(jnewblk, jseg, data)
3556 	struct jnewblk *jnewblk;
3557 	struct jseg *jseg;
3558 	uint8_t *data;
3559 {
3560 	struct jblkrec *rec;
3561 
3562 	jnewblk->jn_jsegdep->jd_seg = jseg;
3563 	rec = (struct jblkrec *)data;
3564 	rec->jb_op = JOP_NEWBLK;
3565 	rec->jb_ino = jnewblk->jn_ino;
3566 	rec->jb_blkno = jnewblk->jn_blkno;
3567 	rec->jb_lbn = jnewblk->jn_lbn;
3568 	rec->jb_frags = jnewblk->jn_frags;
3569 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3570 }
3571 
3572 static void
3573 jfreeblk_write(jfreeblk, jseg, data)
3574 	struct jfreeblk *jfreeblk;
3575 	struct jseg *jseg;
3576 	uint8_t *data;
3577 {
3578 	struct jblkrec *rec;
3579 
3580 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3581 	rec = (struct jblkrec *)data;
3582 	rec->jb_op = JOP_FREEBLK;
3583 	rec->jb_ino = jfreeblk->jf_ino;
3584 	rec->jb_blkno = jfreeblk->jf_blkno;
3585 	rec->jb_lbn = jfreeblk->jf_lbn;
3586 	rec->jb_frags = jfreeblk->jf_frags;
3587 	rec->jb_oldfrags = 0;
3588 }
3589 
3590 static void
3591 jfreefrag_write(jfreefrag, jseg, data)
3592 	struct jfreefrag *jfreefrag;
3593 	struct jseg *jseg;
3594 	uint8_t *data;
3595 {
3596 	struct jblkrec *rec;
3597 
3598 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3599 	rec = (struct jblkrec *)data;
3600 	rec->jb_op = JOP_FREEBLK;
3601 	rec->jb_ino = jfreefrag->fr_ino;
3602 	rec->jb_blkno = jfreefrag->fr_blkno;
3603 	rec->jb_lbn = jfreefrag->fr_lbn;
3604 	rec->jb_frags = jfreefrag->fr_frags;
3605 	rec->jb_oldfrags = 0;
3606 }
3607 
3608 static void
3609 jtrunc_write(jtrunc, jseg, data)
3610 	struct jtrunc *jtrunc;
3611 	struct jseg *jseg;
3612 	uint8_t *data;
3613 {
3614 	struct jtrncrec *rec;
3615 
3616 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3617 	rec = (struct jtrncrec *)data;
3618 	rec->jt_op = JOP_TRUNC;
3619 	rec->jt_ino = jtrunc->jt_ino;
3620 	rec->jt_size = jtrunc->jt_size;
3621 	rec->jt_extsize = jtrunc->jt_extsize;
3622 }
3623 
3624 static void
3625 jfsync_write(jfsync, jseg, data)
3626 	struct jfsync *jfsync;
3627 	struct jseg *jseg;
3628 	uint8_t *data;
3629 {
3630 	struct jtrncrec *rec;
3631 
3632 	rec = (struct jtrncrec *)data;
3633 	rec->jt_op = JOP_SYNC;
3634 	rec->jt_ino = jfsync->jfs_ino;
3635 	rec->jt_size = jfsync->jfs_size;
3636 	rec->jt_extsize = jfsync->jfs_extsize;
3637 }
3638 
3639 static void
3640 softdep_flushjournal(mp)
3641 	struct mount *mp;
3642 {
3643 	struct jblocks *jblocks;
3644 	struct ufsmount *ump;
3645 
3646 	if (MOUNTEDSUJ(mp) == 0)
3647 		return;
3648 	ump = VFSTOUFS(mp);
3649 	jblocks = ump->softdep_jblocks;
3650 	ACQUIRE_LOCK(ump);
3651 	while (ump->softdep_on_journal) {
3652 		jblocks->jb_needseg = 1;
3653 		softdep_process_journal(mp, NULL, MNT_WAIT);
3654 	}
3655 	FREE_LOCK(ump);
3656 }
3657 
3658 static void softdep_synchronize_completed(struct bio *);
3659 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3660 
3661 static void
3662 softdep_synchronize_completed(bp)
3663         struct bio *bp;
3664 {
3665 	struct jseg *oldest;
3666 	struct jseg *jseg;
3667 	struct ufsmount *ump;
3668 
3669 	/*
3670 	 * caller1 marks the last segment written before we issued the
3671 	 * synchronize cache.
3672 	 */
3673 	jseg = bp->bio_caller1;
3674 	if (jseg == NULL) {
3675 		g_destroy_bio(bp);
3676 		return;
3677 	}
3678 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3679 	ACQUIRE_LOCK(ump);
3680 	oldest = NULL;
3681 	/*
3682 	 * Mark all the journal entries waiting on the synchronize cache
3683 	 * as completed so they may continue on.
3684 	 */
3685 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3686 		jseg->js_state |= COMPLETE;
3687 		oldest = jseg;
3688 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3689 	}
3690 	/*
3691 	 * Restart deferred journal entry processing from the oldest
3692 	 * completed jseg.
3693 	 */
3694 	if (oldest)
3695 		complete_jsegs(oldest);
3696 
3697 	FREE_LOCK(ump);
3698 	g_destroy_bio(bp);
3699 }
3700 
3701 /*
3702  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3703  * barriers.  The journal must be written prior to any blocks that depend
3704  * on it and the journal can not be released until the blocks have be
3705  * written.  This code handles both barriers simultaneously.
3706  */
3707 static void
3708 softdep_synchronize(bp, ump, caller1)
3709 	struct bio *bp;
3710 	struct ufsmount *ump;
3711 	void *caller1;
3712 {
3713 
3714 	bp->bio_cmd = BIO_FLUSH;
3715 	bp->bio_flags |= BIO_ORDERED;
3716 	bp->bio_data = NULL;
3717 	bp->bio_offset = ump->um_cp->provider->mediasize;
3718 	bp->bio_length = 0;
3719 	bp->bio_done = softdep_synchronize_completed;
3720 	bp->bio_caller1 = caller1;
3721 	g_io_request(bp, ump->um_cp);
3722 }
3723 
3724 /*
3725  * Flush some journal records to disk.
3726  */
3727 static void
3728 softdep_process_journal(mp, needwk, flags)
3729 	struct mount *mp;
3730 	struct worklist *needwk;
3731 	int flags;
3732 {
3733 	struct jblocks *jblocks;
3734 	struct ufsmount *ump;
3735 	struct worklist *wk;
3736 	struct jseg *jseg;
3737 	struct buf *bp;
3738 	struct bio *bio;
3739 	uint8_t *data;
3740 	struct fs *fs;
3741 	int shouldflush;
3742 	int segwritten;
3743 	int jrecmin;	/* Minimum records per block. */
3744 	int jrecmax;	/* Maximum records per block. */
3745 	int size;
3746 	int cnt;
3747 	int off;
3748 	int devbsize;
3749 
3750 	ump = VFSTOUFS(mp);
3751 	if (ump->um_softdep == NULL || ump->um_softdep->sd_jblocks == NULL)
3752 		return;
3753 	shouldflush = softdep_flushcache;
3754 	bio = NULL;
3755 	jseg = NULL;
3756 	LOCK_OWNED(ump);
3757 	fs = ump->um_fs;
3758 	jblocks = ump->softdep_jblocks;
3759 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3760 	/*
3761 	 * We write anywhere between a disk block and fs block.  The upper
3762 	 * bound is picked to prevent buffer cache fragmentation and limit
3763 	 * processing time per I/O.
3764 	 */
3765 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3766 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3767 	segwritten = 0;
3768 	for (;;) {
3769 		cnt = ump->softdep_on_journal;
3770 		/*
3771 		 * Criteria for writing a segment:
3772 		 * 1) We have a full block.
3773 		 * 2) We're called from jwait() and haven't found the
3774 		 *    journal item yet.
3775 		 * 3) Always write if needseg is set.
3776 		 * 4) If we are called from process_worklist and have
3777 		 *    not yet written anything we write a partial block
3778 		 *    to enforce a 1 second maximum latency on journal
3779 		 *    entries.
3780 		 */
3781 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3782 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3783 			break;
3784 		cnt++;
3785 		/*
3786 		 * Verify some free journal space.  softdep_prealloc() should
3787 		 * guarantee that we don't run out so this is indicative of
3788 		 * a problem with the flow control.  Try to recover
3789 		 * gracefully in any event.
3790 		 */
3791 		while (jblocks->jb_free == 0) {
3792 			if (flags != MNT_WAIT)
3793 				break;
3794 			printf("softdep: Out of journal space!\n");
3795 			softdep_speedup(ump);
3796 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3797 		}
3798 		FREE_LOCK(ump);
3799 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3800 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3801 		LIST_INIT(&jseg->js_entries);
3802 		LIST_INIT(&jseg->js_indirs);
3803 		jseg->js_state = ATTACHED;
3804 		if (shouldflush == 0)
3805 			jseg->js_state |= COMPLETE;
3806 		else if (bio == NULL)
3807 			bio = g_alloc_bio();
3808 		jseg->js_jblocks = jblocks;
3809 		bp = geteblk(fs->fs_bsize, 0);
3810 		ACQUIRE_LOCK(ump);
3811 		/*
3812 		 * If there was a race while we were allocating the block
3813 		 * and jseg the entry we care about was likely written.
3814 		 * We bail out in both the WAIT and NOWAIT case and assume
3815 		 * the caller will loop if the entry it cares about is
3816 		 * not written.
3817 		 */
3818 		cnt = ump->softdep_on_journal;
3819 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3820 			bp->b_flags |= B_INVAL | B_NOCACHE;
3821 			WORKITEM_FREE(jseg, D_JSEG);
3822 			FREE_LOCK(ump);
3823 			brelse(bp);
3824 			ACQUIRE_LOCK(ump);
3825 			break;
3826 		}
3827 		/*
3828 		 * Calculate the disk block size required for the available
3829 		 * records rounded to the min size.
3830 		 */
3831 		if (cnt == 0)
3832 			size = devbsize;
3833 		else if (cnt < jrecmax)
3834 			size = howmany(cnt, jrecmin) * devbsize;
3835 		else
3836 			size = fs->fs_bsize;
3837 		/*
3838 		 * Allocate a disk block for this journal data and account
3839 		 * for truncation of the requested size if enough contiguous
3840 		 * space was not available.
3841 		 */
3842 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3843 		bp->b_lblkno = bp->b_blkno;
3844 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3845 		bp->b_bcount = size;
3846 		bp->b_flags &= ~B_INVAL;
3847 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3848 		/*
3849 		 * Initialize our jseg with cnt records.  Assign the next
3850 		 * sequence number to it and link it in-order.
3851 		 */
3852 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3853 		jseg->js_buf = bp;
3854 		jseg->js_cnt = cnt;
3855 		jseg->js_refs = cnt + 1;	/* Self ref. */
3856 		jseg->js_size = size;
3857 		jseg->js_seq = jblocks->jb_nextseq++;
3858 		if (jblocks->jb_oldestseg == NULL)
3859 			jblocks->jb_oldestseg = jseg;
3860 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3861 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3862 		if (jblocks->jb_writeseg == NULL)
3863 			jblocks->jb_writeseg = jseg;
3864 		/*
3865 		 * Start filling in records from the pending list.
3866 		 */
3867 		data = bp->b_data;
3868 		off = 0;
3869 
3870 		/*
3871 		 * Always put a header on the first block.
3872 		 * XXX As with below, there might not be a chance to get
3873 		 * into the loop.  Ensure that something valid is written.
3874 		 */
3875 		jseg_write(ump, jseg, data);
3876 		off += JREC_SIZE;
3877 		data = bp->b_data + off;
3878 
3879 		/*
3880 		 * XXX Something is wrong here.  There's no work to do,
3881 		 * but we need to perform and I/O and allow it to complete
3882 		 * anyways.
3883 		 */
3884 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3885 			stat_emptyjblocks++;
3886 
3887 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3888 		    != NULL) {
3889 			if (cnt == 0)
3890 				break;
3891 			/* Place a segment header on every device block. */
3892 			if ((off % devbsize) == 0) {
3893 				jseg_write(ump, jseg, data);
3894 				off += JREC_SIZE;
3895 				data = bp->b_data + off;
3896 			}
3897 			if (wk == needwk)
3898 				needwk = NULL;
3899 			remove_from_journal(wk);
3900 			wk->wk_state |= INPROGRESS;
3901 			WORKLIST_INSERT(&jseg->js_entries, wk);
3902 			switch (wk->wk_type) {
3903 			case D_JADDREF:
3904 				jaddref_write(WK_JADDREF(wk), jseg, data);
3905 				break;
3906 			case D_JREMREF:
3907 				jremref_write(WK_JREMREF(wk), jseg, data);
3908 				break;
3909 			case D_JMVREF:
3910 				jmvref_write(WK_JMVREF(wk), jseg, data);
3911 				break;
3912 			case D_JNEWBLK:
3913 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3914 				break;
3915 			case D_JFREEBLK:
3916 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3917 				break;
3918 			case D_JFREEFRAG:
3919 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3920 				break;
3921 			case D_JTRUNC:
3922 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3923 				break;
3924 			case D_JFSYNC:
3925 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3926 				break;
3927 			default:
3928 				panic("process_journal: Unknown type %s",
3929 				    TYPENAME(wk->wk_type));
3930 				/* NOTREACHED */
3931 			}
3932 			off += JREC_SIZE;
3933 			data = bp->b_data + off;
3934 			cnt--;
3935 		}
3936 
3937 		/* Clear any remaining space so we don't leak kernel data */
3938 		if (size > off)
3939 			bzero(data, size - off);
3940 
3941 		/*
3942 		 * Write this one buffer and continue.
3943 		 */
3944 		segwritten = 1;
3945 		jblocks->jb_needseg = 0;
3946 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3947 		FREE_LOCK(ump);
3948 		bp->b_xflags |= BX_CVTENXIO;
3949 		pbgetvp(ump->um_devvp, bp);
3950 		/*
3951 		 * We only do the blocking wait once we find the journal
3952 		 * entry we're looking for.
3953 		 */
3954 		if (needwk == NULL && flags == MNT_WAIT)
3955 			bwrite(bp);
3956 		else
3957 			bawrite(bp);
3958 		ACQUIRE_LOCK(ump);
3959 	}
3960 	/*
3961 	 * If we wrote a segment issue a synchronize cache so the journal
3962 	 * is reflected on disk before the data is written.  Since reclaiming
3963 	 * journal space also requires writing a journal record this
3964 	 * process also enforces a barrier before reclamation.
3965 	 */
3966 	if (segwritten && shouldflush) {
3967 		softdep_synchronize(bio, ump,
3968 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3969 	} else if (bio)
3970 		g_destroy_bio(bio);
3971 	/*
3972 	 * If we've suspended the filesystem because we ran out of journal
3973 	 * space either try to sync it here to make some progress or
3974 	 * unsuspend it if we already have.
3975 	 */
3976 	if (flags == 0 && jblocks->jb_suspended) {
3977 		if (journal_unsuspend(ump))
3978 			return;
3979 		FREE_LOCK(ump);
3980 		VFS_SYNC(mp, MNT_NOWAIT);
3981 		ffs_sbupdate(ump, MNT_WAIT, 0);
3982 		ACQUIRE_LOCK(ump);
3983 	}
3984 }
3985 
3986 /*
3987  * Complete a jseg, allowing all dependencies awaiting journal writes
3988  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3989  * structures so that the journal segment can be freed to reclaim space.
3990  */
3991 static void
3992 complete_jseg(jseg)
3993 	struct jseg *jseg;
3994 {
3995 	struct worklist *wk;
3996 	struct jmvref *jmvref;
3997 #ifdef INVARIANTS
3998 	int i = 0;
3999 #endif
4000 
4001 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
4002 		WORKLIST_REMOVE(wk);
4003 		wk->wk_state &= ~INPROGRESS;
4004 		wk->wk_state |= COMPLETE;
4005 		KASSERT(i++ < jseg->js_cnt,
4006 		    ("handle_written_jseg: overflow %d >= %d",
4007 		    i - 1, jseg->js_cnt));
4008 		switch (wk->wk_type) {
4009 		case D_JADDREF:
4010 			handle_written_jaddref(WK_JADDREF(wk));
4011 			break;
4012 		case D_JREMREF:
4013 			handle_written_jremref(WK_JREMREF(wk));
4014 			break;
4015 		case D_JMVREF:
4016 			rele_jseg(jseg);	/* No jsegdep. */
4017 			jmvref = WK_JMVREF(wk);
4018 			LIST_REMOVE(jmvref, jm_deps);
4019 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
4020 				free_pagedep(jmvref->jm_pagedep);
4021 			WORKITEM_FREE(jmvref, D_JMVREF);
4022 			break;
4023 		case D_JNEWBLK:
4024 			handle_written_jnewblk(WK_JNEWBLK(wk));
4025 			break;
4026 		case D_JFREEBLK:
4027 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
4028 			break;
4029 		case D_JTRUNC:
4030 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
4031 			break;
4032 		case D_JFSYNC:
4033 			rele_jseg(jseg);	/* No jsegdep. */
4034 			WORKITEM_FREE(wk, D_JFSYNC);
4035 			break;
4036 		case D_JFREEFRAG:
4037 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
4038 			break;
4039 		default:
4040 			panic("handle_written_jseg: Unknown type %s",
4041 			    TYPENAME(wk->wk_type));
4042 			/* NOTREACHED */
4043 		}
4044 	}
4045 	/* Release the self reference so the structure may be freed. */
4046 	rele_jseg(jseg);
4047 }
4048 
4049 /*
4050  * Determine which jsegs are ready for completion processing.  Waits for
4051  * synchronize cache to complete as well as forcing in-order completion
4052  * of journal entries.
4053  */
4054 static void
4055 complete_jsegs(jseg)
4056 	struct jseg *jseg;
4057 {
4058 	struct jblocks *jblocks;
4059 	struct jseg *jsegn;
4060 
4061 	jblocks = jseg->js_jblocks;
4062 	/*
4063 	 * Don't allow out of order completions.  If this isn't the first
4064 	 * block wait for it to write before we're done.
4065 	 */
4066 	if (jseg != jblocks->jb_writeseg)
4067 		return;
4068 	/* Iterate through available jsegs processing their entries. */
4069 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
4070 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
4071 		jsegn = TAILQ_NEXT(jseg, js_next);
4072 		complete_jseg(jseg);
4073 		jseg = jsegn;
4074 	}
4075 	jblocks->jb_writeseg = jseg;
4076 	/*
4077 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
4078 	 */
4079 	free_jsegs(jblocks);
4080 }
4081 
4082 /*
4083  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
4084  * the final completions.
4085  */
4086 static void
4087 handle_written_jseg(jseg, bp)
4088 	struct jseg *jseg;
4089 	struct buf *bp;
4090 {
4091 
4092 	if (jseg->js_refs == 0)
4093 		panic("handle_written_jseg: No self-reference on %p", jseg);
4094 	jseg->js_state |= DEPCOMPLETE;
4095 	/*
4096 	 * We'll never need this buffer again, set flags so it will be
4097 	 * discarded.
4098 	 */
4099 	bp->b_flags |= B_INVAL | B_NOCACHE;
4100 	pbrelvp(bp);
4101 	complete_jsegs(jseg);
4102 }
4103 
4104 static inline struct jsegdep *
4105 inoref_jseg(inoref)
4106 	struct inoref *inoref;
4107 {
4108 	struct jsegdep *jsegdep;
4109 
4110 	jsegdep = inoref->if_jsegdep;
4111 	inoref->if_jsegdep = NULL;
4112 
4113 	return (jsegdep);
4114 }
4115 
4116 /*
4117  * Called once a jremref has made it to stable store.  The jremref is marked
4118  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
4119  * for the jremref to complete will be awoken by free_jremref.
4120  */
4121 static void
4122 handle_written_jremref(jremref)
4123 	struct jremref *jremref;
4124 {
4125 	struct inodedep *inodedep;
4126 	struct jsegdep *jsegdep;
4127 	struct dirrem *dirrem;
4128 
4129 	/* Grab the jsegdep. */
4130 	jsegdep = inoref_jseg(&jremref->jr_ref);
4131 	/*
4132 	 * Remove us from the inoref list.
4133 	 */
4134 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
4135 	    0, &inodedep) == 0)
4136 		panic("handle_written_jremref: Lost inodedep");
4137 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
4138 	/*
4139 	 * Complete the dirrem.
4140 	 */
4141 	dirrem = jremref->jr_dirrem;
4142 	jremref->jr_dirrem = NULL;
4143 	LIST_REMOVE(jremref, jr_deps);
4144 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
4145 	jwork_insert(&dirrem->dm_jwork, jsegdep);
4146 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
4147 	    (dirrem->dm_state & COMPLETE) != 0)
4148 		add_to_worklist(&dirrem->dm_list, 0);
4149 	free_jremref(jremref);
4150 }
4151 
4152 /*
4153  * Called once a jaddref has made it to stable store.  The dependency is
4154  * marked complete and any dependent structures are added to the inode
4155  * bufwait list to be completed as soon as it is written.  If a bitmap write
4156  * depends on this entry we move the inode into the inodedephd of the
4157  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
4158  */
4159 static void
4160 handle_written_jaddref(jaddref)
4161 	struct jaddref *jaddref;
4162 {
4163 	struct jsegdep *jsegdep;
4164 	struct inodedep *inodedep;
4165 	struct diradd *diradd;
4166 	struct mkdir *mkdir;
4167 
4168 	/* Grab the jsegdep. */
4169 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4170 	mkdir = NULL;
4171 	diradd = NULL;
4172 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4173 	    0, &inodedep) == 0)
4174 		panic("handle_written_jaddref: Lost inodedep.");
4175 	if (jaddref->ja_diradd == NULL)
4176 		panic("handle_written_jaddref: No dependency");
4177 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
4178 		diradd = jaddref->ja_diradd;
4179 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
4180 	} else if (jaddref->ja_state & MKDIR_PARENT) {
4181 		mkdir = jaddref->ja_mkdir;
4182 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
4183 	} else if (jaddref->ja_state & MKDIR_BODY)
4184 		mkdir = jaddref->ja_mkdir;
4185 	else
4186 		panic("handle_written_jaddref: Unknown dependency %p",
4187 		    jaddref->ja_diradd);
4188 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
4189 	/*
4190 	 * Remove us from the inode list.
4191 	 */
4192 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
4193 	/*
4194 	 * The mkdir may be waiting on the jaddref to clear before freeing.
4195 	 */
4196 	if (mkdir) {
4197 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
4198 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
4199 		    TYPENAME(mkdir->md_list.wk_type)));
4200 		mkdir->md_jaddref = NULL;
4201 		diradd = mkdir->md_diradd;
4202 		mkdir->md_state |= DEPCOMPLETE;
4203 		complete_mkdir(mkdir);
4204 	}
4205 	jwork_insert(&diradd->da_jwork, jsegdep);
4206 	if (jaddref->ja_state & NEWBLOCK) {
4207 		inodedep->id_state |= ONDEPLIST;
4208 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
4209 		    inodedep, id_deps);
4210 	}
4211 	free_jaddref(jaddref);
4212 }
4213 
4214 /*
4215  * Called once a jnewblk journal is written.  The allocdirect or allocindir
4216  * is placed in the bmsafemap to await notification of a written bitmap.  If
4217  * the operation was canceled we add the segdep to the appropriate
4218  * dependency to free the journal space once the canceling operation
4219  * completes.
4220  */
4221 static void
4222 handle_written_jnewblk(jnewblk)
4223 	struct jnewblk *jnewblk;
4224 {
4225 	struct bmsafemap *bmsafemap;
4226 	struct freefrag *freefrag;
4227 	struct freework *freework;
4228 	struct jsegdep *jsegdep;
4229 	struct newblk *newblk;
4230 
4231 	/* Grab the jsegdep. */
4232 	jsegdep = jnewblk->jn_jsegdep;
4233 	jnewblk->jn_jsegdep = NULL;
4234 	if (jnewblk->jn_dep == NULL)
4235 		panic("handle_written_jnewblk: No dependency for the segdep.");
4236 	switch (jnewblk->jn_dep->wk_type) {
4237 	case D_NEWBLK:
4238 	case D_ALLOCDIRECT:
4239 	case D_ALLOCINDIR:
4240 		/*
4241 		 * Add the written block to the bmsafemap so it can
4242 		 * be notified when the bitmap is on disk.
4243 		 */
4244 		newblk = WK_NEWBLK(jnewblk->jn_dep);
4245 		newblk->nb_jnewblk = NULL;
4246 		if ((newblk->nb_state & GOINGAWAY) == 0) {
4247 			bmsafemap = newblk->nb_bmsafemap;
4248 			newblk->nb_state |= ONDEPLIST;
4249 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
4250 			    nb_deps);
4251 		}
4252 		jwork_insert(&newblk->nb_jwork, jsegdep);
4253 		break;
4254 	case D_FREEFRAG:
4255 		/*
4256 		 * A newblock being removed by a freefrag when replaced by
4257 		 * frag extension.
4258 		 */
4259 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
4260 		freefrag->ff_jdep = NULL;
4261 		jwork_insert(&freefrag->ff_jwork, jsegdep);
4262 		break;
4263 	case D_FREEWORK:
4264 		/*
4265 		 * A direct block was removed by truncate.
4266 		 */
4267 		freework = WK_FREEWORK(jnewblk->jn_dep);
4268 		freework->fw_jnewblk = NULL;
4269 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
4270 		break;
4271 	default:
4272 		panic("handle_written_jnewblk: Unknown type %d.",
4273 		    jnewblk->jn_dep->wk_type);
4274 	}
4275 	jnewblk->jn_dep = NULL;
4276 	free_jnewblk(jnewblk);
4277 }
4278 
4279 /*
4280  * Cancel a jfreefrag that won't be needed, probably due to colliding with
4281  * an in-flight allocation that has not yet been committed.  Divorce us
4282  * from the freefrag and mark it DEPCOMPLETE so that it may be added
4283  * to the worklist.
4284  */
4285 static void
4286 cancel_jfreefrag(jfreefrag)
4287 	struct jfreefrag *jfreefrag;
4288 {
4289 	struct freefrag *freefrag;
4290 
4291 	if (jfreefrag->fr_jsegdep) {
4292 		free_jsegdep(jfreefrag->fr_jsegdep);
4293 		jfreefrag->fr_jsegdep = NULL;
4294 	}
4295 	freefrag = jfreefrag->fr_freefrag;
4296 	jfreefrag->fr_freefrag = NULL;
4297 	free_jfreefrag(jfreefrag);
4298 	freefrag->ff_state |= DEPCOMPLETE;
4299 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
4300 }
4301 
4302 /*
4303  * Free a jfreefrag when the parent freefrag is rendered obsolete.
4304  */
4305 static void
4306 free_jfreefrag(jfreefrag)
4307 	struct jfreefrag *jfreefrag;
4308 {
4309 
4310 	if (jfreefrag->fr_state & INPROGRESS)
4311 		WORKLIST_REMOVE(&jfreefrag->fr_list);
4312 	else if (jfreefrag->fr_state & ONWORKLIST)
4313 		remove_from_journal(&jfreefrag->fr_list);
4314 	if (jfreefrag->fr_freefrag != NULL)
4315 		panic("free_jfreefrag:  Still attached to a freefrag.");
4316 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
4317 }
4318 
4319 /*
4320  * Called when the journal write for a jfreefrag completes.  The parent
4321  * freefrag is added to the worklist if this completes its dependencies.
4322  */
4323 static void
4324 handle_written_jfreefrag(jfreefrag)
4325 	struct jfreefrag *jfreefrag;
4326 {
4327 	struct jsegdep *jsegdep;
4328 	struct freefrag *freefrag;
4329 
4330 	/* Grab the jsegdep. */
4331 	jsegdep = jfreefrag->fr_jsegdep;
4332 	jfreefrag->fr_jsegdep = NULL;
4333 	freefrag = jfreefrag->fr_freefrag;
4334 	if (freefrag == NULL)
4335 		panic("handle_written_jfreefrag: No freefrag.");
4336 	freefrag->ff_state |= DEPCOMPLETE;
4337 	freefrag->ff_jdep = NULL;
4338 	jwork_insert(&freefrag->ff_jwork, jsegdep);
4339 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
4340 		add_to_worklist(&freefrag->ff_list, 0);
4341 	jfreefrag->fr_freefrag = NULL;
4342 	free_jfreefrag(jfreefrag);
4343 }
4344 
4345 /*
4346  * Called when the journal write for a jfreeblk completes.  The jfreeblk
4347  * is removed from the freeblks list of pending journal writes and the
4348  * jsegdep is moved to the freeblks jwork to be completed when all blocks
4349  * have been reclaimed.
4350  */
4351 static void
4352 handle_written_jblkdep(jblkdep)
4353 	struct jblkdep *jblkdep;
4354 {
4355 	struct freeblks *freeblks;
4356 	struct jsegdep *jsegdep;
4357 
4358 	/* Grab the jsegdep. */
4359 	jsegdep = jblkdep->jb_jsegdep;
4360 	jblkdep->jb_jsegdep = NULL;
4361 	freeblks = jblkdep->jb_freeblks;
4362 	LIST_REMOVE(jblkdep, jb_deps);
4363 	jwork_insert(&freeblks->fb_jwork, jsegdep);
4364 	/*
4365 	 * If the freeblks is all journaled, we can add it to the worklist.
4366 	 */
4367 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4368 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4369 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4370 
4371 	free_jblkdep(jblkdep);
4372 }
4373 
4374 static struct jsegdep *
4375 newjsegdep(struct worklist *wk)
4376 {
4377 	struct jsegdep *jsegdep;
4378 
4379 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4380 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4381 	jsegdep->jd_seg = NULL;
4382 
4383 	return (jsegdep);
4384 }
4385 
4386 static struct jmvref *
4387 newjmvref(dp, ino, oldoff, newoff)
4388 	struct inode *dp;
4389 	ino_t ino;
4390 	off_t oldoff;
4391 	off_t newoff;
4392 {
4393 	struct jmvref *jmvref;
4394 
4395 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4396 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4397 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4398 	jmvref->jm_parent = dp->i_number;
4399 	jmvref->jm_ino = ino;
4400 	jmvref->jm_oldoff = oldoff;
4401 	jmvref->jm_newoff = newoff;
4402 
4403 	return (jmvref);
4404 }
4405 
4406 /*
4407  * Allocate a new jremref that tracks the removal of ip from dp with the
4408  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4409  * DEPCOMPLETE as we have all the information required for the journal write
4410  * and the directory has already been removed from the buffer.  The caller
4411  * is responsible for linking the jremref into the pagedep and adding it
4412  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4413  * a DOTDOT addition so handle_workitem_remove() can properly assign
4414  * the jsegdep when we're done.
4415  */
4416 static struct jremref *
4417 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4418     off_t diroff, nlink_t nlink)
4419 {
4420 	struct jremref *jremref;
4421 
4422 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4423 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4424 	jremref->jr_state = ATTACHED;
4425 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4426 	   nlink, ip->i_mode);
4427 	jremref->jr_dirrem = dirrem;
4428 
4429 	return (jremref);
4430 }
4431 
4432 static inline void
4433 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4434     nlink_t nlink, uint16_t mode)
4435 {
4436 
4437 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4438 	inoref->if_diroff = diroff;
4439 	inoref->if_ino = ino;
4440 	inoref->if_parent = parent;
4441 	inoref->if_nlink = nlink;
4442 	inoref->if_mode = mode;
4443 }
4444 
4445 /*
4446  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4447  * directory offset may not be known until later.  The caller is responsible
4448  * adding the entry to the journal when this information is available.  nlink
4449  * should be the link count prior to the addition and mode is only required
4450  * to have the correct FMT.
4451  */
4452 static struct jaddref *
4453 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4454     uint16_t mode)
4455 {
4456 	struct jaddref *jaddref;
4457 
4458 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4459 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4460 	jaddref->ja_state = ATTACHED;
4461 	jaddref->ja_mkdir = NULL;
4462 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4463 
4464 	return (jaddref);
4465 }
4466 
4467 /*
4468  * Create a new free dependency for a freework.  The caller is responsible
4469  * for adjusting the reference count when it has the lock held.  The freedep
4470  * will track an outstanding bitmap write that will ultimately clear the
4471  * freework to continue.
4472  */
4473 static struct freedep *
4474 newfreedep(struct freework *freework)
4475 {
4476 	struct freedep *freedep;
4477 
4478 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4479 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4480 	freedep->fd_freework = freework;
4481 
4482 	return (freedep);
4483 }
4484 
4485 /*
4486  * Free a freedep structure once the buffer it is linked to is written.  If
4487  * this is the last reference to the freework schedule it for completion.
4488  */
4489 static void
4490 free_freedep(freedep)
4491 	struct freedep *freedep;
4492 {
4493 	struct freework *freework;
4494 
4495 	freework = freedep->fd_freework;
4496 	freework->fw_freeblks->fb_cgwait--;
4497 	if (--freework->fw_ref == 0)
4498 		freework_enqueue(freework);
4499 	WORKITEM_FREE(freedep, D_FREEDEP);
4500 }
4501 
4502 /*
4503  * Allocate a new freework structure that may be a level in an indirect
4504  * when parent is not NULL or a top level block when it is.  The top level
4505  * freework structures are allocated without the per-filesystem lock held
4506  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4507  */
4508 static struct freework *
4509 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4510 	struct ufsmount *ump;
4511 	struct freeblks *freeblks;
4512 	struct freework *parent;
4513 	ufs_lbn_t lbn;
4514 	ufs2_daddr_t nb;
4515 	int frags;
4516 	int off;
4517 	int journal;
4518 {
4519 	struct freework *freework;
4520 
4521 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4522 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4523 	freework->fw_state = ATTACHED;
4524 	freework->fw_jnewblk = NULL;
4525 	freework->fw_freeblks = freeblks;
4526 	freework->fw_parent = parent;
4527 	freework->fw_lbn = lbn;
4528 	freework->fw_blkno = nb;
4529 	freework->fw_frags = frags;
4530 	freework->fw_indir = NULL;
4531 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4532 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4533 	freework->fw_start = freework->fw_off = off;
4534 	if (journal)
4535 		newjfreeblk(freeblks, lbn, nb, frags);
4536 	if (parent == NULL) {
4537 		ACQUIRE_LOCK(ump);
4538 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4539 		freeblks->fb_ref++;
4540 		FREE_LOCK(ump);
4541 	}
4542 
4543 	return (freework);
4544 }
4545 
4546 /*
4547  * Eliminate a jfreeblk for a block that does not need journaling.
4548  */
4549 static void
4550 cancel_jfreeblk(freeblks, blkno)
4551 	struct freeblks *freeblks;
4552 	ufs2_daddr_t blkno;
4553 {
4554 	struct jfreeblk *jfreeblk;
4555 	struct jblkdep *jblkdep;
4556 
4557 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4558 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4559 			continue;
4560 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4561 		if (jfreeblk->jf_blkno == blkno)
4562 			break;
4563 	}
4564 	if (jblkdep == NULL)
4565 		return;
4566 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4567 	free_jsegdep(jblkdep->jb_jsegdep);
4568 	LIST_REMOVE(jblkdep, jb_deps);
4569 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4570 }
4571 
4572 /*
4573  * Allocate a new jfreeblk to journal top level block pointer when truncating
4574  * a file.  The caller must add this to the worklist when the per-filesystem
4575  * lock is held.
4576  */
4577 static struct jfreeblk *
4578 newjfreeblk(freeblks, lbn, blkno, frags)
4579 	struct freeblks *freeblks;
4580 	ufs_lbn_t lbn;
4581 	ufs2_daddr_t blkno;
4582 	int frags;
4583 {
4584 	struct jfreeblk *jfreeblk;
4585 
4586 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4587 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4588 	    freeblks->fb_list.wk_mp);
4589 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4590 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4591 	jfreeblk->jf_ino = freeblks->fb_inum;
4592 	jfreeblk->jf_lbn = lbn;
4593 	jfreeblk->jf_blkno = blkno;
4594 	jfreeblk->jf_frags = frags;
4595 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4596 
4597 	return (jfreeblk);
4598 }
4599 
4600 /*
4601  * The journal is only prepared to handle full-size block numbers, so we
4602  * have to adjust the record to reflect the change to a full-size block.
4603  * For example, suppose we have a block made up of fragments 8-15 and
4604  * want to free its last two fragments. We are given a request that says:
4605  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4606  * where frags are the number of fragments to free and oldfrags are the
4607  * number of fragments to keep. To block align it, we have to change it to
4608  * have a valid full-size blkno, so it becomes:
4609  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4610  */
4611 static void
4612 adjust_newfreework(freeblks, frag_offset)
4613 	struct freeblks *freeblks;
4614 	int frag_offset;
4615 {
4616 	struct jfreeblk *jfreeblk;
4617 
4618 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4619 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4620 	    ("adjust_newfreework: Missing freeblks dependency"));
4621 
4622 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4623 	jfreeblk->jf_blkno -= frag_offset;
4624 	jfreeblk->jf_frags += frag_offset;
4625 }
4626 
4627 /*
4628  * Allocate a new jtrunc to track a partial truncation.
4629  */
4630 static struct jtrunc *
4631 newjtrunc(freeblks, size, extsize)
4632 	struct freeblks *freeblks;
4633 	off_t size;
4634 	int extsize;
4635 {
4636 	struct jtrunc *jtrunc;
4637 
4638 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4639 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4640 	    freeblks->fb_list.wk_mp);
4641 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4642 	jtrunc->jt_dep.jb_freeblks = freeblks;
4643 	jtrunc->jt_ino = freeblks->fb_inum;
4644 	jtrunc->jt_size = size;
4645 	jtrunc->jt_extsize = extsize;
4646 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4647 
4648 	return (jtrunc);
4649 }
4650 
4651 /*
4652  * If we're canceling a new bitmap we have to search for another ref
4653  * to move into the bmsafemap dep.  This might be better expressed
4654  * with another structure.
4655  */
4656 static void
4657 move_newblock_dep(jaddref, inodedep)
4658 	struct jaddref *jaddref;
4659 	struct inodedep *inodedep;
4660 {
4661 	struct inoref *inoref;
4662 	struct jaddref *jaddrefn;
4663 
4664 	jaddrefn = NULL;
4665 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4666 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4667 		if ((jaddref->ja_state & NEWBLOCK) &&
4668 		    inoref->if_list.wk_type == D_JADDREF) {
4669 			jaddrefn = (struct jaddref *)inoref;
4670 			break;
4671 		}
4672 	}
4673 	if (jaddrefn == NULL)
4674 		return;
4675 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4676 	jaddrefn->ja_state |= jaddref->ja_state &
4677 	    (ATTACHED | UNDONE | NEWBLOCK);
4678 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4679 	jaddref->ja_state |= ATTACHED;
4680 	LIST_REMOVE(jaddref, ja_bmdeps);
4681 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4682 	    ja_bmdeps);
4683 }
4684 
4685 /*
4686  * Cancel a jaddref either before it has been written or while it is being
4687  * written.  This happens when a link is removed before the add reaches
4688  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4689  * and inode to prevent the link count or bitmap from reaching the disk
4690  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4691  * required.
4692  *
4693  * Returns 1 if the canceled addref requires journaling of the remove and
4694  * 0 otherwise.
4695  */
4696 static int
4697 cancel_jaddref(jaddref, inodedep, wkhd)
4698 	struct jaddref *jaddref;
4699 	struct inodedep *inodedep;
4700 	struct workhead *wkhd;
4701 {
4702 	struct inoref *inoref;
4703 	struct jsegdep *jsegdep;
4704 	int needsj;
4705 
4706 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4707 	    ("cancel_jaddref: Canceling complete jaddref"));
4708 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4709 		needsj = 1;
4710 	else
4711 		needsj = 0;
4712 	if (inodedep == NULL)
4713 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4714 		    0, &inodedep) == 0)
4715 			panic("cancel_jaddref: Lost inodedep");
4716 	/*
4717 	 * We must adjust the nlink of any reference operation that follows
4718 	 * us so that it is consistent with the in-memory reference.  This
4719 	 * ensures that inode nlink rollbacks always have the correct link.
4720 	 */
4721 	if (needsj == 0) {
4722 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4723 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4724 			if (inoref->if_state & GOINGAWAY)
4725 				break;
4726 			inoref->if_nlink--;
4727 		}
4728 	}
4729 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4730 	if (jaddref->ja_state & NEWBLOCK)
4731 		move_newblock_dep(jaddref, inodedep);
4732 	wake_worklist(&jaddref->ja_list);
4733 	jaddref->ja_mkdir = NULL;
4734 	if (jaddref->ja_state & INPROGRESS) {
4735 		jaddref->ja_state &= ~INPROGRESS;
4736 		WORKLIST_REMOVE(&jaddref->ja_list);
4737 		jwork_insert(wkhd, jsegdep);
4738 	} else {
4739 		free_jsegdep(jsegdep);
4740 		if (jaddref->ja_state & DEPCOMPLETE)
4741 			remove_from_journal(&jaddref->ja_list);
4742 	}
4743 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4744 	/*
4745 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4746 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4747 	 * no longer need this addref attached to the inoreflst and it
4748 	 * will incorrectly adjust nlink if we leave it.
4749 	 */
4750 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4751 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4752 		    if_deps);
4753 		jaddref->ja_state |= COMPLETE;
4754 		free_jaddref(jaddref);
4755 		return (needsj);
4756 	}
4757 	/*
4758 	 * Leave the head of the list for jsegdeps for fast merging.
4759 	 */
4760 	if (LIST_FIRST(wkhd) != NULL) {
4761 		jaddref->ja_state |= ONWORKLIST;
4762 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4763 	} else
4764 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4765 
4766 	return (needsj);
4767 }
4768 
4769 /*
4770  * Attempt to free a jaddref structure when some work completes.  This
4771  * should only succeed once the entry is written and all dependencies have
4772  * been notified.
4773  */
4774 static void
4775 free_jaddref(jaddref)
4776 	struct jaddref *jaddref;
4777 {
4778 
4779 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4780 		return;
4781 	if (jaddref->ja_ref.if_jsegdep)
4782 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4783 		    jaddref, jaddref->ja_state);
4784 	if (jaddref->ja_state & NEWBLOCK)
4785 		LIST_REMOVE(jaddref, ja_bmdeps);
4786 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4787 		panic("free_jaddref: Bad state %p(0x%X)",
4788 		    jaddref, jaddref->ja_state);
4789 	if (jaddref->ja_mkdir != NULL)
4790 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4791 	WORKITEM_FREE(jaddref, D_JADDREF);
4792 }
4793 
4794 /*
4795  * Free a jremref structure once it has been written or discarded.
4796  */
4797 static void
4798 free_jremref(jremref)
4799 	struct jremref *jremref;
4800 {
4801 
4802 	if (jremref->jr_ref.if_jsegdep)
4803 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4804 	if (jremref->jr_state & INPROGRESS)
4805 		panic("free_jremref: IO still pending");
4806 	WORKITEM_FREE(jremref, D_JREMREF);
4807 }
4808 
4809 /*
4810  * Free a jnewblk structure.
4811  */
4812 static void
4813 free_jnewblk(jnewblk)
4814 	struct jnewblk *jnewblk;
4815 {
4816 
4817 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4818 		return;
4819 	LIST_REMOVE(jnewblk, jn_deps);
4820 	if (jnewblk->jn_dep != NULL)
4821 		panic("free_jnewblk: Dependency still attached.");
4822 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4823 }
4824 
4825 /*
4826  * Cancel a jnewblk which has been been made redundant by frag extension.
4827  */
4828 static void
4829 cancel_jnewblk(jnewblk, wkhd)
4830 	struct jnewblk *jnewblk;
4831 	struct workhead *wkhd;
4832 {
4833 	struct jsegdep *jsegdep;
4834 
4835 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4836 	jsegdep = jnewblk->jn_jsegdep;
4837 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4838 		panic("cancel_jnewblk: Invalid state");
4839 	jnewblk->jn_jsegdep  = NULL;
4840 	jnewblk->jn_dep = NULL;
4841 	jnewblk->jn_state |= GOINGAWAY;
4842 	if (jnewblk->jn_state & INPROGRESS) {
4843 		jnewblk->jn_state &= ~INPROGRESS;
4844 		WORKLIST_REMOVE(&jnewblk->jn_list);
4845 		jwork_insert(wkhd, jsegdep);
4846 	} else {
4847 		free_jsegdep(jsegdep);
4848 		remove_from_journal(&jnewblk->jn_list);
4849 	}
4850 	wake_worklist(&jnewblk->jn_list);
4851 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4852 }
4853 
4854 static void
4855 free_jblkdep(jblkdep)
4856 	struct jblkdep *jblkdep;
4857 {
4858 
4859 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4860 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4861 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4862 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4863 	else
4864 		panic("free_jblkdep: Unexpected type %s",
4865 		    TYPENAME(jblkdep->jb_list.wk_type));
4866 }
4867 
4868 /*
4869  * Free a single jseg once it is no longer referenced in memory or on
4870  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4871  * to disappear.
4872  */
4873 static void
4874 free_jseg(jseg, jblocks)
4875 	struct jseg *jseg;
4876 	struct jblocks *jblocks;
4877 {
4878 	struct freework *freework;
4879 
4880 	/*
4881 	 * Free freework structures that were lingering to indicate freed
4882 	 * indirect blocks that forced journal write ordering on reallocate.
4883 	 */
4884 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4885 		indirblk_remove(freework);
4886 	if (jblocks->jb_oldestseg == jseg)
4887 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4888 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4889 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4890 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4891 	    ("free_jseg: Freed jseg has valid entries."));
4892 	WORKITEM_FREE(jseg, D_JSEG);
4893 }
4894 
4895 /*
4896  * Free all jsegs that meet the criteria for being reclaimed and update
4897  * oldestseg.
4898  */
4899 static void
4900 free_jsegs(jblocks)
4901 	struct jblocks *jblocks;
4902 {
4903 	struct jseg *jseg;
4904 
4905 	/*
4906 	 * Free only those jsegs which have none allocated before them to
4907 	 * preserve the journal space ordering.
4908 	 */
4909 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4910 		/*
4911 		 * Only reclaim space when nothing depends on this journal
4912 		 * set and another set has written that it is no longer
4913 		 * valid.
4914 		 */
4915 		if (jseg->js_refs != 0) {
4916 			jblocks->jb_oldestseg = jseg;
4917 			return;
4918 		}
4919 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4920 			break;
4921 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4922 			break;
4923 		/*
4924 		 * We can free jsegs that didn't write entries when
4925 		 * oldestwrseq == js_seq.
4926 		 */
4927 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4928 		    jseg->js_cnt != 0)
4929 			break;
4930 		free_jseg(jseg, jblocks);
4931 	}
4932 	/*
4933 	 * If we exited the loop above we still must discover the
4934 	 * oldest valid segment.
4935 	 */
4936 	if (jseg)
4937 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4938 		     jseg = TAILQ_NEXT(jseg, js_next))
4939 			if (jseg->js_refs != 0)
4940 				break;
4941 	jblocks->jb_oldestseg = jseg;
4942 	/*
4943 	 * The journal has no valid records but some jsegs may still be
4944 	 * waiting on oldestwrseq to advance.  We force a small record
4945 	 * out to permit these lingering records to be reclaimed.
4946 	 */
4947 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4948 		jblocks->jb_needseg = 1;
4949 }
4950 
4951 /*
4952  * Release one reference to a jseg and free it if the count reaches 0.  This
4953  * should eventually reclaim journal space as well.
4954  */
4955 static void
4956 rele_jseg(jseg)
4957 	struct jseg *jseg;
4958 {
4959 
4960 	KASSERT(jseg->js_refs > 0,
4961 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4962 	if (--jseg->js_refs != 0)
4963 		return;
4964 	free_jsegs(jseg->js_jblocks);
4965 }
4966 
4967 /*
4968  * Release a jsegdep and decrement the jseg count.
4969  */
4970 static void
4971 free_jsegdep(jsegdep)
4972 	struct jsegdep *jsegdep;
4973 {
4974 
4975 	if (jsegdep->jd_seg)
4976 		rele_jseg(jsegdep->jd_seg);
4977 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4978 }
4979 
4980 /*
4981  * Wait for a journal item to make it to disk.  Initiate journal processing
4982  * if required.
4983  */
4984 static int
4985 jwait(wk, waitfor)
4986 	struct worklist *wk;
4987 	int waitfor;
4988 {
4989 
4990 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4991 	/*
4992 	 * Blocking journal waits cause slow synchronous behavior.  Record
4993 	 * stats on the frequency of these blocking operations.
4994 	 */
4995 	if (waitfor == MNT_WAIT) {
4996 		stat_journal_wait++;
4997 		switch (wk->wk_type) {
4998 		case D_JREMREF:
4999 		case D_JMVREF:
5000 			stat_jwait_filepage++;
5001 			break;
5002 		case D_JTRUNC:
5003 		case D_JFREEBLK:
5004 			stat_jwait_freeblks++;
5005 			break;
5006 		case D_JNEWBLK:
5007 			stat_jwait_newblk++;
5008 			break;
5009 		case D_JADDREF:
5010 			stat_jwait_inode++;
5011 			break;
5012 		default:
5013 			break;
5014 		}
5015 	}
5016 	/*
5017 	 * If IO has not started we process the journal.  We can't mark the
5018 	 * worklist item as IOWAITING because we drop the lock while
5019 	 * processing the journal and the worklist entry may be freed after
5020 	 * this point.  The caller may call back in and re-issue the request.
5021 	 */
5022 	if ((wk->wk_state & INPROGRESS) == 0) {
5023 		softdep_process_journal(wk->wk_mp, wk, waitfor);
5024 		if (waitfor != MNT_WAIT)
5025 			return (EBUSY);
5026 		return (0);
5027 	}
5028 	if (waitfor != MNT_WAIT)
5029 		return (EBUSY);
5030 	wait_worklist(wk, "jwait");
5031 	return (0);
5032 }
5033 
5034 /*
5035  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
5036  * appropriate.  This is a convenience function to reduce duplicate code
5037  * for the setup and revert functions below.
5038  */
5039 static struct inodedep *
5040 inodedep_lookup_ip(ip)
5041 	struct inode *ip;
5042 {
5043 	struct inodedep *inodedep;
5044 
5045 	KASSERT(ip->i_nlink >= ip->i_effnlink,
5046 	    ("inodedep_lookup_ip: bad delta"));
5047 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
5048 	    &inodedep);
5049 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
5050 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
5051 
5052 	return (inodedep);
5053 }
5054 
5055 /*
5056  * Called prior to creating a new inode and linking it to a directory.  The
5057  * jaddref structure must already be allocated by softdep_setup_inomapdep
5058  * and it is discovered here so we can initialize the mode and update
5059  * nlinkdelta.
5060  */
5061 void
5062 softdep_setup_create(dp, ip)
5063 	struct inode *dp;
5064 	struct inode *ip;
5065 {
5066 	struct inodedep *inodedep;
5067 	struct jaddref *jaddref __diagused;
5068 	struct vnode *dvp;
5069 
5070 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5071 	    ("softdep_setup_create called on non-softdep filesystem"));
5072 	KASSERT(ip->i_nlink == 1,
5073 	    ("softdep_setup_create: Invalid link count."));
5074 	dvp = ITOV(dp);
5075 	ACQUIRE_LOCK(ITOUMP(dp));
5076 	inodedep = inodedep_lookup_ip(ip);
5077 	if (DOINGSUJ(dvp)) {
5078 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5079 		    inoreflst);
5080 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
5081 		    ("softdep_setup_create: No addref structure present."));
5082 	}
5083 	FREE_LOCK(ITOUMP(dp));
5084 }
5085 
5086 /*
5087  * Create a jaddref structure to track the addition of a DOTDOT link when
5088  * we are reparenting an inode as part of a rename.  This jaddref will be
5089  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
5090  * non-journaling softdep.
5091  */
5092 void
5093 softdep_setup_dotdot_link(dp, ip)
5094 	struct inode *dp;
5095 	struct inode *ip;
5096 {
5097 	struct inodedep *inodedep;
5098 	struct jaddref *jaddref;
5099 	struct vnode *dvp;
5100 
5101 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5102 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
5103 	dvp = ITOV(dp);
5104 	jaddref = NULL;
5105 	/*
5106 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
5107 	 * is used as a normal link would be.
5108 	 */
5109 	if (DOINGSUJ(dvp))
5110 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5111 		    dp->i_effnlink - 1, dp->i_mode);
5112 	ACQUIRE_LOCK(ITOUMP(dp));
5113 	inodedep = inodedep_lookup_ip(dp);
5114 	if (jaddref)
5115 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5116 		    if_deps);
5117 	FREE_LOCK(ITOUMP(dp));
5118 }
5119 
5120 /*
5121  * Create a jaddref structure to track a new link to an inode.  The directory
5122  * offset is not known until softdep_setup_directory_add or
5123  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
5124  * softdep.
5125  */
5126 void
5127 softdep_setup_link(dp, ip)
5128 	struct inode *dp;
5129 	struct inode *ip;
5130 {
5131 	struct inodedep *inodedep;
5132 	struct jaddref *jaddref;
5133 	struct vnode *dvp;
5134 
5135 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5136 	    ("softdep_setup_link called on non-softdep filesystem"));
5137 	dvp = ITOV(dp);
5138 	jaddref = NULL;
5139 	if (DOINGSUJ(dvp))
5140 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
5141 		    ip->i_mode);
5142 	ACQUIRE_LOCK(ITOUMP(dp));
5143 	inodedep = inodedep_lookup_ip(ip);
5144 	if (jaddref)
5145 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5146 		    if_deps);
5147 	FREE_LOCK(ITOUMP(dp));
5148 }
5149 
5150 /*
5151  * Called to create the jaddref structures to track . and .. references as
5152  * well as lookup and further initialize the incomplete jaddref created
5153  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
5154  * nlinkdelta for non-journaling softdep.
5155  */
5156 void
5157 softdep_setup_mkdir(dp, ip)
5158 	struct inode *dp;
5159 	struct inode *ip;
5160 {
5161 	struct inodedep *inodedep;
5162 	struct jaddref *dotdotaddref;
5163 	struct jaddref *dotaddref;
5164 	struct jaddref *jaddref;
5165 	struct vnode *dvp;
5166 
5167 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5168 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
5169 	dvp = ITOV(dp);
5170 	dotaddref = dotdotaddref = NULL;
5171 	if (DOINGSUJ(dvp)) {
5172 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
5173 		    ip->i_mode);
5174 		dotaddref->ja_state |= MKDIR_BODY;
5175 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5176 		    dp->i_effnlink - 1, dp->i_mode);
5177 		dotdotaddref->ja_state |= MKDIR_PARENT;
5178 	}
5179 	ACQUIRE_LOCK(ITOUMP(dp));
5180 	inodedep = inodedep_lookup_ip(ip);
5181 	if (DOINGSUJ(dvp)) {
5182 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5183 		    inoreflst);
5184 		KASSERT(jaddref != NULL,
5185 		    ("softdep_setup_mkdir: No addref structure present."));
5186 		KASSERT(jaddref->ja_parent == dp->i_number,
5187 		    ("softdep_setup_mkdir: bad parent %ju",
5188 		    (uintmax_t)jaddref->ja_parent));
5189 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
5190 		    if_deps);
5191 	}
5192 	inodedep = inodedep_lookup_ip(dp);
5193 	if (DOINGSUJ(dvp))
5194 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
5195 		    &dotdotaddref->ja_ref, if_deps);
5196 	FREE_LOCK(ITOUMP(dp));
5197 }
5198 
5199 /*
5200  * Called to track nlinkdelta of the inode and parent directories prior to
5201  * unlinking a directory.
5202  */
5203 void
5204 softdep_setup_rmdir(dp, ip)
5205 	struct inode *dp;
5206 	struct inode *ip;
5207 {
5208 
5209 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5210 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
5211 	ACQUIRE_LOCK(ITOUMP(dp));
5212 	(void) inodedep_lookup_ip(ip);
5213 	(void) inodedep_lookup_ip(dp);
5214 	FREE_LOCK(ITOUMP(dp));
5215 }
5216 
5217 /*
5218  * Called to track nlinkdelta of the inode and parent directories prior to
5219  * unlink.
5220  */
5221 void
5222 softdep_setup_unlink(dp, ip)
5223 	struct inode *dp;
5224 	struct inode *ip;
5225 {
5226 
5227 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5228 	    ("softdep_setup_unlink called on non-softdep filesystem"));
5229 	ACQUIRE_LOCK(ITOUMP(dp));
5230 	(void) inodedep_lookup_ip(ip);
5231 	(void) inodedep_lookup_ip(dp);
5232 	FREE_LOCK(ITOUMP(dp));
5233 }
5234 
5235 /*
5236  * Called to release the journal structures created by a failed non-directory
5237  * creation.  Adjusts nlinkdelta for non-journaling softdep.
5238  */
5239 void
5240 softdep_revert_create(dp, ip)
5241 	struct inode *dp;
5242 	struct inode *ip;
5243 {
5244 	struct inodedep *inodedep;
5245 	struct jaddref *jaddref;
5246 	struct vnode *dvp;
5247 
5248 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
5249 	    ("softdep_revert_create called on non-softdep filesystem"));
5250 	dvp = ITOV(dp);
5251 	ACQUIRE_LOCK(ITOUMP(dp));
5252 	inodedep = inodedep_lookup_ip(ip);
5253 	if (DOINGSUJ(dvp)) {
5254 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5255 		    inoreflst);
5256 		KASSERT(jaddref->ja_parent == dp->i_number,
5257 		    ("softdep_revert_create: addref parent mismatch"));
5258 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5259 	}
5260 	FREE_LOCK(ITOUMP(dp));
5261 }
5262 
5263 /*
5264  * Called to release the journal structures created by a failed link
5265  * addition.  Adjusts nlinkdelta for non-journaling softdep.
5266  */
5267 void
5268 softdep_revert_link(dp, ip)
5269 	struct inode *dp;
5270 	struct inode *ip;
5271 {
5272 	struct inodedep *inodedep;
5273 	struct jaddref *jaddref;
5274 	struct vnode *dvp;
5275 
5276 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5277 	    ("softdep_revert_link called on non-softdep filesystem"));
5278 	dvp = ITOV(dp);
5279 	ACQUIRE_LOCK(ITOUMP(dp));
5280 	inodedep = inodedep_lookup_ip(ip);
5281 	if (DOINGSUJ(dvp)) {
5282 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5283 		    inoreflst);
5284 		KASSERT(jaddref->ja_parent == dp->i_number,
5285 		    ("softdep_revert_link: addref parent mismatch"));
5286 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5287 	}
5288 	FREE_LOCK(ITOUMP(dp));
5289 }
5290 
5291 /*
5292  * Called to release the journal structures created by a failed mkdir
5293  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
5294  */
5295 void
5296 softdep_revert_mkdir(dp, ip)
5297 	struct inode *dp;
5298 	struct inode *ip;
5299 {
5300 	struct inodedep *inodedep;
5301 	struct jaddref *jaddref;
5302 	struct jaddref *dotaddref;
5303 	struct vnode *dvp;
5304 
5305 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5306 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
5307 	dvp = ITOV(dp);
5308 
5309 	ACQUIRE_LOCK(ITOUMP(dp));
5310 	inodedep = inodedep_lookup_ip(dp);
5311 	if (DOINGSUJ(dvp)) {
5312 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5313 		    inoreflst);
5314 		KASSERT(jaddref->ja_parent == ip->i_number,
5315 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
5316 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5317 	}
5318 	inodedep = inodedep_lookup_ip(ip);
5319 	if (DOINGSUJ(dvp)) {
5320 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5321 		    inoreflst);
5322 		KASSERT(jaddref->ja_parent == dp->i_number,
5323 		    ("softdep_revert_mkdir: addref parent mismatch"));
5324 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
5325 		    inoreflst, if_deps);
5326 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5327 		KASSERT(dotaddref->ja_parent == ip->i_number,
5328 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
5329 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
5330 	}
5331 	FREE_LOCK(ITOUMP(dp));
5332 }
5333 
5334 /*
5335  * Called to correct nlinkdelta after a failed rmdir.
5336  */
5337 void
5338 softdep_revert_rmdir(dp, ip)
5339 	struct inode *dp;
5340 	struct inode *ip;
5341 {
5342 
5343 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5344 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
5345 	ACQUIRE_LOCK(ITOUMP(dp));
5346 	(void) inodedep_lookup_ip(ip);
5347 	(void) inodedep_lookup_ip(dp);
5348 	FREE_LOCK(ITOUMP(dp));
5349 }
5350 
5351 /*
5352  * Protecting the freemaps (or bitmaps).
5353  *
5354  * To eliminate the need to execute fsck before mounting a filesystem
5355  * after a power failure, one must (conservatively) guarantee that the
5356  * on-disk copy of the bitmaps never indicate that a live inode or block is
5357  * free.  So, when a block or inode is allocated, the bitmap should be
5358  * updated (on disk) before any new pointers.  When a block or inode is
5359  * freed, the bitmap should not be updated until all pointers have been
5360  * reset.  The latter dependency is handled by the delayed de-allocation
5361  * approach described below for block and inode de-allocation.  The former
5362  * dependency is handled by calling the following procedure when a block or
5363  * inode is allocated. When an inode is allocated an "inodedep" is created
5364  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5365  * Each "inodedep" is also inserted into the hash indexing structure so
5366  * that any additional link additions can be made dependent on the inode
5367  * allocation.
5368  *
5369  * The ufs filesystem maintains a number of free block counts (e.g., per
5370  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5371  * in addition to the bitmaps.  These counts are used to improve efficiency
5372  * during allocation and therefore must be consistent with the bitmaps.
5373  * There is no convenient way to guarantee post-crash consistency of these
5374  * counts with simple update ordering, for two main reasons: (1) The counts
5375  * and bitmaps for a single cylinder group block are not in the same disk
5376  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5377  * be written and the other not.  (2) Some of the counts are located in the
5378  * superblock rather than the cylinder group block. So, we focus our soft
5379  * updates implementation on protecting the bitmaps. When mounting a
5380  * filesystem, we recompute the auxiliary counts from the bitmaps.
5381  */
5382 
5383 /*
5384  * Called just after updating the cylinder group block to allocate an inode.
5385  */
5386 void
5387 softdep_setup_inomapdep(bp, ip, newinum, mode)
5388 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5389 	struct inode *ip;	/* inode related to allocation */
5390 	ino_t newinum;		/* new inode number being allocated */
5391 	int mode;
5392 {
5393 	struct inodedep *inodedep;
5394 	struct bmsafemap *bmsafemap;
5395 	struct jaddref *jaddref;
5396 	struct mount *mp;
5397 	struct fs *fs;
5398 
5399 	mp = ITOVFS(ip);
5400 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5401 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5402 	fs = VFSTOUFS(mp)->um_fs;
5403 	jaddref = NULL;
5404 
5405 	/*
5406 	 * Allocate the journal reference add structure so that the bitmap
5407 	 * can be dependent on it.
5408 	 */
5409 	if (MOUNTEDSUJ(mp)) {
5410 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5411 		jaddref->ja_state |= NEWBLOCK;
5412 	}
5413 
5414 	/*
5415 	 * Create a dependency for the newly allocated inode.
5416 	 * Panic if it already exists as something is seriously wrong.
5417 	 * Otherwise add it to the dependency list for the buffer holding
5418 	 * the cylinder group map from which it was allocated.
5419 	 *
5420 	 * We have to preallocate a bmsafemap entry in case it is needed
5421 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5422 	 * have to finish initializing it before we can FREE_LOCK().
5423 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5424 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5425 	 * creating the inodedep as it can be freed during the time
5426 	 * that we FREE_LOCK() while allocating the inodedep. We must
5427 	 * call workitem_alloc() before entering the locked section as
5428 	 * it also acquires the lock and we must avoid trying doing so
5429 	 * recursively.
5430 	 */
5431 	bmsafemap = malloc(sizeof(struct bmsafemap),
5432 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5433 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5434 	ACQUIRE_LOCK(ITOUMP(ip));
5435 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5436 		panic("softdep_setup_inomapdep: dependency %p for new"
5437 		    "inode already exists", inodedep);
5438 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5439 	if (jaddref) {
5440 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5441 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5442 		    if_deps);
5443 	} else {
5444 		inodedep->id_state |= ONDEPLIST;
5445 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5446 	}
5447 	inodedep->id_bmsafemap = bmsafemap;
5448 	inodedep->id_state &= ~DEPCOMPLETE;
5449 	FREE_LOCK(ITOUMP(ip));
5450 }
5451 
5452 /*
5453  * Called just after updating the cylinder group block to
5454  * allocate block or fragment.
5455  */
5456 void
5457 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5458 	struct buf *bp;		/* buffer for cylgroup block with block map */
5459 	struct mount *mp;	/* filesystem doing allocation */
5460 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5461 	int frags;		/* Number of fragments. */
5462 	int oldfrags;		/* Previous number of fragments for extend. */
5463 {
5464 	struct newblk *newblk;
5465 	struct bmsafemap *bmsafemap;
5466 	struct jnewblk *jnewblk;
5467 	struct ufsmount *ump;
5468 	struct fs *fs;
5469 
5470 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5471 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5472 	ump = VFSTOUFS(mp);
5473 	fs = ump->um_fs;
5474 	jnewblk = NULL;
5475 	/*
5476 	 * Create a dependency for the newly allocated block.
5477 	 * Add it to the dependency list for the buffer holding
5478 	 * the cylinder group map from which it was allocated.
5479 	 */
5480 	if (MOUNTEDSUJ(mp)) {
5481 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5482 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5483 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5484 		jnewblk->jn_state = ATTACHED;
5485 		jnewblk->jn_blkno = newblkno;
5486 		jnewblk->jn_frags = frags;
5487 		jnewblk->jn_oldfrags = oldfrags;
5488 #ifdef INVARIANTS
5489 		{
5490 			struct cg *cgp;
5491 			uint8_t *blksfree;
5492 			long bno;
5493 			int i;
5494 
5495 			cgp = (struct cg *)bp->b_data;
5496 			blksfree = cg_blksfree(cgp);
5497 			bno = dtogd(fs, jnewblk->jn_blkno);
5498 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5499 			    i++) {
5500 				if (isset(blksfree, bno + i))
5501 					panic("softdep_setup_blkmapdep: "
5502 					    "free fragment %d from %d-%d "
5503 					    "state 0x%X dep %p", i,
5504 					    jnewblk->jn_oldfrags,
5505 					    jnewblk->jn_frags,
5506 					    jnewblk->jn_state,
5507 					    jnewblk->jn_dep);
5508 			}
5509 		}
5510 #endif
5511 	}
5512 
5513 	CTR3(KTR_SUJ,
5514 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5515 	    newblkno, frags, oldfrags);
5516 	ACQUIRE_LOCK(ump);
5517 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5518 		panic("softdep_setup_blkmapdep: found block");
5519 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5520 	    dtog(fs, newblkno), NULL);
5521 	if (jnewblk) {
5522 		jnewblk->jn_dep = (struct worklist *)newblk;
5523 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5524 	} else {
5525 		newblk->nb_state |= ONDEPLIST;
5526 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5527 	}
5528 	newblk->nb_bmsafemap = bmsafemap;
5529 	newblk->nb_jnewblk = jnewblk;
5530 	FREE_LOCK(ump);
5531 }
5532 
5533 #define	BMSAFEMAP_HASH(ump, cg) \
5534       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5535 
5536 static int
5537 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5538 	struct bmsafemap_hashhead *bmsafemaphd;
5539 	int cg;
5540 	struct bmsafemap **bmsafemapp;
5541 {
5542 	struct bmsafemap *bmsafemap;
5543 
5544 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5545 		if (bmsafemap->sm_cg == cg)
5546 			break;
5547 	if (bmsafemap) {
5548 		*bmsafemapp = bmsafemap;
5549 		return (1);
5550 	}
5551 	*bmsafemapp = NULL;
5552 
5553 	return (0);
5554 }
5555 
5556 /*
5557  * Find the bmsafemap associated with a cylinder group buffer.
5558  * If none exists, create one. The buffer must be locked when
5559  * this routine is called and this routine must be called with
5560  * the softdep lock held. To avoid giving up the lock while
5561  * allocating a new bmsafemap, a preallocated bmsafemap may be
5562  * provided. If it is provided but not needed, it is freed.
5563  */
5564 static struct bmsafemap *
5565 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5566 	struct mount *mp;
5567 	struct buf *bp;
5568 	int cg;
5569 	struct bmsafemap *newbmsafemap;
5570 {
5571 	struct bmsafemap_hashhead *bmsafemaphd;
5572 	struct bmsafemap *bmsafemap, *collision;
5573 	struct worklist *wk;
5574 	struct ufsmount *ump;
5575 
5576 	ump = VFSTOUFS(mp);
5577 	LOCK_OWNED(ump);
5578 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5579 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5580 		if (wk->wk_type == D_BMSAFEMAP) {
5581 			if (newbmsafemap)
5582 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5583 			return (WK_BMSAFEMAP(wk));
5584 		}
5585 	}
5586 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5587 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5588 		if (newbmsafemap)
5589 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5590 		return (bmsafemap);
5591 	}
5592 	if (newbmsafemap) {
5593 		bmsafemap = newbmsafemap;
5594 	} else {
5595 		FREE_LOCK(ump);
5596 		bmsafemap = malloc(sizeof(struct bmsafemap),
5597 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5598 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5599 		ACQUIRE_LOCK(ump);
5600 	}
5601 	bmsafemap->sm_buf = bp;
5602 	LIST_INIT(&bmsafemap->sm_inodedephd);
5603 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5604 	LIST_INIT(&bmsafemap->sm_newblkhd);
5605 	LIST_INIT(&bmsafemap->sm_newblkwr);
5606 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5607 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5608 	LIST_INIT(&bmsafemap->sm_freehd);
5609 	LIST_INIT(&bmsafemap->sm_freewr);
5610 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5611 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5612 		return (collision);
5613 	}
5614 	bmsafemap->sm_cg = cg;
5615 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5616 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5617 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5618 	return (bmsafemap);
5619 }
5620 
5621 /*
5622  * Direct block allocation dependencies.
5623  *
5624  * When a new block is allocated, the corresponding disk locations must be
5625  * initialized (with zeros or new data) before the on-disk inode points to
5626  * them.  Also, the freemap from which the block was allocated must be
5627  * updated (on disk) before the inode's pointer. These two dependencies are
5628  * independent of each other and are needed for all file blocks and indirect
5629  * blocks that are pointed to directly by the inode.  Just before the
5630  * "in-core" version of the inode is updated with a newly allocated block
5631  * number, a procedure (below) is called to setup allocation dependency
5632  * structures.  These structures are removed when the corresponding
5633  * dependencies are satisfied or when the block allocation becomes obsolete
5634  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5635  * fragment that gets upgraded).  All of these cases are handled in
5636  * procedures described later.
5637  *
5638  * When a file extension causes a fragment to be upgraded, either to a larger
5639  * fragment or to a full block, the on-disk location may change (if the
5640  * previous fragment could not simply be extended). In this case, the old
5641  * fragment must be de-allocated, but not until after the inode's pointer has
5642  * been updated. In most cases, this is handled by later procedures, which
5643  * will construct a "freefrag" structure to be added to the workitem queue
5644  * when the inode update is complete (or obsolete).  The main exception to
5645  * this is when an allocation occurs while a pending allocation dependency
5646  * (for the same block pointer) remains.  This case is handled in the main
5647  * allocation dependency setup procedure by immediately freeing the
5648  * unreferenced fragments.
5649  */
5650 void
5651 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5652 	struct inode *ip;	/* inode to which block is being added */
5653 	ufs_lbn_t off;		/* block pointer within inode */
5654 	ufs2_daddr_t newblkno;	/* disk block number being added */
5655 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5656 	long newsize;		/* size of new block */
5657 	long oldsize;		/* size of new block */
5658 	struct buf *bp;		/* bp for allocated block */
5659 {
5660 	struct allocdirect *adp, *oldadp;
5661 	struct allocdirectlst *adphead;
5662 	struct freefrag *freefrag;
5663 	struct inodedep *inodedep;
5664 	struct pagedep *pagedep;
5665 	struct jnewblk *jnewblk;
5666 	struct newblk *newblk;
5667 	struct mount *mp;
5668 	ufs_lbn_t lbn;
5669 
5670 	lbn = bp->b_lblkno;
5671 	mp = ITOVFS(ip);
5672 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5673 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5674 	if (oldblkno && oldblkno != newblkno)
5675 		/*
5676 		 * The usual case is that a smaller fragment that
5677 		 * was just allocated has been replaced with a bigger
5678 		 * fragment or a full-size block. If it is marked as
5679 		 * B_DELWRI, the current contents have not been written
5680 		 * to disk. It is possible that the block was written
5681 		 * earlier, but very uncommon. If the block has never
5682 		 * been written, there is no need to send a BIO_DELETE
5683 		 * for it when it is freed. The gain from avoiding the
5684 		 * TRIMs for the common case of unwritten blocks far
5685 		 * exceeds the cost of the write amplification for the
5686 		 * uncommon case of failing to send a TRIM for a block
5687 		 * that had been written.
5688 		 */
5689 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5690 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5691 	else
5692 		freefrag = NULL;
5693 
5694 	CTR6(KTR_SUJ,
5695 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5696 	    "off %jd newsize %ld oldsize %d",
5697 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5698 	ACQUIRE_LOCK(ITOUMP(ip));
5699 	if (off >= UFS_NDADDR) {
5700 		if (lbn > 0)
5701 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5702 			    lbn, off);
5703 		/* allocating an indirect block */
5704 		if (oldblkno != 0)
5705 			panic("softdep_setup_allocdirect: non-zero indir");
5706 	} else {
5707 		if (off != lbn)
5708 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5709 			    lbn, off);
5710 		/*
5711 		 * Allocating a direct block.
5712 		 *
5713 		 * If we are allocating a directory block, then we must
5714 		 * allocate an associated pagedep to track additions and
5715 		 * deletions.
5716 		 */
5717 		if ((ip->i_mode & IFMT) == IFDIR)
5718 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5719 			    &pagedep);
5720 	}
5721 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5722 		panic("softdep_setup_allocdirect: lost block");
5723 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5724 	    ("softdep_setup_allocdirect: newblk already initialized"));
5725 	/*
5726 	 * Convert the newblk to an allocdirect.
5727 	 */
5728 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5729 	adp = (struct allocdirect *)newblk;
5730 	newblk->nb_freefrag = freefrag;
5731 	adp->ad_offset = off;
5732 	adp->ad_oldblkno = oldblkno;
5733 	adp->ad_newsize = newsize;
5734 	adp->ad_oldsize = oldsize;
5735 
5736 	/*
5737 	 * Finish initializing the journal.
5738 	 */
5739 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5740 		jnewblk->jn_ino = ip->i_number;
5741 		jnewblk->jn_lbn = lbn;
5742 		add_to_journal(&jnewblk->jn_list);
5743 	}
5744 	if (freefrag && freefrag->ff_jdep != NULL &&
5745 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5746 		add_to_journal(freefrag->ff_jdep);
5747 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5748 	adp->ad_inodedep = inodedep;
5749 
5750 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5751 	/*
5752 	 * The list of allocdirects must be kept in sorted and ascending
5753 	 * order so that the rollback routines can quickly determine the
5754 	 * first uncommitted block (the size of the file stored on disk
5755 	 * ends at the end of the lowest committed fragment, or if there
5756 	 * are no fragments, at the end of the highest committed block).
5757 	 * Since files generally grow, the typical case is that the new
5758 	 * block is to be added at the end of the list. We speed this
5759 	 * special case by checking against the last allocdirect in the
5760 	 * list before laboriously traversing the list looking for the
5761 	 * insertion point.
5762 	 */
5763 	adphead = &inodedep->id_newinoupdt;
5764 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5765 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5766 		/* insert at end of list */
5767 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5768 		if (oldadp != NULL && oldadp->ad_offset == off)
5769 			allocdirect_merge(adphead, adp, oldadp);
5770 		FREE_LOCK(ITOUMP(ip));
5771 		return;
5772 	}
5773 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5774 		if (oldadp->ad_offset >= off)
5775 			break;
5776 	}
5777 	if (oldadp == NULL)
5778 		panic("softdep_setup_allocdirect: lost entry");
5779 	/* insert in middle of list */
5780 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5781 	if (oldadp->ad_offset == off)
5782 		allocdirect_merge(adphead, adp, oldadp);
5783 
5784 	FREE_LOCK(ITOUMP(ip));
5785 }
5786 
5787 /*
5788  * Merge a newer and older journal record to be stored either in a
5789  * newblock or freefrag.  This handles aggregating journal records for
5790  * fragment allocation into a second record as well as replacing a
5791  * journal free with an aborted journal allocation.  A segment for the
5792  * oldest record will be placed on wkhd if it has been written.  If not
5793  * the segment for the newer record will suffice.
5794  */
5795 static struct worklist *
5796 jnewblk_merge(new, old, wkhd)
5797 	struct worklist *new;
5798 	struct worklist *old;
5799 	struct workhead *wkhd;
5800 {
5801 	struct jnewblk *njnewblk;
5802 	struct jnewblk *jnewblk;
5803 
5804 	/* Handle NULLs to simplify callers. */
5805 	if (new == NULL)
5806 		return (old);
5807 	if (old == NULL)
5808 		return (new);
5809 	/* Replace a jfreefrag with a jnewblk. */
5810 	if (new->wk_type == D_JFREEFRAG) {
5811 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5812 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5813 			    old, new);
5814 		cancel_jfreefrag(WK_JFREEFRAG(new));
5815 		return (old);
5816 	}
5817 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5818 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5819 		    old->wk_type, new->wk_type);
5820 	/*
5821 	 * Handle merging of two jnewblk records that describe
5822 	 * different sets of fragments in the same block.
5823 	 */
5824 	jnewblk = WK_JNEWBLK(old);
5825 	njnewblk = WK_JNEWBLK(new);
5826 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5827 		panic("jnewblk_merge: Merging disparate blocks.");
5828 	/*
5829 	 * The record may be rolled back in the cg.
5830 	 */
5831 	if (jnewblk->jn_state & UNDONE) {
5832 		jnewblk->jn_state &= ~UNDONE;
5833 		njnewblk->jn_state |= UNDONE;
5834 		njnewblk->jn_state &= ~ATTACHED;
5835 	}
5836 	/*
5837 	 * We modify the newer addref and free the older so that if neither
5838 	 * has been written the most up-to-date copy will be on disk.  If
5839 	 * both have been written but rolled back we only temporarily need
5840 	 * one of them to fix the bits when the cg write completes.
5841 	 */
5842 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5843 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5844 	cancel_jnewblk(jnewblk, wkhd);
5845 	WORKLIST_REMOVE(&jnewblk->jn_list);
5846 	free_jnewblk(jnewblk);
5847 	return (new);
5848 }
5849 
5850 /*
5851  * Replace an old allocdirect dependency with a newer one.
5852  */
5853 static void
5854 allocdirect_merge(adphead, newadp, oldadp)
5855 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5856 	struct allocdirect *newadp;	/* allocdirect being added */
5857 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5858 {
5859 	struct worklist *wk;
5860 	struct freefrag *freefrag;
5861 
5862 	freefrag = NULL;
5863 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5864 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5865 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5866 	    newadp->ad_offset >= UFS_NDADDR)
5867 		panic("%s %jd != new %jd || old size %ld != new %ld",
5868 		    "allocdirect_merge: old blkno",
5869 		    (intmax_t)newadp->ad_oldblkno,
5870 		    (intmax_t)oldadp->ad_newblkno,
5871 		    newadp->ad_oldsize, oldadp->ad_newsize);
5872 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5873 	newadp->ad_oldsize = oldadp->ad_oldsize;
5874 	/*
5875 	 * If the old dependency had a fragment to free or had never
5876 	 * previously had a block allocated, then the new dependency
5877 	 * can immediately post its freefrag and adopt the old freefrag.
5878 	 * This action is done by swapping the freefrag dependencies.
5879 	 * The new dependency gains the old one's freefrag, and the
5880 	 * old one gets the new one and then immediately puts it on
5881 	 * the worklist when it is freed by free_newblk. It is
5882 	 * not possible to do this swap when the old dependency had a
5883 	 * non-zero size but no previous fragment to free. This condition
5884 	 * arises when the new block is an extension of the old block.
5885 	 * Here, the first part of the fragment allocated to the new
5886 	 * dependency is part of the block currently claimed on disk by
5887 	 * the old dependency, so cannot legitimately be freed until the
5888 	 * conditions for the new dependency are fulfilled.
5889 	 */
5890 	freefrag = newadp->ad_freefrag;
5891 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5892 		newadp->ad_freefrag = oldadp->ad_freefrag;
5893 		oldadp->ad_freefrag = freefrag;
5894 	}
5895 	/*
5896 	 * If we are tracking a new directory-block allocation,
5897 	 * move it from the old allocdirect to the new allocdirect.
5898 	 */
5899 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5900 		WORKLIST_REMOVE(wk);
5901 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5902 			panic("allocdirect_merge: extra newdirblk");
5903 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5904 	}
5905 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5906 	/*
5907 	 * We need to move any journal dependencies over to the freefrag
5908 	 * that releases this block if it exists.  Otherwise we are
5909 	 * extending an existing block and we'll wait until that is
5910 	 * complete to release the journal space and extend the
5911 	 * new journal to cover this old space as well.
5912 	 */
5913 	if (freefrag == NULL) {
5914 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5915 			panic("allocdirect_merge: %jd != %jd",
5916 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5917 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5918 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5919 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5920 		    &newadp->ad_block.nb_jwork);
5921 		oldadp->ad_block.nb_jnewblk = NULL;
5922 		cancel_newblk(&oldadp->ad_block, NULL,
5923 		    &newadp->ad_block.nb_jwork);
5924 	} else {
5925 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5926 		    &freefrag->ff_list, &freefrag->ff_jwork);
5927 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5928 		    &freefrag->ff_jwork);
5929 	}
5930 	free_newblk(&oldadp->ad_block);
5931 }
5932 
5933 /*
5934  * Allocate a jfreefrag structure to journal a single block free.
5935  */
5936 static struct jfreefrag *
5937 newjfreefrag(freefrag, ip, blkno, size, lbn)
5938 	struct freefrag *freefrag;
5939 	struct inode *ip;
5940 	ufs2_daddr_t blkno;
5941 	long size;
5942 	ufs_lbn_t lbn;
5943 {
5944 	struct jfreefrag *jfreefrag;
5945 	struct fs *fs;
5946 
5947 	fs = ITOFS(ip);
5948 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5949 	    M_SOFTDEP_FLAGS);
5950 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5951 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5952 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5953 	jfreefrag->fr_ino = ip->i_number;
5954 	jfreefrag->fr_lbn = lbn;
5955 	jfreefrag->fr_blkno = blkno;
5956 	jfreefrag->fr_frags = numfrags(fs, size);
5957 	jfreefrag->fr_freefrag = freefrag;
5958 
5959 	return (jfreefrag);
5960 }
5961 
5962 /*
5963  * Allocate a new freefrag structure.
5964  */
5965 static struct freefrag *
5966 newfreefrag(ip, blkno, size, lbn, key)
5967 	struct inode *ip;
5968 	ufs2_daddr_t blkno;
5969 	long size;
5970 	ufs_lbn_t lbn;
5971 	u_long key;
5972 {
5973 	struct freefrag *freefrag;
5974 	struct ufsmount *ump;
5975 	struct fs *fs;
5976 
5977 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5978 	    ip->i_number, blkno, size, lbn);
5979 	ump = ITOUMP(ip);
5980 	fs = ump->um_fs;
5981 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5982 		panic("newfreefrag: frag size");
5983 	freefrag = malloc(sizeof(struct freefrag),
5984 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5985 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5986 	freefrag->ff_state = ATTACHED;
5987 	LIST_INIT(&freefrag->ff_jwork);
5988 	freefrag->ff_inum = ip->i_number;
5989 	freefrag->ff_vtype = ITOV(ip)->v_type;
5990 	freefrag->ff_blkno = blkno;
5991 	freefrag->ff_fragsize = size;
5992 	freefrag->ff_key = key;
5993 
5994 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5995 		freefrag->ff_jdep = (struct worklist *)
5996 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5997 	} else {
5998 		freefrag->ff_state |= DEPCOMPLETE;
5999 		freefrag->ff_jdep = NULL;
6000 	}
6001 
6002 	return (freefrag);
6003 }
6004 
6005 /*
6006  * This workitem de-allocates fragments that were replaced during
6007  * file block allocation.
6008  */
6009 static void
6010 handle_workitem_freefrag(freefrag)
6011 	struct freefrag *freefrag;
6012 {
6013 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
6014 	struct workhead wkhd;
6015 
6016 	CTR3(KTR_SUJ,
6017 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
6018 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
6019 	/*
6020 	 * It would be illegal to add new completion items to the
6021 	 * freefrag after it was schedule to be done so it must be
6022 	 * safe to modify the list head here.
6023 	 */
6024 	LIST_INIT(&wkhd);
6025 	ACQUIRE_LOCK(ump);
6026 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
6027 	/*
6028 	 * If the journal has not been written we must cancel it here.
6029 	 */
6030 	if (freefrag->ff_jdep) {
6031 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
6032 			panic("handle_workitem_freefrag: Unexpected type %d\n",
6033 			    freefrag->ff_jdep->wk_type);
6034 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
6035 	}
6036 	FREE_LOCK(ump);
6037 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
6038 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
6039 	   &wkhd, freefrag->ff_key);
6040 	ACQUIRE_LOCK(ump);
6041 	WORKITEM_FREE(freefrag, D_FREEFRAG);
6042 	FREE_LOCK(ump);
6043 }
6044 
6045 /*
6046  * Set up a dependency structure for an external attributes data block.
6047  * This routine follows much of the structure of softdep_setup_allocdirect.
6048  * See the description of softdep_setup_allocdirect above for details.
6049  */
6050 void
6051 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
6052 	struct inode *ip;
6053 	ufs_lbn_t off;
6054 	ufs2_daddr_t newblkno;
6055 	ufs2_daddr_t oldblkno;
6056 	long newsize;
6057 	long oldsize;
6058 	struct buf *bp;
6059 {
6060 	struct allocdirect *adp, *oldadp;
6061 	struct allocdirectlst *adphead;
6062 	struct freefrag *freefrag;
6063 	struct inodedep *inodedep;
6064 	struct jnewblk *jnewblk;
6065 	struct newblk *newblk;
6066 	struct mount *mp;
6067 	struct ufsmount *ump;
6068 	ufs_lbn_t lbn;
6069 
6070 	mp = ITOVFS(ip);
6071 	ump = VFSTOUFS(mp);
6072 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6073 	    ("softdep_setup_allocext called on non-softdep filesystem"));
6074 	KASSERT(off < UFS_NXADDR,
6075 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
6076 
6077 	lbn = bp->b_lblkno;
6078 	if (oldblkno && oldblkno != newblkno)
6079 		/*
6080 		 * The usual case is that a smaller fragment that
6081 		 * was just allocated has been replaced with a bigger
6082 		 * fragment or a full-size block. If it is marked as
6083 		 * B_DELWRI, the current contents have not been written
6084 		 * to disk. It is possible that the block was written
6085 		 * earlier, but very uncommon. If the block has never
6086 		 * been written, there is no need to send a BIO_DELETE
6087 		 * for it when it is freed. The gain from avoiding the
6088 		 * TRIMs for the common case of unwritten blocks far
6089 		 * exceeds the cost of the write amplification for the
6090 		 * uncommon case of failing to send a TRIM for a block
6091 		 * that had been written.
6092 		 */
6093 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
6094 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
6095 	else
6096 		freefrag = NULL;
6097 
6098 	ACQUIRE_LOCK(ump);
6099 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
6100 		panic("softdep_setup_allocext: lost block");
6101 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6102 	    ("softdep_setup_allocext: newblk already initialized"));
6103 	/*
6104 	 * Convert the newblk to an allocdirect.
6105 	 */
6106 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
6107 	adp = (struct allocdirect *)newblk;
6108 	newblk->nb_freefrag = freefrag;
6109 	adp->ad_offset = off;
6110 	adp->ad_oldblkno = oldblkno;
6111 	adp->ad_newsize = newsize;
6112 	adp->ad_oldsize = oldsize;
6113 	adp->ad_state |=  EXTDATA;
6114 
6115 	/*
6116 	 * Finish initializing the journal.
6117 	 */
6118 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6119 		jnewblk->jn_ino = ip->i_number;
6120 		jnewblk->jn_lbn = lbn;
6121 		add_to_journal(&jnewblk->jn_list);
6122 	}
6123 	if (freefrag && freefrag->ff_jdep != NULL &&
6124 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6125 		add_to_journal(freefrag->ff_jdep);
6126 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6127 	adp->ad_inodedep = inodedep;
6128 
6129 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
6130 	/*
6131 	 * The list of allocdirects must be kept in sorted and ascending
6132 	 * order so that the rollback routines can quickly determine the
6133 	 * first uncommitted block (the size of the file stored on disk
6134 	 * ends at the end of the lowest committed fragment, or if there
6135 	 * are no fragments, at the end of the highest committed block).
6136 	 * Since files generally grow, the typical case is that the new
6137 	 * block is to be added at the end of the list. We speed this
6138 	 * special case by checking against the last allocdirect in the
6139 	 * list before laboriously traversing the list looking for the
6140 	 * insertion point.
6141 	 */
6142 	adphead = &inodedep->id_newextupdt;
6143 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
6144 	if (oldadp == NULL || oldadp->ad_offset <= off) {
6145 		/* insert at end of list */
6146 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
6147 		if (oldadp != NULL && oldadp->ad_offset == off)
6148 			allocdirect_merge(adphead, adp, oldadp);
6149 		FREE_LOCK(ump);
6150 		return;
6151 	}
6152 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
6153 		if (oldadp->ad_offset >= off)
6154 			break;
6155 	}
6156 	if (oldadp == NULL)
6157 		panic("softdep_setup_allocext: lost entry");
6158 	/* insert in middle of list */
6159 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
6160 	if (oldadp->ad_offset == off)
6161 		allocdirect_merge(adphead, adp, oldadp);
6162 	FREE_LOCK(ump);
6163 }
6164 
6165 /*
6166  * Indirect block allocation dependencies.
6167  *
6168  * The same dependencies that exist for a direct block also exist when
6169  * a new block is allocated and pointed to by an entry in a block of
6170  * indirect pointers. The undo/redo states described above are also
6171  * used here. Because an indirect block contains many pointers that
6172  * may have dependencies, a second copy of the entire in-memory indirect
6173  * block is kept. The buffer cache copy is always completely up-to-date.
6174  * The second copy, which is used only as a source for disk writes,
6175  * contains only the safe pointers (i.e., those that have no remaining
6176  * update dependencies). The second copy is freed when all pointers
6177  * are safe. The cache is not allowed to replace indirect blocks with
6178  * pending update dependencies. If a buffer containing an indirect
6179  * block with dependencies is written, these routines will mark it
6180  * dirty again. It can only be successfully written once all the
6181  * dependencies are removed. The ffs_fsync routine in conjunction with
6182  * softdep_sync_metadata work together to get all the dependencies
6183  * removed so that a file can be successfully written to disk. Three
6184  * procedures are used when setting up indirect block pointer
6185  * dependencies. The division is necessary because of the organization
6186  * of the "balloc" routine and because of the distinction between file
6187  * pages and file metadata blocks.
6188  */
6189 
6190 /*
6191  * Allocate a new allocindir structure.
6192  */
6193 static struct allocindir *
6194 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
6195 	struct inode *ip;	/* inode for file being extended */
6196 	int ptrno;		/* offset of pointer in indirect block */
6197 	ufs2_daddr_t newblkno;	/* disk block number being added */
6198 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
6199 	ufs_lbn_t lbn;
6200 {
6201 	struct newblk *newblk;
6202 	struct allocindir *aip;
6203 	struct freefrag *freefrag;
6204 	struct jnewblk *jnewblk;
6205 
6206 	if (oldblkno)
6207 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
6208 		    SINGLETON_KEY);
6209 	else
6210 		freefrag = NULL;
6211 	ACQUIRE_LOCK(ITOUMP(ip));
6212 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
6213 		panic("new_allocindir: lost block");
6214 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6215 	    ("newallocindir: newblk already initialized"));
6216 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
6217 	newblk->nb_freefrag = freefrag;
6218 	aip = (struct allocindir *)newblk;
6219 	aip->ai_offset = ptrno;
6220 	aip->ai_oldblkno = oldblkno;
6221 	aip->ai_lbn = lbn;
6222 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6223 		jnewblk->jn_ino = ip->i_number;
6224 		jnewblk->jn_lbn = lbn;
6225 		add_to_journal(&jnewblk->jn_list);
6226 	}
6227 	if (freefrag && freefrag->ff_jdep != NULL &&
6228 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6229 		add_to_journal(freefrag->ff_jdep);
6230 	return (aip);
6231 }
6232 
6233 /*
6234  * Called just before setting an indirect block pointer
6235  * to a newly allocated file page.
6236  */
6237 void
6238 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
6239 	struct inode *ip;	/* inode for file being extended */
6240 	ufs_lbn_t lbn;		/* allocated block number within file */
6241 	struct buf *bp;		/* buffer with indirect blk referencing page */
6242 	int ptrno;		/* offset of pointer in indirect block */
6243 	ufs2_daddr_t newblkno;	/* disk block number being added */
6244 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
6245 	struct buf *nbp;	/* buffer holding allocated page */
6246 {
6247 	struct inodedep *inodedep;
6248 	struct freefrag *freefrag;
6249 	struct allocindir *aip;
6250 	struct pagedep *pagedep;
6251 	struct mount *mp;
6252 	struct ufsmount *ump;
6253 
6254 	mp = ITOVFS(ip);
6255 	ump = VFSTOUFS(mp);
6256 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6257 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
6258 	KASSERT(lbn == nbp->b_lblkno,
6259 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
6260 	    lbn, bp->b_lblkno));
6261 	CTR4(KTR_SUJ,
6262 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
6263 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
6264 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
6265 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
6266 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6267 	/*
6268 	 * If we are allocating a directory page, then we must
6269 	 * allocate an associated pagedep to track additions and
6270 	 * deletions.
6271 	 */
6272 	if ((ip->i_mode & IFMT) == IFDIR)
6273 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
6274 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6275 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
6276 	FREE_LOCK(ump);
6277 	if (freefrag)
6278 		handle_workitem_freefrag(freefrag);
6279 }
6280 
6281 /*
6282  * Called just before setting an indirect block pointer to a
6283  * newly allocated indirect block.
6284  */
6285 void
6286 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
6287 	struct buf *nbp;	/* newly allocated indirect block */
6288 	struct inode *ip;	/* inode for file being extended */
6289 	struct buf *bp;		/* indirect block referencing allocated block */
6290 	int ptrno;		/* offset of pointer in indirect block */
6291 	ufs2_daddr_t newblkno;	/* disk block number being added */
6292 {
6293 	struct inodedep *inodedep;
6294 	struct allocindir *aip;
6295 	struct ufsmount *ump;
6296 	ufs_lbn_t lbn;
6297 
6298 	ump = ITOUMP(ip);
6299 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6300 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
6301 	CTR3(KTR_SUJ,
6302 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
6303 	    ip->i_number, newblkno, ptrno);
6304 	lbn = nbp->b_lblkno;
6305 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
6306 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
6307 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
6308 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6309 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
6310 		panic("softdep_setup_allocindir_meta: Block already existed");
6311 	FREE_LOCK(ump);
6312 }
6313 
6314 static void
6315 indirdep_complete(indirdep)
6316 	struct indirdep *indirdep;
6317 {
6318 	struct allocindir *aip;
6319 
6320 	LIST_REMOVE(indirdep, ir_next);
6321 	indirdep->ir_state |= DEPCOMPLETE;
6322 
6323 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
6324 		LIST_REMOVE(aip, ai_next);
6325 		free_newblk(&aip->ai_block);
6326 	}
6327 	/*
6328 	 * If this indirdep is not attached to a buf it was simply waiting
6329 	 * on completion to clear completehd.  free_indirdep() asserts
6330 	 * that nothing is dangling.
6331 	 */
6332 	if ((indirdep->ir_state & ONWORKLIST) == 0)
6333 		free_indirdep(indirdep);
6334 }
6335 
6336 static struct indirdep *
6337 indirdep_lookup(mp, ip, bp)
6338 	struct mount *mp;
6339 	struct inode *ip;
6340 	struct buf *bp;
6341 {
6342 	struct indirdep *indirdep, *newindirdep;
6343 	struct newblk *newblk;
6344 	struct ufsmount *ump;
6345 	struct worklist *wk;
6346 	struct fs *fs;
6347 	ufs2_daddr_t blkno;
6348 
6349 	ump = VFSTOUFS(mp);
6350 	LOCK_OWNED(ump);
6351 	indirdep = NULL;
6352 	newindirdep = NULL;
6353 	fs = ump->um_fs;
6354 	for (;;) {
6355 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6356 			if (wk->wk_type != D_INDIRDEP)
6357 				continue;
6358 			indirdep = WK_INDIRDEP(wk);
6359 			break;
6360 		}
6361 		/* Found on the buffer worklist, no new structure to free. */
6362 		if (indirdep != NULL && newindirdep == NULL)
6363 			return (indirdep);
6364 		if (indirdep != NULL && newindirdep != NULL)
6365 			panic("indirdep_lookup: simultaneous create");
6366 		/* None found on the buffer and a new structure is ready. */
6367 		if (indirdep == NULL && newindirdep != NULL)
6368 			break;
6369 		/* None found and no new structure available. */
6370 		FREE_LOCK(ump);
6371 		newindirdep = malloc(sizeof(struct indirdep),
6372 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
6373 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6374 		newindirdep->ir_state = ATTACHED;
6375 		if (I_IS_UFS1(ip))
6376 			newindirdep->ir_state |= UFS1FMT;
6377 		TAILQ_INIT(&newindirdep->ir_trunc);
6378 		newindirdep->ir_saveddata = NULL;
6379 		LIST_INIT(&newindirdep->ir_deplisthd);
6380 		LIST_INIT(&newindirdep->ir_donehd);
6381 		LIST_INIT(&newindirdep->ir_writehd);
6382 		LIST_INIT(&newindirdep->ir_completehd);
6383 		if (bp->b_blkno == bp->b_lblkno) {
6384 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6385 			    NULL, NULL);
6386 			bp->b_blkno = blkno;
6387 		}
6388 		newindirdep->ir_freeblks = NULL;
6389 		newindirdep->ir_savebp =
6390 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6391 		newindirdep->ir_bp = bp;
6392 		BUF_KERNPROC(newindirdep->ir_savebp);
6393 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6394 		ACQUIRE_LOCK(ump);
6395 	}
6396 	indirdep = newindirdep;
6397 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6398 	/*
6399 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6400 	 * that we don't free dependencies until the pointers are valid.
6401 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6402 	 * than using the hash.
6403 	 */
6404 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6405 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6406 	else
6407 		indirdep->ir_state |= DEPCOMPLETE;
6408 	return (indirdep);
6409 }
6410 
6411 /*
6412  * Called to finish the allocation of the "aip" allocated
6413  * by one of the two routines above.
6414  */
6415 static struct freefrag *
6416 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6417 	struct buf *bp;		/* in-memory copy of the indirect block */
6418 	struct inode *ip;	/* inode for file being extended */
6419 	struct inodedep *inodedep; /* Inodedep for ip */
6420 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6421 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6422 {
6423 	struct fs *fs __diagused;
6424 	struct indirdep *indirdep;
6425 	struct allocindir *oldaip;
6426 	struct freefrag *freefrag;
6427 	struct mount *mp;
6428 	struct ufsmount *ump;
6429 
6430 	mp = ITOVFS(ip);
6431 	ump = VFSTOUFS(mp);
6432 	LOCK_OWNED(ump);
6433 	fs = ump->um_fs;
6434 	if (bp->b_lblkno >= 0)
6435 		panic("setup_allocindir_phase2: not indir blk");
6436 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6437 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6438 	indirdep = indirdep_lookup(mp, ip, bp);
6439 	KASSERT(indirdep->ir_savebp != NULL,
6440 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6441 	aip->ai_indirdep = indirdep;
6442 	/*
6443 	 * Check for an unwritten dependency for this indirect offset.  If
6444 	 * there is, merge the old dependency into the new one.  This happens
6445 	 * as a result of reallocblk only.
6446 	 */
6447 	freefrag = NULL;
6448 	if (aip->ai_oldblkno != 0) {
6449 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6450 			if (oldaip->ai_offset == aip->ai_offset) {
6451 				freefrag = allocindir_merge(aip, oldaip);
6452 				goto done;
6453 			}
6454 		}
6455 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6456 			if (oldaip->ai_offset == aip->ai_offset) {
6457 				freefrag = allocindir_merge(aip, oldaip);
6458 				goto done;
6459 			}
6460 		}
6461 	}
6462 done:
6463 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6464 	return (freefrag);
6465 }
6466 
6467 /*
6468  * Merge two allocindirs which refer to the same block.  Move newblock
6469  * dependencies and setup the freefrags appropriately.
6470  */
6471 static struct freefrag *
6472 allocindir_merge(aip, oldaip)
6473 	struct allocindir *aip;
6474 	struct allocindir *oldaip;
6475 {
6476 	struct freefrag *freefrag;
6477 	struct worklist *wk;
6478 
6479 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6480 		panic("allocindir_merge: blkno");
6481 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6482 	freefrag = aip->ai_freefrag;
6483 	aip->ai_freefrag = oldaip->ai_freefrag;
6484 	oldaip->ai_freefrag = NULL;
6485 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6486 	/*
6487 	 * If we are tracking a new directory-block allocation,
6488 	 * move it from the old allocindir to the new allocindir.
6489 	 */
6490 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6491 		WORKLIST_REMOVE(wk);
6492 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6493 			panic("allocindir_merge: extra newdirblk");
6494 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6495 	}
6496 	/*
6497 	 * We can skip journaling for this freefrag and just complete
6498 	 * any pending journal work for the allocindir that is being
6499 	 * removed after the freefrag completes.
6500 	 */
6501 	if (freefrag->ff_jdep)
6502 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6503 	LIST_REMOVE(oldaip, ai_next);
6504 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6505 	    &freefrag->ff_list, &freefrag->ff_jwork);
6506 	free_newblk(&oldaip->ai_block);
6507 
6508 	return (freefrag);
6509 }
6510 
6511 static inline void
6512 setup_freedirect(freeblks, ip, i, needj)
6513 	struct freeblks *freeblks;
6514 	struct inode *ip;
6515 	int i;
6516 	int needj;
6517 {
6518 	struct ufsmount *ump;
6519 	ufs2_daddr_t blkno;
6520 	int frags;
6521 
6522 	blkno = DIP(ip, i_db[i]);
6523 	if (blkno == 0)
6524 		return;
6525 	DIP_SET(ip, i_db[i], 0);
6526 	ump = ITOUMP(ip);
6527 	frags = sblksize(ump->um_fs, ip->i_size, i);
6528 	frags = numfrags(ump->um_fs, frags);
6529 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6530 }
6531 
6532 static inline void
6533 setup_freeext(freeblks, ip, i, needj)
6534 	struct freeblks *freeblks;
6535 	struct inode *ip;
6536 	int i;
6537 	int needj;
6538 {
6539 	struct ufsmount *ump;
6540 	ufs2_daddr_t blkno;
6541 	int frags;
6542 
6543 	blkno = ip->i_din2->di_extb[i];
6544 	if (blkno == 0)
6545 		return;
6546 	ip->i_din2->di_extb[i] = 0;
6547 	ump = ITOUMP(ip);
6548 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6549 	frags = numfrags(ump->um_fs, frags);
6550 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6551 }
6552 
6553 static inline void
6554 setup_freeindir(freeblks, ip, i, lbn, needj)
6555 	struct freeblks *freeblks;
6556 	struct inode *ip;
6557 	int i;
6558 	ufs_lbn_t lbn;
6559 	int needj;
6560 {
6561 	struct ufsmount *ump;
6562 	ufs2_daddr_t blkno;
6563 
6564 	blkno = DIP(ip, i_ib[i]);
6565 	if (blkno == 0)
6566 		return;
6567 	DIP_SET(ip, i_ib[i], 0);
6568 	ump = ITOUMP(ip);
6569 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6570 	    0, needj);
6571 }
6572 
6573 static inline struct freeblks *
6574 newfreeblks(mp, ip)
6575 	struct mount *mp;
6576 	struct inode *ip;
6577 {
6578 	struct freeblks *freeblks;
6579 
6580 	freeblks = malloc(sizeof(struct freeblks),
6581 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6582 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6583 	LIST_INIT(&freeblks->fb_jblkdephd);
6584 	LIST_INIT(&freeblks->fb_jwork);
6585 	freeblks->fb_ref = 0;
6586 	freeblks->fb_cgwait = 0;
6587 	freeblks->fb_state = ATTACHED;
6588 	freeblks->fb_uid = ip->i_uid;
6589 	freeblks->fb_inum = ip->i_number;
6590 	freeblks->fb_vtype = ITOV(ip)->v_type;
6591 	freeblks->fb_modrev = DIP(ip, i_modrev);
6592 	freeblks->fb_devvp = ITODEVVP(ip);
6593 	freeblks->fb_chkcnt = 0;
6594 	freeblks->fb_len = 0;
6595 
6596 	return (freeblks);
6597 }
6598 
6599 static void
6600 trunc_indirdep(indirdep, freeblks, bp, off)
6601 	struct indirdep *indirdep;
6602 	struct freeblks *freeblks;
6603 	struct buf *bp;
6604 	int off;
6605 {
6606 	struct allocindir *aip, *aipn;
6607 
6608 	/*
6609 	 * The first set of allocindirs won't be in savedbp.
6610 	 */
6611 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6612 		if (aip->ai_offset > off)
6613 			cancel_allocindir(aip, bp, freeblks, 1);
6614 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6615 		if (aip->ai_offset > off)
6616 			cancel_allocindir(aip, bp, freeblks, 1);
6617 	/*
6618 	 * These will exist in savedbp.
6619 	 */
6620 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6621 		if (aip->ai_offset > off)
6622 			cancel_allocindir(aip, NULL, freeblks, 0);
6623 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6624 		if (aip->ai_offset > off)
6625 			cancel_allocindir(aip, NULL, freeblks, 0);
6626 }
6627 
6628 /*
6629  * Follow the chain of indirects down to lastlbn creating a freework
6630  * structure for each.  This will be used to start indir_trunc() at
6631  * the right offset and create the journal records for the parrtial
6632  * truncation.  A second step will handle the truncated dependencies.
6633  */
6634 static int
6635 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6636 	struct freeblks *freeblks;
6637 	struct inode *ip;
6638 	ufs_lbn_t lbn;
6639 	ufs_lbn_t lastlbn;
6640 	ufs2_daddr_t blkno;
6641 {
6642 	struct indirdep *indirdep;
6643 	struct indirdep *indirn;
6644 	struct freework *freework;
6645 	struct newblk *newblk;
6646 	struct mount *mp;
6647 	struct ufsmount *ump;
6648 	struct buf *bp;
6649 	uint8_t *start;
6650 	uint8_t *end;
6651 	ufs_lbn_t lbnadd;
6652 	int level;
6653 	int error;
6654 	int off;
6655 
6656 	freework = NULL;
6657 	if (blkno == 0)
6658 		return (0);
6659 	mp = freeblks->fb_list.wk_mp;
6660 	ump = VFSTOUFS(mp);
6661 	/*
6662 	 * Here, calls to VOP_BMAP() will fail.  However, we already have
6663 	 * the on-disk address, so we just pass it to bread() instead of
6664 	 * having bread() attempt to calculate it using VOP_BMAP().
6665 	 */
6666 	error = ffs_breadz(ump, ITOV(ip), lbn, blkptrtodb(ump, blkno),
6667 	    (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6668 	if (error)
6669 		return (error);
6670 	level = lbn_level(lbn);
6671 	lbnadd = lbn_offset(ump->um_fs, level);
6672 	/*
6673 	 * Compute the offset of the last block we want to keep.  Store
6674 	 * in the freework the first block we want to completely free.
6675 	 */
6676 	off = (lastlbn - -(lbn + level)) / lbnadd;
6677 	if (off + 1 == NINDIR(ump->um_fs))
6678 		goto nowork;
6679 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6680 	/*
6681 	 * Link the freework into the indirdep.  This will prevent any new
6682 	 * allocations from proceeding until we are finished with the
6683 	 * truncate and the block is written.
6684 	 */
6685 	ACQUIRE_LOCK(ump);
6686 	indirdep = indirdep_lookup(mp, ip, bp);
6687 	if (indirdep->ir_freeblks)
6688 		panic("setup_trunc_indir: indirdep already truncated.");
6689 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6690 	freework->fw_indir = indirdep;
6691 	/*
6692 	 * Cancel any allocindirs that will not make it to disk.
6693 	 * We have to do this for all copies of the indirdep that
6694 	 * live on this newblk.
6695 	 */
6696 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6697 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6698 		    &newblk) == 0)
6699 			panic("setup_trunc_indir: lost block");
6700 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6701 			trunc_indirdep(indirn, freeblks, bp, off);
6702 	} else
6703 		trunc_indirdep(indirdep, freeblks, bp, off);
6704 	FREE_LOCK(ump);
6705 	/*
6706 	 * Creation is protected by the buf lock. The saveddata is only
6707 	 * needed if a full truncation follows a partial truncation but it
6708 	 * is difficult to allocate in that case so we fetch it anyway.
6709 	 */
6710 	if (indirdep->ir_saveddata == NULL)
6711 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6712 		    M_SOFTDEP_FLAGS);
6713 nowork:
6714 	/* Fetch the blkno of the child and the zero start offset. */
6715 	if (I_IS_UFS1(ip)) {
6716 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6717 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6718 	} else {
6719 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6720 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6721 	}
6722 	if (freework) {
6723 		/* Zero the truncated pointers. */
6724 		end = bp->b_data + bp->b_bcount;
6725 		bzero(start, end - start);
6726 		bdwrite(bp);
6727 	} else
6728 		bqrelse(bp);
6729 	if (level == 0)
6730 		return (0);
6731 	lbn++; /* adjust level */
6732 	lbn -= (off * lbnadd);
6733 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6734 }
6735 
6736 /*
6737  * Complete the partial truncation of an indirect block setup by
6738  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6739  * copy and writes them to disk before the freeblks is allowed to complete.
6740  */
6741 static void
6742 complete_trunc_indir(freework)
6743 	struct freework *freework;
6744 {
6745 	struct freework *fwn;
6746 	struct indirdep *indirdep;
6747 	struct ufsmount *ump;
6748 	struct buf *bp;
6749 	uintptr_t start;
6750 	int count;
6751 
6752 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6753 	LOCK_OWNED(ump);
6754 	indirdep = freework->fw_indir;
6755 	for (;;) {
6756 		bp = indirdep->ir_bp;
6757 		/* See if the block was discarded. */
6758 		if (bp == NULL)
6759 			break;
6760 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6761 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6762 			break;
6763 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6764 		    LOCK_PTR(ump)) == 0)
6765 			BUF_UNLOCK(bp);
6766 		ACQUIRE_LOCK(ump);
6767 	}
6768 	freework->fw_state |= DEPCOMPLETE;
6769 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6770 	/*
6771 	 * Zero the pointers in the saved copy.
6772 	 */
6773 	if (indirdep->ir_state & UFS1FMT)
6774 		start = sizeof(ufs1_daddr_t);
6775 	else
6776 		start = sizeof(ufs2_daddr_t);
6777 	start *= freework->fw_start;
6778 	count = indirdep->ir_savebp->b_bcount - start;
6779 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6780 	bzero((char *)start, count);
6781 	/*
6782 	 * We need to start the next truncation in the list if it has not
6783 	 * been started yet.
6784 	 */
6785 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6786 	if (fwn != NULL) {
6787 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6788 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6789 		if ((fwn->fw_state & ONWORKLIST) == 0)
6790 			freework_enqueue(fwn);
6791 	}
6792 	/*
6793 	 * If bp is NULL the block was fully truncated, restore
6794 	 * the saved block list otherwise free it if it is no
6795 	 * longer needed.
6796 	 */
6797 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6798 		if (bp == NULL)
6799 			bcopy(indirdep->ir_saveddata,
6800 			    indirdep->ir_savebp->b_data,
6801 			    indirdep->ir_savebp->b_bcount);
6802 		free(indirdep->ir_saveddata, M_INDIRDEP);
6803 		indirdep->ir_saveddata = NULL;
6804 	}
6805 	/*
6806 	 * When bp is NULL there is a full truncation pending.  We
6807 	 * must wait for this full truncation to be journaled before
6808 	 * we can release this freework because the disk pointers will
6809 	 * never be written as zero.
6810 	 */
6811 	if (bp == NULL)  {
6812 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6813 			handle_written_freework(freework);
6814 		else
6815 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6816 			   &freework->fw_list);
6817 		if (fwn == NULL) {
6818 			freework->fw_indir = (void *)0x0000deadbeef0000;
6819 			bp = indirdep->ir_savebp;
6820 			indirdep->ir_savebp = NULL;
6821 			free_indirdep(indirdep);
6822 			FREE_LOCK(ump);
6823 			brelse(bp);
6824 			ACQUIRE_LOCK(ump);
6825 		}
6826 	} else {
6827 		/* Complete when the real copy is written. */
6828 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6829 		BUF_UNLOCK(bp);
6830 	}
6831 }
6832 
6833 /*
6834  * Calculate the number of blocks we are going to release where datablocks
6835  * is the current total and length is the new file size.
6836  */
6837 static ufs2_daddr_t
6838 blkcount(fs, datablocks, length)
6839 	struct fs *fs;
6840 	ufs2_daddr_t datablocks;
6841 	off_t length;
6842 {
6843 	off_t totblks, numblks;
6844 
6845 	totblks = 0;
6846 	numblks = howmany(length, fs->fs_bsize);
6847 	if (numblks <= UFS_NDADDR) {
6848 		totblks = howmany(length, fs->fs_fsize);
6849 		goto out;
6850 	}
6851         totblks = blkstofrags(fs, numblks);
6852 	numblks -= UFS_NDADDR;
6853 	/*
6854 	 * Count all single, then double, then triple indirects required.
6855 	 * Subtracting one indirects worth of blocks for each pass
6856 	 * acknowledges one of each pointed to by the inode.
6857 	 */
6858 	for (;;) {
6859 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6860 		numblks -= NINDIR(fs);
6861 		if (numblks <= 0)
6862 			break;
6863 		numblks = howmany(numblks, NINDIR(fs));
6864 	}
6865 out:
6866 	totblks = fsbtodb(fs, totblks);
6867 	/*
6868 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6869 	 * references.  We will correct it later in handle_complete_freeblks()
6870 	 * when we know the real count.
6871 	 */
6872 	if (totblks > datablocks)
6873 		return (0);
6874 	return (datablocks - totblks);
6875 }
6876 
6877 /*
6878  * Handle freeblocks for journaled softupdate filesystems.
6879  *
6880  * Contrary to normal softupdates, we must preserve the block pointers in
6881  * indirects until their subordinates are free.  This is to avoid journaling
6882  * every block that is freed which may consume more space than the journal
6883  * itself.  The recovery program will see the free block journals at the
6884  * base of the truncated area and traverse them to reclaim space.  The
6885  * pointers in the inode may be cleared immediately after the journal
6886  * records are written because each direct and indirect pointer in the
6887  * inode is recorded in a journal.  This permits full truncation to proceed
6888  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6889  *
6890  * The algorithm is as follows:
6891  * 1) Traverse the in-memory state and create journal entries to release
6892  *    the relevant blocks and full indirect trees.
6893  * 2) Traverse the indirect block chain adding partial truncation freework
6894  *    records to indirects in the path to lastlbn.  The freework will
6895  *    prevent new allocation dependencies from being satisfied in this
6896  *    indirect until the truncation completes.
6897  * 3) Read and lock the inode block, performing an update with the new size
6898  *    and pointers.  This prevents truncated data from becoming valid on
6899  *    disk through step 4.
6900  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6901  *    eliminate journal work for those records that do not require it.
6902  * 5) Schedule the journal records to be written followed by the inode block.
6903  * 6) Allocate any necessary frags for the end of file.
6904  * 7) Zero any partially truncated blocks.
6905  *
6906  * From this truncation proceeds asynchronously using the freework and
6907  * indir_trunc machinery.  The file will not be extended again into a
6908  * partially truncated indirect block until all work is completed but
6909  * the normal dependency mechanism ensures that it is rolled back/forward
6910  * as appropriate.  Further truncation may occur without delay and is
6911  * serialized in indir_trunc().
6912  */
6913 void
6914 softdep_journal_freeblocks(ip, cred, length, flags)
6915 	struct inode *ip;	/* The inode whose length is to be reduced */
6916 	struct ucred *cred;
6917 	off_t length;		/* The new length for the file */
6918 	int flags;		/* IO_EXT and/or IO_NORMAL */
6919 {
6920 	struct freeblks *freeblks, *fbn;
6921 	struct worklist *wk, *wkn;
6922 	struct inodedep *inodedep;
6923 	struct jblkdep *jblkdep;
6924 	struct allocdirect *adp, *adpn;
6925 	struct ufsmount *ump;
6926 	struct fs *fs;
6927 	struct buf *bp;
6928 	struct vnode *vp;
6929 	struct mount *mp;
6930 	daddr_t dbn;
6931 	ufs2_daddr_t extblocks, datablocks;
6932 	ufs_lbn_t tmpval, lbn, lastlbn;
6933 	int frags, lastoff, iboff, allocblock, needj, error, i;
6934 
6935 	ump = ITOUMP(ip);
6936 	mp = UFSTOVFS(ump);
6937 	fs = ump->um_fs;
6938 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6939 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6940 	vp = ITOV(ip);
6941 	needj = 1;
6942 	iboff = -1;
6943 	allocblock = 0;
6944 	extblocks = 0;
6945 	datablocks = 0;
6946 	frags = 0;
6947 	freeblks = newfreeblks(mp, ip);
6948 	ACQUIRE_LOCK(ump);
6949 	/*
6950 	 * If we're truncating a removed file that will never be written
6951 	 * we don't need to journal the block frees.  The canceled journals
6952 	 * for the allocations will suffice.
6953 	 */
6954 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6955 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6956 	    length == 0)
6957 		needj = 0;
6958 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6959 	    ip->i_number, length, needj);
6960 	FREE_LOCK(ump);
6961 	/*
6962 	 * Calculate the lbn that we are truncating to.  This results in -1
6963 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6964 	 * to keep, not the first lbn we want to truncate.
6965 	 */
6966 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6967 	lastoff = blkoff(fs, length);
6968 	/*
6969 	 * Compute frags we are keeping in lastlbn.  0 means all.
6970 	 */
6971 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6972 		frags = fragroundup(fs, lastoff);
6973 		/* adp offset of last valid allocdirect. */
6974 		iboff = lastlbn;
6975 	} else if (lastlbn > 0)
6976 		iboff = UFS_NDADDR;
6977 	if (fs->fs_magic == FS_UFS2_MAGIC)
6978 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6979 	/*
6980 	 * Handle normal data blocks and indirects.  This section saves
6981 	 * values used after the inode update to complete frag and indirect
6982 	 * truncation.
6983 	 */
6984 	if ((flags & IO_NORMAL) != 0) {
6985 		/*
6986 		 * Handle truncation of whole direct and indirect blocks.
6987 		 */
6988 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6989 			setup_freedirect(freeblks, ip, i, needj);
6990 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6991 		    i < UFS_NIADDR;
6992 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6993 			/* Release a whole indirect tree. */
6994 			if (lbn > lastlbn) {
6995 				setup_freeindir(freeblks, ip, i, -lbn -i,
6996 				    needj);
6997 				continue;
6998 			}
6999 			iboff = i + UFS_NDADDR;
7000 			/*
7001 			 * Traverse partially truncated indirect tree.
7002 			 */
7003 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
7004 				setup_trunc_indir(freeblks, ip, -lbn - i,
7005 				    lastlbn, DIP(ip, i_ib[i]));
7006 		}
7007 		/*
7008 		 * Handle partial truncation to a frag boundary.
7009 		 */
7010 		if (frags) {
7011 			ufs2_daddr_t blkno;
7012 			long oldfrags;
7013 
7014 			oldfrags = blksize(fs, ip, lastlbn);
7015 			blkno = DIP(ip, i_db[lastlbn]);
7016 			if (blkno && oldfrags != frags) {
7017 				oldfrags -= frags;
7018 				oldfrags = numfrags(fs, oldfrags);
7019 				blkno += numfrags(fs, frags);
7020 				newfreework(ump, freeblks, NULL, lastlbn,
7021 				    blkno, oldfrags, 0, needj);
7022 				if (needj)
7023 					adjust_newfreework(freeblks,
7024 					    numfrags(fs, frags));
7025 			} else if (blkno == 0)
7026 				allocblock = 1;
7027 		}
7028 		/*
7029 		 * Add a journal record for partial truncate if we are
7030 		 * handling indirect blocks.  Non-indirects need no extra
7031 		 * journaling.
7032 		 */
7033 		if (length != 0 && lastlbn >= UFS_NDADDR) {
7034 			UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
7035 			newjtrunc(freeblks, length, 0);
7036 		}
7037 		ip->i_size = length;
7038 		DIP_SET(ip, i_size, ip->i_size);
7039 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7040 		datablocks = DIP(ip, i_blocks) - extblocks;
7041 		if (length != 0)
7042 			datablocks = blkcount(fs, datablocks, length);
7043 		freeblks->fb_len = length;
7044 	}
7045 	if ((flags & IO_EXT) != 0) {
7046 		for (i = 0; i < UFS_NXADDR; i++)
7047 			setup_freeext(freeblks, ip, i, needj);
7048 		ip->i_din2->di_extsize = 0;
7049 		datablocks += extblocks;
7050 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7051 	}
7052 #ifdef QUOTA
7053 	/* Reference the quotas in case the block count is wrong in the end. */
7054 	quotaref(vp, freeblks->fb_quota);
7055 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7056 #endif
7057 	freeblks->fb_chkcnt = -datablocks;
7058 	UFS_LOCK(ump);
7059 	fs->fs_pendingblocks += datablocks;
7060 	UFS_UNLOCK(ump);
7061 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7062 	/*
7063 	 * Handle truncation of incomplete alloc direct dependencies.  We
7064 	 * hold the inode block locked to prevent incomplete dependencies
7065 	 * from reaching the disk while we are eliminating those that
7066 	 * have been truncated.  This is a partially inlined ffs_update().
7067 	 */
7068 	ufs_itimes(vp);
7069 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
7070 	dbn = fsbtodb(fs, ino_to_fsba(fs, ip->i_number));
7071 	error = ffs_breadz(ump, ump->um_devvp, dbn, dbn, (int)fs->fs_bsize,
7072 	    NULL, NULL, 0, cred, 0, NULL, &bp);
7073 	if (error) {
7074 		softdep_error("softdep_journal_freeblocks", error);
7075 		return;
7076 	}
7077 	if (bp->b_bufsize == fs->fs_bsize)
7078 		bp->b_flags |= B_CLUSTEROK;
7079 	softdep_update_inodeblock(ip, bp, 0);
7080 	if (ump->um_fstype == UFS1) {
7081 		*((struct ufs1_dinode *)bp->b_data +
7082 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
7083 	} else {
7084 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7085 		*((struct ufs2_dinode *)bp->b_data +
7086 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
7087 	}
7088 	ACQUIRE_LOCK(ump);
7089 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7090 	if ((inodedep->id_state & IOSTARTED) != 0)
7091 		panic("softdep_setup_freeblocks: inode busy");
7092 	/*
7093 	 * Add the freeblks structure to the list of operations that
7094 	 * must await the zero'ed inode being written to disk. If we
7095 	 * still have a bitmap dependency (needj), then the inode
7096 	 * has never been written to disk, so we can process the
7097 	 * freeblks below once we have deleted the dependencies.
7098 	 */
7099 	if (needj)
7100 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7101 	else
7102 		freeblks->fb_state |= COMPLETE;
7103 	if ((flags & IO_NORMAL) != 0) {
7104 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
7105 			if (adp->ad_offset > iboff)
7106 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
7107 				    freeblks);
7108 			/*
7109 			 * Truncate the allocdirect.  We could eliminate
7110 			 * or modify journal records as well.
7111 			 */
7112 			else if (adp->ad_offset == iboff && frags)
7113 				adp->ad_newsize = frags;
7114 		}
7115 	}
7116 	if ((flags & IO_EXT) != 0)
7117 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7118 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7119 			    freeblks);
7120 	/*
7121 	 * Scan the bufwait list for newblock dependencies that will never
7122 	 * make it to disk.
7123 	 */
7124 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
7125 		if (wk->wk_type != D_ALLOCDIRECT)
7126 			continue;
7127 		adp = WK_ALLOCDIRECT(wk);
7128 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
7129 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
7130 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
7131 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
7132 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7133 		}
7134 	}
7135 	/*
7136 	 * Add journal work.
7137 	 */
7138 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
7139 		add_to_journal(&jblkdep->jb_list);
7140 	FREE_LOCK(ump);
7141 	bdwrite(bp);
7142 	/*
7143 	 * Truncate dependency structures beyond length.
7144 	 */
7145 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
7146 	/*
7147 	 * This is only set when we need to allocate a fragment because
7148 	 * none existed at the end of a frag-sized file.  It handles only
7149 	 * allocating a new, zero filled block.
7150 	 */
7151 	if (allocblock) {
7152 		ip->i_size = length - lastoff;
7153 		DIP_SET(ip, i_size, ip->i_size);
7154 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
7155 		if (error != 0) {
7156 			softdep_error("softdep_journal_freeblks", error);
7157 			return;
7158 		}
7159 		ip->i_size = length;
7160 		DIP_SET(ip, i_size, length);
7161 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
7162 		allocbuf(bp, frags);
7163 		ffs_update(vp, 0);
7164 		bawrite(bp);
7165 	} else if (lastoff != 0 && vp->v_type != VDIR) {
7166 		int size;
7167 
7168 		/*
7169 		 * Zero the end of a truncated frag or block.
7170 		 */
7171 		size = sblksize(fs, length, lastlbn);
7172 		error = bread(vp, lastlbn, size, cred, &bp);
7173 		if (error == 0) {
7174 			bzero((char *)bp->b_data + lastoff, size - lastoff);
7175 			bawrite(bp);
7176 		} else if (!ffs_fsfail_cleanup(ump, error)) {
7177 			softdep_error("softdep_journal_freeblks", error);
7178 			return;
7179 		}
7180 	}
7181 	ACQUIRE_LOCK(ump);
7182 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7183 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
7184 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
7185 	/*
7186 	 * We zero earlier truncations so they don't erroneously
7187 	 * update i_blocks.
7188 	 */
7189 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
7190 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
7191 			fbn->fb_len = 0;
7192 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
7193 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7194 		freeblks->fb_state |= INPROGRESS;
7195 	else
7196 		freeblks = NULL;
7197 	FREE_LOCK(ump);
7198 	if (freeblks)
7199 		handle_workitem_freeblocks(freeblks, 0);
7200 	trunc_pages(ip, length, extblocks, flags);
7201 
7202 }
7203 
7204 /*
7205  * Flush a JOP_SYNC to the journal.
7206  */
7207 void
7208 softdep_journal_fsync(ip)
7209 	struct inode *ip;
7210 {
7211 	struct jfsync *jfsync;
7212 	struct ufsmount *ump;
7213 
7214 	ump = ITOUMP(ip);
7215 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7216 	    ("softdep_journal_fsync called on non-softdep filesystem"));
7217 	if ((ip->i_flag & IN_TRUNCATED) == 0)
7218 		return;
7219 	ip->i_flag &= ~IN_TRUNCATED;
7220 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
7221 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
7222 	jfsync->jfs_size = ip->i_size;
7223 	jfsync->jfs_ino = ip->i_number;
7224 	ACQUIRE_LOCK(ump);
7225 	add_to_journal(&jfsync->jfs_list);
7226 	jwait(&jfsync->jfs_list, MNT_WAIT);
7227 	FREE_LOCK(ump);
7228 }
7229 
7230 /*
7231  * Block de-allocation dependencies.
7232  *
7233  * When blocks are de-allocated, the on-disk pointers must be nullified before
7234  * the blocks are made available for use by other files.  (The true
7235  * requirement is that old pointers must be nullified before new on-disk
7236  * pointers are set.  We chose this slightly more stringent requirement to
7237  * reduce complexity.) Our implementation handles this dependency by updating
7238  * the inode (or indirect block) appropriately but delaying the actual block
7239  * de-allocation (i.e., freemap and free space count manipulation) until
7240  * after the updated versions reach stable storage.  After the disk is
7241  * updated, the blocks can be safely de-allocated whenever it is convenient.
7242  * This implementation handles only the common case of reducing a file's
7243  * length to zero. Other cases are handled by the conventional synchronous
7244  * write approach.
7245  *
7246  * The ffs implementation with which we worked double-checks
7247  * the state of the block pointers and file size as it reduces
7248  * a file's length.  Some of this code is replicated here in our
7249  * soft updates implementation.  The freeblks->fb_chkcnt field is
7250  * used to transfer a part of this information to the procedure
7251  * that eventually de-allocates the blocks.
7252  *
7253  * This routine should be called from the routine that shortens
7254  * a file's length, before the inode's size or block pointers
7255  * are modified. It will save the block pointer information for
7256  * later release and zero the inode so that the calling routine
7257  * can release it.
7258  */
7259 void
7260 softdep_setup_freeblocks(ip, length, flags)
7261 	struct inode *ip;	/* The inode whose length is to be reduced */
7262 	off_t length;		/* The new length for the file */
7263 	int flags;		/* IO_EXT and/or IO_NORMAL */
7264 {
7265 	struct ufs1_dinode *dp1;
7266 	struct ufs2_dinode *dp2;
7267 	struct freeblks *freeblks;
7268 	struct inodedep *inodedep;
7269 	struct allocdirect *adp;
7270 	struct ufsmount *ump;
7271 	struct buf *bp;
7272 	struct fs *fs;
7273 	ufs2_daddr_t extblocks, datablocks;
7274 	struct mount *mp;
7275 	int i, delay, error;
7276 	ufs_lbn_t tmpval;
7277 	ufs_lbn_t lbn;
7278 
7279 	ump = ITOUMP(ip);
7280 	mp = UFSTOVFS(ump);
7281 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
7282 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
7283 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
7284 	    ip->i_number, length);
7285 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
7286 	fs = ump->um_fs;
7287 	if ((error = bread(ump->um_devvp,
7288 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
7289 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
7290 		if (!ffs_fsfail_cleanup(ump, error))
7291 			softdep_error("softdep_setup_freeblocks", error);
7292 		return;
7293 	}
7294 	freeblks = newfreeblks(mp, ip);
7295 	extblocks = 0;
7296 	datablocks = 0;
7297 	if (fs->fs_magic == FS_UFS2_MAGIC)
7298 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
7299 	if ((flags & IO_NORMAL) != 0) {
7300 		for (i = 0; i < UFS_NDADDR; i++)
7301 			setup_freedirect(freeblks, ip, i, 0);
7302 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
7303 		    i < UFS_NIADDR;
7304 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
7305 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
7306 		ip->i_size = 0;
7307 		DIP_SET(ip, i_size, 0);
7308 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7309 		datablocks = DIP(ip, i_blocks) - extblocks;
7310 	}
7311 	if ((flags & IO_EXT) != 0) {
7312 		for (i = 0; i < UFS_NXADDR; i++)
7313 			setup_freeext(freeblks, ip, i, 0);
7314 		ip->i_din2->di_extsize = 0;
7315 		datablocks += extblocks;
7316 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7317 	}
7318 #ifdef QUOTA
7319 	/* Reference the quotas in case the block count is wrong in the end. */
7320 	quotaref(ITOV(ip), freeblks->fb_quota);
7321 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7322 #endif
7323 	freeblks->fb_chkcnt = -datablocks;
7324 	UFS_LOCK(ump);
7325 	fs->fs_pendingblocks += datablocks;
7326 	UFS_UNLOCK(ump);
7327 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7328 	/*
7329 	 * Push the zero'ed inode to its disk buffer so that we are free
7330 	 * to delete its dependencies below. Once the dependencies are gone
7331 	 * the buffer can be safely released.
7332 	 */
7333 	if (ump->um_fstype == UFS1) {
7334 		dp1 = ((struct ufs1_dinode *)bp->b_data +
7335 		    ino_to_fsbo(fs, ip->i_number));
7336 		ip->i_din1->di_freelink = dp1->di_freelink;
7337 		*dp1 = *ip->i_din1;
7338 	} else {
7339 		dp2 = ((struct ufs2_dinode *)bp->b_data +
7340 		    ino_to_fsbo(fs, ip->i_number));
7341 		ip->i_din2->di_freelink = dp2->di_freelink;
7342 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7343 		*dp2 = *ip->i_din2;
7344 	}
7345 	/*
7346 	 * Find and eliminate any inode dependencies.
7347 	 */
7348 	ACQUIRE_LOCK(ump);
7349 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7350 	if ((inodedep->id_state & IOSTARTED) != 0)
7351 		panic("softdep_setup_freeblocks: inode busy");
7352 	/*
7353 	 * Add the freeblks structure to the list of operations that
7354 	 * must await the zero'ed inode being written to disk. If we
7355 	 * still have a bitmap dependency (delay == 0), then the inode
7356 	 * has never been written to disk, so we can process the
7357 	 * freeblks below once we have deleted the dependencies.
7358 	 */
7359 	delay = (inodedep->id_state & DEPCOMPLETE);
7360 	if (delay)
7361 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7362 	else
7363 		freeblks->fb_state |= COMPLETE;
7364 	/*
7365 	 * Because the file length has been truncated to zero, any
7366 	 * pending block allocation dependency structures associated
7367 	 * with this inode are obsolete and can simply be de-allocated.
7368 	 * We must first merge the two dependency lists to get rid of
7369 	 * any duplicate freefrag structures, then purge the merged list.
7370 	 * If we still have a bitmap dependency, then the inode has never
7371 	 * been written to disk, so we can free any fragments without delay.
7372 	 */
7373 	if (flags & IO_NORMAL) {
7374 		merge_inode_lists(&inodedep->id_newinoupdt,
7375 		    &inodedep->id_inoupdt);
7376 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7377 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7378 			    freeblks);
7379 	}
7380 	if (flags & IO_EXT) {
7381 		merge_inode_lists(&inodedep->id_newextupdt,
7382 		    &inodedep->id_extupdt);
7383 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7384 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7385 			    freeblks);
7386 	}
7387 	FREE_LOCK(ump);
7388 	bdwrite(bp);
7389 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7390 	ACQUIRE_LOCK(ump);
7391 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7392 		(void) free_inodedep(inodedep);
7393 	freeblks->fb_state |= DEPCOMPLETE;
7394 	/*
7395 	 * If the inode with zeroed block pointers is now on disk
7396 	 * we can start freeing blocks.
7397 	 */
7398 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7399 		freeblks->fb_state |= INPROGRESS;
7400 	else
7401 		freeblks = NULL;
7402 	FREE_LOCK(ump);
7403 	if (freeblks)
7404 		handle_workitem_freeblocks(freeblks, 0);
7405 	trunc_pages(ip, length, extblocks, flags);
7406 }
7407 
7408 /*
7409  * Eliminate pages from the page cache that back parts of this inode and
7410  * adjust the vnode pager's idea of our size.  This prevents stale data
7411  * from hanging around in the page cache.
7412  */
7413 static void
7414 trunc_pages(ip, length, extblocks, flags)
7415 	struct inode *ip;
7416 	off_t length;
7417 	ufs2_daddr_t extblocks;
7418 	int flags;
7419 {
7420 	struct vnode *vp;
7421 	struct fs *fs;
7422 	ufs_lbn_t lbn;
7423 	off_t end, extend;
7424 
7425 	vp = ITOV(ip);
7426 	fs = ITOFS(ip);
7427 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7428 	if ((flags & IO_EXT) != 0)
7429 		vn_pages_remove(vp, extend, 0);
7430 	if ((flags & IO_NORMAL) == 0)
7431 		return;
7432 	BO_LOCK(&vp->v_bufobj);
7433 	drain_output(vp);
7434 	BO_UNLOCK(&vp->v_bufobj);
7435 	/*
7436 	 * The vnode pager eliminates file pages we eliminate indirects
7437 	 * below.
7438 	 */
7439 	vnode_pager_setsize(vp, length);
7440 	/*
7441 	 * Calculate the end based on the last indirect we want to keep.  If
7442 	 * the block extends into indirects we can just use the negative of
7443 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7444 	 * be careful not to remove those, if they exist.  double and triple
7445 	 * indirect lbns do not overlap with others so it is not important
7446 	 * to verify how many levels are required.
7447 	 */
7448 	lbn = lblkno(fs, length);
7449 	if (lbn >= UFS_NDADDR) {
7450 		/* Calculate the virtual lbn of the triple indirect. */
7451 		lbn = -lbn - (UFS_NIADDR - 1);
7452 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7453 	} else
7454 		end = extend;
7455 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7456 }
7457 
7458 /*
7459  * See if the buf bp is in the range eliminated by truncation.
7460  */
7461 static int
7462 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7463 	struct buf *bp;
7464 	int *blkoffp;
7465 	ufs_lbn_t lastlbn;
7466 	int lastoff;
7467 	int flags;
7468 {
7469 	ufs_lbn_t lbn;
7470 
7471 	*blkoffp = 0;
7472 	/* Only match ext/normal blocks as appropriate. */
7473 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7474 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7475 		return (0);
7476 	/* ALTDATA is always a full truncation. */
7477 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7478 		return (1);
7479 	/* -1 is full truncation. */
7480 	if (lastlbn == -1)
7481 		return (1);
7482 	/*
7483 	 * If this is a partial truncate we only want those
7484 	 * blocks and indirect blocks that cover the range
7485 	 * we're after.
7486 	 */
7487 	lbn = bp->b_lblkno;
7488 	if (lbn < 0)
7489 		lbn = -(lbn + lbn_level(lbn));
7490 	if (lbn < lastlbn)
7491 		return (0);
7492 	/* Here we only truncate lblkno if it's partial. */
7493 	if (lbn == lastlbn) {
7494 		if (lastoff == 0)
7495 			return (0);
7496 		*blkoffp = lastoff;
7497 	}
7498 	return (1);
7499 }
7500 
7501 /*
7502  * Eliminate any dependencies that exist in memory beyond lblkno:off
7503  */
7504 static void
7505 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7506 	struct inode *ip;
7507 	struct freeblks *freeblks;
7508 	ufs_lbn_t lastlbn;
7509 	int lastoff;
7510 	int flags;
7511 {
7512 	struct bufobj *bo;
7513 	struct vnode *vp;
7514 	struct buf *bp;
7515 	int blkoff;
7516 
7517 	/*
7518 	 * We must wait for any I/O in progress to finish so that
7519 	 * all potential buffers on the dirty list will be visible.
7520 	 * Once they are all there, walk the list and get rid of
7521 	 * any dependencies.
7522 	 */
7523 	vp = ITOV(ip);
7524 	bo = &vp->v_bufobj;
7525 	BO_LOCK(bo);
7526 	drain_output(vp);
7527 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7528 		bp->b_vflags &= ~BV_SCANNED;
7529 restart:
7530 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7531 		if (bp->b_vflags & BV_SCANNED)
7532 			continue;
7533 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7534 			bp->b_vflags |= BV_SCANNED;
7535 			continue;
7536 		}
7537 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7538 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7539 			goto restart;
7540 		BO_UNLOCK(bo);
7541 		if (deallocate_dependencies(bp, freeblks, blkoff))
7542 			bqrelse(bp);
7543 		else
7544 			brelse(bp);
7545 		BO_LOCK(bo);
7546 		goto restart;
7547 	}
7548 	/*
7549 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7550 	 */
7551 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7552 		bp->b_vflags &= ~BV_SCANNED;
7553 cleanrestart:
7554 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7555 		if (bp->b_vflags & BV_SCANNED)
7556 			continue;
7557 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7558 			bp->b_vflags |= BV_SCANNED;
7559 			continue;
7560 		}
7561 		if (BUF_LOCK(bp,
7562 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7563 		    BO_LOCKPTR(bo)) == ENOLCK) {
7564 			BO_LOCK(bo);
7565 			goto cleanrestart;
7566 		}
7567 		BO_LOCK(bo);
7568 		bp->b_vflags |= BV_SCANNED;
7569 		BO_UNLOCK(bo);
7570 		bremfree(bp);
7571 		if (blkoff != 0) {
7572 			allocbuf(bp, blkoff);
7573 			bqrelse(bp);
7574 		} else {
7575 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7576 			brelse(bp);
7577 		}
7578 		BO_LOCK(bo);
7579 		goto cleanrestart;
7580 	}
7581 	drain_output(vp);
7582 	BO_UNLOCK(bo);
7583 }
7584 
7585 static int
7586 cancel_pagedep(pagedep, freeblks, blkoff)
7587 	struct pagedep *pagedep;
7588 	struct freeblks *freeblks;
7589 	int blkoff;
7590 {
7591 	struct jremref *jremref;
7592 	struct jmvref *jmvref;
7593 	struct dirrem *dirrem, *tmp;
7594 	int i;
7595 
7596 	/*
7597 	 * Copy any directory remove dependencies to the list
7598 	 * to be processed after the freeblks proceeds.  If
7599 	 * directory entry never made it to disk they
7600 	 * can be dumped directly onto the work list.
7601 	 */
7602 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7603 		/* Skip this directory removal if it is intended to remain. */
7604 		if (dirrem->dm_offset < blkoff)
7605 			continue;
7606 		/*
7607 		 * If there are any dirrems we wait for the journal write
7608 		 * to complete and then restart the buf scan as the lock
7609 		 * has been dropped.
7610 		 */
7611 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7612 			jwait(&jremref->jr_list, MNT_WAIT);
7613 			return (ERESTART);
7614 		}
7615 		LIST_REMOVE(dirrem, dm_next);
7616 		dirrem->dm_dirinum = pagedep->pd_ino;
7617 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7618 	}
7619 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7620 		jwait(&jmvref->jm_list, MNT_WAIT);
7621 		return (ERESTART);
7622 	}
7623 	/*
7624 	 * When we're partially truncating a pagedep we just want to flush
7625 	 * journal entries and return.  There can not be any adds in the
7626 	 * truncated portion of the directory and newblk must remain if
7627 	 * part of the block remains.
7628 	 */
7629 	if (blkoff != 0) {
7630 		struct diradd *dap;
7631 
7632 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7633 			if (dap->da_offset > blkoff)
7634 				panic("cancel_pagedep: diradd %p off %d > %d",
7635 				    dap, dap->da_offset, blkoff);
7636 		for (i = 0; i < DAHASHSZ; i++)
7637 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7638 				if (dap->da_offset > blkoff)
7639 					panic("cancel_pagedep: diradd %p off %d > %d",
7640 					    dap, dap->da_offset, blkoff);
7641 		return (0);
7642 	}
7643 	/*
7644 	 * There should be no directory add dependencies present
7645 	 * as the directory could not be truncated until all
7646 	 * children were removed.
7647 	 */
7648 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7649 	    ("deallocate_dependencies: pendinghd != NULL"));
7650 	for (i = 0; i < DAHASHSZ; i++)
7651 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7652 		    ("deallocate_dependencies: diraddhd != NULL"));
7653 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7654 		free_newdirblk(pagedep->pd_newdirblk);
7655 	if (free_pagedep(pagedep) == 0)
7656 		panic("Failed to free pagedep %p", pagedep);
7657 	return (0);
7658 }
7659 
7660 /*
7661  * Reclaim any dependency structures from a buffer that is about to
7662  * be reallocated to a new vnode. The buffer must be locked, thus,
7663  * no I/O completion operations can occur while we are manipulating
7664  * its associated dependencies. The mutex is held so that other I/O's
7665  * associated with related dependencies do not occur.
7666  */
7667 static int
7668 deallocate_dependencies(bp, freeblks, off)
7669 	struct buf *bp;
7670 	struct freeblks *freeblks;
7671 	int off;
7672 {
7673 	struct indirdep *indirdep;
7674 	struct pagedep *pagedep;
7675 	struct worklist *wk, *wkn;
7676 	struct ufsmount *ump;
7677 
7678 	ump = softdep_bp_to_mp(bp);
7679 	if (ump == NULL)
7680 		goto done;
7681 	ACQUIRE_LOCK(ump);
7682 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7683 		switch (wk->wk_type) {
7684 		case D_INDIRDEP:
7685 			indirdep = WK_INDIRDEP(wk);
7686 			if (bp->b_lblkno >= 0 ||
7687 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7688 				panic("deallocate_dependencies: not indir");
7689 			cancel_indirdep(indirdep, bp, freeblks);
7690 			continue;
7691 
7692 		case D_PAGEDEP:
7693 			pagedep = WK_PAGEDEP(wk);
7694 			if (cancel_pagedep(pagedep, freeblks, off)) {
7695 				FREE_LOCK(ump);
7696 				return (ERESTART);
7697 			}
7698 			continue;
7699 
7700 		case D_ALLOCINDIR:
7701 			/*
7702 			 * Simply remove the allocindir, we'll find it via
7703 			 * the indirdep where we can clear pointers if
7704 			 * needed.
7705 			 */
7706 			WORKLIST_REMOVE(wk);
7707 			continue;
7708 
7709 		case D_FREEWORK:
7710 			/*
7711 			 * A truncation is waiting for the zero'd pointers
7712 			 * to be written.  It can be freed when the freeblks
7713 			 * is journaled.
7714 			 */
7715 			WORKLIST_REMOVE(wk);
7716 			wk->wk_state |= ONDEPLIST;
7717 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7718 			break;
7719 
7720 		case D_ALLOCDIRECT:
7721 			if (off != 0)
7722 				continue;
7723 			/* FALLTHROUGH */
7724 		default:
7725 			panic("deallocate_dependencies: Unexpected type %s",
7726 			    TYPENAME(wk->wk_type));
7727 			/* NOTREACHED */
7728 		}
7729 	}
7730 	FREE_LOCK(ump);
7731 done:
7732 	/*
7733 	 * Don't throw away this buf, we were partially truncating and
7734 	 * some deps may always remain.
7735 	 */
7736 	if (off) {
7737 		allocbuf(bp, off);
7738 		bp->b_vflags |= BV_SCANNED;
7739 		return (EBUSY);
7740 	}
7741 	bp->b_flags |= B_INVAL | B_NOCACHE;
7742 
7743 	return (0);
7744 }
7745 
7746 /*
7747  * An allocdirect is being canceled due to a truncate.  We must make sure
7748  * the journal entry is released in concert with the blkfree that releases
7749  * the storage.  Completed journal entries must not be released until the
7750  * space is no longer pointed to by the inode or in the bitmap.
7751  */
7752 static void
7753 cancel_allocdirect(adphead, adp, freeblks)
7754 	struct allocdirectlst *adphead;
7755 	struct allocdirect *adp;
7756 	struct freeblks *freeblks;
7757 {
7758 	struct freework *freework;
7759 	struct newblk *newblk;
7760 	struct worklist *wk;
7761 
7762 	TAILQ_REMOVE(adphead, adp, ad_next);
7763 	newblk = (struct newblk *)adp;
7764 	freework = NULL;
7765 	/*
7766 	 * Find the correct freework structure.
7767 	 */
7768 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7769 		if (wk->wk_type != D_FREEWORK)
7770 			continue;
7771 		freework = WK_FREEWORK(wk);
7772 		if (freework->fw_blkno == newblk->nb_newblkno)
7773 			break;
7774 	}
7775 	if (freework == NULL)
7776 		panic("cancel_allocdirect: Freework not found");
7777 	/*
7778 	 * If a newblk exists at all we still have the journal entry that
7779 	 * initiated the allocation so we do not need to journal the free.
7780 	 */
7781 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7782 	/*
7783 	 * If the journal hasn't been written the jnewblk must be passed
7784 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7785 	 * this by linking the journal dependency into the freework to be
7786 	 * freed when freework_freeblock() is called.  If the journal has
7787 	 * been written we can simply reclaim the journal space when the
7788 	 * freeblks work is complete.
7789 	 */
7790 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7791 	    &freeblks->fb_jwork);
7792 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7793 }
7794 
7795 /*
7796  * Cancel a new block allocation.  May be an indirect or direct block.  We
7797  * remove it from various lists and return any journal record that needs to
7798  * be resolved by the caller.
7799  *
7800  * A special consideration is made for indirects which were never pointed
7801  * at on disk and will never be found once this block is released.
7802  */
7803 static struct jnewblk *
7804 cancel_newblk(newblk, wk, wkhd)
7805 	struct newblk *newblk;
7806 	struct worklist *wk;
7807 	struct workhead *wkhd;
7808 {
7809 	struct jnewblk *jnewblk;
7810 
7811 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7812 
7813 	newblk->nb_state |= GOINGAWAY;
7814 	/*
7815 	 * Previously we traversed the completedhd on each indirdep
7816 	 * attached to this newblk to cancel them and gather journal
7817 	 * work.  Since we need only the oldest journal segment and
7818 	 * the lowest point on the tree will always have the oldest
7819 	 * journal segment we are free to release the segments
7820 	 * of any subordinates and may leave the indirdep list to
7821 	 * indirdep_complete() when this newblk is freed.
7822 	 */
7823 	if (newblk->nb_state & ONDEPLIST) {
7824 		newblk->nb_state &= ~ONDEPLIST;
7825 		LIST_REMOVE(newblk, nb_deps);
7826 	}
7827 	if (newblk->nb_state & ONWORKLIST)
7828 		WORKLIST_REMOVE(&newblk->nb_list);
7829 	/*
7830 	 * If the journal entry hasn't been written we save a pointer to
7831 	 * the dependency that frees it until it is written or the
7832 	 * superseding operation completes.
7833 	 */
7834 	jnewblk = newblk->nb_jnewblk;
7835 	if (jnewblk != NULL && wk != NULL) {
7836 		newblk->nb_jnewblk = NULL;
7837 		jnewblk->jn_dep = wk;
7838 	}
7839 	if (!LIST_EMPTY(&newblk->nb_jwork))
7840 		jwork_move(wkhd, &newblk->nb_jwork);
7841 	/*
7842 	 * When truncating we must free the newdirblk early to remove
7843 	 * the pagedep from the hash before returning.
7844 	 */
7845 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7846 		free_newdirblk(WK_NEWDIRBLK(wk));
7847 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7848 		panic("cancel_newblk: extra newdirblk");
7849 
7850 	return (jnewblk);
7851 }
7852 
7853 /*
7854  * Schedule the freefrag associated with a newblk to be released once
7855  * the pointers are written and the previous block is no longer needed.
7856  */
7857 static void
7858 newblk_freefrag(newblk)
7859 	struct newblk *newblk;
7860 {
7861 	struct freefrag *freefrag;
7862 
7863 	if (newblk->nb_freefrag == NULL)
7864 		return;
7865 	freefrag = newblk->nb_freefrag;
7866 	newblk->nb_freefrag = NULL;
7867 	freefrag->ff_state |= COMPLETE;
7868 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7869 		add_to_worklist(&freefrag->ff_list, 0);
7870 }
7871 
7872 /*
7873  * Free a newblk. Generate a new freefrag work request if appropriate.
7874  * This must be called after the inode pointer and any direct block pointers
7875  * are valid or fully removed via truncate or frag extension.
7876  */
7877 static void
7878 free_newblk(newblk)
7879 	struct newblk *newblk;
7880 {
7881 	struct indirdep *indirdep;
7882 	struct worklist *wk;
7883 
7884 	KASSERT(newblk->nb_jnewblk == NULL,
7885 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7886 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7887 	    ("free_newblk: unclaimed newblk"));
7888 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7889 	newblk_freefrag(newblk);
7890 	if (newblk->nb_state & ONDEPLIST)
7891 		LIST_REMOVE(newblk, nb_deps);
7892 	if (newblk->nb_state & ONWORKLIST)
7893 		WORKLIST_REMOVE(&newblk->nb_list);
7894 	LIST_REMOVE(newblk, nb_hash);
7895 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7896 		free_newdirblk(WK_NEWDIRBLK(wk));
7897 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7898 		panic("free_newblk: extra newdirblk");
7899 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7900 		indirdep_complete(indirdep);
7901 	handle_jwork(&newblk->nb_jwork);
7902 	WORKITEM_FREE(newblk, D_NEWBLK);
7903 }
7904 
7905 /*
7906  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7907  */
7908 static void
7909 free_newdirblk(newdirblk)
7910 	struct newdirblk *newdirblk;
7911 {
7912 	struct pagedep *pagedep;
7913 	struct diradd *dap;
7914 	struct worklist *wk;
7915 
7916 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7917 	WORKLIST_REMOVE(&newdirblk->db_list);
7918 	/*
7919 	 * If the pagedep is still linked onto the directory buffer
7920 	 * dependency chain, then some of the entries on the
7921 	 * pd_pendinghd list may not be committed to disk yet. In
7922 	 * this case, we will simply clear the NEWBLOCK flag and
7923 	 * let the pd_pendinghd list be processed when the pagedep
7924 	 * is next written. If the pagedep is no longer on the buffer
7925 	 * dependency chain, then all the entries on the pd_pending
7926 	 * list are committed to disk and we can free them here.
7927 	 */
7928 	pagedep = newdirblk->db_pagedep;
7929 	pagedep->pd_state &= ~NEWBLOCK;
7930 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7931 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7932 			free_diradd(dap, NULL);
7933 		/*
7934 		 * If no dependencies remain, the pagedep will be freed.
7935 		 */
7936 		free_pagedep(pagedep);
7937 	}
7938 	/* Should only ever be one item in the list. */
7939 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7940 		WORKLIST_REMOVE(wk);
7941 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7942 	}
7943 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7944 }
7945 
7946 /*
7947  * Prepare an inode to be freed. The actual free operation is not
7948  * done until the zero'ed inode has been written to disk.
7949  */
7950 void
7951 softdep_freefile(pvp, ino, mode)
7952 	struct vnode *pvp;
7953 	ino_t ino;
7954 	int mode;
7955 {
7956 	struct inode *ip = VTOI(pvp);
7957 	struct inodedep *inodedep;
7958 	struct freefile *freefile;
7959 	struct freeblks *freeblks;
7960 	struct ufsmount *ump;
7961 
7962 	ump = ITOUMP(ip);
7963 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7964 	    ("softdep_freefile called on non-softdep filesystem"));
7965 	/*
7966 	 * This sets up the inode de-allocation dependency.
7967 	 */
7968 	freefile = malloc(sizeof(struct freefile),
7969 		M_FREEFILE, M_SOFTDEP_FLAGS);
7970 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7971 	freefile->fx_mode = mode;
7972 	freefile->fx_oldinum = ino;
7973 	freefile->fx_devvp = ump->um_devvp;
7974 	LIST_INIT(&freefile->fx_jwork);
7975 	UFS_LOCK(ump);
7976 	ump->um_fs->fs_pendinginodes += 1;
7977 	UFS_UNLOCK(ump);
7978 
7979 	/*
7980 	 * If the inodedep does not exist, then the zero'ed inode has
7981 	 * been written to disk. If the allocated inode has never been
7982 	 * written to disk, then the on-disk inode is zero'ed. In either
7983 	 * case we can free the file immediately.  If the journal was
7984 	 * canceled before being written the inode will never make it to
7985 	 * disk and we must send the canceled journal entrys to
7986 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7987 	 * Any blocks waiting on the inode to write can be safely freed
7988 	 * here as it will never been written.
7989 	 */
7990 	ACQUIRE_LOCK(ump);
7991 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7992 	if (inodedep) {
7993 		/*
7994 		 * Clear out freeblks that no longer need to reference
7995 		 * this inode.
7996 		 */
7997 		while ((freeblks =
7998 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7999 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
8000 			    fb_next);
8001 			freeblks->fb_state &= ~ONDEPLIST;
8002 		}
8003 		/*
8004 		 * Remove this inode from the unlinked list.
8005 		 */
8006 		if (inodedep->id_state & UNLINKED) {
8007 			/*
8008 			 * Save the journal work to be freed with the bitmap
8009 			 * before we clear UNLINKED.  Otherwise it can be lost
8010 			 * if the inode block is written.
8011 			 */
8012 			handle_bufwait(inodedep, &freefile->fx_jwork);
8013 			clear_unlinked_inodedep(inodedep);
8014 			/*
8015 			 * Re-acquire inodedep as we've dropped the
8016 			 * per-filesystem lock in clear_unlinked_inodedep().
8017 			 */
8018 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
8019 		}
8020 	}
8021 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
8022 		FREE_LOCK(ump);
8023 		handle_workitem_freefile(freefile);
8024 		return;
8025 	}
8026 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
8027 		inodedep->id_state |= GOINGAWAY;
8028 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
8029 	FREE_LOCK(ump);
8030 	if (ip->i_number == ino)
8031 		UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
8032 }
8033 
8034 /*
8035  * Check to see if an inode has never been written to disk. If
8036  * so free the inodedep and return success, otherwise return failure.
8037  *
8038  * If we still have a bitmap dependency, then the inode has never
8039  * been written to disk. Drop the dependency as it is no longer
8040  * necessary since the inode is being deallocated. We set the
8041  * ALLCOMPLETE flags since the bitmap now properly shows that the
8042  * inode is not allocated. Even if the inode is actively being
8043  * written, it has been rolled back to its zero'ed state, so we
8044  * are ensured that a zero inode is what is on the disk. For short
8045  * lived files, this change will usually result in removing all the
8046  * dependencies from the inode so that it can be freed immediately.
8047  */
8048 static int
8049 check_inode_unwritten(inodedep)
8050 	struct inodedep *inodedep;
8051 {
8052 
8053 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8054 
8055 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
8056 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
8057 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
8058 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
8059 	    !LIST_EMPTY(&inodedep->id_inowait) ||
8060 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
8061 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
8062 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
8063 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
8064 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
8065 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
8066 	    inodedep->id_mkdiradd != NULL ||
8067 	    inodedep->id_nlinkdelta != 0)
8068 		return (0);
8069 	/*
8070 	 * Another process might be in initiate_write_inodeblock_ufs[12]
8071 	 * trying to allocate memory without holding "Softdep Lock".
8072 	 */
8073 	if ((inodedep->id_state & IOSTARTED) != 0 &&
8074 	    inodedep->id_savedino1 == NULL)
8075 		return (0);
8076 
8077 	if (inodedep->id_state & ONDEPLIST)
8078 		LIST_REMOVE(inodedep, id_deps);
8079 	inodedep->id_state &= ~ONDEPLIST;
8080 	inodedep->id_state |= ALLCOMPLETE;
8081 	inodedep->id_bmsafemap = NULL;
8082 	if (inodedep->id_state & ONWORKLIST)
8083 		WORKLIST_REMOVE(&inodedep->id_list);
8084 	if (inodedep->id_savedino1 != NULL) {
8085 		free(inodedep->id_savedino1, M_SAVEDINO);
8086 		inodedep->id_savedino1 = NULL;
8087 	}
8088 	if (free_inodedep(inodedep) == 0)
8089 		panic("check_inode_unwritten: busy inode");
8090 	return (1);
8091 }
8092 
8093 static int
8094 check_inodedep_free(inodedep)
8095 	struct inodedep *inodedep;
8096 {
8097 
8098 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8099 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
8100 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
8101 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
8102 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
8103 	    !LIST_EMPTY(&inodedep->id_inowait) ||
8104 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
8105 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
8106 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
8107 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
8108 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
8109 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
8110 	    inodedep->id_mkdiradd != NULL ||
8111 	    inodedep->id_nlinkdelta != 0 ||
8112 	    inodedep->id_savedino1 != NULL)
8113 		return (0);
8114 	return (1);
8115 }
8116 
8117 /*
8118  * Try to free an inodedep structure. Return 1 if it could be freed.
8119  */
8120 static int
8121 free_inodedep(inodedep)
8122 	struct inodedep *inodedep;
8123 {
8124 
8125 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8126 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
8127 	    !check_inodedep_free(inodedep))
8128 		return (0);
8129 	if (inodedep->id_state & ONDEPLIST)
8130 		LIST_REMOVE(inodedep, id_deps);
8131 	LIST_REMOVE(inodedep, id_hash);
8132 	WORKITEM_FREE(inodedep, D_INODEDEP);
8133 	return (1);
8134 }
8135 
8136 /*
8137  * Free the block referenced by a freework structure.  The parent freeblks
8138  * structure is released and completed when the final cg bitmap reaches
8139  * the disk.  This routine may be freeing a jnewblk which never made it to
8140  * disk in which case we do not have to wait as the operation is undone
8141  * in memory immediately.
8142  */
8143 static void
8144 freework_freeblock(freework, key)
8145 	struct freework *freework;
8146 	u_long key;
8147 {
8148 	struct freeblks *freeblks;
8149 	struct jnewblk *jnewblk;
8150 	struct ufsmount *ump;
8151 	struct workhead wkhd;
8152 	struct fs *fs;
8153 	int bsize;
8154 	int needj;
8155 
8156 	ump = VFSTOUFS(freework->fw_list.wk_mp);
8157 	LOCK_OWNED(ump);
8158 	/*
8159 	 * Handle partial truncate separately.
8160 	 */
8161 	if (freework->fw_indir) {
8162 		complete_trunc_indir(freework);
8163 		return;
8164 	}
8165 	freeblks = freework->fw_freeblks;
8166 	fs = ump->um_fs;
8167 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
8168 	bsize = lfragtosize(fs, freework->fw_frags);
8169 	LIST_INIT(&wkhd);
8170 	/*
8171 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
8172 	 * on the indirblk hashtable and prevents premature freeing.
8173 	 */
8174 	freework->fw_state |= DEPCOMPLETE;
8175 	/*
8176 	 * SUJ needs to wait for the segment referencing freed indirect
8177 	 * blocks to expire so that we know the checker will not confuse
8178 	 * a re-allocated indirect block with its old contents.
8179 	 */
8180 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
8181 		indirblk_insert(freework);
8182 	/*
8183 	 * If we are canceling an existing jnewblk pass it to the free
8184 	 * routine, otherwise pass the freeblk which will ultimately
8185 	 * release the freeblks.  If we're not journaling, we can just
8186 	 * free the freeblks immediately.
8187 	 */
8188 	jnewblk = freework->fw_jnewblk;
8189 	if (jnewblk != NULL) {
8190 		cancel_jnewblk(jnewblk, &wkhd);
8191 		needj = 0;
8192 	} else if (needj) {
8193 		freework->fw_state |= DELAYEDFREE;
8194 		freeblks->fb_cgwait++;
8195 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
8196 	}
8197 	FREE_LOCK(ump);
8198 	freeblks_free(ump, freeblks, btodb(bsize));
8199 	CTR4(KTR_SUJ,
8200 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
8201 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
8202 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
8203 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
8204 	ACQUIRE_LOCK(ump);
8205 	/*
8206 	 * The jnewblk will be discarded and the bits in the map never
8207 	 * made it to disk.  We can immediately free the freeblk.
8208 	 */
8209 	if (needj == 0)
8210 		handle_written_freework(freework);
8211 }
8212 
8213 /*
8214  * We enqueue freework items that need processing back on the freeblks and
8215  * add the freeblks to the worklist.  This makes it easier to find all work
8216  * required to flush a truncation in process_truncates().
8217  */
8218 static void
8219 freework_enqueue(freework)
8220 	struct freework *freework;
8221 {
8222 	struct freeblks *freeblks;
8223 
8224 	freeblks = freework->fw_freeblks;
8225 	if ((freework->fw_state & INPROGRESS) == 0)
8226 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
8227 	if ((freeblks->fb_state &
8228 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
8229 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
8230 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8231 }
8232 
8233 /*
8234  * Start, continue, or finish the process of freeing an indirect block tree.
8235  * The free operation may be paused at any point with fw_off containing the
8236  * offset to restart from.  This enables us to implement some flow control
8237  * for large truncates which may fan out and generate a huge number of
8238  * dependencies.
8239  */
8240 static void
8241 handle_workitem_indirblk(freework)
8242 	struct freework *freework;
8243 {
8244 	struct freeblks *freeblks;
8245 	struct ufsmount *ump;
8246 	struct fs *fs;
8247 
8248 	freeblks = freework->fw_freeblks;
8249 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8250 	fs = ump->um_fs;
8251 	if (freework->fw_state & DEPCOMPLETE) {
8252 		handle_written_freework(freework);
8253 		return;
8254 	}
8255 	if (freework->fw_off == NINDIR(fs)) {
8256 		freework_freeblock(freework, SINGLETON_KEY);
8257 		return;
8258 	}
8259 	freework->fw_state |= INPROGRESS;
8260 	FREE_LOCK(ump);
8261 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
8262 	    freework->fw_lbn);
8263 	ACQUIRE_LOCK(ump);
8264 }
8265 
8266 /*
8267  * Called when a freework structure attached to a cg buf is written.  The
8268  * ref on either the parent or the freeblks structure is released and
8269  * the freeblks is added back to the worklist if there is more work to do.
8270  */
8271 static void
8272 handle_written_freework(freework)
8273 	struct freework *freework;
8274 {
8275 	struct freeblks *freeblks;
8276 	struct freework *parent;
8277 
8278 	freeblks = freework->fw_freeblks;
8279 	parent = freework->fw_parent;
8280 	if (freework->fw_state & DELAYEDFREE)
8281 		freeblks->fb_cgwait--;
8282 	freework->fw_state |= COMPLETE;
8283 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
8284 		WORKITEM_FREE(freework, D_FREEWORK);
8285 	if (parent) {
8286 		if (--parent->fw_ref == 0)
8287 			freework_enqueue(parent);
8288 		return;
8289 	}
8290 	if (--freeblks->fb_ref != 0)
8291 		return;
8292 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
8293 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
8294 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8295 }
8296 
8297 /*
8298  * This workitem routine performs the block de-allocation.
8299  * The workitem is added to the pending list after the updated
8300  * inode block has been written to disk.  As mentioned above,
8301  * checks regarding the number of blocks de-allocated (compared
8302  * to the number of blocks allocated for the file) are also
8303  * performed in this function.
8304  */
8305 static int
8306 handle_workitem_freeblocks(freeblks, flags)
8307 	struct freeblks *freeblks;
8308 	int flags;
8309 {
8310 	struct freework *freework;
8311 	struct newblk *newblk;
8312 	struct allocindir *aip;
8313 	struct ufsmount *ump;
8314 	struct worklist *wk;
8315 	u_long key;
8316 
8317 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
8318 	    ("handle_workitem_freeblocks: Journal entries not written."));
8319 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8320 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8321 	ACQUIRE_LOCK(ump);
8322 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
8323 		WORKLIST_REMOVE(wk);
8324 		switch (wk->wk_type) {
8325 		case D_DIRREM:
8326 			wk->wk_state |= COMPLETE;
8327 			add_to_worklist(wk, 0);
8328 			continue;
8329 
8330 		case D_ALLOCDIRECT:
8331 			free_newblk(WK_NEWBLK(wk));
8332 			continue;
8333 
8334 		case D_ALLOCINDIR:
8335 			aip = WK_ALLOCINDIR(wk);
8336 			freework = NULL;
8337 			if (aip->ai_state & DELAYEDFREE) {
8338 				FREE_LOCK(ump);
8339 				freework = newfreework(ump, freeblks, NULL,
8340 				    aip->ai_lbn, aip->ai_newblkno,
8341 				    ump->um_fs->fs_frag, 0, 0);
8342 				ACQUIRE_LOCK(ump);
8343 			}
8344 			newblk = WK_NEWBLK(wk);
8345 			if (newblk->nb_jnewblk) {
8346 				freework->fw_jnewblk = newblk->nb_jnewblk;
8347 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
8348 				newblk->nb_jnewblk = NULL;
8349 			}
8350 			free_newblk(newblk);
8351 			continue;
8352 
8353 		case D_FREEWORK:
8354 			freework = WK_FREEWORK(wk);
8355 			if (freework->fw_lbn <= -UFS_NDADDR)
8356 				handle_workitem_indirblk(freework);
8357 			else
8358 				freework_freeblock(freework, key);
8359 			continue;
8360 		default:
8361 			panic("handle_workitem_freeblocks: Unknown type %s",
8362 			    TYPENAME(wk->wk_type));
8363 		}
8364 	}
8365 	if (freeblks->fb_ref != 0) {
8366 		freeblks->fb_state &= ~INPROGRESS;
8367 		wake_worklist(&freeblks->fb_list);
8368 		freeblks = NULL;
8369 	}
8370 	FREE_LOCK(ump);
8371 	ffs_blkrelease_finish(ump, key);
8372 	if (freeblks)
8373 		return handle_complete_freeblocks(freeblks, flags);
8374 	return (0);
8375 }
8376 
8377 /*
8378  * Handle completion of block free via truncate.  This allows fs_pending
8379  * to track the actual free block count more closely than if we only updated
8380  * it at the end.  We must be careful to handle cases where the block count
8381  * on free was incorrect.
8382  */
8383 static void
8384 freeblks_free(ump, freeblks, blocks)
8385 	struct ufsmount *ump;
8386 	struct freeblks *freeblks;
8387 	int blocks;
8388 {
8389 	struct fs *fs;
8390 	ufs2_daddr_t remain;
8391 
8392 	UFS_LOCK(ump);
8393 	remain = -freeblks->fb_chkcnt;
8394 	freeblks->fb_chkcnt += blocks;
8395 	if (remain > 0) {
8396 		if (remain < blocks)
8397 			blocks = remain;
8398 		fs = ump->um_fs;
8399 		fs->fs_pendingblocks -= blocks;
8400 	}
8401 	UFS_UNLOCK(ump);
8402 }
8403 
8404 /*
8405  * Once all of the freework workitems are complete we can retire the
8406  * freeblocks dependency and any journal work awaiting completion.  This
8407  * can not be called until all other dependencies are stable on disk.
8408  */
8409 static int
8410 handle_complete_freeblocks(freeblks, flags)
8411 	struct freeblks *freeblks;
8412 	int flags;
8413 {
8414 	struct inodedep *inodedep;
8415 	struct inode *ip;
8416 	struct vnode *vp;
8417 	struct fs *fs;
8418 	struct ufsmount *ump;
8419 	ufs2_daddr_t spare;
8420 
8421 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8422 	fs = ump->um_fs;
8423 	flags = LK_EXCLUSIVE | flags;
8424 	spare = freeblks->fb_chkcnt;
8425 
8426 	/*
8427 	 * If we did not release the expected number of blocks we may have
8428 	 * to adjust the inode block count here.  Only do so if it wasn't
8429 	 * a truncation to zero and the modrev still matches.
8430 	 */
8431 	if (spare && freeblks->fb_len != 0) {
8432 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8433 		    flags, &vp, FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP) != 0)
8434 			return (EBUSY);
8435 		ip = VTOI(vp);
8436 		if (ip->i_mode == 0) {
8437 			vgone(vp);
8438 		} else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8439 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8440 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8441 			/*
8442 			 * We must wait so this happens before the
8443 			 * journal is reclaimed.
8444 			 */
8445 			ffs_update(vp, 1);
8446 		}
8447 		vput(vp);
8448 	}
8449 	if (spare < 0) {
8450 		UFS_LOCK(ump);
8451 		fs->fs_pendingblocks += spare;
8452 		UFS_UNLOCK(ump);
8453 	}
8454 #ifdef QUOTA
8455 	/* Handle spare. */
8456 	if (spare)
8457 		quotaadj(freeblks->fb_quota, ump, -spare);
8458 	quotarele(freeblks->fb_quota);
8459 #endif
8460 	ACQUIRE_LOCK(ump);
8461 	if (freeblks->fb_state & ONDEPLIST) {
8462 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8463 		    0, &inodedep);
8464 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8465 		freeblks->fb_state &= ~ONDEPLIST;
8466 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8467 			free_inodedep(inodedep);
8468 	}
8469 	/*
8470 	 * All of the freeblock deps must be complete prior to this call
8471 	 * so it's now safe to complete earlier outstanding journal entries.
8472 	 */
8473 	handle_jwork(&freeblks->fb_jwork);
8474 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8475 	FREE_LOCK(ump);
8476 	return (0);
8477 }
8478 
8479 /*
8480  * Release blocks associated with the freeblks and stored in the indirect
8481  * block dbn. If level is greater than SINGLE, the block is an indirect block
8482  * and recursive calls to indirtrunc must be used to cleanse other indirect
8483  * blocks.
8484  *
8485  * This handles partial and complete truncation of blocks.  Partial is noted
8486  * with goingaway == 0.  In this case the freework is completed after the
8487  * zero'd indirects are written to disk.  For full truncation the freework
8488  * is completed after the block is freed.
8489  */
8490 static void
8491 indir_trunc(freework, dbn, lbn)
8492 	struct freework *freework;
8493 	ufs2_daddr_t dbn;
8494 	ufs_lbn_t lbn;
8495 {
8496 	struct freework *nfreework;
8497 	struct workhead wkhd;
8498 	struct freeblks *freeblks;
8499 	struct buf *bp;
8500 	struct fs *fs;
8501 	struct indirdep *indirdep;
8502 	struct mount *mp;
8503 	struct ufsmount *ump;
8504 	ufs1_daddr_t *bap1;
8505 	ufs2_daddr_t nb, nnb, *bap2;
8506 	ufs_lbn_t lbnadd, nlbn;
8507 	u_long key;
8508 	int nblocks, ufs1fmt, freedblocks;
8509 	int goingaway, freedeps, needj, level, cnt, i, error;
8510 
8511 	freeblks = freework->fw_freeblks;
8512 	mp = freeblks->fb_list.wk_mp;
8513 	ump = VFSTOUFS(mp);
8514 	fs = ump->um_fs;
8515 	/*
8516 	 * Get buffer of block pointers to be freed.  There are three cases:
8517 	 *
8518 	 * 1) Partial truncate caches the indirdep pointer in the freework
8519 	 *    which provides us a back copy to the save bp which holds the
8520 	 *    pointers we want to clear.  When this completes the zero
8521 	 *    pointers are written to the real copy.
8522 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8523 	 *    eliminated the real copy and placed the indirdep on the saved
8524 	 *    copy.  The indirdep and buf are discarded when this completes.
8525 	 * 3) The indirect was not in memory, we read a copy off of the disk
8526 	 *    using the devvp and drop and invalidate the buffer when we're
8527 	 *    done.
8528 	 */
8529 	goingaway = 1;
8530 	indirdep = NULL;
8531 	if (freework->fw_indir != NULL) {
8532 		goingaway = 0;
8533 		indirdep = freework->fw_indir;
8534 		bp = indirdep->ir_savebp;
8535 		if (bp == NULL || bp->b_blkno != dbn)
8536 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8537 			    bp, (intmax_t)dbn);
8538 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8539 		/*
8540 		 * The lock prevents the buf dep list from changing and
8541 	 	 * indirects on devvp should only ever have one dependency.
8542 		 */
8543 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8544 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8545 			panic("indir_trunc: Bad indirdep %p from buf %p",
8546 			    indirdep, bp);
8547 	} else {
8548 		error = ffs_breadz(ump, freeblks->fb_devvp, dbn, dbn,
8549 		    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
8550 		if (error)
8551 			return;
8552 	}
8553 	ACQUIRE_LOCK(ump);
8554 	/* Protects against a race with complete_trunc_indir(). */
8555 	freework->fw_state &= ~INPROGRESS;
8556 	/*
8557 	 * If we have an indirdep we need to enforce the truncation order
8558 	 * and discard it when it is complete.
8559 	 */
8560 	if (indirdep) {
8561 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8562 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8563 			/*
8564 			 * Add the complete truncate to the list on the
8565 			 * indirdep to enforce in-order processing.
8566 			 */
8567 			if (freework->fw_indir == NULL)
8568 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8569 				    freework, fw_next);
8570 			FREE_LOCK(ump);
8571 			return;
8572 		}
8573 		/*
8574 		 * If we're goingaway, free the indirdep.  Otherwise it will
8575 		 * linger until the write completes.
8576 		 */
8577 		if (goingaway) {
8578 			KASSERT(indirdep->ir_savebp == bp,
8579 			    ("indir_trunc: losing ir_savebp %p",
8580 			    indirdep->ir_savebp));
8581 			indirdep->ir_savebp = NULL;
8582 			free_indirdep(indirdep);
8583 		}
8584 	}
8585 	FREE_LOCK(ump);
8586 	/* Initialize pointers depending on block size. */
8587 	if (ump->um_fstype == UFS1) {
8588 		bap1 = (ufs1_daddr_t *)bp->b_data;
8589 		nb = bap1[freework->fw_off];
8590 		ufs1fmt = 1;
8591 		bap2 = NULL;
8592 	} else {
8593 		bap2 = (ufs2_daddr_t *)bp->b_data;
8594 		nb = bap2[freework->fw_off];
8595 		ufs1fmt = 0;
8596 		bap1 = NULL;
8597 	}
8598 	level = lbn_level(lbn);
8599 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8600 	lbnadd = lbn_offset(fs, level);
8601 	nblocks = btodb(fs->fs_bsize);
8602 	nfreework = freework;
8603 	freedeps = 0;
8604 	cnt = 0;
8605 	/*
8606 	 * Reclaim blocks.  Traverses into nested indirect levels and
8607 	 * arranges for the current level to be freed when subordinates
8608 	 * are free when journaling.
8609 	 */
8610 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8611 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8612 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8613 		    fs->fs_bsize) != 0)
8614 			nb = 0;
8615 		if (i != NINDIR(fs) - 1) {
8616 			if (ufs1fmt)
8617 				nnb = bap1[i+1];
8618 			else
8619 				nnb = bap2[i+1];
8620 		} else
8621 			nnb = 0;
8622 		if (nb == 0)
8623 			continue;
8624 		cnt++;
8625 		if (level != 0) {
8626 			nlbn = (lbn + 1) - (i * lbnadd);
8627 			if (needj != 0) {
8628 				nfreework = newfreework(ump, freeblks, freework,
8629 				    nlbn, nb, fs->fs_frag, 0, 0);
8630 				freedeps++;
8631 			}
8632 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8633 		} else {
8634 			struct freedep *freedep;
8635 
8636 			/*
8637 			 * Attempt to aggregate freedep dependencies for
8638 			 * all blocks being released to the same CG.
8639 			 */
8640 			LIST_INIT(&wkhd);
8641 			if (needj != 0 &&
8642 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8643 				freedep = newfreedep(freework);
8644 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8645 				    &freedep->fd_list);
8646 				freedeps++;
8647 			}
8648 			CTR3(KTR_SUJ,
8649 			    "indir_trunc: ino %jd blkno %jd size %d",
8650 			    freeblks->fb_inum, nb, fs->fs_bsize);
8651 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8652 			    fs->fs_bsize, freeblks->fb_inum,
8653 			    freeblks->fb_vtype, &wkhd, key);
8654 		}
8655 	}
8656 	ffs_blkrelease_finish(ump, key);
8657 	if (goingaway) {
8658 		bp->b_flags |= B_INVAL | B_NOCACHE;
8659 		brelse(bp);
8660 	}
8661 	freedblocks = 0;
8662 	if (level == 0)
8663 		freedblocks = (nblocks * cnt);
8664 	if (needj == 0)
8665 		freedblocks += nblocks;
8666 	freeblks_free(ump, freeblks, freedblocks);
8667 	/*
8668 	 * If we are journaling set up the ref counts and offset so this
8669 	 * indirect can be completed when its children are free.
8670 	 */
8671 	if (needj) {
8672 		ACQUIRE_LOCK(ump);
8673 		freework->fw_off = i;
8674 		freework->fw_ref += freedeps;
8675 		freework->fw_ref -= NINDIR(fs) + 1;
8676 		if (level == 0)
8677 			freeblks->fb_cgwait += freedeps;
8678 		if (freework->fw_ref == 0)
8679 			freework_freeblock(freework, SINGLETON_KEY);
8680 		FREE_LOCK(ump);
8681 		return;
8682 	}
8683 	/*
8684 	 * If we're not journaling we can free the indirect now.
8685 	 */
8686 	dbn = dbtofsb(fs, dbn);
8687 	CTR3(KTR_SUJ,
8688 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8689 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8690 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8691 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8692 	/* Non SUJ softdep does single-threaded truncations. */
8693 	if (freework->fw_blkno == dbn) {
8694 		freework->fw_state |= ALLCOMPLETE;
8695 		ACQUIRE_LOCK(ump);
8696 		handle_written_freework(freework);
8697 		FREE_LOCK(ump);
8698 	}
8699 	return;
8700 }
8701 
8702 /*
8703  * Cancel an allocindir when it is removed via truncation.  When bp is not
8704  * NULL the indirect never appeared on disk and is scheduled to be freed
8705  * independently of the indir so we can more easily track journal work.
8706  */
8707 static void
8708 cancel_allocindir(aip, bp, freeblks, trunc)
8709 	struct allocindir *aip;
8710 	struct buf *bp;
8711 	struct freeblks *freeblks;
8712 	int trunc;
8713 {
8714 	struct indirdep *indirdep;
8715 	struct freefrag *freefrag;
8716 	struct newblk *newblk;
8717 
8718 	newblk = (struct newblk *)aip;
8719 	LIST_REMOVE(aip, ai_next);
8720 	/*
8721 	 * We must eliminate the pointer in bp if it must be freed on its
8722 	 * own due to partial truncate or pending journal work.
8723 	 */
8724 	if (bp && (trunc || newblk->nb_jnewblk)) {
8725 		/*
8726 		 * Clear the pointer and mark the aip to be freed
8727 		 * directly if it never existed on disk.
8728 		 */
8729 		aip->ai_state |= DELAYEDFREE;
8730 		indirdep = aip->ai_indirdep;
8731 		if (indirdep->ir_state & UFS1FMT)
8732 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8733 		else
8734 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8735 	}
8736 	/*
8737 	 * When truncating the previous pointer will be freed via
8738 	 * savedbp.  Eliminate the freefrag which would dup free.
8739 	 */
8740 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8741 		newblk->nb_freefrag = NULL;
8742 		if (freefrag->ff_jdep)
8743 			cancel_jfreefrag(
8744 			    WK_JFREEFRAG(freefrag->ff_jdep));
8745 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8746 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8747 	}
8748 	/*
8749 	 * If the journal hasn't been written the jnewblk must be passed
8750 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8751 	 * this by leaving the journal dependency on the newblk to be freed
8752 	 * when a freework is created in handle_workitem_freeblocks().
8753 	 */
8754 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8755 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8756 }
8757 
8758 /*
8759  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8760  * in to a newdirblk so any subsequent additions are tracked properly.  The
8761  * caller is responsible for adding the mkdir1 dependency to the journal
8762  * and updating id_mkdiradd.  This function returns with the per-filesystem
8763  * lock held.
8764  */
8765 static struct mkdir *
8766 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8767 	struct diradd *dap;
8768 	ino_t newinum;
8769 	ino_t dinum;
8770 	struct buf *newdirbp;
8771 	struct mkdir **mkdirp;
8772 {
8773 	struct newblk *newblk;
8774 	struct pagedep *pagedep;
8775 	struct inodedep *inodedep;
8776 	struct newdirblk *newdirblk;
8777 	struct mkdir *mkdir1, *mkdir2;
8778 	struct worklist *wk;
8779 	struct jaddref *jaddref;
8780 	struct ufsmount *ump;
8781 	struct mount *mp;
8782 
8783 	mp = dap->da_list.wk_mp;
8784 	ump = VFSTOUFS(mp);
8785 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8786 	    M_SOFTDEP_FLAGS);
8787 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8788 	LIST_INIT(&newdirblk->db_mkdir);
8789 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8790 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8791 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8792 	mkdir1->md_diradd = dap;
8793 	mkdir1->md_jaddref = NULL;
8794 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8795 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8796 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8797 	mkdir2->md_diradd = dap;
8798 	mkdir2->md_jaddref = NULL;
8799 	if (MOUNTEDSUJ(mp) == 0) {
8800 		mkdir1->md_state |= DEPCOMPLETE;
8801 		mkdir2->md_state |= DEPCOMPLETE;
8802 	}
8803 	/*
8804 	 * Dependency on "." and ".." being written to disk.
8805 	 */
8806 	mkdir1->md_buf = newdirbp;
8807 	ACQUIRE_LOCK(VFSTOUFS(mp));
8808 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8809 	/*
8810 	 * We must link the pagedep, allocdirect, and newdirblk for
8811 	 * the initial file page so the pointer to the new directory
8812 	 * is not written until the directory contents are live and
8813 	 * any subsequent additions are not marked live until the
8814 	 * block is reachable via the inode.
8815 	 */
8816 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8817 		panic("setup_newdir: lost pagedep");
8818 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8819 		if (wk->wk_type == D_ALLOCDIRECT)
8820 			break;
8821 	if (wk == NULL)
8822 		panic("setup_newdir: lost allocdirect");
8823 	if (pagedep->pd_state & NEWBLOCK)
8824 		panic("setup_newdir: NEWBLOCK already set");
8825 	newblk = WK_NEWBLK(wk);
8826 	pagedep->pd_state |= NEWBLOCK;
8827 	pagedep->pd_newdirblk = newdirblk;
8828 	newdirblk->db_pagedep = pagedep;
8829 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8830 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8831 	/*
8832 	 * Look up the inodedep for the parent directory so that we
8833 	 * can link mkdir2 into the pending dotdot jaddref or
8834 	 * the inode write if there is none.  If the inode is
8835 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8836 	 * been satisfied and mkdir2 can be freed.
8837 	 */
8838 	inodedep_lookup(mp, dinum, 0, &inodedep);
8839 	if (MOUNTEDSUJ(mp)) {
8840 		if (inodedep == NULL)
8841 			panic("setup_newdir: Lost parent.");
8842 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8843 		    inoreflst);
8844 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8845 		    (jaddref->ja_state & MKDIR_PARENT),
8846 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8847 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8848 		mkdir2->md_jaddref = jaddref;
8849 		jaddref->ja_mkdir = mkdir2;
8850 	} else if (inodedep == NULL ||
8851 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8852 		dap->da_state &= ~MKDIR_PARENT;
8853 		WORKITEM_FREE(mkdir2, D_MKDIR);
8854 		mkdir2 = NULL;
8855 	} else {
8856 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8857 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8858 	}
8859 	*mkdirp = mkdir2;
8860 
8861 	return (mkdir1);
8862 }
8863 
8864 /*
8865  * Directory entry addition dependencies.
8866  *
8867  * When adding a new directory entry, the inode (with its incremented link
8868  * count) must be written to disk before the directory entry's pointer to it.
8869  * Also, if the inode is newly allocated, the corresponding freemap must be
8870  * updated (on disk) before the directory entry's pointer. These requirements
8871  * are met via undo/redo on the directory entry's pointer, which consists
8872  * simply of the inode number.
8873  *
8874  * As directory entries are added and deleted, the free space within a
8875  * directory block can become fragmented.  The ufs filesystem will compact
8876  * a fragmented directory block to make space for a new entry. When this
8877  * occurs, the offsets of previously added entries change. Any "diradd"
8878  * dependency structures corresponding to these entries must be updated with
8879  * the new offsets.
8880  */
8881 
8882 /*
8883  * This routine is called after the in-memory inode's link
8884  * count has been incremented, but before the directory entry's
8885  * pointer to the inode has been set.
8886  */
8887 int
8888 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8889 	struct buf *bp;		/* buffer containing directory block */
8890 	struct inode *dp;	/* inode for directory */
8891 	off_t diroffset;	/* offset of new entry in directory */
8892 	ino_t newinum;		/* inode referenced by new directory entry */
8893 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8894 	int isnewblk;		/* entry is in a newly allocated block */
8895 {
8896 	int offset;		/* offset of new entry within directory block */
8897 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8898 	struct fs *fs;
8899 	struct diradd *dap;
8900 	struct newblk *newblk;
8901 	struct pagedep *pagedep;
8902 	struct inodedep *inodedep;
8903 	struct newdirblk *newdirblk;
8904 	struct mkdir *mkdir1, *mkdir2;
8905 	struct jaddref *jaddref;
8906 	struct ufsmount *ump;
8907 	struct mount *mp;
8908 	int isindir;
8909 
8910 	mp = ITOVFS(dp);
8911 	ump = VFSTOUFS(mp);
8912 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8913 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8914 	/*
8915 	 * Whiteouts have no dependencies.
8916 	 */
8917 	if (newinum == UFS_WINO) {
8918 		if (newdirbp != NULL)
8919 			bdwrite(newdirbp);
8920 		return (0);
8921 	}
8922 	jaddref = NULL;
8923 	mkdir1 = mkdir2 = NULL;
8924 	fs = ump->um_fs;
8925 	lbn = lblkno(fs, diroffset);
8926 	offset = blkoff(fs, diroffset);
8927 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8928 		M_SOFTDEP_FLAGS|M_ZERO);
8929 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8930 	dap->da_offset = offset;
8931 	dap->da_newinum = newinum;
8932 	dap->da_state = ATTACHED;
8933 	LIST_INIT(&dap->da_jwork);
8934 	isindir = bp->b_lblkno >= UFS_NDADDR;
8935 	newdirblk = NULL;
8936 	if (isnewblk &&
8937 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8938 		newdirblk = malloc(sizeof(struct newdirblk),
8939 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8940 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8941 		LIST_INIT(&newdirblk->db_mkdir);
8942 	}
8943 	/*
8944 	 * If we're creating a new directory setup the dependencies and set
8945 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8946 	 * we can move on.
8947 	 */
8948 	if (newdirbp == NULL) {
8949 		dap->da_state |= DEPCOMPLETE;
8950 		ACQUIRE_LOCK(ump);
8951 	} else {
8952 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8953 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8954 		    &mkdir2);
8955 	}
8956 	/*
8957 	 * Link into parent directory pagedep to await its being written.
8958 	 */
8959 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8960 #ifdef INVARIANTS
8961 	if (diradd_lookup(pagedep, offset) != NULL)
8962 		panic("softdep_setup_directory_add: %p already at off %d\n",
8963 		    diradd_lookup(pagedep, offset), offset);
8964 #endif
8965 	dap->da_pagedep = pagedep;
8966 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8967 	    da_pdlist);
8968 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8969 	/*
8970 	 * If we're journaling, link the diradd into the jaddref so it
8971 	 * may be completed after the journal entry is written.  Otherwise,
8972 	 * link the diradd into its inodedep.  If the inode is not yet
8973 	 * written place it on the bufwait list, otherwise do the post-inode
8974 	 * write processing to put it on the id_pendinghd list.
8975 	 */
8976 	if (MOUNTEDSUJ(mp)) {
8977 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8978 		    inoreflst);
8979 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8980 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8981 		jaddref->ja_diroff = diroffset;
8982 		jaddref->ja_diradd = dap;
8983 		add_to_journal(&jaddref->ja_list);
8984 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8985 		diradd_inode_written(dap, inodedep);
8986 	else
8987 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8988 	/*
8989 	 * Add the journal entries for . and .. links now that the primary
8990 	 * link is written.
8991 	 */
8992 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8993 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8994 		    inoreflst, if_deps);
8995 		KASSERT(jaddref != NULL &&
8996 		    jaddref->ja_ino == jaddref->ja_parent &&
8997 		    (jaddref->ja_state & MKDIR_BODY),
8998 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8999 		    jaddref));
9000 		mkdir1->md_jaddref = jaddref;
9001 		jaddref->ja_mkdir = mkdir1;
9002 		/*
9003 		 * It is important that the dotdot journal entry
9004 		 * is added prior to the dot entry since dot writes
9005 		 * both the dot and dotdot links.  These both must
9006 		 * be added after the primary link for the journal
9007 		 * to remain consistent.
9008 		 */
9009 		add_to_journal(&mkdir2->md_jaddref->ja_list);
9010 		add_to_journal(&jaddref->ja_list);
9011 	}
9012 	/*
9013 	 * If we are adding a new directory remember this diradd so that if
9014 	 * we rename it we can keep the dot and dotdot dependencies.  If
9015 	 * we are adding a new name for an inode that has a mkdiradd we
9016 	 * must be in rename and we have to move the dot and dotdot
9017 	 * dependencies to this new name.  The old name is being orphaned
9018 	 * soon.
9019 	 */
9020 	if (mkdir1 != NULL) {
9021 		if (inodedep->id_mkdiradd != NULL)
9022 			panic("softdep_setup_directory_add: Existing mkdir");
9023 		inodedep->id_mkdiradd = dap;
9024 	} else if (inodedep->id_mkdiradd)
9025 		merge_diradd(inodedep, dap);
9026 	if (newdirblk != NULL) {
9027 		/*
9028 		 * There is nothing to do if we are already tracking
9029 		 * this block.
9030 		 */
9031 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
9032 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
9033 			FREE_LOCK(ump);
9034 			return (0);
9035 		}
9036 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
9037 		    == 0)
9038 			panic("softdep_setup_directory_add: lost entry");
9039 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
9040 		pagedep->pd_state |= NEWBLOCK;
9041 		pagedep->pd_newdirblk = newdirblk;
9042 		newdirblk->db_pagedep = pagedep;
9043 		FREE_LOCK(ump);
9044 		/*
9045 		 * If we extended into an indirect signal direnter to sync.
9046 		 */
9047 		if (isindir)
9048 			return (1);
9049 		return (0);
9050 	}
9051 	FREE_LOCK(ump);
9052 	return (0);
9053 }
9054 
9055 /*
9056  * This procedure is called to change the offset of a directory
9057  * entry when compacting a directory block which must be owned
9058  * exclusively by the caller. Note that the actual entry movement
9059  * must be done in this procedure to ensure that no I/O completions
9060  * occur while the move is in progress.
9061  */
9062 void
9063 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
9064 	struct buf *bp;		/* Buffer holding directory block. */
9065 	struct inode *dp;	/* inode for directory */
9066 	caddr_t base;		/* address of dp->i_offset */
9067 	caddr_t oldloc;		/* address of old directory location */
9068 	caddr_t newloc;		/* address of new directory location */
9069 	int entrysize;		/* size of directory entry */
9070 {
9071 	int offset, oldoffset, newoffset;
9072 	struct pagedep *pagedep;
9073 	struct jmvref *jmvref;
9074 	struct diradd *dap;
9075 	struct direct *de;
9076 	struct mount *mp;
9077 	struct ufsmount *ump;
9078 	ufs_lbn_t lbn;
9079 	int flags;
9080 
9081 	mp = ITOVFS(dp);
9082 	ump = VFSTOUFS(mp);
9083 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9084 	    ("softdep_change_directoryentry_offset called on "
9085 	     "non-softdep filesystem"));
9086 	de = (struct direct *)oldloc;
9087 	jmvref = NULL;
9088 	flags = 0;
9089 	/*
9090 	 * Moves are always journaled as it would be too complex to
9091 	 * determine if any affected adds or removes are present in the
9092 	 * journal.
9093 	 */
9094 	if (MOUNTEDSUJ(mp)) {
9095 		flags = DEPALLOC;
9096 		jmvref = newjmvref(dp, de->d_ino,
9097 		    I_OFFSET(dp) + (oldloc - base),
9098 		    I_OFFSET(dp) + (newloc - base));
9099 	}
9100 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9101 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9102 	oldoffset = offset + (oldloc - base);
9103 	newoffset = offset + (newloc - base);
9104 	ACQUIRE_LOCK(ump);
9105 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
9106 		goto done;
9107 	dap = diradd_lookup(pagedep, oldoffset);
9108 	if (dap) {
9109 		dap->da_offset = newoffset;
9110 		newoffset = DIRADDHASH(newoffset);
9111 		oldoffset = DIRADDHASH(oldoffset);
9112 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
9113 		    newoffset != oldoffset) {
9114 			LIST_REMOVE(dap, da_pdlist);
9115 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
9116 			    dap, da_pdlist);
9117 		}
9118 	}
9119 done:
9120 	if (jmvref) {
9121 		jmvref->jm_pagedep = pagedep;
9122 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
9123 		add_to_journal(&jmvref->jm_list);
9124 	}
9125 	bcopy(oldloc, newloc, entrysize);
9126 	FREE_LOCK(ump);
9127 }
9128 
9129 /*
9130  * Move the mkdir dependencies and journal work from one diradd to another
9131  * when renaming a directory.  The new name must depend on the mkdir deps
9132  * completing as the old name did.  Directories can only have one valid link
9133  * at a time so one must be canonical.
9134  */
9135 static void
9136 merge_diradd(inodedep, newdap)
9137 	struct inodedep *inodedep;
9138 	struct diradd *newdap;
9139 {
9140 	struct diradd *olddap;
9141 	struct mkdir *mkdir, *nextmd;
9142 	struct ufsmount *ump;
9143 	short state;
9144 
9145 	olddap = inodedep->id_mkdiradd;
9146 	inodedep->id_mkdiradd = newdap;
9147 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9148 		newdap->da_state &= ~DEPCOMPLETE;
9149 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
9150 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9151 		     mkdir = nextmd) {
9152 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9153 			if (mkdir->md_diradd != olddap)
9154 				continue;
9155 			mkdir->md_diradd = newdap;
9156 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
9157 			newdap->da_state |= state;
9158 			olddap->da_state &= ~state;
9159 			if ((olddap->da_state &
9160 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
9161 				break;
9162 		}
9163 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9164 			panic("merge_diradd: unfound ref");
9165 	}
9166 	/*
9167 	 * Any mkdir related journal items are not safe to be freed until
9168 	 * the new name is stable.
9169 	 */
9170 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
9171 	olddap->da_state |= DEPCOMPLETE;
9172 	complete_diradd(olddap);
9173 }
9174 
9175 /*
9176  * Move the diradd to the pending list when all diradd dependencies are
9177  * complete.
9178  */
9179 static void
9180 complete_diradd(dap)
9181 	struct diradd *dap;
9182 {
9183 	struct pagedep *pagedep;
9184 
9185 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
9186 		if (dap->da_state & DIRCHG)
9187 			pagedep = dap->da_previous->dm_pagedep;
9188 		else
9189 			pagedep = dap->da_pagedep;
9190 		LIST_REMOVE(dap, da_pdlist);
9191 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9192 	}
9193 }
9194 
9195 /*
9196  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
9197  * add entries and conditionally journal the remove.
9198  */
9199 static void
9200 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
9201 	struct diradd *dap;
9202 	struct dirrem *dirrem;
9203 	struct jremref *jremref;
9204 	struct jremref *dotremref;
9205 	struct jremref *dotdotremref;
9206 {
9207 	struct inodedep *inodedep;
9208 	struct jaddref *jaddref;
9209 	struct inoref *inoref;
9210 	struct ufsmount *ump;
9211 	struct mkdir *mkdir;
9212 
9213 	/*
9214 	 * If no remove references were allocated we're on a non-journaled
9215 	 * filesystem and can skip the cancel step.
9216 	 */
9217 	if (jremref == NULL) {
9218 		free_diradd(dap, NULL);
9219 		return;
9220 	}
9221 	/*
9222 	 * Cancel the primary name an free it if it does not require
9223 	 * journaling.
9224 	 */
9225 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
9226 	    0, &inodedep) != 0) {
9227 		/* Abort the addref that reference this diradd.  */
9228 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
9229 			if (inoref->if_list.wk_type != D_JADDREF)
9230 				continue;
9231 			jaddref = (struct jaddref *)inoref;
9232 			if (jaddref->ja_diradd != dap)
9233 				continue;
9234 			if (cancel_jaddref(jaddref, inodedep,
9235 			    &dirrem->dm_jwork) == 0) {
9236 				free_jremref(jremref);
9237 				jremref = NULL;
9238 			}
9239 			break;
9240 		}
9241 	}
9242 	/*
9243 	 * Cancel subordinate names and free them if they do not require
9244 	 * journaling.
9245 	 */
9246 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9247 		ump = VFSTOUFS(dap->da_list.wk_mp);
9248 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
9249 			if (mkdir->md_diradd != dap)
9250 				continue;
9251 			if ((jaddref = mkdir->md_jaddref) == NULL)
9252 				continue;
9253 			mkdir->md_jaddref = NULL;
9254 			if (mkdir->md_state & MKDIR_PARENT) {
9255 				if (cancel_jaddref(jaddref, NULL,
9256 				    &dirrem->dm_jwork) == 0) {
9257 					free_jremref(dotdotremref);
9258 					dotdotremref = NULL;
9259 				}
9260 			} else {
9261 				if (cancel_jaddref(jaddref, inodedep,
9262 				    &dirrem->dm_jwork) == 0) {
9263 					free_jremref(dotremref);
9264 					dotremref = NULL;
9265 				}
9266 			}
9267 		}
9268 	}
9269 
9270 	if (jremref)
9271 		journal_jremref(dirrem, jremref, inodedep);
9272 	if (dotremref)
9273 		journal_jremref(dirrem, dotremref, inodedep);
9274 	if (dotdotremref)
9275 		journal_jremref(dirrem, dotdotremref, NULL);
9276 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
9277 	free_diradd(dap, &dirrem->dm_jwork);
9278 }
9279 
9280 /*
9281  * Free a diradd dependency structure.
9282  */
9283 static void
9284 free_diradd(dap, wkhd)
9285 	struct diradd *dap;
9286 	struct workhead *wkhd;
9287 {
9288 	struct dirrem *dirrem;
9289 	struct pagedep *pagedep;
9290 	struct inodedep *inodedep;
9291 	struct mkdir *mkdir, *nextmd;
9292 	struct ufsmount *ump;
9293 
9294 	ump = VFSTOUFS(dap->da_list.wk_mp);
9295 	LOCK_OWNED(ump);
9296 	LIST_REMOVE(dap, da_pdlist);
9297 	if (dap->da_state & ONWORKLIST)
9298 		WORKLIST_REMOVE(&dap->da_list);
9299 	if ((dap->da_state & DIRCHG) == 0) {
9300 		pagedep = dap->da_pagedep;
9301 	} else {
9302 		dirrem = dap->da_previous;
9303 		pagedep = dirrem->dm_pagedep;
9304 		dirrem->dm_dirinum = pagedep->pd_ino;
9305 		dirrem->dm_state |= COMPLETE;
9306 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9307 			add_to_worklist(&dirrem->dm_list, 0);
9308 	}
9309 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
9310 	    0, &inodedep) != 0)
9311 		if (inodedep->id_mkdiradd == dap)
9312 			inodedep->id_mkdiradd = NULL;
9313 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9314 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9315 		     mkdir = nextmd) {
9316 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9317 			if (mkdir->md_diradd != dap)
9318 				continue;
9319 			dap->da_state &=
9320 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
9321 			LIST_REMOVE(mkdir, md_mkdirs);
9322 			if (mkdir->md_state & ONWORKLIST)
9323 				WORKLIST_REMOVE(&mkdir->md_list);
9324 			if (mkdir->md_jaddref != NULL)
9325 				panic("free_diradd: Unexpected jaddref");
9326 			WORKITEM_FREE(mkdir, D_MKDIR);
9327 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
9328 				break;
9329 		}
9330 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9331 			panic("free_diradd: unfound ref");
9332 	}
9333 	if (inodedep)
9334 		free_inodedep(inodedep);
9335 	/*
9336 	 * Free any journal segments waiting for the directory write.
9337 	 */
9338 	handle_jwork(&dap->da_jwork);
9339 	WORKITEM_FREE(dap, D_DIRADD);
9340 }
9341 
9342 /*
9343  * Directory entry removal dependencies.
9344  *
9345  * When removing a directory entry, the entry's inode pointer must be
9346  * zero'ed on disk before the corresponding inode's link count is decremented
9347  * (possibly freeing the inode for re-use). This dependency is handled by
9348  * updating the directory entry but delaying the inode count reduction until
9349  * after the directory block has been written to disk. After this point, the
9350  * inode count can be decremented whenever it is convenient.
9351  */
9352 
9353 /*
9354  * This routine should be called immediately after removing
9355  * a directory entry.  The inode's link count should not be
9356  * decremented by the calling procedure -- the soft updates
9357  * code will do this task when it is safe.
9358  */
9359 void
9360 softdep_setup_remove(bp, dp, ip, isrmdir)
9361 	struct buf *bp;		/* buffer containing directory block */
9362 	struct inode *dp;	/* inode for the directory being modified */
9363 	struct inode *ip;	/* inode for directory entry being removed */
9364 	int isrmdir;		/* indicates if doing RMDIR */
9365 {
9366 	struct dirrem *dirrem, *prevdirrem;
9367 	struct inodedep *inodedep;
9368 	struct ufsmount *ump;
9369 	int direct;
9370 
9371 	ump = ITOUMP(ip);
9372 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9373 	    ("softdep_setup_remove called on non-softdep filesystem"));
9374 	/*
9375 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9376 	 * newdirrem() to setup the full directory remove which requires
9377 	 * isrmdir > 1.
9378 	 */
9379 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9380 	/*
9381 	 * Add the dirrem to the inodedep's pending remove list for quick
9382 	 * discovery later.
9383 	 */
9384 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9385 		panic("softdep_setup_remove: Lost inodedep.");
9386 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9387 	dirrem->dm_state |= ONDEPLIST;
9388 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9389 
9390 	/*
9391 	 * If the COMPLETE flag is clear, then there were no active
9392 	 * entries and we want to roll back to a zeroed entry until
9393 	 * the new inode is committed to disk. If the COMPLETE flag is
9394 	 * set then we have deleted an entry that never made it to
9395 	 * disk. If the entry we deleted resulted from a name change,
9396 	 * then the old name still resides on disk. We cannot delete
9397 	 * its inode (returned to us in prevdirrem) until the zeroed
9398 	 * directory entry gets to disk. The new inode has never been
9399 	 * referenced on the disk, so can be deleted immediately.
9400 	 */
9401 	if ((dirrem->dm_state & COMPLETE) == 0) {
9402 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9403 		    dm_next);
9404 		FREE_LOCK(ump);
9405 	} else {
9406 		if (prevdirrem != NULL)
9407 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9408 			    prevdirrem, dm_next);
9409 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9410 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9411 		FREE_LOCK(ump);
9412 		if (direct)
9413 			handle_workitem_remove(dirrem, 0);
9414 	}
9415 }
9416 
9417 /*
9418  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9419  * pd_pendinghd list of a pagedep.
9420  */
9421 static struct diradd *
9422 diradd_lookup(pagedep, offset)
9423 	struct pagedep *pagedep;
9424 	int offset;
9425 {
9426 	struct diradd *dap;
9427 
9428 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9429 		if (dap->da_offset == offset)
9430 			return (dap);
9431 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9432 		if (dap->da_offset == offset)
9433 			return (dap);
9434 	return (NULL);
9435 }
9436 
9437 /*
9438  * Search for a .. diradd dependency in a directory that is being removed.
9439  * If the directory was renamed to a new parent we have a diradd rather
9440  * than a mkdir for the .. entry.  We need to cancel it now before
9441  * it is found in truncate().
9442  */
9443 static struct jremref *
9444 cancel_diradd_dotdot(ip, dirrem, jremref)
9445 	struct inode *ip;
9446 	struct dirrem *dirrem;
9447 	struct jremref *jremref;
9448 {
9449 	struct pagedep *pagedep;
9450 	struct diradd *dap;
9451 	struct worklist *wk;
9452 
9453 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9454 		return (jremref);
9455 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9456 	if (dap == NULL)
9457 		return (jremref);
9458 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9459 	/*
9460 	 * Mark any journal work as belonging to the parent so it is freed
9461 	 * with the .. reference.
9462 	 */
9463 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9464 		wk->wk_state |= MKDIR_PARENT;
9465 	return (NULL);
9466 }
9467 
9468 /*
9469  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9470  * replace it with a dirrem/diradd pair as a result of re-parenting a
9471  * directory.  This ensures that we don't simultaneously have a mkdir and
9472  * a diradd for the same .. entry.
9473  */
9474 static struct jremref *
9475 cancel_mkdir_dotdot(ip, dirrem, jremref)
9476 	struct inode *ip;
9477 	struct dirrem *dirrem;
9478 	struct jremref *jremref;
9479 {
9480 	struct inodedep *inodedep;
9481 	struct jaddref *jaddref;
9482 	struct ufsmount *ump;
9483 	struct mkdir *mkdir;
9484 	struct diradd *dap;
9485 	struct mount *mp;
9486 
9487 	mp = ITOVFS(ip);
9488 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9489 		return (jremref);
9490 	dap = inodedep->id_mkdiradd;
9491 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9492 		return (jremref);
9493 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9494 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9495 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9496 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9497 			break;
9498 	if (mkdir == NULL)
9499 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9500 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9501 		mkdir->md_jaddref = NULL;
9502 		jaddref->ja_state &= ~MKDIR_PARENT;
9503 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9504 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9505 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9506 			journal_jremref(dirrem, jremref, inodedep);
9507 			jremref = NULL;
9508 		}
9509 	}
9510 	if (mkdir->md_state & ONWORKLIST)
9511 		WORKLIST_REMOVE(&mkdir->md_list);
9512 	mkdir->md_state |= ALLCOMPLETE;
9513 	complete_mkdir(mkdir);
9514 	return (jremref);
9515 }
9516 
9517 static void
9518 journal_jremref(dirrem, jremref, inodedep)
9519 	struct dirrem *dirrem;
9520 	struct jremref *jremref;
9521 	struct inodedep *inodedep;
9522 {
9523 
9524 	if (inodedep == NULL)
9525 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9526 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9527 			panic("journal_jremref: Lost inodedep");
9528 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9529 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9530 	add_to_journal(&jremref->jr_list);
9531 }
9532 
9533 static void
9534 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9535 	struct dirrem *dirrem;
9536 	struct jremref *jremref;
9537 	struct jremref *dotremref;
9538 	struct jremref *dotdotremref;
9539 {
9540 	struct inodedep *inodedep;
9541 
9542 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9543 	    &inodedep) == 0)
9544 		panic("dirrem_journal: Lost inodedep");
9545 	journal_jremref(dirrem, jremref, inodedep);
9546 	if (dotremref)
9547 		journal_jremref(dirrem, dotremref, inodedep);
9548 	if (dotdotremref)
9549 		journal_jremref(dirrem, dotdotremref, NULL);
9550 }
9551 
9552 /*
9553  * Allocate a new dirrem if appropriate and return it along with
9554  * its associated pagedep. Called without a lock, returns with lock.
9555  */
9556 static struct dirrem *
9557 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9558 	struct buf *bp;		/* buffer containing directory block */
9559 	struct inode *dp;	/* inode for the directory being modified */
9560 	struct inode *ip;	/* inode for directory entry being removed */
9561 	int isrmdir;		/* indicates if doing RMDIR */
9562 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9563 {
9564 	int offset;
9565 	ufs_lbn_t lbn;
9566 	struct diradd *dap;
9567 	struct dirrem *dirrem;
9568 	struct pagedep *pagedep;
9569 	struct jremref *jremref;
9570 	struct jremref *dotremref;
9571 	struct jremref *dotdotremref;
9572 	struct vnode *dvp;
9573 	struct ufsmount *ump;
9574 
9575 	/*
9576 	 * Whiteouts have no deletion dependencies.
9577 	 */
9578 	if (ip == NULL)
9579 		panic("newdirrem: whiteout");
9580 	dvp = ITOV(dp);
9581 	ump = ITOUMP(dp);
9582 
9583 	/*
9584 	 * If the system is over its limit and our filesystem is
9585 	 * responsible for more than our share of that usage and
9586 	 * we are not a snapshot, request some inodedep cleanup.
9587 	 * Limiting the number of dirrem structures will also limit
9588 	 * the number of freefile and freeblks structures.
9589 	 */
9590 	ACQUIRE_LOCK(ump);
9591 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9592 		schedule_cleanup(UFSTOVFS(ump));
9593 	else
9594 		FREE_LOCK(ump);
9595 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9596 	    M_ZERO);
9597 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9598 	LIST_INIT(&dirrem->dm_jremrefhd);
9599 	LIST_INIT(&dirrem->dm_jwork);
9600 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9601 	dirrem->dm_oldinum = ip->i_number;
9602 	*prevdirremp = NULL;
9603 	/*
9604 	 * Allocate remove reference structures to track journal write
9605 	 * dependencies.  We will always have one for the link and
9606 	 * when doing directories we will always have one more for dot.
9607 	 * When renaming a directory we skip the dotdot link change so
9608 	 * this is not needed.
9609 	 */
9610 	jremref = dotremref = dotdotremref = NULL;
9611 	if (DOINGSUJ(dvp)) {
9612 		if (isrmdir) {
9613 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9614 			    ip->i_effnlink + 2);
9615 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9616 			    ip->i_effnlink + 1);
9617 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9618 			    dp->i_effnlink + 1);
9619 			dotdotremref->jr_state |= MKDIR_PARENT;
9620 		} else
9621 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9622 			    ip->i_effnlink + 1);
9623 	}
9624 	ACQUIRE_LOCK(ump);
9625 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9626 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9627 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9628 	    &pagedep);
9629 	dirrem->dm_pagedep = pagedep;
9630 	dirrem->dm_offset = offset;
9631 	/*
9632 	 * If we're renaming a .. link to a new directory, cancel any
9633 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9634 	 * the jremref is preserved for any potential diradd in this
9635 	 * location.  This can not coincide with a rmdir.
9636 	 */
9637 	if (I_OFFSET(dp) == DOTDOT_OFFSET) {
9638 		if (isrmdir)
9639 			panic("newdirrem: .. directory change during remove?");
9640 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9641 	}
9642 	/*
9643 	 * If we're removing a directory search for the .. dependency now and
9644 	 * cancel it.  Any pending journal work will be added to the dirrem
9645 	 * to be completed when the workitem remove completes.
9646 	 */
9647 	if (isrmdir)
9648 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9649 	/*
9650 	 * Check for a diradd dependency for the same directory entry.
9651 	 * If present, then both dependencies become obsolete and can
9652 	 * be de-allocated.
9653 	 */
9654 	dap = diradd_lookup(pagedep, offset);
9655 	if (dap == NULL) {
9656 		/*
9657 		 * Link the jremref structures into the dirrem so they are
9658 		 * written prior to the pagedep.
9659 		 */
9660 		if (jremref)
9661 			dirrem_journal(dirrem, jremref, dotremref,
9662 			    dotdotremref);
9663 		return (dirrem);
9664 	}
9665 	/*
9666 	 * Must be ATTACHED at this point.
9667 	 */
9668 	if ((dap->da_state & ATTACHED) == 0)
9669 		panic("newdirrem: not ATTACHED");
9670 	if (dap->da_newinum != ip->i_number)
9671 		panic("newdirrem: inum %ju should be %ju",
9672 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9673 	/*
9674 	 * If we are deleting a changed name that never made it to disk,
9675 	 * then return the dirrem describing the previous inode (which
9676 	 * represents the inode currently referenced from this entry on disk).
9677 	 */
9678 	if ((dap->da_state & DIRCHG) != 0) {
9679 		*prevdirremp = dap->da_previous;
9680 		dap->da_state &= ~DIRCHG;
9681 		dap->da_pagedep = pagedep;
9682 	}
9683 	/*
9684 	 * We are deleting an entry that never made it to disk.
9685 	 * Mark it COMPLETE so we can delete its inode immediately.
9686 	 */
9687 	dirrem->dm_state |= COMPLETE;
9688 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9689 #ifdef INVARIANTS
9690 	if (isrmdir == 0) {
9691 		struct worklist *wk;
9692 
9693 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9694 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9695 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9696 	}
9697 #endif
9698 
9699 	return (dirrem);
9700 }
9701 
9702 /*
9703  * Directory entry change dependencies.
9704  *
9705  * Changing an existing directory entry requires that an add operation
9706  * be completed first followed by a deletion. The semantics for the addition
9707  * are identical to the description of adding a new entry above except
9708  * that the rollback is to the old inode number rather than zero. Once
9709  * the addition dependency is completed, the removal is done as described
9710  * in the removal routine above.
9711  */
9712 
9713 /*
9714  * This routine should be called immediately after changing
9715  * a directory entry.  The inode's link count should not be
9716  * decremented by the calling procedure -- the soft updates
9717  * code will perform this task when it is safe.
9718  */
9719 void
9720 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9721 	struct buf *bp;		/* buffer containing directory block */
9722 	struct inode *dp;	/* inode for the directory being modified */
9723 	struct inode *ip;	/* inode for directory entry being removed */
9724 	ino_t newinum;		/* new inode number for changed entry */
9725 	int isrmdir;		/* indicates if doing RMDIR */
9726 {
9727 	int offset;
9728 	struct diradd *dap = NULL;
9729 	struct dirrem *dirrem, *prevdirrem;
9730 	struct pagedep *pagedep;
9731 	struct inodedep *inodedep;
9732 	struct jaddref *jaddref;
9733 	struct mount *mp;
9734 	struct ufsmount *ump;
9735 
9736 	mp = ITOVFS(dp);
9737 	ump = VFSTOUFS(mp);
9738 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9739 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9740 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9741 
9742 	/*
9743 	 * Whiteouts do not need diradd dependencies.
9744 	 */
9745 	if (newinum != UFS_WINO) {
9746 		dap = malloc(sizeof(struct diradd),
9747 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9748 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9749 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9750 		dap->da_offset = offset;
9751 		dap->da_newinum = newinum;
9752 		LIST_INIT(&dap->da_jwork);
9753 	}
9754 
9755 	/*
9756 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9757 	 */
9758 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9759 	pagedep = dirrem->dm_pagedep;
9760 	/*
9761 	 * The possible values for isrmdir:
9762 	 *	0 - non-directory file rename
9763 	 *	1 - directory rename within same directory
9764 	 *   inum - directory rename to new directory of given inode number
9765 	 * When renaming to a new directory, we are both deleting and
9766 	 * creating a new directory entry, so the link count on the new
9767 	 * directory should not change. Thus we do not need the followup
9768 	 * dirrem which is usually done in handle_workitem_remove. We set
9769 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9770 	 * followup dirrem.
9771 	 */
9772 	if (isrmdir > 1)
9773 		dirrem->dm_state |= DIRCHG;
9774 
9775 	/*
9776 	 * Whiteouts have no additional dependencies,
9777 	 * so just put the dirrem on the correct list.
9778 	 */
9779 	if (newinum == UFS_WINO) {
9780 		if ((dirrem->dm_state & COMPLETE) == 0) {
9781 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9782 			    dm_next);
9783 		} else {
9784 			dirrem->dm_dirinum = pagedep->pd_ino;
9785 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9786 				add_to_worklist(&dirrem->dm_list, 0);
9787 		}
9788 		FREE_LOCK(ump);
9789 		return;
9790 	}
9791 	/*
9792 	 * Add the dirrem to the inodedep's pending remove list for quick
9793 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9794 	 * will not fail.
9795 	 */
9796 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9797 		panic("softdep_setup_directory_change: Lost inodedep.");
9798 	dirrem->dm_state |= ONDEPLIST;
9799 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9800 
9801 	/*
9802 	 * If the COMPLETE flag is clear, then there were no active
9803 	 * entries and we want to roll back to the previous inode until
9804 	 * the new inode is committed to disk. If the COMPLETE flag is
9805 	 * set, then we have deleted an entry that never made it to disk.
9806 	 * If the entry we deleted resulted from a name change, then the old
9807 	 * inode reference still resides on disk. Any rollback that we do
9808 	 * needs to be to that old inode (returned to us in prevdirrem). If
9809 	 * the entry we deleted resulted from a create, then there is
9810 	 * no entry on the disk, so we want to roll back to zero rather
9811 	 * than the uncommitted inode. In either of the COMPLETE cases we
9812 	 * want to immediately free the unwritten and unreferenced inode.
9813 	 */
9814 	if ((dirrem->dm_state & COMPLETE) == 0) {
9815 		dap->da_previous = dirrem;
9816 	} else {
9817 		if (prevdirrem != NULL) {
9818 			dap->da_previous = prevdirrem;
9819 		} else {
9820 			dap->da_state &= ~DIRCHG;
9821 			dap->da_pagedep = pagedep;
9822 		}
9823 		dirrem->dm_dirinum = pagedep->pd_ino;
9824 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9825 			add_to_worklist(&dirrem->dm_list, 0);
9826 	}
9827 	/*
9828 	 * Lookup the jaddref for this journal entry.  We must finish
9829 	 * initializing it and make the diradd write dependent on it.
9830 	 * If we're not journaling, put it on the id_bufwait list if the
9831 	 * inode is not yet written. If it is written, do the post-inode
9832 	 * write processing to put it on the id_pendinghd list.
9833 	 */
9834 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9835 	if (MOUNTEDSUJ(mp)) {
9836 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9837 		    inoreflst);
9838 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9839 		    ("softdep_setup_directory_change: bad jaddref %p",
9840 		    jaddref));
9841 		jaddref->ja_diroff = I_OFFSET(dp);
9842 		jaddref->ja_diradd = dap;
9843 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9844 		    dap, da_pdlist);
9845 		add_to_journal(&jaddref->ja_list);
9846 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9847 		dap->da_state |= COMPLETE;
9848 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9849 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9850 	} else {
9851 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9852 		    dap, da_pdlist);
9853 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9854 	}
9855 	/*
9856 	 * If we're making a new name for a directory that has not been
9857 	 * committed when need to move the dot and dotdot references to
9858 	 * this new name.
9859 	 */
9860 	if (inodedep->id_mkdiradd && I_OFFSET(dp) != DOTDOT_OFFSET)
9861 		merge_diradd(inodedep, dap);
9862 	FREE_LOCK(ump);
9863 }
9864 
9865 /*
9866  * Called whenever the link count on an inode is changed.
9867  * It creates an inode dependency so that the new reference(s)
9868  * to the inode cannot be committed to disk until the updated
9869  * inode has been written.
9870  */
9871 void
9872 softdep_change_linkcnt(ip)
9873 	struct inode *ip;	/* the inode with the increased link count */
9874 {
9875 	struct inodedep *inodedep;
9876 	struct ufsmount *ump;
9877 
9878 	ump = ITOUMP(ip);
9879 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9880 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9881 	ACQUIRE_LOCK(ump);
9882 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9883 	if (ip->i_nlink < ip->i_effnlink)
9884 		panic("softdep_change_linkcnt: bad delta");
9885 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9886 	FREE_LOCK(ump);
9887 }
9888 
9889 /*
9890  * Attach a sbdep dependency to the superblock buf so that we can keep
9891  * track of the head of the linked list of referenced but unlinked inodes.
9892  */
9893 void
9894 softdep_setup_sbupdate(ump, fs, bp)
9895 	struct ufsmount *ump;
9896 	struct fs *fs;
9897 	struct buf *bp;
9898 {
9899 	struct sbdep *sbdep;
9900 	struct worklist *wk;
9901 
9902 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9903 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9904 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9905 		if (wk->wk_type == D_SBDEP)
9906 			break;
9907 	if (wk != NULL)
9908 		return;
9909 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9910 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9911 	sbdep->sb_fs = fs;
9912 	sbdep->sb_ump = ump;
9913 	ACQUIRE_LOCK(ump);
9914 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9915 	FREE_LOCK(ump);
9916 }
9917 
9918 /*
9919  * Return the first unlinked inodedep which is ready to be the head of the
9920  * list.  The inodedep and all those after it must have valid next pointers.
9921  */
9922 static struct inodedep *
9923 first_unlinked_inodedep(ump)
9924 	struct ufsmount *ump;
9925 {
9926 	struct inodedep *inodedep;
9927 	struct inodedep *idp;
9928 
9929 	LOCK_OWNED(ump);
9930 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9931 	    inodedep; inodedep = idp) {
9932 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9933 			return (NULL);
9934 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9935 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9936 			break;
9937 		if ((inodedep->id_state & UNLINKPREV) == 0)
9938 			break;
9939 	}
9940 	return (inodedep);
9941 }
9942 
9943 /*
9944  * Set the sujfree unlinked head pointer prior to writing a superblock.
9945  */
9946 static void
9947 initiate_write_sbdep(sbdep)
9948 	struct sbdep *sbdep;
9949 {
9950 	struct inodedep *inodedep;
9951 	struct fs *bpfs;
9952 	struct fs *fs;
9953 
9954 	bpfs = sbdep->sb_fs;
9955 	fs = sbdep->sb_ump->um_fs;
9956 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9957 	if (inodedep) {
9958 		fs->fs_sujfree = inodedep->id_ino;
9959 		inodedep->id_state |= UNLINKPREV;
9960 	} else
9961 		fs->fs_sujfree = 0;
9962 	bpfs->fs_sujfree = fs->fs_sujfree;
9963 	/*
9964 	 * Because we have made changes to the superblock, we need to
9965 	 * recompute its check-hash.
9966 	 */
9967 	bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9968 }
9969 
9970 /*
9971  * After a superblock is written determine whether it must be written again
9972  * due to a changing unlinked list head.
9973  */
9974 static int
9975 handle_written_sbdep(sbdep, bp)
9976 	struct sbdep *sbdep;
9977 	struct buf *bp;
9978 {
9979 	struct inodedep *inodedep;
9980 	struct fs *fs;
9981 
9982 	LOCK_OWNED(sbdep->sb_ump);
9983 	fs = sbdep->sb_fs;
9984 	/*
9985 	 * If the superblock doesn't match the in-memory list start over.
9986 	 */
9987 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9988 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9989 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9990 		bdirty(bp);
9991 		return (1);
9992 	}
9993 	WORKITEM_FREE(sbdep, D_SBDEP);
9994 	if (fs->fs_sujfree == 0)
9995 		return (0);
9996 	/*
9997 	 * Now that we have a record of this inode in stable store allow it
9998 	 * to be written to free up pending work.  Inodes may see a lot of
9999 	 * write activity after they are unlinked which we must not hold up.
10000 	 */
10001 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
10002 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
10003 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
10004 			    inodedep, inodedep->id_state);
10005 		if (inodedep->id_state & UNLINKONLIST)
10006 			break;
10007 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
10008 	}
10009 
10010 	return (0);
10011 }
10012 
10013 /*
10014  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
10015  */
10016 static void
10017 unlinked_inodedep(mp, inodedep)
10018 	struct mount *mp;
10019 	struct inodedep *inodedep;
10020 {
10021 	struct ufsmount *ump;
10022 
10023 	ump = VFSTOUFS(mp);
10024 	LOCK_OWNED(ump);
10025 	if (MOUNTEDSUJ(mp) == 0)
10026 		return;
10027 	ump->um_fs->fs_fmod = 1;
10028 	if (inodedep->id_state & UNLINKED)
10029 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
10030 	inodedep->id_state |= UNLINKED;
10031 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
10032 }
10033 
10034 /*
10035  * Remove an inodedep from the unlinked inodedep list.  This may require
10036  * disk writes if the inode has made it that far.
10037  */
10038 static void
10039 clear_unlinked_inodedep(inodedep)
10040 	struct inodedep *inodedep;
10041 {
10042 	struct ufs2_dinode *dip;
10043 	struct ufsmount *ump;
10044 	struct inodedep *idp;
10045 	struct inodedep *idn;
10046 	struct fs *fs, *bpfs;
10047 	struct buf *bp;
10048 	daddr_t dbn;
10049 	ino_t ino;
10050 	ino_t nino;
10051 	ino_t pino;
10052 	int error;
10053 
10054 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10055 	fs = ump->um_fs;
10056 	ino = inodedep->id_ino;
10057 	error = 0;
10058 	for (;;) {
10059 		LOCK_OWNED(ump);
10060 		KASSERT((inodedep->id_state & UNLINKED) != 0,
10061 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
10062 		    inodedep));
10063 		/*
10064 		 * If nothing has yet been written simply remove us from
10065 		 * the in memory list and return.  This is the most common
10066 		 * case where handle_workitem_remove() loses the final
10067 		 * reference.
10068 		 */
10069 		if ((inodedep->id_state & UNLINKLINKS) == 0)
10070 			break;
10071 		/*
10072 		 * If we have a NEXT pointer and no PREV pointer we can simply
10073 		 * clear NEXT's PREV and remove ourselves from the list.  Be
10074 		 * careful not to clear PREV if the superblock points at
10075 		 * next as well.
10076 		 */
10077 		idn = TAILQ_NEXT(inodedep, id_unlinked);
10078 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
10079 			if (idn && fs->fs_sujfree != idn->id_ino)
10080 				idn->id_state &= ~UNLINKPREV;
10081 			break;
10082 		}
10083 		/*
10084 		 * Here we have an inodedep which is actually linked into
10085 		 * the list.  We must remove it by forcing a write to the
10086 		 * link before us, whether it be the superblock or an inode.
10087 		 * Unfortunately the list may change while we're waiting
10088 		 * on the buf lock for either resource so we must loop until
10089 		 * we lock the right one.  If both the superblock and an
10090 		 * inode point to this inode we must clear the inode first
10091 		 * followed by the superblock.
10092 		 */
10093 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
10094 		pino = 0;
10095 		if (idp && (idp->id_state & UNLINKNEXT))
10096 			pino = idp->id_ino;
10097 		FREE_LOCK(ump);
10098 		if (pino == 0) {
10099 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
10100 			    (int)fs->fs_sbsize, 0, 0, 0);
10101 		} else {
10102 			dbn = fsbtodb(fs, ino_to_fsba(fs, pino));
10103 			error = ffs_breadz(ump, ump->um_devvp, dbn, dbn,
10104 			    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL,
10105 			    &bp);
10106 		}
10107 		ACQUIRE_LOCK(ump);
10108 		if (error)
10109 			break;
10110 		/* If the list has changed restart the loop. */
10111 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
10112 		nino = 0;
10113 		if (idp && (idp->id_state & UNLINKNEXT))
10114 			nino = idp->id_ino;
10115 		if (nino != pino ||
10116 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
10117 			FREE_LOCK(ump);
10118 			brelse(bp);
10119 			ACQUIRE_LOCK(ump);
10120 			continue;
10121 		}
10122 		nino = 0;
10123 		idn = TAILQ_NEXT(inodedep, id_unlinked);
10124 		if (idn)
10125 			nino = idn->id_ino;
10126 		/*
10127 		 * Remove us from the in memory list.  After this we cannot
10128 		 * access the inodedep.
10129 		 */
10130 		KASSERT((inodedep->id_state & UNLINKED) != 0,
10131 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
10132 		    inodedep));
10133 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
10134 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
10135 		FREE_LOCK(ump);
10136 		/*
10137 		 * The predecessor's next pointer is manually updated here
10138 		 * so that the NEXT flag is never cleared for an element
10139 		 * that is in the list.
10140 		 */
10141 		if (pino == 0) {
10142 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
10143 			bpfs = (struct fs *)bp->b_data;
10144 			ffs_oldfscompat_write(bpfs, ump);
10145 			softdep_setup_sbupdate(ump, bpfs, bp);
10146 			/*
10147 			 * Because we may have made changes to the superblock,
10148 			 * we need to recompute its check-hash.
10149 			 */
10150 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
10151 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
10152 			((struct ufs1_dinode *)bp->b_data +
10153 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
10154 		} else {
10155 			dip = (struct ufs2_dinode *)bp->b_data +
10156 			    ino_to_fsbo(fs, pino);
10157 			dip->di_freelink = nino;
10158 			ffs_update_dinode_ckhash(fs, dip);
10159 		}
10160 		/*
10161 		 * If the bwrite fails we have no recourse to recover.  The
10162 		 * filesystem is corrupted already.
10163 		 */
10164 		bwrite(bp);
10165 		ACQUIRE_LOCK(ump);
10166 		/*
10167 		 * If the superblock pointer still needs to be cleared force
10168 		 * a write here.
10169 		 */
10170 		if (fs->fs_sujfree == ino) {
10171 			FREE_LOCK(ump);
10172 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
10173 			    (int)fs->fs_sbsize, 0, 0, 0);
10174 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
10175 			bpfs = (struct fs *)bp->b_data;
10176 			ffs_oldfscompat_write(bpfs, ump);
10177 			softdep_setup_sbupdate(ump, bpfs, bp);
10178 			/*
10179 			 * Because we may have made changes to the superblock,
10180 			 * we need to recompute its check-hash.
10181 			 */
10182 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
10183 			bwrite(bp);
10184 			ACQUIRE_LOCK(ump);
10185 		}
10186 
10187 		if (fs->fs_sujfree != ino)
10188 			return;
10189 		panic("clear_unlinked_inodedep: Failed to clear free head");
10190 	}
10191 	if (inodedep->id_ino == fs->fs_sujfree)
10192 		panic("clear_unlinked_inodedep: Freeing head of free list");
10193 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
10194 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
10195 	return;
10196 }
10197 
10198 /*
10199  * This workitem decrements the inode's link count.
10200  * If the link count reaches zero, the file is removed.
10201  */
10202 static int
10203 handle_workitem_remove(dirrem, flags)
10204 	struct dirrem *dirrem;
10205 	int flags;
10206 {
10207 	struct inodedep *inodedep;
10208 	struct workhead dotdotwk;
10209 	struct worklist *wk;
10210 	struct ufsmount *ump;
10211 	struct mount *mp;
10212 	struct vnode *vp;
10213 	struct inode *ip;
10214 	ino_t oldinum;
10215 
10216 	if (dirrem->dm_state & ONWORKLIST)
10217 		panic("handle_workitem_remove: dirrem %p still on worklist",
10218 		    dirrem);
10219 	oldinum = dirrem->dm_oldinum;
10220 	mp = dirrem->dm_list.wk_mp;
10221 	ump = VFSTOUFS(mp);
10222 	flags |= LK_EXCLUSIVE;
10223 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ |
10224 	    FFSV_FORCEINODEDEP) != 0)
10225 		return (EBUSY);
10226 	ip = VTOI(vp);
10227 	MPASS(ip->i_mode != 0);
10228 	ACQUIRE_LOCK(ump);
10229 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
10230 		panic("handle_workitem_remove: lost inodedep");
10231 	if (dirrem->dm_state & ONDEPLIST)
10232 		LIST_REMOVE(dirrem, dm_inonext);
10233 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
10234 	    ("handle_workitem_remove:  Journal entries not written."));
10235 
10236 	/*
10237 	 * Move all dependencies waiting on the remove to complete
10238 	 * from the dirrem to the inode inowait list to be completed
10239 	 * after the inode has been updated and written to disk.
10240 	 *
10241 	 * Any marked MKDIR_PARENT are saved to be completed when the
10242 	 * dotdot ref is removed unless DIRCHG is specified.  For
10243 	 * directory change operations there will be no further
10244 	 * directory writes and the jsegdeps need to be moved along
10245 	 * with the rest to be completed when the inode is free or
10246 	 * stable in the inode free list.
10247 	 */
10248 	LIST_INIT(&dotdotwk);
10249 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
10250 		WORKLIST_REMOVE(wk);
10251 		if ((dirrem->dm_state & DIRCHG) == 0 &&
10252 		    wk->wk_state & MKDIR_PARENT) {
10253 			wk->wk_state &= ~MKDIR_PARENT;
10254 			WORKLIST_INSERT(&dotdotwk, wk);
10255 			continue;
10256 		}
10257 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
10258 	}
10259 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
10260 	/*
10261 	 * Normal file deletion.
10262 	 */
10263 	if ((dirrem->dm_state & RMDIR) == 0) {
10264 		ip->i_nlink--;
10265 		KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
10266 		    "%ju negative i_nlink %d", (intmax_t)ip->i_number,
10267 		    ip->i_nlink));
10268 		DIP_SET(ip, i_nlink, ip->i_nlink);
10269 		UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10270 		if (ip->i_nlink < ip->i_effnlink)
10271 			panic("handle_workitem_remove: bad file delta");
10272 		if (ip->i_nlink == 0)
10273 			unlinked_inodedep(mp, inodedep);
10274 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10275 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10276 		    ("handle_workitem_remove: worklist not empty. %s",
10277 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
10278 		WORKITEM_FREE(dirrem, D_DIRREM);
10279 		FREE_LOCK(ump);
10280 		goto out;
10281 	}
10282 	/*
10283 	 * Directory deletion. Decrement reference count for both the
10284 	 * just deleted parent directory entry and the reference for ".".
10285 	 * Arrange to have the reference count on the parent decremented
10286 	 * to account for the loss of "..".
10287 	 */
10288 	ip->i_nlink -= 2;
10289 	KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
10290 	    "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
10291 	DIP_SET(ip, i_nlink, ip->i_nlink);
10292 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10293 	if (ip->i_nlink < ip->i_effnlink)
10294 		panic("handle_workitem_remove: bad dir delta");
10295 	if (ip->i_nlink == 0)
10296 		unlinked_inodedep(mp, inodedep);
10297 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10298 	/*
10299 	 * Rename a directory to a new parent. Since, we are both deleting
10300 	 * and creating a new directory entry, the link count on the new
10301 	 * directory should not change. Thus we skip the followup dirrem.
10302 	 */
10303 	if (dirrem->dm_state & DIRCHG) {
10304 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10305 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
10306 		WORKITEM_FREE(dirrem, D_DIRREM);
10307 		FREE_LOCK(ump);
10308 		goto out;
10309 	}
10310 	dirrem->dm_state = ONDEPLIST;
10311 	dirrem->dm_oldinum = dirrem->dm_dirinum;
10312 	/*
10313 	 * Place the dirrem on the parent's diremhd list.
10314 	 */
10315 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
10316 		panic("handle_workitem_remove: lost dir inodedep");
10317 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
10318 	/*
10319 	 * If the allocated inode has never been written to disk, then
10320 	 * the on-disk inode is zero'ed and we can remove the file
10321 	 * immediately.  When journaling if the inode has been marked
10322 	 * unlinked and not DEPCOMPLETE we know it can never be written.
10323 	 */
10324 	inodedep_lookup(mp, oldinum, 0, &inodedep);
10325 	if (inodedep == NULL ||
10326 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
10327 	    check_inode_unwritten(inodedep)) {
10328 		FREE_LOCK(ump);
10329 		vput(vp);
10330 		return handle_workitem_remove(dirrem, flags);
10331 	}
10332 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
10333 	FREE_LOCK(ump);
10334 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10335 out:
10336 	ffs_update(vp, 0);
10337 	vput(vp);
10338 	return (0);
10339 }
10340 
10341 /*
10342  * Inode de-allocation dependencies.
10343  *
10344  * When an inode's link count is reduced to zero, it can be de-allocated. We
10345  * found it convenient to postpone de-allocation until after the inode is
10346  * written to disk with its new link count (zero).  At this point, all of the
10347  * on-disk inode's block pointers are nullified and, with careful dependency
10348  * list ordering, all dependencies related to the inode will be satisfied and
10349  * the corresponding dependency structures de-allocated.  So, if/when the
10350  * inode is reused, there will be no mixing of old dependencies with new
10351  * ones.  This artificial dependency is set up by the block de-allocation
10352  * procedure above (softdep_setup_freeblocks) and completed by the
10353  * following procedure.
10354  */
10355 static void
10356 handle_workitem_freefile(freefile)
10357 	struct freefile *freefile;
10358 {
10359 	struct workhead wkhd;
10360 	struct fs *fs;
10361 	struct ufsmount *ump;
10362 	int error;
10363 #ifdef INVARIANTS
10364 	struct inodedep *idp;
10365 #endif
10366 
10367 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
10368 	fs = ump->um_fs;
10369 #ifdef INVARIANTS
10370 	ACQUIRE_LOCK(ump);
10371 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10372 	FREE_LOCK(ump);
10373 	if (error)
10374 		panic("handle_workitem_freefile: inodedep %p survived", idp);
10375 #endif
10376 	UFS_LOCK(ump);
10377 	fs->fs_pendinginodes -= 1;
10378 	UFS_UNLOCK(ump);
10379 	LIST_INIT(&wkhd);
10380 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10381 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10382 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10383 		softdep_error("handle_workitem_freefile", error);
10384 	ACQUIRE_LOCK(ump);
10385 	WORKITEM_FREE(freefile, D_FREEFILE);
10386 	FREE_LOCK(ump);
10387 }
10388 
10389 /*
10390  * Helper function which unlinks marker element from work list and returns
10391  * the next element on the list.
10392  */
10393 static __inline struct worklist *
10394 markernext(struct worklist *marker)
10395 {
10396 	struct worklist *next;
10397 
10398 	next = LIST_NEXT(marker, wk_list);
10399 	LIST_REMOVE(marker, wk_list);
10400 	return next;
10401 }
10402 
10403 /*
10404  * Disk writes.
10405  *
10406  * The dependency structures constructed above are most actively used when file
10407  * system blocks are written to disk.  No constraints are placed on when a
10408  * block can be written, but unsatisfied update dependencies are made safe by
10409  * modifying (or replacing) the source memory for the duration of the disk
10410  * write.  When the disk write completes, the memory block is again brought
10411  * up-to-date.
10412  *
10413  * In-core inode structure reclamation.
10414  *
10415  * Because there are a finite number of "in-core" inode structures, they are
10416  * reused regularly.  By transferring all inode-related dependencies to the
10417  * in-memory inode block and indexing them separately (via "inodedep"s), we
10418  * can allow "in-core" inode structures to be reused at any time and avoid
10419  * any increase in contention.
10420  *
10421  * Called just before entering the device driver to initiate a new disk I/O.
10422  * The buffer must be locked, thus, no I/O completion operations can occur
10423  * while we are manipulating its associated dependencies.
10424  */
10425 static void
10426 softdep_disk_io_initiation(bp)
10427 	struct buf *bp;		/* structure describing disk write to occur */
10428 {
10429 	struct worklist *wk;
10430 	struct worklist marker;
10431 	struct inodedep *inodedep;
10432 	struct freeblks *freeblks;
10433 	struct jblkdep *jblkdep;
10434 	struct newblk *newblk;
10435 	struct ufsmount *ump;
10436 
10437 	/*
10438 	 * We only care about write operations. There should never
10439 	 * be dependencies for reads.
10440 	 */
10441 	if (bp->b_iocmd != BIO_WRITE)
10442 		panic("softdep_disk_io_initiation: not write");
10443 
10444 	if (bp->b_vflags & BV_BKGRDINPROG)
10445 		panic("softdep_disk_io_initiation: Writing buffer with "
10446 		    "background write in progress: %p", bp);
10447 
10448 	ump = softdep_bp_to_mp(bp);
10449 	if (ump == NULL)
10450 		return;
10451 
10452 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10453 	PHOLD(curproc);			/* Don't swap out kernel stack */
10454 	ACQUIRE_LOCK(ump);
10455 	/*
10456 	 * Do any necessary pre-I/O processing.
10457 	 */
10458 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10459 	     wk = markernext(&marker)) {
10460 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10461 		switch (wk->wk_type) {
10462 		case D_PAGEDEP:
10463 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10464 			continue;
10465 
10466 		case D_INODEDEP:
10467 			inodedep = WK_INODEDEP(wk);
10468 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10469 				initiate_write_inodeblock_ufs1(inodedep, bp);
10470 			else
10471 				initiate_write_inodeblock_ufs2(inodedep, bp);
10472 			continue;
10473 
10474 		case D_INDIRDEP:
10475 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10476 			continue;
10477 
10478 		case D_BMSAFEMAP:
10479 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10480 			continue;
10481 
10482 		case D_JSEG:
10483 			WK_JSEG(wk)->js_buf = NULL;
10484 			continue;
10485 
10486 		case D_FREEBLKS:
10487 			freeblks = WK_FREEBLKS(wk);
10488 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10489 			/*
10490 			 * We have to wait for the freeblks to be journaled
10491 			 * before we can write an inodeblock with updated
10492 			 * pointers.  Be careful to arrange the marker so
10493 			 * we revisit the freeblks if it's not removed by
10494 			 * the first jwait().
10495 			 */
10496 			if (jblkdep != NULL) {
10497 				LIST_REMOVE(&marker, wk_list);
10498 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10499 				jwait(&jblkdep->jb_list, MNT_WAIT);
10500 			}
10501 			continue;
10502 		case D_ALLOCDIRECT:
10503 		case D_ALLOCINDIR:
10504 			/*
10505 			 * We have to wait for the jnewblk to be journaled
10506 			 * before we can write to a block if the contents
10507 			 * may be confused with an earlier file's indirect
10508 			 * at recovery time.  Handle the marker as described
10509 			 * above.
10510 			 */
10511 			newblk = WK_NEWBLK(wk);
10512 			if (newblk->nb_jnewblk != NULL &&
10513 			    indirblk_lookup(newblk->nb_list.wk_mp,
10514 			    newblk->nb_newblkno)) {
10515 				LIST_REMOVE(&marker, wk_list);
10516 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10517 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10518 			}
10519 			continue;
10520 
10521 		case D_SBDEP:
10522 			initiate_write_sbdep(WK_SBDEP(wk));
10523 			continue;
10524 
10525 		case D_MKDIR:
10526 		case D_FREEWORK:
10527 		case D_FREEDEP:
10528 		case D_JSEGDEP:
10529 			continue;
10530 
10531 		default:
10532 			panic("handle_disk_io_initiation: Unexpected type %s",
10533 			    TYPENAME(wk->wk_type));
10534 			/* NOTREACHED */
10535 		}
10536 	}
10537 	FREE_LOCK(ump);
10538 	PRELE(curproc);			/* Allow swapout of kernel stack */
10539 }
10540 
10541 /*
10542  * Called from within the procedure above to deal with unsatisfied
10543  * allocation dependencies in a directory. The buffer must be locked,
10544  * thus, no I/O completion operations can occur while we are
10545  * manipulating its associated dependencies.
10546  */
10547 static void
10548 initiate_write_filepage(pagedep, bp)
10549 	struct pagedep *pagedep;
10550 	struct buf *bp;
10551 {
10552 	struct jremref *jremref;
10553 	struct jmvref *jmvref;
10554 	struct dirrem *dirrem;
10555 	struct diradd *dap;
10556 	struct direct *ep;
10557 	int i;
10558 
10559 	if (pagedep->pd_state & IOSTARTED) {
10560 		/*
10561 		 * This can only happen if there is a driver that does not
10562 		 * understand chaining. Here biodone will reissue the call
10563 		 * to strategy for the incomplete buffers.
10564 		 */
10565 		printf("initiate_write_filepage: already started\n");
10566 		return;
10567 	}
10568 	pagedep->pd_state |= IOSTARTED;
10569 	/*
10570 	 * Wait for all journal remove dependencies to hit the disk.
10571 	 * We can not allow any potentially conflicting directory adds
10572 	 * to be visible before removes and rollback is too difficult.
10573 	 * The per-filesystem lock may be dropped and re-acquired, however
10574 	 * we hold the buf locked so the dependency can not go away.
10575 	 */
10576 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10577 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10578 			jwait(&jremref->jr_list, MNT_WAIT);
10579 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10580 		jwait(&jmvref->jm_list, MNT_WAIT);
10581 	for (i = 0; i < DAHASHSZ; i++) {
10582 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10583 			ep = (struct direct *)
10584 			    ((char *)bp->b_data + dap->da_offset);
10585 			if (ep->d_ino != dap->da_newinum)
10586 				panic("%s: dir inum %ju != new %ju",
10587 				    "initiate_write_filepage",
10588 				    (uintmax_t)ep->d_ino,
10589 				    (uintmax_t)dap->da_newinum);
10590 			if (dap->da_state & DIRCHG)
10591 				ep->d_ino = dap->da_previous->dm_oldinum;
10592 			else
10593 				ep->d_ino = 0;
10594 			dap->da_state &= ~ATTACHED;
10595 			dap->da_state |= UNDONE;
10596 		}
10597 	}
10598 }
10599 
10600 /*
10601  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10602  * Note that any bug fixes made to this routine must be done in the
10603  * version found below.
10604  *
10605  * Called from within the procedure above to deal with unsatisfied
10606  * allocation dependencies in an inodeblock. The buffer must be
10607  * locked, thus, no I/O completion operations can occur while we
10608  * are manipulating its associated dependencies.
10609  */
10610 static void
10611 initiate_write_inodeblock_ufs1(inodedep, bp)
10612 	struct inodedep *inodedep;
10613 	struct buf *bp;			/* The inode block */
10614 {
10615 	struct allocdirect *adp, *lastadp;
10616 	struct ufs1_dinode *dp;
10617 	struct ufs1_dinode *sip;
10618 	struct inoref *inoref;
10619 	struct ufsmount *ump;
10620 	struct fs *fs;
10621 	ufs_lbn_t i;
10622 #ifdef INVARIANTS
10623 	ufs_lbn_t prevlbn = 0;
10624 #endif
10625 	int deplist __diagused;
10626 
10627 	if (inodedep->id_state & IOSTARTED)
10628 		panic("initiate_write_inodeblock_ufs1: already started");
10629 	inodedep->id_state |= IOSTARTED;
10630 	fs = inodedep->id_fs;
10631 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10632 	LOCK_OWNED(ump);
10633 	dp = (struct ufs1_dinode *)bp->b_data +
10634 	    ino_to_fsbo(fs, inodedep->id_ino);
10635 
10636 	/*
10637 	 * If we're on the unlinked list but have not yet written our
10638 	 * next pointer initialize it here.
10639 	 */
10640 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10641 		struct inodedep *inon;
10642 
10643 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10644 		dp->di_freelink = inon ? inon->id_ino : 0;
10645 	}
10646 	/*
10647 	 * If the bitmap is not yet written, then the allocated
10648 	 * inode cannot be written to disk.
10649 	 */
10650 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10651 		if (inodedep->id_savedino1 != NULL)
10652 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10653 		FREE_LOCK(ump);
10654 		sip = malloc(sizeof(struct ufs1_dinode),
10655 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10656 		ACQUIRE_LOCK(ump);
10657 		inodedep->id_savedino1 = sip;
10658 		*inodedep->id_savedino1 = *dp;
10659 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10660 		dp->di_gen = inodedep->id_savedino1->di_gen;
10661 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10662 		return;
10663 	}
10664 	/*
10665 	 * If no dependencies, then there is nothing to roll back.
10666 	 */
10667 	inodedep->id_savedsize = dp->di_size;
10668 	inodedep->id_savedextsize = 0;
10669 	inodedep->id_savednlink = dp->di_nlink;
10670 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10671 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10672 		return;
10673 	/*
10674 	 * Revert the link count to that of the first unwritten journal entry.
10675 	 */
10676 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10677 	if (inoref)
10678 		dp->di_nlink = inoref->if_nlink;
10679 	/*
10680 	 * Set the dependencies to busy.
10681 	 */
10682 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10683 	     adp = TAILQ_NEXT(adp, ad_next)) {
10684 #ifdef INVARIANTS
10685 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10686 			panic("softdep_write_inodeblock: lbn order");
10687 		prevlbn = adp->ad_offset;
10688 		if (adp->ad_offset < UFS_NDADDR &&
10689 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10690 			panic("initiate_write_inodeblock_ufs1: "
10691 			    "direct pointer #%jd mismatch %d != %jd",
10692 			    (intmax_t)adp->ad_offset,
10693 			    dp->di_db[adp->ad_offset],
10694 			    (intmax_t)adp->ad_newblkno);
10695 		if (adp->ad_offset >= UFS_NDADDR &&
10696 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10697 			panic("initiate_write_inodeblock_ufs1: "
10698 			    "indirect pointer #%jd mismatch %d != %jd",
10699 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10700 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10701 			    (intmax_t)adp->ad_newblkno);
10702 		deplist |= 1 << adp->ad_offset;
10703 		if ((adp->ad_state & ATTACHED) == 0)
10704 			panic("initiate_write_inodeblock_ufs1: "
10705 			    "Unknown state 0x%x", adp->ad_state);
10706 #endif /* INVARIANTS */
10707 		adp->ad_state &= ~ATTACHED;
10708 		adp->ad_state |= UNDONE;
10709 	}
10710 	/*
10711 	 * The on-disk inode cannot claim to be any larger than the last
10712 	 * fragment that has been written. Otherwise, the on-disk inode
10713 	 * might have fragments that were not the last block in the file
10714 	 * which would corrupt the filesystem.
10715 	 */
10716 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10717 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10718 		if (adp->ad_offset >= UFS_NDADDR)
10719 			break;
10720 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10721 		/* keep going until hitting a rollback to a frag */
10722 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10723 			continue;
10724 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10725 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10726 #ifdef INVARIANTS
10727 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10728 				panic("initiate_write_inodeblock_ufs1: "
10729 				    "lost dep1");
10730 #endif /* INVARIANTS */
10731 			dp->di_db[i] = 0;
10732 		}
10733 		for (i = 0; i < UFS_NIADDR; i++) {
10734 #ifdef INVARIANTS
10735 			if (dp->di_ib[i] != 0 &&
10736 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10737 				panic("initiate_write_inodeblock_ufs1: "
10738 				    "lost dep2");
10739 #endif /* INVARIANTS */
10740 			dp->di_ib[i] = 0;
10741 		}
10742 		return;
10743 	}
10744 	/*
10745 	 * If we have zero'ed out the last allocated block of the file,
10746 	 * roll back the size to the last currently allocated block.
10747 	 * We know that this last allocated block is a full-sized as
10748 	 * we already checked for fragments in the loop above.
10749 	 */
10750 	if (lastadp != NULL &&
10751 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10752 		for (i = lastadp->ad_offset; i >= 0; i--)
10753 			if (dp->di_db[i] != 0)
10754 				break;
10755 		dp->di_size = (i + 1) * fs->fs_bsize;
10756 	}
10757 	/*
10758 	 * The only dependencies are for indirect blocks.
10759 	 *
10760 	 * The file size for indirect block additions is not guaranteed.
10761 	 * Such a guarantee would be non-trivial to achieve. The conventional
10762 	 * synchronous write implementation also does not make this guarantee.
10763 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10764 	 * can be over-estimated without destroying integrity when the file
10765 	 * moves into the indirect blocks (i.e., is large). If we want to
10766 	 * postpone fsck, we are stuck with this argument.
10767 	 */
10768 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10769 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10770 }
10771 
10772 /*
10773  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10774  * Note that any bug fixes made to this routine must be done in the
10775  * version found above.
10776  *
10777  * Called from within the procedure above to deal with unsatisfied
10778  * allocation dependencies in an inodeblock. The buffer must be
10779  * locked, thus, no I/O completion operations can occur while we
10780  * are manipulating its associated dependencies.
10781  */
10782 static void
10783 initiate_write_inodeblock_ufs2(inodedep, bp)
10784 	struct inodedep *inodedep;
10785 	struct buf *bp;			/* The inode block */
10786 {
10787 	struct allocdirect *adp, *lastadp;
10788 	struct ufs2_dinode *dp;
10789 	struct ufs2_dinode *sip;
10790 	struct inoref *inoref;
10791 	struct ufsmount *ump;
10792 	struct fs *fs;
10793 	ufs_lbn_t i;
10794 #ifdef INVARIANTS
10795 	ufs_lbn_t prevlbn = 0;
10796 #endif
10797 	int deplist __diagused;
10798 
10799 	if (inodedep->id_state & IOSTARTED)
10800 		panic("initiate_write_inodeblock_ufs2: already started");
10801 	inodedep->id_state |= IOSTARTED;
10802 	fs = inodedep->id_fs;
10803 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10804 	LOCK_OWNED(ump);
10805 	dp = (struct ufs2_dinode *)bp->b_data +
10806 	    ino_to_fsbo(fs, inodedep->id_ino);
10807 
10808 	/*
10809 	 * If we're on the unlinked list but have not yet written our
10810 	 * next pointer initialize it here.
10811 	 */
10812 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10813 		struct inodedep *inon;
10814 
10815 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10816 		dp->di_freelink = inon ? inon->id_ino : 0;
10817 		ffs_update_dinode_ckhash(fs, dp);
10818 	}
10819 	/*
10820 	 * If the bitmap is not yet written, then the allocated
10821 	 * inode cannot be written to disk.
10822 	 */
10823 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10824 		if (inodedep->id_savedino2 != NULL)
10825 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10826 		FREE_LOCK(ump);
10827 		sip = malloc(sizeof(struct ufs2_dinode),
10828 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10829 		ACQUIRE_LOCK(ump);
10830 		inodedep->id_savedino2 = sip;
10831 		*inodedep->id_savedino2 = *dp;
10832 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10833 		dp->di_gen = inodedep->id_savedino2->di_gen;
10834 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10835 		return;
10836 	}
10837 	/*
10838 	 * If no dependencies, then there is nothing to roll back.
10839 	 */
10840 	inodedep->id_savedsize = dp->di_size;
10841 	inodedep->id_savedextsize = dp->di_extsize;
10842 	inodedep->id_savednlink = dp->di_nlink;
10843 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10844 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10845 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10846 		return;
10847 	/*
10848 	 * Revert the link count to that of the first unwritten journal entry.
10849 	 */
10850 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10851 	if (inoref)
10852 		dp->di_nlink = inoref->if_nlink;
10853 
10854 	/*
10855 	 * Set the ext data dependencies to busy.
10856 	 */
10857 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10858 	     adp = TAILQ_NEXT(adp, ad_next)) {
10859 #ifdef INVARIANTS
10860 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10861 			panic("initiate_write_inodeblock_ufs2: lbn order");
10862 		prevlbn = adp->ad_offset;
10863 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10864 			panic("initiate_write_inodeblock_ufs2: "
10865 			    "ext pointer #%jd mismatch %jd != %jd",
10866 			    (intmax_t)adp->ad_offset,
10867 			    (intmax_t)dp->di_extb[adp->ad_offset],
10868 			    (intmax_t)adp->ad_newblkno);
10869 		deplist |= 1 << adp->ad_offset;
10870 		if ((adp->ad_state & ATTACHED) == 0)
10871 			panic("initiate_write_inodeblock_ufs2: Unknown "
10872 			    "state 0x%x", adp->ad_state);
10873 #endif /* INVARIANTS */
10874 		adp->ad_state &= ~ATTACHED;
10875 		adp->ad_state |= UNDONE;
10876 	}
10877 	/*
10878 	 * The on-disk inode cannot claim to be any larger than the last
10879 	 * fragment that has been written. Otherwise, the on-disk inode
10880 	 * might have fragments that were not the last block in the ext
10881 	 * data which would corrupt the filesystem.
10882 	 */
10883 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10884 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10885 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10886 		/* keep going until hitting a rollback to a frag */
10887 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10888 			continue;
10889 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10890 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10891 #ifdef INVARIANTS
10892 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10893 				panic("initiate_write_inodeblock_ufs2: "
10894 				    "lost dep1");
10895 #endif /* INVARIANTS */
10896 			dp->di_extb[i] = 0;
10897 		}
10898 		lastadp = NULL;
10899 		break;
10900 	}
10901 	/*
10902 	 * If we have zero'ed out the last allocated block of the ext
10903 	 * data, roll back the size to the last currently allocated block.
10904 	 * We know that this last allocated block is a full-sized as
10905 	 * we already checked for fragments in the loop above.
10906 	 */
10907 	if (lastadp != NULL &&
10908 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10909 		for (i = lastadp->ad_offset; i >= 0; i--)
10910 			if (dp->di_extb[i] != 0)
10911 				break;
10912 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10913 	}
10914 	/*
10915 	 * Set the file data dependencies to busy.
10916 	 */
10917 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10918 	     adp = TAILQ_NEXT(adp, ad_next)) {
10919 #ifdef INVARIANTS
10920 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10921 			panic("softdep_write_inodeblock: lbn order");
10922 		if ((adp->ad_state & ATTACHED) == 0)
10923 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10924 		prevlbn = adp->ad_offset;
10925 		if (!ffs_fsfail_cleanup(ump, 0) &&
10926 		    adp->ad_offset < UFS_NDADDR &&
10927 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10928 			panic("initiate_write_inodeblock_ufs2: "
10929 			    "direct pointer #%jd mismatch %jd != %jd",
10930 			    (intmax_t)adp->ad_offset,
10931 			    (intmax_t)dp->di_db[adp->ad_offset],
10932 			    (intmax_t)adp->ad_newblkno);
10933 		if (!ffs_fsfail_cleanup(ump, 0) &&
10934 		    adp->ad_offset >= UFS_NDADDR &&
10935 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10936 			panic("initiate_write_inodeblock_ufs2: "
10937 			    "indirect pointer #%jd mismatch %jd != %jd",
10938 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10939 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10940 			    (intmax_t)adp->ad_newblkno);
10941 		deplist |= 1 << adp->ad_offset;
10942 		if ((adp->ad_state & ATTACHED) == 0)
10943 			panic("initiate_write_inodeblock_ufs2: Unknown "
10944 			     "state 0x%x", adp->ad_state);
10945 #endif /* INVARIANTS */
10946 		adp->ad_state &= ~ATTACHED;
10947 		adp->ad_state |= UNDONE;
10948 	}
10949 	/*
10950 	 * The on-disk inode cannot claim to be any larger than the last
10951 	 * fragment that has been written. Otherwise, the on-disk inode
10952 	 * might have fragments that were not the last block in the file
10953 	 * which would corrupt the filesystem.
10954 	 */
10955 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10956 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10957 		if (adp->ad_offset >= UFS_NDADDR)
10958 			break;
10959 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10960 		/* keep going until hitting a rollback to a frag */
10961 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10962 			continue;
10963 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10964 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10965 #ifdef INVARIANTS
10966 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10967 				panic("initiate_write_inodeblock_ufs2: "
10968 				    "lost dep2");
10969 #endif /* INVARIANTS */
10970 			dp->di_db[i] = 0;
10971 		}
10972 		for (i = 0; i < UFS_NIADDR; i++) {
10973 #ifdef INVARIANTS
10974 			if (dp->di_ib[i] != 0 &&
10975 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10976 				panic("initiate_write_inodeblock_ufs2: "
10977 				    "lost dep3");
10978 #endif /* INVARIANTS */
10979 			dp->di_ib[i] = 0;
10980 		}
10981 		ffs_update_dinode_ckhash(fs, dp);
10982 		return;
10983 	}
10984 	/*
10985 	 * If we have zero'ed out the last allocated block of the file,
10986 	 * roll back the size to the last currently allocated block.
10987 	 * We know that this last allocated block is a full-sized as
10988 	 * we already checked for fragments in the loop above.
10989 	 */
10990 	if (lastadp != NULL &&
10991 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10992 		for (i = lastadp->ad_offset; i >= 0; i--)
10993 			if (dp->di_db[i] != 0)
10994 				break;
10995 		dp->di_size = (i + 1) * fs->fs_bsize;
10996 	}
10997 	/*
10998 	 * The only dependencies are for indirect blocks.
10999 	 *
11000 	 * The file size for indirect block additions is not guaranteed.
11001 	 * Such a guarantee would be non-trivial to achieve. The conventional
11002 	 * synchronous write implementation also does not make this guarantee.
11003 	 * Fsck should catch and fix discrepancies. Arguably, the file size
11004 	 * can be over-estimated without destroying integrity when the file
11005 	 * moves into the indirect blocks (i.e., is large). If we want to
11006 	 * postpone fsck, we are stuck with this argument.
11007 	 */
11008 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
11009 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
11010 	ffs_update_dinode_ckhash(fs, dp);
11011 }
11012 
11013 /*
11014  * Cancel an indirdep as a result of truncation.  Release all of the
11015  * children allocindirs and place their journal work on the appropriate
11016  * list.
11017  */
11018 static void
11019 cancel_indirdep(indirdep, bp, freeblks)
11020 	struct indirdep *indirdep;
11021 	struct buf *bp;
11022 	struct freeblks *freeblks;
11023 {
11024 	struct allocindir *aip;
11025 
11026 	/*
11027 	 * None of the indirect pointers will ever be visible,
11028 	 * so they can simply be tossed. GOINGAWAY ensures
11029 	 * that allocated pointers will be saved in the buffer
11030 	 * cache until they are freed. Note that they will
11031 	 * only be able to be found by their physical address
11032 	 * since the inode mapping the logical address will
11033 	 * be gone. The save buffer used for the safe copy
11034 	 * was allocated in setup_allocindir_phase2 using
11035 	 * the physical address so it could be used for this
11036 	 * purpose. Hence we swap the safe copy with the real
11037 	 * copy, allowing the safe copy to be freed and holding
11038 	 * on to the real copy for later use in indir_trunc.
11039 	 */
11040 	if (indirdep->ir_state & GOINGAWAY)
11041 		panic("cancel_indirdep: already gone");
11042 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11043 		indirdep->ir_state |= DEPCOMPLETE;
11044 		LIST_REMOVE(indirdep, ir_next);
11045 	}
11046 	indirdep->ir_state |= GOINGAWAY;
11047 	/*
11048 	 * Pass in bp for blocks still have journal writes
11049 	 * pending so we can cancel them on their own.
11050 	 */
11051 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
11052 		cancel_allocindir(aip, bp, freeblks, 0);
11053 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
11054 		cancel_allocindir(aip, NULL, freeblks, 0);
11055 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
11056 		cancel_allocindir(aip, NULL, freeblks, 0);
11057 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
11058 		cancel_allocindir(aip, NULL, freeblks, 0);
11059 	/*
11060 	 * If there are pending partial truncations we need to keep the
11061 	 * old block copy around until they complete.  This is because
11062 	 * the current b_data is not a perfect superset of the available
11063 	 * blocks.
11064 	 */
11065 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
11066 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
11067 	else
11068 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
11069 	WORKLIST_REMOVE(&indirdep->ir_list);
11070 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
11071 	indirdep->ir_bp = NULL;
11072 	indirdep->ir_freeblks = freeblks;
11073 }
11074 
11075 /*
11076  * Free an indirdep once it no longer has new pointers to track.
11077  */
11078 static void
11079 free_indirdep(indirdep)
11080 	struct indirdep *indirdep;
11081 {
11082 
11083 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
11084 	    ("free_indirdep: Indir trunc list not empty."));
11085 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
11086 	    ("free_indirdep: Complete head not empty."));
11087 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
11088 	    ("free_indirdep: write head not empty."));
11089 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
11090 	    ("free_indirdep: done head not empty."));
11091 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
11092 	    ("free_indirdep: deplist head not empty."));
11093 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
11094 	    ("free_indirdep: %p still on newblk list.", indirdep));
11095 	KASSERT(indirdep->ir_saveddata == NULL,
11096 	    ("free_indirdep: %p still has saved data.", indirdep));
11097 	KASSERT(indirdep->ir_savebp == NULL,
11098 	    ("free_indirdep: %p still has savebp buffer.", indirdep));
11099 	if (indirdep->ir_state & ONWORKLIST)
11100 		WORKLIST_REMOVE(&indirdep->ir_list);
11101 	WORKITEM_FREE(indirdep, D_INDIRDEP);
11102 }
11103 
11104 /*
11105  * Called before a write to an indirdep.  This routine is responsible for
11106  * rolling back pointers to a safe state which includes only those
11107  * allocindirs which have been completed.
11108  */
11109 static void
11110 initiate_write_indirdep(indirdep, bp)
11111 	struct indirdep *indirdep;
11112 	struct buf *bp;
11113 {
11114 	struct ufsmount *ump;
11115 
11116 	indirdep->ir_state |= IOSTARTED;
11117 	if (indirdep->ir_state & GOINGAWAY)
11118 		panic("disk_io_initiation: indirdep gone");
11119 	/*
11120 	 * If there are no remaining dependencies, this will be writing
11121 	 * the real pointers.
11122 	 */
11123 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
11124 	    TAILQ_EMPTY(&indirdep->ir_trunc))
11125 		return;
11126 	/*
11127 	 * Replace up-to-date version with safe version.
11128 	 */
11129 	if (indirdep->ir_saveddata == NULL) {
11130 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
11131 		LOCK_OWNED(ump);
11132 		FREE_LOCK(ump);
11133 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
11134 		    M_SOFTDEP_FLAGS);
11135 		ACQUIRE_LOCK(ump);
11136 	}
11137 	indirdep->ir_state &= ~ATTACHED;
11138 	indirdep->ir_state |= UNDONE;
11139 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
11140 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
11141 	    bp->b_bcount);
11142 }
11143 
11144 /*
11145  * Called when an inode has been cleared in a cg bitmap.  This finally
11146  * eliminates any canceled jaddrefs
11147  */
11148 void
11149 softdep_setup_inofree(mp, bp, ino, wkhd)
11150 	struct mount *mp;
11151 	struct buf *bp;
11152 	ino_t ino;
11153 	struct workhead *wkhd;
11154 {
11155 	struct worklist *wk, *wkn;
11156 	struct inodedep *inodedep;
11157 	struct ufsmount *ump;
11158 	uint8_t *inosused;
11159 	struct cg *cgp;
11160 	struct fs *fs;
11161 
11162 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
11163 	    ("softdep_setup_inofree called on non-softdep filesystem"));
11164 	ump = VFSTOUFS(mp);
11165 	ACQUIRE_LOCK(ump);
11166 	if (!ffs_fsfail_cleanup(ump, 0)) {
11167 		fs = ump->um_fs;
11168 		cgp = (struct cg *)bp->b_data;
11169 		inosused = cg_inosused(cgp);
11170 		if (isset(inosused, ino % fs->fs_ipg))
11171 			panic("softdep_setup_inofree: inode %ju not freed.",
11172 			    (uintmax_t)ino);
11173 	}
11174 	if (inodedep_lookup(mp, ino, 0, &inodedep))
11175 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
11176 		    (uintmax_t)ino, inodedep);
11177 	if (wkhd) {
11178 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
11179 			if (wk->wk_type != D_JADDREF)
11180 				continue;
11181 			WORKLIST_REMOVE(wk);
11182 			/*
11183 			 * We can free immediately even if the jaddref
11184 			 * isn't attached in a background write as now
11185 			 * the bitmaps are reconciled.
11186 			 */
11187 			wk->wk_state |= COMPLETE | ATTACHED;
11188 			free_jaddref(WK_JADDREF(wk));
11189 		}
11190 		jwork_move(&bp->b_dep, wkhd);
11191 	}
11192 	FREE_LOCK(ump);
11193 }
11194 
11195 /*
11196  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
11197  * map.  Any dependencies waiting for the write to clear are added to the
11198  * buf's list and any jnewblks that are being canceled are discarded
11199  * immediately.
11200  */
11201 void
11202 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
11203 	struct mount *mp;
11204 	struct buf *bp;
11205 	ufs2_daddr_t blkno;
11206 	int frags;
11207 	struct workhead *wkhd;
11208 {
11209 	struct bmsafemap *bmsafemap;
11210 	struct jnewblk *jnewblk;
11211 	struct ufsmount *ump;
11212 	struct worklist *wk;
11213 	struct fs *fs;
11214 #ifdef INVARIANTS
11215 	uint8_t *blksfree;
11216 	struct cg *cgp;
11217 	ufs2_daddr_t jstart;
11218 	ufs2_daddr_t jend;
11219 	ufs2_daddr_t end;
11220 	long bno;
11221 	int i;
11222 #endif
11223 
11224 	CTR3(KTR_SUJ,
11225 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
11226 	    blkno, frags, wkhd);
11227 
11228 	ump = VFSTOUFS(mp);
11229 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
11230 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
11231 	ACQUIRE_LOCK(ump);
11232 	/* Lookup the bmsafemap so we track when it is dirty. */
11233 	fs = ump->um_fs;
11234 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11235 	/*
11236 	 * Detach any jnewblks which have been canceled.  They must linger
11237 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
11238 	 * an unjournaled allocation from hitting the disk.
11239 	 */
11240 	if (wkhd) {
11241 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
11242 			CTR2(KTR_SUJ,
11243 			    "softdep_setup_blkfree: blkno %jd wk type %d",
11244 			    blkno, wk->wk_type);
11245 			WORKLIST_REMOVE(wk);
11246 			if (wk->wk_type != D_JNEWBLK) {
11247 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
11248 				continue;
11249 			}
11250 			jnewblk = WK_JNEWBLK(wk);
11251 			KASSERT(jnewblk->jn_state & GOINGAWAY,
11252 			    ("softdep_setup_blkfree: jnewblk not canceled."));
11253 #ifdef INVARIANTS
11254 			/*
11255 			 * Assert that this block is free in the bitmap
11256 			 * before we discard the jnewblk.
11257 			 */
11258 			cgp = (struct cg *)bp->b_data;
11259 			blksfree = cg_blksfree(cgp);
11260 			bno = dtogd(fs, jnewblk->jn_blkno);
11261 			for (i = jnewblk->jn_oldfrags;
11262 			    i < jnewblk->jn_frags; i++) {
11263 				if (isset(blksfree, bno + i))
11264 					continue;
11265 				panic("softdep_setup_blkfree: not free");
11266 			}
11267 #endif
11268 			/*
11269 			 * Even if it's not attached we can free immediately
11270 			 * as the new bitmap is correct.
11271 			 */
11272 			wk->wk_state |= COMPLETE | ATTACHED;
11273 			free_jnewblk(jnewblk);
11274 		}
11275 	}
11276 
11277 #ifdef INVARIANTS
11278 	/*
11279 	 * Assert that we are not freeing a block which has an outstanding
11280 	 * allocation dependency.
11281 	 */
11282 	fs = VFSTOUFS(mp)->um_fs;
11283 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11284 	end = blkno + frags;
11285 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11286 		/*
11287 		 * Don't match against blocks that will be freed when the
11288 		 * background write is done.
11289 		 */
11290 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
11291 		    (COMPLETE | DEPCOMPLETE))
11292 			continue;
11293 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
11294 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
11295 		if ((blkno >= jstart && blkno < jend) ||
11296 		    (end > jstart && end <= jend)) {
11297 			printf("state 0x%X %jd - %d %d dep %p\n",
11298 			    jnewblk->jn_state, jnewblk->jn_blkno,
11299 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
11300 			    jnewblk->jn_dep);
11301 			panic("softdep_setup_blkfree: "
11302 			    "%jd-%jd(%d) overlaps with %jd-%jd",
11303 			    blkno, end, frags, jstart, jend);
11304 		}
11305 	}
11306 #endif
11307 	FREE_LOCK(ump);
11308 }
11309 
11310 /*
11311  * Revert a block allocation when the journal record that describes it
11312  * is not yet written.
11313  */
11314 static int
11315 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
11316 	struct jnewblk *jnewblk;
11317 	struct fs *fs;
11318 	struct cg *cgp;
11319 	uint8_t *blksfree;
11320 {
11321 	ufs1_daddr_t fragno;
11322 	long cgbno, bbase;
11323 	int frags, blk;
11324 	int i;
11325 
11326 	frags = 0;
11327 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11328 	/*
11329 	 * We have to test which frags need to be rolled back.  We may
11330 	 * be operating on a stale copy when doing background writes.
11331 	 */
11332 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
11333 		if (isclr(blksfree, cgbno + i))
11334 			frags++;
11335 	if (frags == 0)
11336 		return (0);
11337 	/*
11338 	 * This is mostly ffs_blkfree() sans some validation and
11339 	 * superblock updates.
11340 	 */
11341 	if (frags == fs->fs_frag) {
11342 		fragno = fragstoblks(fs, cgbno);
11343 		ffs_setblock(fs, blksfree, fragno);
11344 		ffs_clusteracct(fs, cgp, fragno, 1);
11345 		cgp->cg_cs.cs_nbfree++;
11346 	} else {
11347 		cgbno += jnewblk->jn_oldfrags;
11348 		bbase = cgbno - fragnum(fs, cgbno);
11349 		/* Decrement the old frags.  */
11350 		blk = blkmap(fs, blksfree, bbase);
11351 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11352 		/* Deallocate the fragment */
11353 		for (i = 0; i < frags; i++)
11354 			setbit(blksfree, cgbno + i);
11355 		cgp->cg_cs.cs_nffree += frags;
11356 		/* Add back in counts associated with the new frags */
11357 		blk = blkmap(fs, blksfree, bbase);
11358 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11359 		/* If a complete block has been reassembled, account for it. */
11360 		fragno = fragstoblks(fs, bbase);
11361 		if (ffs_isblock(fs, blksfree, fragno)) {
11362 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
11363 			ffs_clusteracct(fs, cgp, fragno, 1);
11364 			cgp->cg_cs.cs_nbfree++;
11365 		}
11366 	}
11367 	stat_jnewblk++;
11368 	jnewblk->jn_state &= ~ATTACHED;
11369 	jnewblk->jn_state |= UNDONE;
11370 
11371 	return (frags);
11372 }
11373 
11374 static void
11375 initiate_write_bmsafemap(bmsafemap, bp)
11376 	struct bmsafemap *bmsafemap;
11377 	struct buf *bp;			/* The cg block. */
11378 {
11379 	struct jaddref *jaddref;
11380 	struct jnewblk *jnewblk;
11381 	uint8_t *inosused;
11382 	uint8_t *blksfree;
11383 	struct cg *cgp;
11384 	struct fs *fs;
11385 	ino_t ino;
11386 
11387 	/*
11388 	 * If this is a background write, we did this at the time that
11389 	 * the copy was made, so do not need to do it again.
11390 	 */
11391 	if (bmsafemap->sm_state & IOSTARTED)
11392 		return;
11393 	bmsafemap->sm_state |= IOSTARTED;
11394 	/*
11395 	 * Clear any inode allocations which are pending journal writes.
11396 	 */
11397 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11398 		cgp = (struct cg *)bp->b_data;
11399 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11400 		inosused = cg_inosused(cgp);
11401 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11402 			ino = jaddref->ja_ino % fs->fs_ipg;
11403 			if (isset(inosused, ino)) {
11404 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11405 					cgp->cg_cs.cs_ndir--;
11406 				cgp->cg_cs.cs_nifree++;
11407 				clrbit(inosused, ino);
11408 				jaddref->ja_state &= ~ATTACHED;
11409 				jaddref->ja_state |= UNDONE;
11410 				stat_jaddref++;
11411 			} else
11412 				panic("initiate_write_bmsafemap: inode %ju "
11413 				    "marked free", (uintmax_t)jaddref->ja_ino);
11414 		}
11415 	}
11416 	/*
11417 	 * Clear any block allocations which are pending journal writes.
11418 	 */
11419 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11420 		cgp = (struct cg *)bp->b_data;
11421 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11422 		blksfree = cg_blksfree(cgp);
11423 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11424 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11425 				continue;
11426 			panic("initiate_write_bmsafemap: block %jd "
11427 			    "marked free", jnewblk->jn_blkno);
11428 		}
11429 	}
11430 	/*
11431 	 * Move allocation lists to the written lists so they can be
11432 	 * cleared once the block write is complete.
11433 	 */
11434 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11435 	    inodedep, id_deps);
11436 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11437 	    newblk, nb_deps);
11438 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11439 	    wk_list);
11440 }
11441 
11442 void
11443 softdep_handle_error(struct buf *bp)
11444 {
11445 	struct ufsmount *ump;
11446 
11447 	ump = softdep_bp_to_mp(bp);
11448 	if (ump == NULL)
11449 		return;
11450 
11451 	if (ffs_fsfail_cleanup(ump, bp->b_error)) {
11452 		/*
11453 		 * No future writes will succeed, so the on-disk image is safe.
11454 		 * Pretend that this write succeeded so that the softdep state
11455 		 * will be cleaned up naturally.
11456 		 */
11457 		bp->b_ioflags &= ~BIO_ERROR;
11458 		bp->b_error = 0;
11459 	}
11460 }
11461 
11462 /*
11463  * This routine is called during the completion interrupt
11464  * service routine for a disk write (from the procedure called
11465  * by the device driver to inform the filesystem caches of
11466  * a request completion).  It should be called early in this
11467  * procedure, before the block is made available to other
11468  * processes or other routines are called.
11469  *
11470  */
11471 static void
11472 softdep_disk_write_complete(bp)
11473 	struct buf *bp;		/* describes the completed disk write */
11474 {
11475 	struct worklist *wk;
11476 	struct worklist *owk;
11477 	struct ufsmount *ump;
11478 	struct workhead reattach;
11479 	struct freeblks *freeblks;
11480 	struct buf *sbp;
11481 
11482 	ump = softdep_bp_to_mp(bp);
11483 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11484 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11485 	     "with outstanding dependencies for buffer %p", bp));
11486 	if (ump == NULL)
11487 		return;
11488 	if ((bp->b_ioflags & BIO_ERROR) != 0)
11489 		softdep_handle_error(bp);
11490 	/*
11491 	 * If an error occurred while doing the write, then the data
11492 	 * has not hit the disk and the dependencies cannot be processed.
11493 	 * But we do have to go through and roll forward any dependencies
11494 	 * that were rolled back before the disk write.
11495 	 */
11496 	sbp = NULL;
11497 	ACQUIRE_LOCK(ump);
11498 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11499 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11500 			switch (wk->wk_type) {
11501 			case D_PAGEDEP:
11502 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11503 				continue;
11504 
11505 			case D_INODEDEP:
11506 				handle_written_inodeblock(WK_INODEDEP(wk),
11507 				    bp, 0);
11508 				continue;
11509 
11510 			case D_BMSAFEMAP:
11511 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11512 				    bp, 0);
11513 				continue;
11514 
11515 			case D_INDIRDEP:
11516 				handle_written_indirdep(WK_INDIRDEP(wk),
11517 				    bp, &sbp, 0);
11518 				continue;
11519 			default:
11520 				/* nothing to roll forward */
11521 				continue;
11522 			}
11523 		}
11524 		FREE_LOCK(ump);
11525 		if (sbp)
11526 			brelse(sbp);
11527 		return;
11528 	}
11529 	LIST_INIT(&reattach);
11530 
11531 	/*
11532 	 * Ump SU lock must not be released anywhere in this code segment.
11533 	 */
11534 	owk = NULL;
11535 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11536 		WORKLIST_REMOVE(wk);
11537 		atomic_add_long(&dep_write[wk->wk_type], 1);
11538 		if (wk == owk)
11539 			panic("duplicate worklist: %p\n", wk);
11540 		owk = wk;
11541 		switch (wk->wk_type) {
11542 		case D_PAGEDEP:
11543 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11544 			    WRITESUCCEEDED))
11545 				WORKLIST_INSERT(&reattach, wk);
11546 			continue;
11547 
11548 		case D_INODEDEP:
11549 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11550 			    WRITESUCCEEDED))
11551 				WORKLIST_INSERT(&reattach, wk);
11552 			continue;
11553 
11554 		case D_BMSAFEMAP:
11555 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11556 			    WRITESUCCEEDED))
11557 				WORKLIST_INSERT(&reattach, wk);
11558 			continue;
11559 
11560 		case D_MKDIR:
11561 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11562 			continue;
11563 
11564 		case D_ALLOCDIRECT:
11565 			wk->wk_state |= COMPLETE;
11566 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11567 			continue;
11568 
11569 		case D_ALLOCINDIR:
11570 			wk->wk_state |= COMPLETE;
11571 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11572 			continue;
11573 
11574 		case D_INDIRDEP:
11575 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11576 			    WRITESUCCEEDED))
11577 				WORKLIST_INSERT(&reattach, wk);
11578 			continue;
11579 
11580 		case D_FREEBLKS:
11581 			wk->wk_state |= COMPLETE;
11582 			freeblks = WK_FREEBLKS(wk);
11583 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11584 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11585 				add_to_worklist(wk, WK_NODELAY);
11586 			continue;
11587 
11588 		case D_FREEWORK:
11589 			handle_written_freework(WK_FREEWORK(wk));
11590 			break;
11591 
11592 		case D_JSEGDEP:
11593 			free_jsegdep(WK_JSEGDEP(wk));
11594 			continue;
11595 
11596 		case D_JSEG:
11597 			handle_written_jseg(WK_JSEG(wk), bp);
11598 			continue;
11599 
11600 		case D_SBDEP:
11601 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11602 				WORKLIST_INSERT(&reattach, wk);
11603 			continue;
11604 
11605 		case D_FREEDEP:
11606 			free_freedep(WK_FREEDEP(wk));
11607 			continue;
11608 
11609 		default:
11610 			panic("handle_disk_write_complete: Unknown type %s",
11611 			    TYPENAME(wk->wk_type));
11612 			/* NOTREACHED */
11613 		}
11614 	}
11615 	/*
11616 	 * Reattach any requests that must be redone.
11617 	 */
11618 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11619 		WORKLIST_REMOVE(wk);
11620 		WORKLIST_INSERT(&bp->b_dep, wk);
11621 	}
11622 	FREE_LOCK(ump);
11623 	if (sbp)
11624 		brelse(sbp);
11625 }
11626 
11627 /*
11628  * Called from within softdep_disk_write_complete above.
11629  */
11630 static void
11631 handle_allocdirect_partdone(adp, wkhd)
11632 	struct allocdirect *adp;	/* the completed allocdirect */
11633 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11634 {
11635 	struct allocdirectlst *listhead;
11636 	struct allocdirect *listadp;
11637 	struct inodedep *inodedep;
11638 	long bsize;
11639 
11640 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11641 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11642 		return;
11643 	/*
11644 	 * The on-disk inode cannot claim to be any larger than the last
11645 	 * fragment that has been written. Otherwise, the on-disk inode
11646 	 * might have fragments that were not the last block in the file
11647 	 * which would corrupt the filesystem. Thus, we cannot free any
11648 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11649 	 * these blocks must be rolled back to zero before writing the inode.
11650 	 * We check the currently active set of allocdirects in id_inoupdt
11651 	 * or id_extupdt as appropriate.
11652 	 */
11653 	inodedep = adp->ad_inodedep;
11654 	bsize = inodedep->id_fs->fs_bsize;
11655 	if (adp->ad_state & EXTDATA)
11656 		listhead = &inodedep->id_extupdt;
11657 	else
11658 		listhead = &inodedep->id_inoupdt;
11659 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11660 		/* found our block */
11661 		if (listadp == adp)
11662 			break;
11663 		/* continue if ad_oldlbn is not a fragment */
11664 		if (listadp->ad_oldsize == 0 ||
11665 		    listadp->ad_oldsize == bsize)
11666 			continue;
11667 		/* hit a fragment */
11668 		return;
11669 	}
11670 	/*
11671 	 * If we have reached the end of the current list without
11672 	 * finding the just finished dependency, then it must be
11673 	 * on the future dependency list. Future dependencies cannot
11674 	 * be freed until they are moved to the current list.
11675 	 */
11676 	if (listadp == NULL) {
11677 #ifdef INVARIANTS
11678 		if (adp->ad_state & EXTDATA)
11679 			listhead = &inodedep->id_newextupdt;
11680 		else
11681 			listhead = &inodedep->id_newinoupdt;
11682 		TAILQ_FOREACH(listadp, listhead, ad_next)
11683 			/* found our block */
11684 			if (listadp == adp)
11685 				break;
11686 		if (listadp == NULL)
11687 			panic("handle_allocdirect_partdone: lost dep");
11688 #endif /* INVARIANTS */
11689 		return;
11690 	}
11691 	/*
11692 	 * If we have found the just finished dependency, then queue
11693 	 * it along with anything that follows it that is complete.
11694 	 * Since the pointer has not yet been written in the inode
11695 	 * as the dependency prevents it, place the allocdirect on the
11696 	 * bufwait list where it will be freed once the pointer is
11697 	 * valid.
11698 	 */
11699 	if (wkhd == NULL)
11700 		wkhd = &inodedep->id_bufwait;
11701 	for (; adp; adp = listadp) {
11702 		listadp = TAILQ_NEXT(adp, ad_next);
11703 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11704 			return;
11705 		TAILQ_REMOVE(listhead, adp, ad_next);
11706 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11707 	}
11708 }
11709 
11710 /*
11711  * Called from within softdep_disk_write_complete above.  This routine
11712  * completes successfully written allocindirs.
11713  */
11714 static void
11715 handle_allocindir_partdone(aip)
11716 	struct allocindir *aip;		/* the completed allocindir */
11717 {
11718 	struct indirdep *indirdep;
11719 
11720 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11721 		return;
11722 	indirdep = aip->ai_indirdep;
11723 	LIST_REMOVE(aip, ai_next);
11724 	/*
11725 	 * Don't set a pointer while the buffer is undergoing IO or while
11726 	 * we have active truncations.
11727 	 */
11728 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11729 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11730 		return;
11731 	}
11732 	if (indirdep->ir_state & UFS1FMT)
11733 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11734 		    aip->ai_newblkno;
11735 	else
11736 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11737 		    aip->ai_newblkno;
11738 	/*
11739 	 * Await the pointer write before freeing the allocindir.
11740 	 */
11741 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11742 }
11743 
11744 /*
11745  * Release segments held on a jwork list.
11746  */
11747 static void
11748 handle_jwork(wkhd)
11749 	struct workhead *wkhd;
11750 {
11751 	struct worklist *wk;
11752 
11753 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11754 		WORKLIST_REMOVE(wk);
11755 		switch (wk->wk_type) {
11756 		case D_JSEGDEP:
11757 			free_jsegdep(WK_JSEGDEP(wk));
11758 			continue;
11759 		case D_FREEDEP:
11760 			free_freedep(WK_FREEDEP(wk));
11761 			continue;
11762 		case D_FREEFRAG:
11763 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11764 			WORKITEM_FREE(wk, D_FREEFRAG);
11765 			continue;
11766 		case D_FREEWORK:
11767 			handle_written_freework(WK_FREEWORK(wk));
11768 			continue;
11769 		default:
11770 			panic("handle_jwork: Unknown type %s\n",
11771 			    TYPENAME(wk->wk_type));
11772 		}
11773 	}
11774 }
11775 
11776 /*
11777  * Handle the bufwait list on an inode when it is safe to release items
11778  * held there.  This normally happens after an inode block is written but
11779  * may be delayed and handled later if there are pending journal items that
11780  * are not yet safe to be released.
11781  */
11782 static struct freefile *
11783 handle_bufwait(inodedep, refhd)
11784 	struct inodedep *inodedep;
11785 	struct workhead *refhd;
11786 {
11787 	struct jaddref *jaddref;
11788 	struct freefile *freefile;
11789 	struct worklist *wk;
11790 
11791 	freefile = NULL;
11792 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11793 		WORKLIST_REMOVE(wk);
11794 		switch (wk->wk_type) {
11795 		case D_FREEFILE:
11796 			/*
11797 			 * We defer adding freefile to the worklist
11798 			 * until all other additions have been made to
11799 			 * ensure that it will be done after all the
11800 			 * old blocks have been freed.
11801 			 */
11802 			if (freefile != NULL)
11803 				panic("handle_bufwait: freefile");
11804 			freefile = WK_FREEFILE(wk);
11805 			continue;
11806 
11807 		case D_MKDIR:
11808 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11809 			continue;
11810 
11811 		case D_DIRADD:
11812 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11813 			continue;
11814 
11815 		case D_FREEFRAG:
11816 			wk->wk_state |= COMPLETE;
11817 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11818 				add_to_worklist(wk, 0);
11819 			continue;
11820 
11821 		case D_DIRREM:
11822 			wk->wk_state |= COMPLETE;
11823 			add_to_worklist(wk, 0);
11824 			continue;
11825 
11826 		case D_ALLOCDIRECT:
11827 		case D_ALLOCINDIR:
11828 			free_newblk(WK_NEWBLK(wk));
11829 			continue;
11830 
11831 		case D_JNEWBLK:
11832 			wk->wk_state |= COMPLETE;
11833 			free_jnewblk(WK_JNEWBLK(wk));
11834 			continue;
11835 
11836 		/*
11837 		 * Save freed journal segments and add references on
11838 		 * the supplied list which will delay their release
11839 		 * until the cg bitmap is cleared on disk.
11840 		 */
11841 		case D_JSEGDEP:
11842 			if (refhd == NULL)
11843 				free_jsegdep(WK_JSEGDEP(wk));
11844 			else
11845 				WORKLIST_INSERT(refhd, wk);
11846 			continue;
11847 
11848 		case D_JADDREF:
11849 			jaddref = WK_JADDREF(wk);
11850 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11851 			    if_deps);
11852 			/*
11853 			 * Transfer any jaddrefs to the list to be freed with
11854 			 * the bitmap if we're handling a removed file.
11855 			 */
11856 			if (refhd == NULL) {
11857 				wk->wk_state |= COMPLETE;
11858 				free_jaddref(jaddref);
11859 			} else
11860 				WORKLIST_INSERT(refhd, wk);
11861 			continue;
11862 
11863 		default:
11864 			panic("handle_bufwait: Unknown type %p(%s)",
11865 			    wk, TYPENAME(wk->wk_type));
11866 			/* NOTREACHED */
11867 		}
11868 	}
11869 	return (freefile);
11870 }
11871 /*
11872  * Called from within softdep_disk_write_complete above to restore
11873  * in-memory inode block contents to their most up-to-date state. Note
11874  * that this routine is always called from interrupt level with further
11875  * interrupts from this device blocked.
11876  *
11877  * If the write did not succeed, we will do all the roll-forward
11878  * operations, but we will not take the actions that will allow its
11879  * dependencies to be processed.
11880  */
11881 static int
11882 handle_written_inodeblock(inodedep, bp, flags)
11883 	struct inodedep *inodedep;
11884 	struct buf *bp;		/* buffer containing the inode block */
11885 	int flags;
11886 {
11887 	struct freefile *freefile;
11888 	struct allocdirect *adp, *nextadp;
11889 	struct ufs1_dinode *dp1 = NULL;
11890 	struct ufs2_dinode *dp2 = NULL;
11891 	struct workhead wkhd;
11892 	int hadchanges, fstype;
11893 	ino_t freelink;
11894 
11895 	LIST_INIT(&wkhd);
11896 	hadchanges = 0;
11897 	freefile = NULL;
11898 	if ((inodedep->id_state & IOSTARTED) == 0)
11899 		panic("handle_written_inodeblock: not started");
11900 	inodedep->id_state &= ~IOSTARTED;
11901 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11902 		fstype = UFS1;
11903 		dp1 = (struct ufs1_dinode *)bp->b_data +
11904 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11905 		freelink = dp1->di_freelink;
11906 	} else {
11907 		fstype = UFS2;
11908 		dp2 = (struct ufs2_dinode *)bp->b_data +
11909 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11910 		freelink = dp2->di_freelink;
11911 	}
11912 	/*
11913 	 * Leave this inodeblock dirty until it's in the list.
11914 	 */
11915 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11916 	    (flags & WRITESUCCEEDED)) {
11917 		struct inodedep *inon;
11918 
11919 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11920 		if ((inon == NULL && freelink == 0) ||
11921 		    (inon && inon->id_ino == freelink)) {
11922 			if (inon)
11923 				inon->id_state |= UNLINKPREV;
11924 			inodedep->id_state |= UNLINKNEXT;
11925 		}
11926 		hadchanges = 1;
11927 	}
11928 	/*
11929 	 * If we had to rollback the inode allocation because of
11930 	 * bitmaps being incomplete, then simply restore it.
11931 	 * Keep the block dirty so that it will not be reclaimed until
11932 	 * all associated dependencies have been cleared and the
11933 	 * corresponding updates written to disk.
11934 	 */
11935 	if (inodedep->id_savedino1 != NULL) {
11936 		hadchanges = 1;
11937 		if (fstype == UFS1)
11938 			*dp1 = *inodedep->id_savedino1;
11939 		else
11940 			*dp2 = *inodedep->id_savedino2;
11941 		free(inodedep->id_savedino1, M_SAVEDINO);
11942 		inodedep->id_savedino1 = NULL;
11943 		if ((bp->b_flags & B_DELWRI) == 0)
11944 			stat_inode_bitmap++;
11945 		bdirty(bp);
11946 		/*
11947 		 * If the inode is clear here and GOINGAWAY it will never
11948 		 * be written.  Process the bufwait and clear any pending
11949 		 * work which may include the freefile.
11950 		 */
11951 		if (inodedep->id_state & GOINGAWAY)
11952 			goto bufwait;
11953 		return (1);
11954 	}
11955 	if (flags & WRITESUCCEEDED)
11956 		inodedep->id_state |= COMPLETE;
11957 	/*
11958 	 * Roll forward anything that had to be rolled back before
11959 	 * the inode could be updated.
11960 	 */
11961 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11962 		nextadp = TAILQ_NEXT(adp, ad_next);
11963 		if (adp->ad_state & ATTACHED)
11964 			panic("handle_written_inodeblock: new entry");
11965 		if (fstype == UFS1) {
11966 			if (adp->ad_offset < UFS_NDADDR) {
11967 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11968 					panic("%s %s #%jd mismatch %d != %jd",
11969 					    "handle_written_inodeblock:",
11970 					    "direct pointer",
11971 					    (intmax_t)adp->ad_offset,
11972 					    dp1->di_db[adp->ad_offset],
11973 					    (intmax_t)adp->ad_oldblkno);
11974 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11975 			} else {
11976 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11977 				    0)
11978 					panic("%s: %s #%jd allocated as %d",
11979 					    "handle_written_inodeblock",
11980 					    "indirect pointer",
11981 					    (intmax_t)adp->ad_offset -
11982 					    UFS_NDADDR,
11983 					    dp1->di_ib[adp->ad_offset -
11984 					    UFS_NDADDR]);
11985 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11986 				    adp->ad_newblkno;
11987 			}
11988 		} else {
11989 			if (adp->ad_offset < UFS_NDADDR) {
11990 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11991 					panic("%s: %s #%jd %s %jd != %jd",
11992 					    "handle_written_inodeblock",
11993 					    "direct pointer",
11994 					    (intmax_t)adp->ad_offset, "mismatch",
11995 					    (intmax_t)dp2->di_db[adp->ad_offset],
11996 					    (intmax_t)adp->ad_oldblkno);
11997 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11998 			} else {
11999 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
12000 				    0)
12001 					panic("%s: %s #%jd allocated as %jd",
12002 					    "handle_written_inodeblock",
12003 					    "indirect pointer",
12004 					    (intmax_t)adp->ad_offset -
12005 					    UFS_NDADDR,
12006 					    (intmax_t)
12007 					    dp2->di_ib[adp->ad_offset -
12008 					    UFS_NDADDR]);
12009 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
12010 				    adp->ad_newblkno;
12011 			}
12012 		}
12013 		adp->ad_state &= ~UNDONE;
12014 		adp->ad_state |= ATTACHED;
12015 		hadchanges = 1;
12016 	}
12017 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
12018 		nextadp = TAILQ_NEXT(adp, ad_next);
12019 		if (adp->ad_state & ATTACHED)
12020 			panic("handle_written_inodeblock: new entry");
12021 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
12022 			panic("%s: direct pointers #%jd %s %jd != %jd",
12023 			    "handle_written_inodeblock",
12024 			    (intmax_t)adp->ad_offset, "mismatch",
12025 			    (intmax_t)dp2->di_extb[adp->ad_offset],
12026 			    (intmax_t)adp->ad_oldblkno);
12027 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
12028 		adp->ad_state &= ~UNDONE;
12029 		adp->ad_state |= ATTACHED;
12030 		hadchanges = 1;
12031 	}
12032 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
12033 		stat_direct_blk_ptrs++;
12034 	/*
12035 	 * Reset the file size to its most up-to-date value.
12036 	 */
12037 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
12038 		panic("handle_written_inodeblock: bad size");
12039 	if (inodedep->id_savednlink > UFS_LINK_MAX)
12040 		panic("handle_written_inodeblock: Invalid link count "
12041 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
12042 		    inodedep);
12043 	if (fstype == UFS1) {
12044 		if (dp1->di_nlink != inodedep->id_savednlink) {
12045 			dp1->di_nlink = inodedep->id_savednlink;
12046 			hadchanges = 1;
12047 		}
12048 		if (dp1->di_size != inodedep->id_savedsize) {
12049 			dp1->di_size = inodedep->id_savedsize;
12050 			hadchanges = 1;
12051 		}
12052 	} else {
12053 		if (dp2->di_nlink != inodedep->id_savednlink) {
12054 			dp2->di_nlink = inodedep->id_savednlink;
12055 			hadchanges = 1;
12056 		}
12057 		if (dp2->di_size != inodedep->id_savedsize) {
12058 			dp2->di_size = inodedep->id_savedsize;
12059 			hadchanges = 1;
12060 		}
12061 		if (dp2->di_extsize != inodedep->id_savedextsize) {
12062 			dp2->di_extsize = inodedep->id_savedextsize;
12063 			hadchanges = 1;
12064 		}
12065 	}
12066 	inodedep->id_savedsize = -1;
12067 	inodedep->id_savedextsize = -1;
12068 	inodedep->id_savednlink = -1;
12069 	/*
12070 	 * If there were any rollbacks in the inode block, then it must be
12071 	 * marked dirty so that its will eventually get written back in
12072 	 * its correct form.
12073 	 */
12074 	if (hadchanges) {
12075 		if (fstype == UFS2)
12076 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
12077 		bdirty(bp);
12078 	}
12079 bufwait:
12080 	/*
12081 	 * If the write did not succeed, we have done all the roll-forward
12082 	 * operations, but we cannot take the actions that will allow its
12083 	 * dependencies to be processed.
12084 	 */
12085 	if ((flags & WRITESUCCEEDED) == 0)
12086 		return (hadchanges);
12087 	/*
12088 	 * Process any allocdirects that completed during the update.
12089 	 */
12090 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
12091 		handle_allocdirect_partdone(adp, &wkhd);
12092 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
12093 		handle_allocdirect_partdone(adp, &wkhd);
12094 	/*
12095 	 * Process deallocations that were held pending until the
12096 	 * inode had been written to disk. Freeing of the inode
12097 	 * is delayed until after all blocks have been freed to
12098 	 * avoid creation of new <vfsid, inum, lbn> triples
12099 	 * before the old ones have been deleted.  Completely
12100 	 * unlinked inodes are not processed until the unlinked
12101 	 * inode list is written or the last reference is removed.
12102 	 */
12103 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
12104 		freefile = handle_bufwait(inodedep, NULL);
12105 		if (freefile && !LIST_EMPTY(&wkhd)) {
12106 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
12107 			freefile = NULL;
12108 		}
12109 	}
12110 	/*
12111 	 * Move rolled forward dependency completions to the bufwait list
12112 	 * now that those that were already written have been processed.
12113 	 */
12114 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
12115 		panic("handle_written_inodeblock: bufwait but no changes");
12116 	jwork_move(&inodedep->id_bufwait, &wkhd);
12117 
12118 	if (freefile != NULL) {
12119 		/*
12120 		 * If the inode is goingaway it was never written.  Fake up
12121 		 * the state here so free_inodedep() can succeed.
12122 		 */
12123 		if (inodedep->id_state & GOINGAWAY)
12124 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
12125 		if (free_inodedep(inodedep) == 0)
12126 			panic("handle_written_inodeblock: live inodedep %p",
12127 			    inodedep);
12128 		add_to_worklist(&freefile->fx_list, 0);
12129 		return (0);
12130 	}
12131 
12132 	/*
12133 	 * If no outstanding dependencies, free it.
12134 	 */
12135 	if (free_inodedep(inodedep) ||
12136 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
12137 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
12138 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
12139 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
12140 		return (0);
12141 	return (hadchanges);
12142 }
12143 
12144 /*
12145  * Perform needed roll-forwards and kick off any dependencies that
12146  * can now be processed.
12147  *
12148  * If the write did not succeed, we will do all the roll-forward
12149  * operations, but we will not take the actions that will allow its
12150  * dependencies to be processed.
12151  */
12152 static int
12153 handle_written_indirdep(indirdep, bp, bpp, flags)
12154 	struct indirdep *indirdep;
12155 	struct buf *bp;
12156 	struct buf **bpp;
12157 	int flags;
12158 {
12159 	struct allocindir *aip;
12160 	struct buf *sbp;
12161 	int chgs;
12162 
12163 	if (indirdep->ir_state & GOINGAWAY)
12164 		panic("handle_written_indirdep: indirdep gone");
12165 	if ((indirdep->ir_state & IOSTARTED) == 0)
12166 		panic("handle_written_indirdep: IO not started");
12167 	chgs = 0;
12168 	/*
12169 	 * If there were rollbacks revert them here.
12170 	 */
12171 	if (indirdep->ir_saveddata) {
12172 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
12173 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
12174 			free(indirdep->ir_saveddata, M_INDIRDEP);
12175 			indirdep->ir_saveddata = NULL;
12176 		}
12177 		chgs = 1;
12178 	}
12179 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
12180 	indirdep->ir_state |= ATTACHED;
12181 	/*
12182 	 * If the write did not succeed, we have done all the roll-forward
12183 	 * operations, but we cannot take the actions that will allow its
12184 	 * dependencies to be processed.
12185 	 */
12186 	if ((flags & WRITESUCCEEDED) == 0) {
12187 		stat_indir_blk_ptrs++;
12188 		bdirty(bp);
12189 		return (1);
12190 	}
12191 	/*
12192 	 * Move allocindirs with written pointers to the completehd if
12193 	 * the indirdep's pointer is not yet written.  Otherwise
12194 	 * free them here.
12195 	 */
12196 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
12197 		LIST_REMOVE(aip, ai_next);
12198 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
12199 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
12200 			    ai_next);
12201 			newblk_freefrag(&aip->ai_block);
12202 			continue;
12203 		}
12204 		free_newblk(&aip->ai_block);
12205 	}
12206 	/*
12207 	 * Move allocindirs that have finished dependency processing from
12208 	 * the done list to the write list after updating the pointers.
12209 	 */
12210 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
12211 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
12212 			handle_allocindir_partdone(aip);
12213 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
12214 				panic("disk_write_complete: not gone");
12215 			chgs = 1;
12216 		}
12217 	}
12218 	/*
12219 	 * Preserve the indirdep if there were any changes or if it is not
12220 	 * yet valid on disk.
12221 	 */
12222 	if (chgs) {
12223 		stat_indir_blk_ptrs++;
12224 		bdirty(bp);
12225 		return (1);
12226 	}
12227 	/*
12228 	 * If there were no changes we can discard the savedbp and detach
12229 	 * ourselves from the buf.  We are only carrying completed pointers
12230 	 * in this case.
12231 	 */
12232 	sbp = indirdep->ir_savebp;
12233 	sbp->b_flags |= B_INVAL | B_NOCACHE;
12234 	indirdep->ir_savebp = NULL;
12235 	indirdep->ir_bp = NULL;
12236 	if (*bpp != NULL)
12237 		panic("handle_written_indirdep: bp already exists.");
12238 	*bpp = sbp;
12239 	/*
12240 	 * The indirdep may not be freed until its parent points at it.
12241 	 */
12242 	if (indirdep->ir_state & DEPCOMPLETE)
12243 		free_indirdep(indirdep);
12244 
12245 	return (0);
12246 }
12247 
12248 /*
12249  * Process a diradd entry after its dependent inode has been written.
12250  */
12251 static void
12252 diradd_inode_written(dap, inodedep)
12253 	struct diradd *dap;
12254 	struct inodedep *inodedep;
12255 {
12256 
12257 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
12258 	dap->da_state |= COMPLETE;
12259 	complete_diradd(dap);
12260 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
12261 }
12262 
12263 /*
12264  * Returns true if the bmsafemap will have rollbacks when written.  Must only
12265  * be called with the per-filesystem lock and the buf lock on the cg held.
12266  */
12267 static int
12268 bmsafemap_backgroundwrite(bmsafemap, bp)
12269 	struct bmsafemap *bmsafemap;
12270 	struct buf *bp;
12271 {
12272 	int dirty;
12273 
12274 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
12275 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
12276 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
12277 	/*
12278 	 * If we're initiating a background write we need to process the
12279 	 * rollbacks as they exist now, not as they exist when IO starts.
12280 	 * No other consumers will look at the contents of the shadowed
12281 	 * buf so this is safe to do here.
12282 	 */
12283 	if (bp->b_xflags & BX_BKGRDMARKER)
12284 		initiate_write_bmsafemap(bmsafemap, bp);
12285 
12286 	return (dirty);
12287 }
12288 
12289 /*
12290  * Re-apply an allocation when a cg write is complete.
12291  */
12292 static int
12293 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
12294 	struct jnewblk *jnewblk;
12295 	struct fs *fs;
12296 	struct cg *cgp;
12297 	uint8_t *blksfree;
12298 {
12299 	ufs1_daddr_t fragno;
12300 	ufs2_daddr_t blkno;
12301 	long cgbno, bbase;
12302 	int frags, blk;
12303 	int i;
12304 
12305 	frags = 0;
12306 	cgbno = dtogd(fs, jnewblk->jn_blkno);
12307 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
12308 		if (isclr(blksfree, cgbno + i))
12309 			panic("jnewblk_rollforward: re-allocated fragment");
12310 		frags++;
12311 	}
12312 	if (frags == fs->fs_frag) {
12313 		blkno = fragstoblks(fs, cgbno);
12314 		ffs_clrblock(fs, blksfree, (long)blkno);
12315 		ffs_clusteracct(fs, cgp, blkno, -1);
12316 		cgp->cg_cs.cs_nbfree--;
12317 	} else {
12318 		bbase = cgbno - fragnum(fs, cgbno);
12319 		cgbno += jnewblk->jn_oldfrags;
12320                 /* If a complete block had been reassembled, account for it. */
12321 		fragno = fragstoblks(fs, bbase);
12322 		if (ffs_isblock(fs, blksfree, fragno)) {
12323 			cgp->cg_cs.cs_nffree += fs->fs_frag;
12324 			ffs_clusteracct(fs, cgp, fragno, -1);
12325 			cgp->cg_cs.cs_nbfree--;
12326 		}
12327 		/* Decrement the old frags.  */
12328 		blk = blkmap(fs, blksfree, bbase);
12329 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
12330 		/* Allocate the fragment */
12331 		for (i = 0; i < frags; i++)
12332 			clrbit(blksfree, cgbno + i);
12333 		cgp->cg_cs.cs_nffree -= frags;
12334 		/* Add back in counts associated with the new frags */
12335 		blk = blkmap(fs, blksfree, bbase);
12336 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
12337 	}
12338 	return (frags);
12339 }
12340 
12341 /*
12342  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
12343  * changes if it's not a background write.  Set all written dependencies
12344  * to DEPCOMPLETE and free the structure if possible.
12345  *
12346  * If the write did not succeed, we will do all the roll-forward
12347  * operations, but we will not take the actions that will allow its
12348  * dependencies to be processed.
12349  */
12350 static int
12351 handle_written_bmsafemap(bmsafemap, bp, flags)
12352 	struct bmsafemap *bmsafemap;
12353 	struct buf *bp;
12354 	int flags;
12355 {
12356 	struct newblk *newblk;
12357 	struct inodedep *inodedep;
12358 	struct jaddref *jaddref, *jatmp;
12359 	struct jnewblk *jnewblk, *jntmp;
12360 	struct ufsmount *ump;
12361 	uint8_t *inosused;
12362 	uint8_t *blksfree;
12363 	struct cg *cgp;
12364 	struct fs *fs;
12365 	ino_t ino;
12366 	int foreground;
12367 	int chgs;
12368 
12369 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
12370 		panic("handle_written_bmsafemap: Not started\n");
12371 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
12372 	chgs = 0;
12373 	bmsafemap->sm_state &= ~IOSTARTED;
12374 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
12375 	/*
12376 	 * If write was successful, release journal work that was waiting
12377 	 * on the write. Otherwise move the work back.
12378 	 */
12379 	if (flags & WRITESUCCEEDED)
12380 		handle_jwork(&bmsafemap->sm_freewr);
12381 	else
12382 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12383 		    worklist, wk_list);
12384 
12385 	/*
12386 	 * Restore unwritten inode allocation pending jaddref writes.
12387 	 */
12388 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
12389 		cgp = (struct cg *)bp->b_data;
12390 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12391 		inosused = cg_inosused(cgp);
12392 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
12393 		    ja_bmdeps, jatmp) {
12394 			if ((jaddref->ja_state & UNDONE) == 0)
12395 				continue;
12396 			ino = jaddref->ja_ino % fs->fs_ipg;
12397 			if (isset(inosused, ino))
12398 				panic("handle_written_bmsafemap: "
12399 				    "re-allocated inode");
12400 			/* Do the roll-forward only if it's a real copy. */
12401 			if (foreground) {
12402 				if ((jaddref->ja_mode & IFMT) == IFDIR)
12403 					cgp->cg_cs.cs_ndir++;
12404 				cgp->cg_cs.cs_nifree--;
12405 				setbit(inosused, ino);
12406 				chgs = 1;
12407 			}
12408 			jaddref->ja_state &= ~UNDONE;
12409 			jaddref->ja_state |= ATTACHED;
12410 			free_jaddref(jaddref);
12411 		}
12412 	}
12413 	/*
12414 	 * Restore any block allocations which are pending journal writes.
12415 	 */
12416 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12417 		cgp = (struct cg *)bp->b_data;
12418 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12419 		blksfree = cg_blksfree(cgp);
12420 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12421 		    jntmp) {
12422 			if ((jnewblk->jn_state & UNDONE) == 0)
12423 				continue;
12424 			/* Do the roll-forward only if it's a real copy. */
12425 			if (foreground &&
12426 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12427 				chgs = 1;
12428 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12429 			jnewblk->jn_state |= ATTACHED;
12430 			free_jnewblk(jnewblk);
12431 		}
12432 	}
12433 	/*
12434 	 * If the write did not succeed, we have done all the roll-forward
12435 	 * operations, but we cannot take the actions that will allow its
12436 	 * dependencies to be processed.
12437 	 */
12438 	if ((flags & WRITESUCCEEDED) == 0) {
12439 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12440 		    newblk, nb_deps);
12441 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12442 		    worklist, wk_list);
12443 		if (foreground)
12444 			bdirty(bp);
12445 		return (1);
12446 	}
12447 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12448 		newblk->nb_state |= DEPCOMPLETE;
12449 		newblk->nb_state &= ~ONDEPLIST;
12450 		newblk->nb_bmsafemap = NULL;
12451 		LIST_REMOVE(newblk, nb_deps);
12452 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12453 			handle_allocdirect_partdone(
12454 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12455 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12456 			handle_allocindir_partdone(
12457 			    WK_ALLOCINDIR(&newblk->nb_list));
12458 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12459 			panic("handle_written_bmsafemap: Unexpected type: %s",
12460 			    TYPENAME(newblk->nb_list.wk_type));
12461 	}
12462 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12463 		inodedep->id_state |= DEPCOMPLETE;
12464 		inodedep->id_state &= ~ONDEPLIST;
12465 		LIST_REMOVE(inodedep, id_deps);
12466 		inodedep->id_bmsafemap = NULL;
12467 	}
12468 	LIST_REMOVE(bmsafemap, sm_next);
12469 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12470 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12471 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12472 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12473 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12474 		LIST_REMOVE(bmsafemap, sm_hash);
12475 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12476 		return (0);
12477 	}
12478 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12479 	if (foreground)
12480 		bdirty(bp);
12481 	return (1);
12482 }
12483 
12484 /*
12485  * Try to free a mkdir dependency.
12486  */
12487 static void
12488 complete_mkdir(mkdir)
12489 	struct mkdir *mkdir;
12490 {
12491 	struct diradd *dap;
12492 
12493 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12494 		return;
12495 	LIST_REMOVE(mkdir, md_mkdirs);
12496 	dap = mkdir->md_diradd;
12497 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12498 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12499 		dap->da_state |= DEPCOMPLETE;
12500 		complete_diradd(dap);
12501 	}
12502 	WORKITEM_FREE(mkdir, D_MKDIR);
12503 }
12504 
12505 /*
12506  * Handle the completion of a mkdir dependency.
12507  */
12508 static void
12509 handle_written_mkdir(mkdir, type)
12510 	struct mkdir *mkdir;
12511 	int type;
12512 {
12513 
12514 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12515 		panic("handle_written_mkdir: bad type");
12516 	mkdir->md_state |= COMPLETE;
12517 	complete_mkdir(mkdir);
12518 }
12519 
12520 static int
12521 free_pagedep(pagedep)
12522 	struct pagedep *pagedep;
12523 {
12524 	int i;
12525 
12526 	if (pagedep->pd_state & NEWBLOCK)
12527 		return (0);
12528 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12529 		return (0);
12530 	for (i = 0; i < DAHASHSZ; i++)
12531 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12532 			return (0);
12533 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12534 		return (0);
12535 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12536 		return (0);
12537 	if (pagedep->pd_state & ONWORKLIST)
12538 		WORKLIST_REMOVE(&pagedep->pd_list);
12539 	LIST_REMOVE(pagedep, pd_hash);
12540 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12541 
12542 	return (1);
12543 }
12544 
12545 /*
12546  * Called from within softdep_disk_write_complete above.
12547  * A write operation was just completed. Removed inodes can
12548  * now be freed and associated block pointers may be committed.
12549  * Note that this routine is always called from interrupt level
12550  * with further interrupts from this device blocked.
12551  *
12552  * If the write did not succeed, we will do all the roll-forward
12553  * operations, but we will not take the actions that will allow its
12554  * dependencies to be processed.
12555  */
12556 static int
12557 handle_written_filepage(pagedep, bp, flags)
12558 	struct pagedep *pagedep;
12559 	struct buf *bp;		/* buffer containing the written page */
12560 	int flags;
12561 {
12562 	struct dirrem *dirrem;
12563 	struct diradd *dap, *nextdap;
12564 	struct direct *ep;
12565 	int i, chgs;
12566 
12567 	if ((pagedep->pd_state & IOSTARTED) == 0)
12568 		panic("handle_written_filepage: not started");
12569 	pagedep->pd_state &= ~IOSTARTED;
12570 	if ((flags & WRITESUCCEEDED) == 0)
12571 		goto rollforward;
12572 	/*
12573 	 * Process any directory removals that have been committed.
12574 	 */
12575 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12576 		LIST_REMOVE(dirrem, dm_next);
12577 		dirrem->dm_state |= COMPLETE;
12578 		dirrem->dm_dirinum = pagedep->pd_ino;
12579 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12580 		    ("handle_written_filepage: Journal entries not written."));
12581 		add_to_worklist(&dirrem->dm_list, 0);
12582 	}
12583 	/*
12584 	 * Free any directory additions that have been committed.
12585 	 * If it is a newly allocated block, we have to wait until
12586 	 * the on-disk directory inode claims the new block.
12587 	 */
12588 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12589 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12590 			free_diradd(dap, NULL);
12591 rollforward:
12592 	/*
12593 	 * Uncommitted directory entries must be restored.
12594 	 */
12595 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12596 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12597 		     dap = nextdap) {
12598 			nextdap = LIST_NEXT(dap, da_pdlist);
12599 			if (dap->da_state & ATTACHED)
12600 				panic("handle_written_filepage: attached");
12601 			ep = (struct direct *)
12602 			    ((char *)bp->b_data + dap->da_offset);
12603 			ep->d_ino = dap->da_newinum;
12604 			dap->da_state &= ~UNDONE;
12605 			dap->da_state |= ATTACHED;
12606 			chgs = 1;
12607 			/*
12608 			 * If the inode referenced by the directory has
12609 			 * been written out, then the dependency can be
12610 			 * moved to the pending list.
12611 			 */
12612 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12613 				LIST_REMOVE(dap, da_pdlist);
12614 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12615 				    da_pdlist);
12616 			}
12617 		}
12618 	}
12619 	/*
12620 	 * If there were any rollbacks in the directory, then it must be
12621 	 * marked dirty so that its will eventually get written back in
12622 	 * its correct form.
12623 	 */
12624 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12625 		if ((bp->b_flags & B_DELWRI) == 0)
12626 			stat_dir_entry++;
12627 		bdirty(bp);
12628 		return (1);
12629 	}
12630 	/*
12631 	 * If we are not waiting for a new directory block to be
12632 	 * claimed by its inode, then the pagedep will be freed.
12633 	 * Otherwise it will remain to track any new entries on
12634 	 * the page in case they are fsync'ed.
12635 	 */
12636 	free_pagedep(pagedep);
12637 	return (0);
12638 }
12639 
12640 /*
12641  * Writing back in-core inode structures.
12642  *
12643  * The filesystem only accesses an inode's contents when it occupies an
12644  * "in-core" inode structure.  These "in-core" structures are separate from
12645  * the page frames used to cache inode blocks.  Only the latter are
12646  * transferred to/from the disk.  So, when the updated contents of the
12647  * "in-core" inode structure are copied to the corresponding in-memory inode
12648  * block, the dependencies are also transferred.  The following procedure is
12649  * called when copying a dirty "in-core" inode to a cached inode block.
12650  */
12651 
12652 /*
12653  * Called when an inode is loaded from disk. If the effective link count
12654  * differed from the actual link count when it was last flushed, then we
12655  * need to ensure that the correct effective link count is put back.
12656  */
12657 void
12658 softdep_load_inodeblock(ip)
12659 	struct inode *ip;	/* the "in_core" copy of the inode */
12660 {
12661 	struct inodedep *inodedep;
12662 	struct ufsmount *ump;
12663 
12664 	ump = ITOUMP(ip);
12665 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12666 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12667 	/*
12668 	 * Check for alternate nlink count.
12669 	 */
12670 	ip->i_effnlink = ip->i_nlink;
12671 	ACQUIRE_LOCK(ump);
12672 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12673 		FREE_LOCK(ump);
12674 		return;
12675 	}
12676 	if (ip->i_nlink != inodedep->id_nlinkwrote &&
12677 	    inodedep->id_nlinkwrote != -1) {
12678 		KASSERT(ip->i_nlink == 0 &&
12679 		    (ump->um_flags & UM_FSFAIL_CLEANUP) != 0,
12680 		    ("read bad i_nlink value"));
12681 		ip->i_effnlink = ip->i_nlink = inodedep->id_nlinkwrote;
12682 	}
12683 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12684 	KASSERT(ip->i_effnlink >= 0,
12685 	    ("softdep_load_inodeblock: negative i_effnlink"));
12686 	FREE_LOCK(ump);
12687 }
12688 
12689 /*
12690  * This routine is called just before the "in-core" inode
12691  * information is to be copied to the in-memory inode block.
12692  * Recall that an inode block contains several inodes. If
12693  * the force flag is set, then the dependencies will be
12694  * cleared so that the update can always be made. Note that
12695  * the buffer is locked when this routine is called, so we
12696  * will never be in the middle of writing the inode block
12697  * to disk.
12698  */
12699 void
12700 softdep_update_inodeblock(ip, bp, waitfor)
12701 	struct inode *ip;	/* the "in_core" copy of the inode */
12702 	struct buf *bp;		/* the buffer containing the inode block */
12703 	int waitfor;		/* nonzero => update must be allowed */
12704 {
12705 	struct inodedep *inodedep;
12706 	struct inoref *inoref;
12707 	struct ufsmount *ump;
12708 	struct worklist *wk;
12709 	struct mount *mp;
12710 	struct buf *ibp;
12711 	struct fs *fs;
12712 	int error;
12713 
12714 	ump = ITOUMP(ip);
12715 	mp = UFSTOVFS(ump);
12716 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12717 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12718 	fs = ump->um_fs;
12719 	/*
12720 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12721 	 * does not have access to the in-core ip so must write directly into
12722 	 * the inode block buffer when setting freelink.
12723 	 */
12724 	if (fs->fs_magic == FS_UFS1_MAGIC)
12725 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12726 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12727 	else
12728 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12729 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12730 	/*
12731 	 * If the effective link count is not equal to the actual link
12732 	 * count, then we must track the difference in an inodedep while
12733 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12734 	 * if there is no existing inodedep, then there are no dependencies
12735 	 * to track.
12736 	 */
12737 	ACQUIRE_LOCK(ump);
12738 again:
12739 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12740 		FREE_LOCK(ump);
12741 		if (ip->i_effnlink != ip->i_nlink)
12742 			panic("softdep_update_inodeblock: bad link count");
12743 		return;
12744 	}
12745 	KASSERT(ip->i_nlink >= inodedep->id_nlinkdelta,
12746 	    ("softdep_update_inodeblock inconsistent ip %p i_nlink %d "
12747 	    "inodedep %p id_nlinkdelta %jd",
12748 	    ip, ip->i_nlink, inodedep, (intmax_t)inodedep->id_nlinkdelta));
12749 	inodedep->id_nlinkwrote = ip->i_nlink;
12750 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12751 		panic("softdep_update_inodeblock: bad delta");
12752 	/*
12753 	 * If we're flushing all dependencies we must also move any waiting
12754 	 * for journal writes onto the bufwait list prior to I/O.
12755 	 */
12756 	if (waitfor) {
12757 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12758 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12759 			    == DEPCOMPLETE) {
12760 				jwait(&inoref->if_list, MNT_WAIT);
12761 				goto again;
12762 			}
12763 		}
12764 	}
12765 	/*
12766 	 * Changes have been initiated. Anything depending on these
12767 	 * changes cannot occur until this inode has been written.
12768 	 */
12769 	inodedep->id_state &= ~COMPLETE;
12770 	if ((inodedep->id_state & ONWORKLIST) == 0)
12771 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12772 	/*
12773 	 * Any new dependencies associated with the incore inode must
12774 	 * now be moved to the list associated with the buffer holding
12775 	 * the in-memory copy of the inode. Once merged process any
12776 	 * allocdirects that are completed by the merger.
12777 	 */
12778 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12779 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12780 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12781 		    NULL);
12782 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12783 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12784 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12785 		    NULL);
12786 	/*
12787 	 * Now that the inode has been pushed into the buffer, the
12788 	 * operations dependent on the inode being written to disk
12789 	 * can be moved to the id_bufwait so that they will be
12790 	 * processed when the buffer I/O completes.
12791 	 */
12792 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12793 		WORKLIST_REMOVE(wk);
12794 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12795 	}
12796 	/*
12797 	 * Newly allocated inodes cannot be written until the bitmap
12798 	 * that allocates them have been written (indicated by
12799 	 * DEPCOMPLETE being set in id_state). If we are doing a
12800 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12801 	 * to be written so that the update can be done.
12802 	 */
12803 	if (waitfor == 0) {
12804 		FREE_LOCK(ump);
12805 		return;
12806 	}
12807 retry:
12808 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12809 		FREE_LOCK(ump);
12810 		return;
12811 	}
12812 	ibp = inodedep->id_bmsafemap->sm_buf;
12813 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12814 	if (ibp == NULL) {
12815 		/*
12816 		 * If ibp came back as NULL, the dependency could have been
12817 		 * freed while we slept.  Look it up again, and check to see
12818 		 * that it has completed.
12819 		 */
12820 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12821 			goto retry;
12822 		FREE_LOCK(ump);
12823 		return;
12824 	}
12825 	FREE_LOCK(ump);
12826 	if ((error = bwrite(ibp)) != 0)
12827 		softdep_error("softdep_update_inodeblock: bwrite", error);
12828 }
12829 
12830 /*
12831  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12832  * old inode dependency list (such as id_inoupdt).
12833  */
12834 static void
12835 merge_inode_lists(newlisthead, oldlisthead)
12836 	struct allocdirectlst *newlisthead;
12837 	struct allocdirectlst *oldlisthead;
12838 {
12839 	struct allocdirect *listadp, *newadp;
12840 
12841 	newadp = TAILQ_FIRST(newlisthead);
12842 	if (newadp != NULL)
12843 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12844 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12845 		if (listadp->ad_offset < newadp->ad_offset) {
12846 			listadp = TAILQ_NEXT(listadp, ad_next);
12847 			continue;
12848 		}
12849 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12850 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12851 		if (listadp->ad_offset == newadp->ad_offset) {
12852 			allocdirect_merge(oldlisthead, newadp,
12853 			    listadp);
12854 			listadp = newadp;
12855 		}
12856 		newadp = TAILQ_FIRST(newlisthead);
12857 	}
12858 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12859 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12860 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12861 	}
12862 }
12863 
12864 /*
12865  * If we are doing an fsync, then we must ensure that any directory
12866  * entries for the inode have been written after the inode gets to disk.
12867  */
12868 int
12869 softdep_fsync(vp)
12870 	struct vnode *vp;	/* the "in_core" copy of the inode */
12871 {
12872 	struct inodedep *inodedep;
12873 	struct pagedep *pagedep;
12874 	struct inoref *inoref;
12875 	struct ufsmount *ump;
12876 	struct worklist *wk;
12877 	struct diradd *dap;
12878 	struct mount *mp;
12879 	struct vnode *pvp;
12880 	struct inode *ip;
12881 	struct buf *bp;
12882 	struct fs *fs;
12883 	struct thread *td = curthread;
12884 	int error, flushparent, pagedep_new_block;
12885 	ino_t parentino;
12886 	ufs_lbn_t lbn;
12887 
12888 	ip = VTOI(vp);
12889 	mp = vp->v_mount;
12890 	ump = VFSTOUFS(mp);
12891 	fs = ump->um_fs;
12892 	if (MOUNTEDSOFTDEP(mp) == 0)
12893 		return (0);
12894 	ACQUIRE_LOCK(ump);
12895 restart:
12896 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12897 		FREE_LOCK(ump);
12898 		return (0);
12899 	}
12900 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12901 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12902 		    == DEPCOMPLETE) {
12903 			jwait(&inoref->if_list, MNT_WAIT);
12904 			goto restart;
12905 		}
12906 	}
12907 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12908 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12909 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12910 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12911 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12912 		panic("softdep_fsync: pending ops %p", inodedep);
12913 	for (error = 0, flushparent = 0; ; ) {
12914 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12915 			break;
12916 		if (wk->wk_type != D_DIRADD)
12917 			panic("softdep_fsync: Unexpected type %s",
12918 			    TYPENAME(wk->wk_type));
12919 		dap = WK_DIRADD(wk);
12920 		/*
12921 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12922 		 * dependency or is contained in a newly allocated block.
12923 		 */
12924 		if (dap->da_state & DIRCHG)
12925 			pagedep = dap->da_previous->dm_pagedep;
12926 		else
12927 			pagedep = dap->da_pagedep;
12928 		parentino = pagedep->pd_ino;
12929 		lbn = pagedep->pd_lbn;
12930 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12931 			panic("softdep_fsync: dirty");
12932 		if ((dap->da_state & MKDIR_PARENT) ||
12933 		    (pagedep->pd_state & NEWBLOCK))
12934 			flushparent = 1;
12935 		else
12936 			flushparent = 0;
12937 		/*
12938 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12939 		 * then we will not be able to release and recover the
12940 		 * vnode below, so we just have to give up on writing its
12941 		 * directory entry out. It will eventually be written, just
12942 		 * not now, but then the user was not asking to have it
12943 		 * written, so we are not breaking any promises.
12944 		 */
12945 		if (VN_IS_DOOMED(vp))
12946 			break;
12947 		/*
12948 		 * We prevent deadlock by always fetching inodes from the
12949 		 * root, moving down the directory tree. Thus, when fetching
12950 		 * our parent directory, we first try to get the lock. If
12951 		 * that fails, we must unlock ourselves before requesting
12952 		 * the lock on our parent. See the comment in ufs_lookup
12953 		 * for details on possible races.
12954 		 */
12955 		FREE_LOCK(ump);
12956 		error = get_parent_vp(vp, mp, parentino, NULL, NULL, NULL,
12957 		    &pvp);
12958 		if (error == ERELOOKUP)
12959 			error = 0;
12960 		if (error != 0)
12961 			return (error);
12962 		/*
12963 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12964 		 * that are contained in direct blocks will be resolved by
12965 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12966 		 * may require a complete sync'ing of the directory. So, we
12967 		 * try the cheap and fast ffs_update first, and if that fails,
12968 		 * then we do the slower ffs_syncvnode of the directory.
12969 		 */
12970 		if (flushparent) {
12971 			int locked;
12972 
12973 			if ((error = ffs_update(pvp, 1)) != 0) {
12974 				vput(pvp);
12975 				return (error);
12976 			}
12977 			ACQUIRE_LOCK(ump);
12978 			locked = 1;
12979 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12980 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12981 					if (wk->wk_type != D_DIRADD)
12982 						panic("softdep_fsync: Unexpected type %s",
12983 						      TYPENAME(wk->wk_type));
12984 					dap = WK_DIRADD(wk);
12985 					if (dap->da_state & DIRCHG)
12986 						pagedep = dap->da_previous->dm_pagedep;
12987 					else
12988 						pagedep = dap->da_pagedep;
12989 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12990 					FREE_LOCK(ump);
12991 					locked = 0;
12992 					if (pagedep_new_block && (error =
12993 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12994 						vput(pvp);
12995 						return (error);
12996 					}
12997 				}
12998 			}
12999 			if (locked)
13000 				FREE_LOCK(ump);
13001 		}
13002 		/*
13003 		 * Flush directory page containing the inode's name.
13004 		 */
13005 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
13006 		    &bp);
13007 		if (error == 0)
13008 			error = bwrite(bp);
13009 		else
13010 			brelse(bp);
13011 		vput(pvp);
13012 		if (!ffs_fsfail_cleanup(ump, error))
13013 			return (error);
13014 		ACQUIRE_LOCK(ump);
13015 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
13016 			break;
13017 	}
13018 	FREE_LOCK(ump);
13019 	return (0);
13020 }
13021 
13022 /*
13023  * Flush all the dirty bitmaps associated with the block device
13024  * before flushing the rest of the dirty blocks so as to reduce
13025  * the number of dependencies that will have to be rolled back.
13026  *
13027  * XXX Unused?
13028  */
13029 void
13030 softdep_fsync_mountdev(vp)
13031 	struct vnode *vp;
13032 {
13033 	struct buf *bp, *nbp;
13034 	struct worklist *wk;
13035 	struct bufobj *bo;
13036 
13037 	if (!vn_isdisk(vp))
13038 		panic("softdep_fsync_mountdev: vnode not a disk");
13039 	bo = &vp->v_bufobj;
13040 restart:
13041 	BO_LOCK(bo);
13042 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
13043 		/*
13044 		 * If it is already scheduled, skip to the next buffer.
13045 		 */
13046 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
13047 			continue;
13048 
13049 		if ((bp->b_flags & B_DELWRI) == 0)
13050 			panic("softdep_fsync_mountdev: not dirty");
13051 		/*
13052 		 * We are only interested in bitmaps with outstanding
13053 		 * dependencies.
13054 		 */
13055 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
13056 		    wk->wk_type != D_BMSAFEMAP ||
13057 		    (bp->b_vflags & BV_BKGRDINPROG)) {
13058 			BUF_UNLOCK(bp);
13059 			continue;
13060 		}
13061 		BO_UNLOCK(bo);
13062 		bremfree(bp);
13063 		(void) bawrite(bp);
13064 		goto restart;
13065 	}
13066 	drain_output(vp);
13067 	BO_UNLOCK(bo);
13068 }
13069 
13070 /*
13071  * Sync all cylinder groups that were dirty at the time this function is
13072  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
13073  * is used to flush freedep activity that may be holding up writes to a
13074  * indirect block.
13075  */
13076 static int
13077 sync_cgs(mp, waitfor)
13078 	struct mount *mp;
13079 	int waitfor;
13080 {
13081 	struct bmsafemap *bmsafemap;
13082 	struct bmsafemap *sentinel;
13083 	struct ufsmount *ump;
13084 	struct buf *bp;
13085 	int error;
13086 
13087 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
13088 	sentinel->sm_cg = -1;
13089 	ump = VFSTOUFS(mp);
13090 	error = 0;
13091 	ACQUIRE_LOCK(ump);
13092 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
13093 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
13094 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
13095 		/* Skip sentinels and cgs with no work to release. */
13096 		if (bmsafemap->sm_cg == -1 ||
13097 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
13098 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
13099 			LIST_REMOVE(sentinel, sm_next);
13100 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
13101 			continue;
13102 		}
13103 		/*
13104 		 * If we don't get the lock and we're waiting try again, if
13105 		 * not move on to the next buf and try to sync it.
13106 		 */
13107 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
13108 		if (bp == NULL && waitfor == MNT_WAIT)
13109 			continue;
13110 		LIST_REMOVE(sentinel, sm_next);
13111 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
13112 		if (bp == NULL)
13113 			continue;
13114 		FREE_LOCK(ump);
13115 		if (waitfor == MNT_NOWAIT)
13116 			bawrite(bp);
13117 		else
13118 			error = bwrite(bp);
13119 		ACQUIRE_LOCK(ump);
13120 		if (error)
13121 			break;
13122 	}
13123 	LIST_REMOVE(sentinel, sm_next);
13124 	FREE_LOCK(ump);
13125 	free(sentinel, M_BMSAFEMAP);
13126 	return (error);
13127 }
13128 
13129 /*
13130  * This routine is called when we are trying to synchronously flush a
13131  * file. This routine must eliminate any filesystem metadata dependencies
13132  * so that the syncing routine can succeed.
13133  */
13134 int
13135 softdep_sync_metadata(struct vnode *vp)
13136 {
13137 	struct inode *ip;
13138 	int error;
13139 
13140 	ip = VTOI(vp);
13141 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13142 	    ("softdep_sync_metadata called on non-softdep filesystem"));
13143 	/*
13144 	 * Ensure that any direct block dependencies have been cleared,
13145 	 * truncations are started, and inode references are journaled.
13146 	 */
13147 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
13148 	/*
13149 	 * Write all journal records to prevent rollbacks on devvp.
13150 	 */
13151 	if (vp->v_type == VCHR)
13152 		softdep_flushjournal(vp->v_mount);
13153 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
13154 	/*
13155 	 * Ensure that all truncates are written so we won't find deps on
13156 	 * indirect blocks.
13157 	 */
13158 	process_truncates(vp);
13159 	FREE_LOCK(VFSTOUFS(vp->v_mount));
13160 
13161 	return (error);
13162 }
13163 
13164 /*
13165  * This routine is called when we are attempting to sync a buf with
13166  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
13167  * other IO it can but returns EBUSY if the buffer is not yet able to
13168  * be written.  Dependencies which will not cause rollbacks will always
13169  * return 0.
13170  */
13171 int
13172 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
13173 {
13174 	struct indirdep *indirdep;
13175 	struct pagedep *pagedep;
13176 	struct allocindir *aip;
13177 	struct newblk *newblk;
13178 	struct ufsmount *ump;
13179 	struct buf *nbp;
13180 	struct worklist *wk;
13181 	int i, error;
13182 
13183 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13184 	    ("softdep_sync_buf called on non-softdep filesystem"));
13185 	/*
13186 	 * For VCHR we just don't want to force flush any dependencies that
13187 	 * will cause rollbacks.
13188 	 */
13189 	if (vp->v_type == VCHR) {
13190 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
13191 			return (EBUSY);
13192 		return (0);
13193 	}
13194 	ump = VFSTOUFS(vp->v_mount);
13195 	ACQUIRE_LOCK(ump);
13196 	/*
13197 	 * As we hold the buffer locked, none of its dependencies
13198 	 * will disappear.
13199 	 */
13200 	error = 0;
13201 top:
13202 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13203 		switch (wk->wk_type) {
13204 		case D_ALLOCDIRECT:
13205 		case D_ALLOCINDIR:
13206 			newblk = WK_NEWBLK(wk);
13207 			if (newblk->nb_jnewblk != NULL) {
13208 				if (waitfor == MNT_NOWAIT) {
13209 					error = EBUSY;
13210 					goto out_unlock;
13211 				}
13212 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
13213 				goto top;
13214 			}
13215 			if (newblk->nb_state & DEPCOMPLETE ||
13216 			    waitfor == MNT_NOWAIT)
13217 				continue;
13218 			nbp = newblk->nb_bmsafemap->sm_buf;
13219 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13220 			if (nbp == NULL)
13221 				goto top;
13222 			FREE_LOCK(ump);
13223 			if ((error = bwrite(nbp)) != 0)
13224 				goto out;
13225 			ACQUIRE_LOCK(ump);
13226 			continue;
13227 
13228 		case D_INDIRDEP:
13229 			indirdep = WK_INDIRDEP(wk);
13230 			if (waitfor == MNT_NOWAIT) {
13231 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
13232 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
13233 					error = EBUSY;
13234 					goto out_unlock;
13235 				}
13236 			}
13237 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
13238 				panic("softdep_sync_buf: truncation pending.");
13239 		restart:
13240 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13241 				newblk = (struct newblk *)aip;
13242 				if (newblk->nb_jnewblk != NULL) {
13243 					jwait(&newblk->nb_jnewblk->jn_list,
13244 					    waitfor);
13245 					goto restart;
13246 				}
13247 				if (newblk->nb_state & DEPCOMPLETE)
13248 					continue;
13249 				nbp = newblk->nb_bmsafemap->sm_buf;
13250 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13251 				if (nbp == NULL)
13252 					goto restart;
13253 				FREE_LOCK(ump);
13254 				if ((error = bwrite(nbp)) != 0)
13255 					goto out;
13256 				ACQUIRE_LOCK(ump);
13257 				goto restart;
13258 			}
13259 			continue;
13260 
13261 		case D_PAGEDEP:
13262 			/*
13263 			 * Only flush directory entries in synchronous passes.
13264 			 */
13265 			if (waitfor != MNT_WAIT) {
13266 				error = EBUSY;
13267 				goto out_unlock;
13268 			}
13269 			/*
13270 			 * While syncing snapshots, we must allow recursive
13271 			 * lookups.
13272 			 */
13273 			BUF_AREC(bp);
13274 			/*
13275 			 * We are trying to sync a directory that may
13276 			 * have dependencies on both its own metadata
13277 			 * and/or dependencies on the inodes of any
13278 			 * recently allocated files. We walk its diradd
13279 			 * lists pushing out the associated inode.
13280 			 */
13281 			pagedep = WK_PAGEDEP(wk);
13282 			for (i = 0; i < DAHASHSZ; i++) {
13283 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
13284 					continue;
13285 				error = flush_pagedep_deps(vp, wk->wk_mp,
13286 				    &pagedep->pd_diraddhd[i], bp);
13287 				if (error != 0) {
13288 					if (error != ERELOOKUP)
13289 						BUF_NOREC(bp);
13290 					goto out_unlock;
13291 				}
13292 			}
13293 			BUF_NOREC(bp);
13294 			continue;
13295 
13296 		case D_FREEWORK:
13297 		case D_FREEDEP:
13298 		case D_JSEGDEP:
13299 		case D_JNEWBLK:
13300 			continue;
13301 
13302 		default:
13303 			panic("softdep_sync_buf: Unknown type %s",
13304 			    TYPENAME(wk->wk_type));
13305 			/* NOTREACHED */
13306 		}
13307 	}
13308 out_unlock:
13309 	FREE_LOCK(ump);
13310 out:
13311 	return (error);
13312 }
13313 
13314 /*
13315  * Flush the dependencies associated with an inodedep.
13316  */
13317 static int
13318 flush_inodedep_deps(vp, mp, ino)
13319 	struct vnode *vp;
13320 	struct mount *mp;
13321 	ino_t ino;
13322 {
13323 	struct inodedep *inodedep;
13324 	struct inoref *inoref;
13325 	struct ufsmount *ump;
13326 	int error, waitfor;
13327 
13328 	/*
13329 	 * This work is done in two passes. The first pass grabs most
13330 	 * of the buffers and begins asynchronously writing them. The
13331 	 * only way to wait for these asynchronous writes is to sleep
13332 	 * on the filesystem vnode which may stay busy for a long time
13333 	 * if the filesystem is active. So, instead, we make a second
13334 	 * pass over the dependencies blocking on each write. In the
13335 	 * usual case we will be blocking against a write that we
13336 	 * initiated, so when it is done the dependency will have been
13337 	 * resolved. Thus the second pass is expected to end quickly.
13338 	 * We give a brief window at the top of the loop to allow
13339 	 * any pending I/O to complete.
13340 	 */
13341 	ump = VFSTOUFS(mp);
13342 	LOCK_OWNED(ump);
13343 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
13344 		if (error)
13345 			return (error);
13346 		FREE_LOCK(ump);
13347 		ACQUIRE_LOCK(ump);
13348 restart:
13349 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13350 			return (0);
13351 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13352 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13353 			    == DEPCOMPLETE) {
13354 				jwait(&inoref->if_list, MNT_WAIT);
13355 				goto restart;
13356 			}
13357 		}
13358 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
13359 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
13360 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
13361 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
13362 			continue;
13363 		/*
13364 		 * If pass2, we are done, otherwise do pass 2.
13365 		 */
13366 		if (waitfor == MNT_WAIT)
13367 			break;
13368 		waitfor = MNT_WAIT;
13369 	}
13370 	/*
13371 	 * Try freeing inodedep in case all dependencies have been removed.
13372 	 */
13373 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
13374 		(void) free_inodedep(inodedep);
13375 	return (0);
13376 }
13377 
13378 /*
13379  * Flush an inode dependency list.
13380  */
13381 static int
13382 flush_deplist(listhead, waitfor, errorp)
13383 	struct allocdirectlst *listhead;
13384 	int waitfor;
13385 	int *errorp;
13386 {
13387 	struct allocdirect *adp;
13388 	struct newblk *newblk;
13389 	struct ufsmount *ump;
13390 	struct buf *bp;
13391 
13392 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
13393 		return (0);
13394 	ump = VFSTOUFS(adp->ad_list.wk_mp);
13395 	LOCK_OWNED(ump);
13396 	TAILQ_FOREACH(adp, listhead, ad_next) {
13397 		newblk = (struct newblk *)adp;
13398 		if (newblk->nb_jnewblk != NULL) {
13399 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13400 			return (1);
13401 		}
13402 		if (newblk->nb_state & DEPCOMPLETE)
13403 			continue;
13404 		bp = newblk->nb_bmsafemap->sm_buf;
13405 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13406 		if (bp == NULL) {
13407 			if (waitfor == MNT_NOWAIT)
13408 				continue;
13409 			return (1);
13410 		}
13411 		FREE_LOCK(ump);
13412 		if (waitfor == MNT_NOWAIT)
13413 			bawrite(bp);
13414 		else
13415 			*errorp = bwrite(bp);
13416 		ACQUIRE_LOCK(ump);
13417 		return (1);
13418 	}
13419 	return (0);
13420 }
13421 
13422 /*
13423  * Flush dependencies associated with an allocdirect block.
13424  */
13425 static int
13426 flush_newblk_dep(vp, mp, lbn)
13427 	struct vnode *vp;
13428 	struct mount *mp;
13429 	ufs_lbn_t lbn;
13430 {
13431 	struct newblk *newblk;
13432 	struct ufsmount *ump;
13433 	struct bufobj *bo;
13434 	struct inode *ip;
13435 	struct buf *bp;
13436 	ufs2_daddr_t blkno;
13437 	int error;
13438 
13439 	error = 0;
13440 	bo = &vp->v_bufobj;
13441 	ip = VTOI(vp);
13442 	blkno = DIP(ip, i_db[lbn]);
13443 	if (blkno == 0)
13444 		panic("flush_newblk_dep: Missing block");
13445 	ump = VFSTOUFS(mp);
13446 	ACQUIRE_LOCK(ump);
13447 	/*
13448 	 * Loop until all dependencies related to this block are satisfied.
13449 	 * We must be careful to restart after each sleep in case a write
13450 	 * completes some part of this process for us.
13451 	 */
13452 	for (;;) {
13453 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13454 			FREE_LOCK(ump);
13455 			break;
13456 		}
13457 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13458 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13459 		/*
13460 		 * Flush the journal.
13461 		 */
13462 		if (newblk->nb_jnewblk != NULL) {
13463 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13464 			continue;
13465 		}
13466 		/*
13467 		 * Write the bitmap dependency.
13468 		 */
13469 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13470 			bp = newblk->nb_bmsafemap->sm_buf;
13471 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13472 			if (bp == NULL)
13473 				continue;
13474 			FREE_LOCK(ump);
13475 			error = bwrite(bp);
13476 			if (error)
13477 				break;
13478 			ACQUIRE_LOCK(ump);
13479 			continue;
13480 		}
13481 		/*
13482 		 * Write the buffer.
13483 		 */
13484 		FREE_LOCK(ump);
13485 		BO_LOCK(bo);
13486 		bp = gbincore(bo, lbn);
13487 		if (bp != NULL) {
13488 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13489 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13490 			if (error == ENOLCK) {
13491 				ACQUIRE_LOCK(ump);
13492 				error = 0;
13493 				continue; /* Slept, retry */
13494 			}
13495 			if (error != 0)
13496 				break;	/* Failed */
13497 			if (bp->b_flags & B_DELWRI) {
13498 				bremfree(bp);
13499 				error = bwrite(bp);
13500 				if (error)
13501 					break;
13502 			} else
13503 				BUF_UNLOCK(bp);
13504 		} else
13505 			BO_UNLOCK(bo);
13506 		/*
13507 		 * We have to wait for the direct pointers to
13508 		 * point at the newdirblk before the dependency
13509 		 * will go away.
13510 		 */
13511 		error = ffs_update(vp, 1);
13512 		if (error)
13513 			break;
13514 		ACQUIRE_LOCK(ump);
13515 	}
13516 	return (error);
13517 }
13518 
13519 /*
13520  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13521  */
13522 static int
13523 flush_pagedep_deps(pvp, mp, diraddhdp, locked_bp)
13524 	struct vnode *pvp;
13525 	struct mount *mp;
13526 	struct diraddhd *diraddhdp;
13527 	struct buf *locked_bp;
13528 {
13529 	struct inodedep *inodedep;
13530 	struct inoref *inoref;
13531 	struct ufsmount *ump;
13532 	struct diradd *dap;
13533 	struct vnode *vp;
13534 	int error = 0;
13535 	struct buf *bp;
13536 	ino_t inum;
13537 	struct diraddhd unfinished;
13538 
13539 	LIST_INIT(&unfinished);
13540 	ump = VFSTOUFS(mp);
13541 	LOCK_OWNED(ump);
13542 restart:
13543 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13544 		/*
13545 		 * Flush ourselves if this directory entry
13546 		 * has a MKDIR_PARENT dependency.
13547 		 */
13548 		if (dap->da_state & MKDIR_PARENT) {
13549 			FREE_LOCK(ump);
13550 			if ((error = ffs_update(pvp, 1)) != 0)
13551 				break;
13552 			ACQUIRE_LOCK(ump);
13553 			/*
13554 			 * If that cleared dependencies, go on to next.
13555 			 */
13556 			if (dap != LIST_FIRST(diraddhdp))
13557 				continue;
13558 			/*
13559 			 * All MKDIR_PARENT dependencies and all the
13560 			 * NEWBLOCK pagedeps that are contained in direct
13561 			 * blocks were resolved by doing above ffs_update.
13562 			 * Pagedeps contained in indirect blocks may
13563 			 * require a complete sync'ing of the directory.
13564 			 * We are in the midst of doing a complete sync,
13565 			 * so if they are not resolved in this pass we
13566 			 * defer them for now as they will be sync'ed by
13567 			 * our caller shortly.
13568 			 */
13569 			LIST_REMOVE(dap, da_pdlist);
13570 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13571 			continue;
13572 		}
13573 		/*
13574 		 * A newly allocated directory must have its "." and
13575 		 * ".." entries written out before its name can be
13576 		 * committed in its parent.
13577 		 */
13578 		inum = dap->da_newinum;
13579 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13580 			panic("flush_pagedep_deps: lost inode1");
13581 		/*
13582 		 * Wait for any pending journal adds to complete so we don't
13583 		 * cause rollbacks while syncing.
13584 		 */
13585 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13586 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13587 			    == DEPCOMPLETE) {
13588 				jwait(&inoref->if_list, MNT_WAIT);
13589 				goto restart;
13590 			}
13591 		}
13592 		if (dap->da_state & MKDIR_BODY) {
13593 			FREE_LOCK(ump);
13594 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13595 			    diraddhdp, &unfinished, &vp);
13596 			if (error != 0)
13597 				break;
13598 			error = flush_newblk_dep(vp, mp, 0);
13599 			/*
13600 			 * If we still have the dependency we might need to
13601 			 * update the vnode to sync the new link count to
13602 			 * disk.
13603 			 */
13604 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13605 				error = ffs_update(vp, 1);
13606 			vput(vp);
13607 			if (error != 0)
13608 				break;
13609 			ACQUIRE_LOCK(ump);
13610 			/*
13611 			 * If that cleared dependencies, go on to next.
13612 			 */
13613 			if (dap != LIST_FIRST(diraddhdp))
13614 				continue;
13615 			if (dap->da_state & MKDIR_BODY) {
13616 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13617 				    &inodedep);
13618 				panic("flush_pagedep_deps: MKDIR_BODY "
13619 				    "inodedep %p dap %p vp %p",
13620 				    inodedep, dap, vp);
13621 			}
13622 		}
13623 		/*
13624 		 * Flush the inode on which the directory entry depends.
13625 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13626 		 * the only remaining dependency is that the updated inode
13627 		 * count must get pushed to disk. The inode has already
13628 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13629 		 * the time of the reference count change. So we need only
13630 		 * locate that buffer, ensure that there will be no rollback
13631 		 * caused by a bitmap dependency, then write the inode buffer.
13632 		 */
13633 retry:
13634 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13635 			panic("flush_pagedep_deps: lost inode");
13636 		/*
13637 		 * If the inode still has bitmap dependencies,
13638 		 * push them to disk.
13639 		 */
13640 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13641 			bp = inodedep->id_bmsafemap->sm_buf;
13642 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13643 			if (bp == NULL)
13644 				goto retry;
13645 			FREE_LOCK(ump);
13646 			if ((error = bwrite(bp)) != 0)
13647 				break;
13648 			ACQUIRE_LOCK(ump);
13649 			if (dap != LIST_FIRST(diraddhdp))
13650 				continue;
13651 		}
13652 		/*
13653 		 * If the inode is still sitting in a buffer waiting
13654 		 * to be written or waiting for the link count to be
13655 		 * adjusted update it here to flush it to disk.
13656 		 */
13657 		if (dap == LIST_FIRST(diraddhdp)) {
13658 			FREE_LOCK(ump);
13659 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13660 			    diraddhdp, &unfinished, &vp);
13661 			if (error != 0)
13662 				break;
13663 			error = ffs_update(vp, 1);
13664 			vput(vp);
13665 			if (error)
13666 				break;
13667 			ACQUIRE_LOCK(ump);
13668 		}
13669 		/*
13670 		 * If we have failed to get rid of all the dependencies
13671 		 * then something is seriously wrong.
13672 		 */
13673 		if (dap == LIST_FIRST(diraddhdp)) {
13674 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13675 			panic("flush_pagedep_deps: failed to flush "
13676 			    "inodedep %p ino %ju dap %p",
13677 			    inodedep, (uintmax_t)inum, dap);
13678 		}
13679 	}
13680 	if (error)
13681 		ACQUIRE_LOCK(ump);
13682 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13683 		LIST_REMOVE(dap, da_pdlist);
13684 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13685 	}
13686 	return (error);
13687 }
13688 
13689 /*
13690  * A large burst of file addition or deletion activity can drive the
13691  * memory load excessively high. First attempt to slow things down
13692  * using the techniques below. If that fails, this routine requests
13693  * the offending operations to fall back to running synchronously
13694  * until the memory load returns to a reasonable level.
13695  */
13696 int
13697 softdep_slowdown(vp)
13698 	struct vnode *vp;
13699 {
13700 	struct ufsmount *ump;
13701 	int jlow;
13702 	int max_softdeps_hard;
13703 
13704 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13705 	    ("softdep_slowdown called on non-softdep filesystem"));
13706 	ump = VFSTOUFS(vp->v_mount);
13707 	ACQUIRE_LOCK(ump);
13708 	jlow = 0;
13709 	/*
13710 	 * Check for journal space if needed.
13711 	 */
13712 	if (DOINGSUJ(vp)) {
13713 		if (journal_space(ump, 0) == 0)
13714 			jlow = 1;
13715 	}
13716 	/*
13717 	 * If the system is under its limits and our filesystem is
13718 	 * not responsible for more than our share of the usage and
13719 	 * we are not low on journal space, then no need to slow down.
13720 	 */
13721 	max_softdeps_hard = max_softdeps * 11 / 10;
13722 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13723 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13724 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13725 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13726 	    ump->softdep_curdeps[D_DIRREM] <
13727 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13728 	    ump->softdep_curdeps[D_INODEDEP] <
13729 	    max_softdeps_hard / stat_flush_threads &&
13730 	    ump->softdep_curdeps[D_INDIRDEP] <
13731 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13732 	    ump->softdep_curdeps[D_FREEBLKS] <
13733 	    max_softdeps_hard / stat_flush_threads) {
13734 		FREE_LOCK(ump);
13735   		return (0);
13736 	}
13737 	/*
13738 	 * If the journal is low or our filesystem is over its limit
13739 	 * then speedup the cleanup.
13740 	 */
13741 	if (ump->softdep_curdeps[D_INDIRDEP] <
13742 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13743 		softdep_speedup(ump);
13744 	stat_sync_limit_hit += 1;
13745 	FREE_LOCK(ump);
13746 	/*
13747 	 * We only slow down the rate at which new dependencies are
13748 	 * generated if we are not using journaling. With journaling,
13749 	 * the cleanup should always be sufficient to keep things
13750 	 * under control.
13751 	 */
13752 	if (DOINGSUJ(vp))
13753 		return (0);
13754 	return (1);
13755 }
13756 
13757 static int
13758 softdep_request_cleanup_filter(struct vnode *vp, void *arg __unused)
13759 {
13760 	return ((vp->v_iflag & VI_OWEINACT) != 0 && vp->v_usecount == 0 &&
13761 	    ((vp->v_vflag & VV_NOSYNC) != 0 || VTOI(vp)->i_effnlink == 0));
13762 }
13763 
13764 static void
13765 softdep_request_cleanup_inactivate(struct mount *mp)
13766 {
13767 	struct vnode *vp, *mvp;
13768 	int error;
13769 
13770 	MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, softdep_request_cleanup_filter,
13771 	    NULL) {
13772 		vholdl(vp);
13773 		vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
13774 		VI_LOCK(vp);
13775 		if (vp->v_data != NULL && vp->v_usecount == 0) {
13776 			while ((vp->v_iflag & VI_OWEINACT) != 0) {
13777 				error = vinactive(vp);
13778 				if (error != 0 && error != ERELOOKUP)
13779 					break;
13780 			}
13781 			atomic_add_int(&stat_delayed_inact, 1);
13782 		}
13783 		VOP_UNLOCK(vp);
13784 		vdropl(vp);
13785 	}
13786 }
13787 
13788 /*
13789  * Called by the allocation routines when they are about to fail
13790  * in the hope that we can free up the requested resource (inodes
13791  * or disk space).
13792  *
13793  * First check to see if the work list has anything on it. If it has,
13794  * clean up entries until we successfully free the requested resource.
13795  * Because this process holds inodes locked, we cannot handle any remove
13796  * requests that might block on a locked inode as that could lead to
13797  * deadlock. If the worklist yields none of the requested resource,
13798  * start syncing out vnodes to free up the needed space.
13799  */
13800 int
13801 softdep_request_cleanup(fs, vp, cred, resource)
13802 	struct fs *fs;
13803 	struct vnode *vp;
13804 	struct ucred *cred;
13805 	int resource;
13806 {
13807 	struct ufsmount *ump;
13808 	struct mount *mp;
13809 	long starttime;
13810 	ufs2_daddr_t needed;
13811 	int error, failed_vnode;
13812 
13813 	/*
13814 	 * If we are being called because of a process doing a
13815 	 * copy-on-write, then it is not safe to process any
13816 	 * worklist items as we will recurse into the copyonwrite
13817 	 * routine.  This will result in an incoherent snapshot.
13818 	 * If the vnode that we hold is a snapshot, we must avoid
13819 	 * handling other resources that could cause deadlock.
13820 	 */
13821 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13822 		return (0);
13823 
13824 	if (resource == FLUSH_BLOCKS_WAIT)
13825 		stat_cleanup_blkrequests += 1;
13826 	else
13827 		stat_cleanup_inorequests += 1;
13828 
13829 	mp = vp->v_mount;
13830 	ump = VFSTOUFS(mp);
13831 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13832 	UFS_UNLOCK(ump);
13833 	error = ffs_update(vp, 1);
13834 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13835 		UFS_LOCK(ump);
13836 		return (0);
13837 	}
13838 	/*
13839 	 * If we are in need of resources, start by cleaning up
13840 	 * any block removals associated with our inode.
13841 	 */
13842 	ACQUIRE_LOCK(ump);
13843 	process_removes(vp);
13844 	process_truncates(vp);
13845 	FREE_LOCK(ump);
13846 	/*
13847 	 * Now clean up at least as many resources as we will need.
13848 	 *
13849 	 * When requested to clean up inodes, the number that are needed
13850 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13851 	 * plus a bit of slop (2) in case some more writers show up while
13852 	 * we are cleaning.
13853 	 *
13854 	 * When requested to free up space, the amount of space that
13855 	 * we need is enough blocks to allocate a full-sized segment
13856 	 * (fs_contigsumsize). The number of such segments that will
13857 	 * be needed is set by the number of simultaneous writers
13858 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13859 	 * writers show up while we are cleaning.
13860 	 *
13861 	 * Additionally, if we are unpriviledged and allocating space,
13862 	 * we need to ensure that we clean up enough blocks to get the
13863 	 * needed number of blocks over the threshold of the minimum
13864 	 * number of blocks required to be kept free by the filesystem
13865 	 * (fs_minfree).
13866 	 */
13867 	if (resource == FLUSH_INODES_WAIT) {
13868 		needed = vfs_mount_fetch_counter(vp->v_mount,
13869 		    MNT_COUNT_WRITEOPCOUNT) + 2;
13870 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13871 		needed = (vfs_mount_fetch_counter(vp->v_mount,
13872 		    MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13873 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13874 			needed += fragstoblks(fs,
13875 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13876 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13877 	} else {
13878 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13879 		    resource);
13880 		UFS_LOCK(ump);
13881 		return (0);
13882 	}
13883 	starttime = time_second;
13884 retry:
13885 	if (resource == FLUSH_BLOCKS_WAIT &&
13886 	    fs->fs_cstotal.cs_nbfree <= needed)
13887 		softdep_send_speedup(ump, needed * fs->fs_bsize,
13888 		    BIO_SPEEDUP_TRIM);
13889 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13890 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13891 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13892 	    fs->fs_cstotal.cs_nifree <= needed)) {
13893 		ACQUIRE_LOCK(ump);
13894 		if (ump->softdep_on_worklist > 0 &&
13895 		    process_worklist_item(UFSTOVFS(ump),
13896 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13897 			stat_worklist_push += 1;
13898 		FREE_LOCK(ump);
13899 	}
13900 
13901 	/*
13902 	 * Check that there are vnodes pending inactivation.  As they
13903 	 * have been unlinked, inactivating them will free up their
13904 	 * inodes.
13905 	 */
13906 	ACQUIRE_LOCK(ump);
13907 	if (resource == FLUSH_INODES_WAIT &&
13908 	    fs->fs_cstotal.cs_nifree <= needed &&
13909 	    fs->fs_pendinginodes <= needed) {
13910 		if ((ump->um_softdep->sd_flags & FLUSH_DI_ACTIVE) == 0) {
13911 			ump->um_softdep->sd_flags |= FLUSH_DI_ACTIVE;
13912 			FREE_LOCK(ump);
13913 			softdep_request_cleanup_inactivate(mp);
13914 			ACQUIRE_LOCK(ump);
13915 			ump->um_softdep->sd_flags &= ~FLUSH_DI_ACTIVE;
13916 			wakeup(&ump->um_softdep->sd_flags);
13917 		} else {
13918 			while ((ump->um_softdep->sd_flags &
13919 			    FLUSH_DI_ACTIVE) != 0) {
13920 				msleep(&ump->um_softdep->sd_flags,
13921 				    LOCK_PTR(ump), PVM, "ffsvina", hz);
13922 			}
13923 		}
13924 	}
13925 	FREE_LOCK(ump);
13926 
13927 	/*
13928 	 * If we still need resources and there are no more worklist
13929 	 * entries to process to obtain them, we have to start flushing
13930 	 * the dirty vnodes to force the release of additional requests
13931 	 * to the worklist that we can then process to reap addition
13932 	 * resources. We walk the vnodes associated with the mount point
13933 	 * until we get the needed worklist requests that we can reap.
13934 	 *
13935 	 * If there are several threads all needing to clean the same
13936 	 * mount point, only one is allowed to walk the mount list.
13937 	 * When several threads all try to walk the same mount list,
13938 	 * they end up competing with each other and often end up in
13939 	 * livelock. This approach ensures that forward progress is
13940 	 * made at the cost of occational ENOSPC errors being returned
13941 	 * that might otherwise have been avoided.
13942 	 */
13943 	error = 1;
13944 	if ((resource == FLUSH_BLOCKS_WAIT &&
13945 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13946 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13947 	     fs->fs_cstotal.cs_nifree <= needed)) {
13948 		ACQUIRE_LOCK(ump);
13949 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13950 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13951 			FREE_LOCK(ump);
13952 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13953 			ACQUIRE_LOCK(ump);
13954 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13955 			wakeup(&ump->um_softdep->sd_flags);
13956 			FREE_LOCK(ump);
13957 			if (ump->softdep_on_worklist > 0) {
13958 				stat_cleanup_retries += 1;
13959 				if (!failed_vnode)
13960 					goto retry;
13961 			}
13962 		} else {
13963 			while ((ump->um_softdep->sd_flags &
13964 			    FLUSH_RC_ACTIVE) != 0) {
13965 				msleep(&ump->um_softdep->sd_flags,
13966 				    LOCK_PTR(ump), PVM, "ffsrca", hz);
13967 			}
13968 			FREE_LOCK(ump);
13969 			error = 0;
13970 		}
13971 		stat_cleanup_failures += 1;
13972 	}
13973 	if (time_second - starttime > stat_cleanup_high_delay)
13974 		stat_cleanup_high_delay = time_second - starttime;
13975 	UFS_LOCK(ump);
13976 	return (error);
13977 }
13978 
13979 /*
13980  * Scan the vnodes for the specified mount point flushing out any
13981  * vnodes that can be locked without waiting. Finally, try to flush
13982  * the device associated with the mount point if it can be locked
13983  * without waiting.
13984  *
13985  * We return 0 if we were able to lock every vnode in our scan.
13986  * If we had to skip one or more vnodes, we return 1.
13987  */
13988 static int
13989 softdep_request_cleanup_flush(mp, ump)
13990 	struct mount *mp;
13991 	struct ufsmount *ump;
13992 {
13993 	struct thread *td;
13994 	struct vnode *lvp, *mvp;
13995 	int failed_vnode;
13996 
13997 	failed_vnode = 0;
13998 	td = curthread;
13999 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
14000 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
14001 			VI_UNLOCK(lvp);
14002 			continue;
14003 		}
14004 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT) != 0) {
14005 			failed_vnode = 1;
14006 			continue;
14007 		}
14008 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
14009 			vput(lvp);
14010 			continue;
14011 		}
14012 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
14013 		vput(lvp);
14014 	}
14015 	lvp = ump->um_devvp;
14016 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
14017 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
14018 		VOP_UNLOCK(lvp);
14019 	}
14020 	return (failed_vnode);
14021 }
14022 
14023 static bool
14024 softdep_excess_items(struct ufsmount *ump, int item)
14025 {
14026 
14027 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
14028 	return (dep_current[item] > max_softdeps &&
14029 	    ump->softdep_curdeps[item] > max_softdeps /
14030 	    stat_flush_threads);
14031 }
14032 
14033 static void
14034 schedule_cleanup(struct mount *mp)
14035 {
14036 	struct ufsmount *ump;
14037 	struct thread *td;
14038 
14039 	ump = VFSTOUFS(mp);
14040 	LOCK_OWNED(ump);
14041 	FREE_LOCK(ump);
14042 	td = curthread;
14043 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
14044 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
14045 		/*
14046 		 * No ast is delivered to kernel threads, so nobody
14047 		 * would deref the mp.  Some kernel threads
14048 		 * explicitely check for AST, e.g. NFS daemon does
14049 		 * this in the serving loop.
14050 		 */
14051 		return;
14052 	}
14053 	if (td->td_su != NULL)
14054 		vfs_rel(td->td_su);
14055 	vfs_ref(mp);
14056 	td->td_su = mp;
14057 	thread_lock(td);
14058 	td->td_flags |= TDF_ASTPENDING;
14059 	thread_unlock(td);
14060 }
14061 
14062 static void
14063 softdep_ast_cleanup_proc(struct thread *td)
14064 {
14065 	struct mount *mp;
14066 	struct ufsmount *ump;
14067 	int error;
14068 	bool req;
14069 
14070 	while ((mp = td->td_su) != NULL) {
14071 		td->td_su = NULL;
14072 		error = vfs_busy(mp, MBF_NOWAIT);
14073 		vfs_rel(mp);
14074 		if (error != 0)
14075 			return;
14076 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
14077 			ump = VFSTOUFS(mp);
14078 			for (;;) {
14079 				req = false;
14080 				ACQUIRE_LOCK(ump);
14081 				if (softdep_excess_items(ump, D_INODEDEP)) {
14082 					req = true;
14083 					request_cleanup(mp, FLUSH_INODES);
14084 				}
14085 				if (softdep_excess_items(ump, D_DIRREM)) {
14086 					req = true;
14087 					request_cleanup(mp, FLUSH_BLOCKS);
14088 				}
14089 				FREE_LOCK(ump);
14090 				if (softdep_excess_items(ump, D_NEWBLK) ||
14091 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
14092 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
14093 					error = vn_start_write(NULL, &mp,
14094 					    V_WAIT);
14095 					if (error == 0) {
14096 						req = true;
14097 						VFS_SYNC(mp, MNT_WAIT);
14098 						vn_finished_write(mp);
14099 					}
14100 				}
14101 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
14102 					break;
14103 			}
14104 		}
14105 		vfs_unbusy(mp);
14106 	}
14107 	if ((mp = td->td_su) != NULL) {
14108 		td->td_su = NULL;
14109 		vfs_rel(mp);
14110 	}
14111 }
14112 
14113 /*
14114  * If memory utilization has gotten too high, deliberately slow things
14115  * down and speed up the I/O processing.
14116  */
14117 static int
14118 request_cleanup(mp, resource)
14119 	struct mount *mp;
14120 	int resource;
14121 {
14122 	struct thread *td = curthread;
14123 	struct ufsmount *ump;
14124 
14125 	ump = VFSTOUFS(mp);
14126 	LOCK_OWNED(ump);
14127 	/*
14128 	 * We never hold up the filesystem syncer or buf daemon.
14129 	 */
14130 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
14131 		return (0);
14132 	/*
14133 	 * First check to see if the work list has gotten backlogged.
14134 	 * If it has, co-opt this process to help clean up two entries.
14135 	 * Because this process may hold inodes locked, we cannot
14136 	 * handle any remove requests that might block on a locked
14137 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
14138 	 * to avoid recursively processing the worklist.
14139 	 */
14140 	if (ump->softdep_on_worklist > max_softdeps / 10) {
14141 		td->td_pflags |= TDP_SOFTDEP;
14142 		process_worklist_item(mp, 2, LK_NOWAIT);
14143 		td->td_pflags &= ~TDP_SOFTDEP;
14144 		stat_worklist_push += 2;
14145 		return(1);
14146 	}
14147 	/*
14148 	 * Next, we attempt to speed up the syncer process. If that
14149 	 * is successful, then we allow the process to continue.
14150 	 */
14151 	if (softdep_speedup(ump) &&
14152 	    resource != FLUSH_BLOCKS_WAIT &&
14153 	    resource != FLUSH_INODES_WAIT)
14154 		return(0);
14155 	/*
14156 	 * If we are resource constrained on inode dependencies, try
14157 	 * flushing some dirty inodes. Otherwise, we are constrained
14158 	 * by file deletions, so try accelerating flushes of directories
14159 	 * with removal dependencies. We would like to do the cleanup
14160 	 * here, but we probably hold an inode locked at this point and
14161 	 * that might deadlock against one that we try to clean. So,
14162 	 * the best that we can do is request the syncer daemon to do
14163 	 * the cleanup for us.
14164 	 */
14165 	switch (resource) {
14166 	case FLUSH_INODES:
14167 	case FLUSH_INODES_WAIT:
14168 		ACQUIRE_GBLLOCK(&lk);
14169 		stat_ino_limit_push += 1;
14170 		req_clear_inodedeps += 1;
14171 		FREE_GBLLOCK(&lk);
14172 		stat_countp = &stat_ino_limit_hit;
14173 		break;
14174 
14175 	case FLUSH_BLOCKS:
14176 	case FLUSH_BLOCKS_WAIT:
14177 		ACQUIRE_GBLLOCK(&lk);
14178 		stat_blk_limit_push += 1;
14179 		req_clear_remove += 1;
14180 		FREE_GBLLOCK(&lk);
14181 		stat_countp = &stat_blk_limit_hit;
14182 		break;
14183 
14184 	default:
14185 		panic("request_cleanup: unknown type");
14186 	}
14187 	/*
14188 	 * Hopefully the syncer daemon will catch up and awaken us.
14189 	 * We wait at most tickdelay before proceeding in any case.
14190 	 */
14191 	ACQUIRE_GBLLOCK(&lk);
14192 	FREE_LOCK(ump);
14193 	proc_waiting += 1;
14194 	if (callout_pending(&softdep_callout) == FALSE)
14195 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
14196 		    pause_timer, 0);
14197 
14198 	if ((td->td_pflags & TDP_KTHREAD) == 0)
14199 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
14200 	proc_waiting -= 1;
14201 	FREE_GBLLOCK(&lk);
14202 	ACQUIRE_LOCK(ump);
14203 	return (1);
14204 }
14205 
14206 /*
14207  * Awaken processes pausing in request_cleanup and clear proc_waiting
14208  * to indicate that there is no longer a timer running. Pause_timer
14209  * will be called with the global softdep mutex (&lk) locked.
14210  */
14211 static void
14212 pause_timer(arg)
14213 	void *arg;
14214 {
14215 
14216 	GBLLOCK_OWNED(&lk);
14217 	/*
14218 	 * The callout_ API has acquired mtx and will hold it around this
14219 	 * function call.
14220 	 */
14221 	*stat_countp += proc_waiting;
14222 	wakeup(&proc_waiting);
14223 }
14224 
14225 /*
14226  * If requested, try removing inode or removal dependencies.
14227  */
14228 static void
14229 check_clear_deps(mp)
14230 	struct mount *mp;
14231 {
14232 	struct ufsmount *ump;
14233 	bool suj_susp;
14234 
14235 	/*
14236 	 * Tell the lower layers that any TRIM or WRITE transactions that have
14237 	 * been delayed for performance reasons should proceed to help alleviate
14238 	 * the shortage faster. The race between checking req_* and the softdep
14239 	 * mutex (lk) is fine since this is an advisory operation that at most
14240 	 * causes deferred work to be done sooner.
14241 	 */
14242 	ump = VFSTOUFS(mp);
14243 	suj_susp = ump->um_softdep->sd_jblocks != NULL &&
14244 	    ump->softdep_jblocks->jb_suspended;
14245 	if (req_clear_remove || req_clear_inodedeps || suj_susp) {
14246 		FREE_LOCK(ump);
14247 		softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
14248 		ACQUIRE_LOCK(ump);
14249 	}
14250 
14251 	/*
14252 	 * If we are suspended, it may be because of our using
14253 	 * too many inodedeps, so help clear them out.
14254 	 */
14255 	if (suj_susp)
14256 		clear_inodedeps(mp);
14257 
14258 	/*
14259 	 * General requests for cleanup of backed up dependencies
14260 	 */
14261 	ACQUIRE_GBLLOCK(&lk);
14262 	if (req_clear_inodedeps) {
14263 		req_clear_inodedeps -= 1;
14264 		FREE_GBLLOCK(&lk);
14265 		clear_inodedeps(mp);
14266 		ACQUIRE_GBLLOCK(&lk);
14267 		wakeup(&proc_waiting);
14268 	}
14269 	if (req_clear_remove) {
14270 		req_clear_remove -= 1;
14271 		FREE_GBLLOCK(&lk);
14272 		clear_remove(mp);
14273 		ACQUIRE_GBLLOCK(&lk);
14274 		wakeup(&proc_waiting);
14275 	}
14276 	FREE_GBLLOCK(&lk);
14277 }
14278 
14279 /*
14280  * Flush out a directory with at least one removal dependency in an effort to
14281  * reduce the number of dirrem, freefile, and freeblks dependency structures.
14282  */
14283 static void
14284 clear_remove(mp)
14285 	struct mount *mp;
14286 {
14287 	struct pagedep_hashhead *pagedephd;
14288 	struct pagedep *pagedep;
14289 	struct ufsmount *ump;
14290 	struct vnode *vp;
14291 	struct bufobj *bo;
14292 	int error, cnt;
14293 	ino_t ino;
14294 
14295 	ump = VFSTOUFS(mp);
14296 	LOCK_OWNED(ump);
14297 
14298 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
14299 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
14300 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
14301 			ump->pagedep_nextclean = 0;
14302 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
14303 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
14304 				continue;
14305 			ino = pagedep->pd_ino;
14306 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14307 				continue;
14308 			FREE_LOCK(ump);
14309 
14310 			/*
14311 			 * Let unmount clear deps
14312 			 */
14313 			error = vfs_busy(mp, MBF_NOWAIT);
14314 			if (error != 0)
14315 				goto finish_write;
14316 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14317 			     FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
14318 			vfs_unbusy(mp);
14319 			if (error != 0) {
14320 				softdep_error("clear_remove: vget", error);
14321 				goto finish_write;
14322 			}
14323 			MPASS(VTOI(vp)->i_mode != 0);
14324 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14325 				softdep_error("clear_remove: fsync", error);
14326 			bo = &vp->v_bufobj;
14327 			BO_LOCK(bo);
14328 			drain_output(vp);
14329 			BO_UNLOCK(bo);
14330 			vput(vp);
14331 		finish_write:
14332 			vn_finished_write(mp);
14333 			ACQUIRE_LOCK(ump);
14334 			return;
14335 		}
14336 	}
14337 }
14338 
14339 /*
14340  * Clear out a block of dirty inodes in an effort to reduce
14341  * the number of inodedep dependency structures.
14342  */
14343 static void
14344 clear_inodedeps(mp)
14345 	struct mount *mp;
14346 {
14347 	struct inodedep_hashhead *inodedephd;
14348 	struct inodedep *inodedep;
14349 	struct ufsmount *ump;
14350 	struct vnode *vp;
14351 	struct fs *fs;
14352 	int error, cnt;
14353 	ino_t firstino, lastino, ino;
14354 
14355 	ump = VFSTOUFS(mp);
14356 	fs = ump->um_fs;
14357 	LOCK_OWNED(ump);
14358 	/*
14359 	 * Pick a random inode dependency to be cleared.
14360 	 * We will then gather up all the inodes in its block
14361 	 * that have dependencies and flush them out.
14362 	 */
14363 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
14364 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
14365 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
14366 			ump->inodedep_nextclean = 0;
14367 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
14368 			break;
14369 	}
14370 	if (inodedep == NULL)
14371 		return;
14372 	/*
14373 	 * Find the last inode in the block with dependencies.
14374 	 */
14375 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
14376 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
14377 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
14378 			break;
14379 	/*
14380 	 * Asynchronously push all but the last inode with dependencies.
14381 	 * Synchronously push the last inode with dependencies to ensure
14382 	 * that the inode block gets written to free up the inodedeps.
14383 	 */
14384 	for (ino = firstino; ino <= lastino; ino++) {
14385 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
14386 			continue;
14387 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14388 			continue;
14389 		FREE_LOCK(ump);
14390 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
14391 		if (error != 0) {
14392 			vn_finished_write(mp);
14393 			ACQUIRE_LOCK(ump);
14394 			return;
14395 		}
14396 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14397 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP)) != 0) {
14398 			softdep_error("clear_inodedeps: vget", error);
14399 			vfs_unbusy(mp);
14400 			vn_finished_write(mp);
14401 			ACQUIRE_LOCK(ump);
14402 			return;
14403 		}
14404 		vfs_unbusy(mp);
14405 		if (VTOI(vp)->i_mode == 0) {
14406 			vgone(vp);
14407 		} else if (ino == lastino) {
14408 			do {
14409 				error = ffs_syncvnode(vp, MNT_WAIT, 0);
14410 			} while (error == ERELOOKUP);
14411 			if (error != 0)
14412 				softdep_error("clear_inodedeps: fsync1", error);
14413 		} else {
14414 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14415 				softdep_error("clear_inodedeps: fsync2", error);
14416 			BO_LOCK(&vp->v_bufobj);
14417 			drain_output(vp);
14418 			BO_UNLOCK(&vp->v_bufobj);
14419 		}
14420 		vput(vp);
14421 		vn_finished_write(mp);
14422 		ACQUIRE_LOCK(ump);
14423 	}
14424 }
14425 
14426 void
14427 softdep_buf_append(bp, wkhd)
14428 	struct buf *bp;
14429 	struct workhead *wkhd;
14430 {
14431 	struct worklist *wk;
14432 	struct ufsmount *ump;
14433 
14434 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14435 		return;
14436 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14437 	    ("softdep_buf_append called on non-softdep filesystem"));
14438 	ump = VFSTOUFS(wk->wk_mp);
14439 	ACQUIRE_LOCK(ump);
14440 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
14441 		WORKLIST_REMOVE(wk);
14442 		WORKLIST_INSERT(&bp->b_dep, wk);
14443 	}
14444 	FREE_LOCK(ump);
14445 
14446 }
14447 
14448 void
14449 softdep_inode_append(ip, cred, wkhd)
14450 	struct inode *ip;
14451 	struct ucred *cred;
14452 	struct workhead *wkhd;
14453 {
14454 	struct buf *bp;
14455 	struct fs *fs;
14456 	struct ufsmount *ump;
14457 	int error;
14458 
14459 	ump = ITOUMP(ip);
14460 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
14461 	    ("softdep_inode_append called on non-softdep filesystem"));
14462 	fs = ump->um_fs;
14463 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14464 	    (int)fs->fs_bsize, cred, &bp);
14465 	if (error) {
14466 		bqrelse(bp);
14467 		softdep_freework(wkhd);
14468 		return;
14469 	}
14470 	softdep_buf_append(bp, wkhd);
14471 	bqrelse(bp);
14472 }
14473 
14474 void
14475 softdep_freework(wkhd)
14476 	struct workhead *wkhd;
14477 {
14478 	struct worklist *wk;
14479 	struct ufsmount *ump;
14480 
14481 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14482 		return;
14483 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14484 	    ("softdep_freework called on non-softdep filesystem"));
14485 	ump = VFSTOUFS(wk->wk_mp);
14486 	ACQUIRE_LOCK(ump);
14487 	handle_jwork(wkhd);
14488 	FREE_LOCK(ump);
14489 }
14490 
14491 static struct ufsmount *
14492 softdep_bp_to_mp(bp)
14493 	struct buf *bp;
14494 {
14495 	struct mount *mp;
14496 	struct vnode *vp;
14497 
14498 	if (LIST_EMPTY(&bp->b_dep))
14499 		return (NULL);
14500 	vp = bp->b_vp;
14501 	KASSERT(vp != NULL,
14502 	    ("%s, buffer with dependencies lacks vnode", __func__));
14503 
14504 	/*
14505 	 * The ump mount point is stable after we get a correct
14506 	 * pointer, since bp is locked and this prevents unmount from
14507 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
14508 	 * head wk_mp, because we do not yet own SU ump lock and
14509 	 * workitem might be freed while dereferenced.
14510 	 */
14511 retry:
14512 	switch (vp->v_type) {
14513 	case VCHR:
14514 		VI_LOCK(vp);
14515 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14516 		VI_UNLOCK(vp);
14517 		if (mp == NULL)
14518 			goto retry;
14519 		break;
14520 	case VREG:
14521 	case VDIR:
14522 	case VLNK:
14523 	case VFIFO:
14524 	case VSOCK:
14525 		mp = vp->v_mount;
14526 		break;
14527 	case VBLK:
14528 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14529 		/* FALLTHROUGH */
14530 	case VNON:
14531 	case VBAD:
14532 	case VMARKER:
14533 		mp = NULL;
14534 		break;
14535 	default:
14536 		vn_printf(vp, "unknown vnode type");
14537 		mp = NULL;
14538 		break;
14539 	}
14540 	return (VFSTOUFS(mp));
14541 }
14542 
14543 /*
14544  * Function to determine if the buffer has outstanding dependencies
14545  * that will cause a roll-back if the buffer is written. If wantcount
14546  * is set, return number of dependencies, otherwise just yes or no.
14547  */
14548 static int
14549 softdep_count_dependencies(bp, wantcount)
14550 	struct buf *bp;
14551 	int wantcount;
14552 {
14553 	struct worklist *wk;
14554 	struct ufsmount *ump;
14555 	struct bmsafemap *bmsafemap;
14556 	struct freework *freework;
14557 	struct inodedep *inodedep;
14558 	struct indirdep *indirdep;
14559 	struct freeblks *freeblks;
14560 	struct allocindir *aip;
14561 	struct pagedep *pagedep;
14562 	struct dirrem *dirrem;
14563 	struct newblk *newblk;
14564 	struct mkdir *mkdir;
14565 	struct diradd *dap;
14566 	int i, retval;
14567 
14568 	ump = softdep_bp_to_mp(bp);
14569 	if (ump == NULL)
14570 		return (0);
14571 	retval = 0;
14572 	ACQUIRE_LOCK(ump);
14573 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14574 		switch (wk->wk_type) {
14575 		case D_INODEDEP:
14576 			inodedep = WK_INODEDEP(wk);
14577 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14578 				/* bitmap allocation dependency */
14579 				retval += 1;
14580 				if (!wantcount)
14581 					goto out;
14582 			}
14583 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14584 				/* direct block pointer dependency */
14585 				retval += 1;
14586 				if (!wantcount)
14587 					goto out;
14588 			}
14589 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14590 				/* direct block pointer dependency */
14591 				retval += 1;
14592 				if (!wantcount)
14593 					goto out;
14594 			}
14595 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14596 				/* Add reference dependency. */
14597 				retval += 1;
14598 				if (!wantcount)
14599 					goto out;
14600 			}
14601 			continue;
14602 
14603 		case D_INDIRDEP:
14604 			indirdep = WK_INDIRDEP(wk);
14605 
14606 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14607 				/* indirect truncation dependency */
14608 				retval += 1;
14609 				if (!wantcount)
14610 					goto out;
14611 			}
14612 
14613 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14614 				/* indirect block pointer dependency */
14615 				retval += 1;
14616 				if (!wantcount)
14617 					goto out;
14618 			}
14619 			continue;
14620 
14621 		case D_PAGEDEP:
14622 			pagedep = WK_PAGEDEP(wk);
14623 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14624 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14625 					/* Journal remove ref dependency. */
14626 					retval += 1;
14627 					if (!wantcount)
14628 						goto out;
14629 				}
14630 			}
14631 			for (i = 0; i < DAHASHSZ; i++) {
14632 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14633 					/* directory entry dependency */
14634 					retval += 1;
14635 					if (!wantcount)
14636 						goto out;
14637 				}
14638 			}
14639 			continue;
14640 
14641 		case D_BMSAFEMAP:
14642 			bmsafemap = WK_BMSAFEMAP(wk);
14643 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14644 				/* Add reference dependency. */
14645 				retval += 1;
14646 				if (!wantcount)
14647 					goto out;
14648 			}
14649 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14650 				/* Allocate block dependency. */
14651 				retval += 1;
14652 				if (!wantcount)
14653 					goto out;
14654 			}
14655 			continue;
14656 
14657 		case D_FREEBLKS:
14658 			freeblks = WK_FREEBLKS(wk);
14659 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14660 				/* Freeblk journal dependency. */
14661 				retval += 1;
14662 				if (!wantcount)
14663 					goto out;
14664 			}
14665 			continue;
14666 
14667 		case D_ALLOCDIRECT:
14668 		case D_ALLOCINDIR:
14669 			newblk = WK_NEWBLK(wk);
14670 			if (newblk->nb_jnewblk) {
14671 				/* Journal allocate dependency. */
14672 				retval += 1;
14673 				if (!wantcount)
14674 					goto out;
14675 			}
14676 			continue;
14677 
14678 		case D_MKDIR:
14679 			mkdir = WK_MKDIR(wk);
14680 			if (mkdir->md_jaddref) {
14681 				/* Journal reference dependency. */
14682 				retval += 1;
14683 				if (!wantcount)
14684 					goto out;
14685 			}
14686 			continue;
14687 
14688 		case D_FREEWORK:
14689 		case D_FREEDEP:
14690 		case D_JSEGDEP:
14691 		case D_JSEG:
14692 		case D_SBDEP:
14693 			/* never a dependency on these blocks */
14694 			continue;
14695 
14696 		default:
14697 			panic("softdep_count_dependencies: Unexpected type %s",
14698 			    TYPENAME(wk->wk_type));
14699 			/* NOTREACHED */
14700 		}
14701 	}
14702 out:
14703 	FREE_LOCK(ump);
14704 	return (retval);
14705 }
14706 
14707 /*
14708  * Acquire exclusive access to a buffer.
14709  * Must be called with a locked mtx parameter.
14710  * Return acquired buffer or NULL on failure.
14711  */
14712 static struct buf *
14713 getdirtybuf(bp, lock, waitfor)
14714 	struct buf *bp;
14715 	struct rwlock *lock;
14716 	int waitfor;
14717 {
14718 	int error;
14719 
14720 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14721 		if (waitfor != MNT_WAIT)
14722 			return (NULL);
14723 		error = BUF_LOCK(bp,
14724 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14725 		/*
14726 		 * Even if we successfully acquire bp here, we have dropped
14727 		 * lock, which may violates our guarantee.
14728 		 */
14729 		if (error == 0)
14730 			BUF_UNLOCK(bp);
14731 		else if (error != ENOLCK)
14732 			panic("getdirtybuf: inconsistent lock: %d", error);
14733 		rw_wlock(lock);
14734 		return (NULL);
14735 	}
14736 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14737 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14738 			rw_wunlock(lock);
14739 			BO_LOCK(bp->b_bufobj);
14740 			BUF_UNLOCK(bp);
14741 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14742 				bp->b_vflags |= BV_BKGRDWAIT;
14743 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14744 				       PRIBIO | PDROP, "getbuf", 0);
14745 			} else
14746 				BO_UNLOCK(bp->b_bufobj);
14747 			rw_wlock(lock);
14748 			return (NULL);
14749 		}
14750 		BUF_UNLOCK(bp);
14751 		if (waitfor != MNT_WAIT)
14752 			return (NULL);
14753 #ifdef DEBUG_VFS_LOCKS
14754 		if (bp->b_vp->v_type != VCHR)
14755 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14756 #endif
14757 		bp->b_vflags |= BV_BKGRDWAIT;
14758 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14759 		return (NULL);
14760 	}
14761 	if ((bp->b_flags & B_DELWRI) == 0) {
14762 		BUF_UNLOCK(bp);
14763 		return (NULL);
14764 	}
14765 	bremfree(bp);
14766 	return (bp);
14767 }
14768 
14769 /*
14770  * Check if it is safe to suspend the file system now.  On entry,
14771  * the vnode interlock for devvp should be held.  Return 0 with
14772  * the mount interlock held if the file system can be suspended now,
14773  * otherwise return EAGAIN with the mount interlock held.
14774  */
14775 int
14776 softdep_check_suspend(struct mount *mp,
14777 		      struct vnode *devvp,
14778 		      int softdep_depcnt,
14779 		      int softdep_accdepcnt,
14780 		      int secondary_writes,
14781 		      int secondary_accwrites)
14782 {
14783 	struct buf *bp;
14784 	struct bufobj *bo;
14785 	struct ufsmount *ump;
14786 	struct inodedep *inodedep;
14787 	struct indirdep *indirdep;
14788 	struct worklist *wk, *nextwk;
14789 	int error, unlinked;
14790 
14791 	bo = &devvp->v_bufobj;
14792 	ASSERT_BO_WLOCKED(bo);
14793 
14794 	/*
14795 	 * If we are not running with soft updates, then we need only
14796 	 * deal with secondary writes as we try to suspend.
14797 	 */
14798 	if (MOUNTEDSOFTDEP(mp) == 0) {
14799 		MNT_ILOCK(mp);
14800 		while (mp->mnt_secondary_writes != 0) {
14801 			BO_UNLOCK(bo);
14802 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14803 			    (PUSER - 1) | PDROP, "secwr", 0);
14804 			BO_LOCK(bo);
14805 			MNT_ILOCK(mp);
14806 		}
14807 
14808 		/*
14809 		 * Reasons for needing more work before suspend:
14810 		 * - Dirty buffers on devvp.
14811 		 * - Secondary writes occurred after start of vnode sync loop
14812 		 */
14813 		error = 0;
14814 		if (bo->bo_numoutput > 0 ||
14815 		    bo->bo_dirty.bv_cnt > 0 ||
14816 		    secondary_writes != 0 ||
14817 		    mp->mnt_secondary_writes != 0 ||
14818 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14819 			error = EAGAIN;
14820 		BO_UNLOCK(bo);
14821 		return (error);
14822 	}
14823 
14824 	/*
14825 	 * If we are running with soft updates, then we need to coordinate
14826 	 * with them as we try to suspend.
14827 	 */
14828 	ump = VFSTOUFS(mp);
14829 	for (;;) {
14830 		if (!TRY_ACQUIRE_LOCK(ump)) {
14831 			BO_UNLOCK(bo);
14832 			ACQUIRE_LOCK(ump);
14833 			FREE_LOCK(ump);
14834 			BO_LOCK(bo);
14835 			continue;
14836 		}
14837 		MNT_ILOCK(mp);
14838 		if (mp->mnt_secondary_writes != 0) {
14839 			FREE_LOCK(ump);
14840 			BO_UNLOCK(bo);
14841 			msleep(&mp->mnt_secondary_writes,
14842 			       MNT_MTX(mp),
14843 			       (PUSER - 1) | PDROP, "secwr", 0);
14844 			BO_LOCK(bo);
14845 			continue;
14846 		}
14847 		break;
14848 	}
14849 
14850 	unlinked = 0;
14851 	if (MOUNTEDSUJ(mp)) {
14852 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14853 		    inodedep != NULL;
14854 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14855 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14856 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14857 			    UNLINKONLIST) ||
14858 			    !check_inodedep_free(inodedep))
14859 				continue;
14860 			unlinked++;
14861 		}
14862 	}
14863 
14864 	/*
14865 	 * XXX Check for orphaned indirdep dependency structures.
14866 	 *
14867 	 * During forcible unmount after a disk failure there is a
14868 	 * bug that causes one or more indirdep dependency structures
14869 	 * to fail to be deallocated. We check for them here and clean
14870 	 * them up so that the unmount can succeed.
14871 	 */
14872 	if ((ump->um_flags & UM_FSFAIL_CLEANUP) != 0 && ump->softdep_deps > 0 &&
14873 	    ump->softdep_deps == ump->softdep_curdeps[D_INDIRDEP]) {
14874 		LIST_FOREACH_SAFE(wk, &ump->softdep_alldeps[D_INDIRDEP],
14875 		    wk_all, nextwk) {
14876 			indirdep = WK_INDIRDEP(wk);
14877 			if ((indirdep->ir_state & (GOINGAWAY | DEPCOMPLETE)) !=
14878 			    (GOINGAWAY | DEPCOMPLETE) ||
14879 			    !TAILQ_EMPTY(&indirdep->ir_trunc) ||
14880 			    !LIST_EMPTY(&indirdep->ir_completehd) ||
14881 			    !LIST_EMPTY(&indirdep->ir_writehd) ||
14882 			    !LIST_EMPTY(&indirdep->ir_donehd) ||
14883 			    !LIST_EMPTY(&indirdep->ir_deplisthd) ||
14884 			    indirdep->ir_saveddata != NULL ||
14885 			    indirdep->ir_savebp == NULL) {
14886 				printf("%s: skipping orphaned indirdep %p\n",
14887 				    __FUNCTION__, indirdep);
14888 				continue;
14889 			}
14890 			printf("%s: freeing orphaned indirdep %p\n",
14891 			    __FUNCTION__, indirdep);
14892 			bp = indirdep->ir_savebp;
14893 			indirdep->ir_savebp = NULL;
14894 			free_indirdep(indirdep);
14895 			FREE_LOCK(ump);
14896 			brelse(bp);
14897 			while (!TRY_ACQUIRE_LOCK(ump)) {
14898 				BO_UNLOCK(bo);
14899 				ACQUIRE_LOCK(ump);
14900 				FREE_LOCK(ump);
14901 				BO_LOCK(bo);
14902 			}
14903 		}
14904 	}
14905 
14906 	/*
14907 	 * Reasons for needing more work before suspend:
14908 	 * - Dirty buffers on devvp.
14909 	 * - Dependency structures still exist
14910 	 * - Softdep activity occurred after start of vnode sync loop
14911 	 * - Secondary writes occurred after start of vnode sync loop
14912 	 */
14913 	error = 0;
14914 	if (bo->bo_numoutput > 0 ||
14915 	    bo->bo_dirty.bv_cnt > 0 ||
14916 	    softdep_depcnt != unlinked ||
14917 	    ump->softdep_deps != unlinked ||
14918 	    softdep_accdepcnt != ump->softdep_accdeps ||
14919 	    secondary_writes != 0 ||
14920 	    mp->mnt_secondary_writes != 0 ||
14921 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14922 		error = EAGAIN;
14923 	FREE_LOCK(ump);
14924 	BO_UNLOCK(bo);
14925 	return (error);
14926 }
14927 
14928 /*
14929  * Get the number of dependency structures for the file system, both
14930  * the current number and the total number allocated.  These will
14931  * later be used to detect that softdep processing has occurred.
14932  */
14933 void
14934 softdep_get_depcounts(struct mount *mp,
14935 		      int *softdep_depsp,
14936 		      int *softdep_accdepsp)
14937 {
14938 	struct ufsmount *ump;
14939 
14940 	if (MOUNTEDSOFTDEP(mp) == 0) {
14941 		*softdep_depsp = 0;
14942 		*softdep_accdepsp = 0;
14943 		return;
14944 	}
14945 	ump = VFSTOUFS(mp);
14946 	ACQUIRE_LOCK(ump);
14947 	*softdep_depsp = ump->softdep_deps;
14948 	*softdep_accdepsp = ump->softdep_accdeps;
14949 	FREE_LOCK(ump);
14950 }
14951 
14952 /*
14953  * Wait for pending output on a vnode to complete.
14954  */
14955 static void
14956 drain_output(vp)
14957 	struct vnode *vp;
14958 {
14959 
14960 	ASSERT_VOP_LOCKED(vp, "drain_output");
14961 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14962 }
14963 
14964 /*
14965  * Called whenever a buffer that is being invalidated or reallocated
14966  * contains dependencies. This should only happen if an I/O error has
14967  * occurred. The routine is called with the buffer locked.
14968  */
14969 static void
14970 softdep_deallocate_dependencies(bp)
14971 	struct buf *bp;
14972 {
14973 
14974 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14975 		panic("softdep_deallocate_dependencies: dangling deps");
14976 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14977 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14978 	else
14979 		printf("softdep_deallocate_dependencies: "
14980 		    "got error %d while accessing filesystem\n", bp->b_error);
14981 	if (bp->b_error != ENXIO)
14982 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14983 }
14984 
14985 /*
14986  * Function to handle asynchronous write errors in the filesystem.
14987  */
14988 static void
14989 softdep_error(func, error)
14990 	char *func;
14991 	int error;
14992 {
14993 
14994 	/* XXX should do something better! */
14995 	printf("%s: got error %d while accessing filesystem\n", func, error);
14996 }
14997 
14998 #ifdef DDB
14999 
15000 /* exported to ffs_vfsops.c */
15001 extern void db_print_ffs(struct ufsmount *ump);
15002 void
15003 db_print_ffs(struct ufsmount *ump)
15004 {
15005 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
15006 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
15007 	db_printf("    fs %p ", ump->um_fs);
15008 
15009 	if (ump->um_softdep != NULL) {
15010 		db_printf("su_wl %d su_deps %d su_req %d\n",
15011 		    ump->softdep_on_worklist, ump->softdep_deps,
15012 		    ump->softdep_req);
15013 	} else {
15014 		db_printf("su disabled\n");
15015 	}
15016 }
15017 
15018 static void
15019 worklist_print(struct worklist *wk, int verbose)
15020 {
15021 
15022 	if (!verbose) {
15023 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
15024 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
15025 		return;
15026 	}
15027 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
15028 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
15029 	    LIST_NEXT(wk, wk_list));
15030 	db_print_ffs(VFSTOUFS(wk->wk_mp));
15031 }
15032 
15033 static void
15034 inodedep_print(struct inodedep *inodedep, int verbose)
15035 {
15036 
15037 	worklist_print(&inodedep->id_list, 0);
15038 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
15039 	    inodedep->id_fs,
15040 	    (intmax_t)inodedep->id_ino,
15041 	    (intmax_t)fsbtodb(inodedep->id_fs,
15042 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
15043 	    (intmax_t)inodedep->id_nlinkdelta,
15044 	    (intmax_t)inodedep->id_savednlink);
15045 
15046 	if (verbose == 0)
15047 		return;
15048 
15049 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
15050 	    inodedep->id_bmsafemap,
15051 	    inodedep->id_mkdiradd,
15052 	    TAILQ_FIRST(&inodedep->id_inoreflst));
15053 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
15054 	    LIST_FIRST(&inodedep->id_dirremhd),
15055 	    LIST_FIRST(&inodedep->id_pendinghd),
15056 	    LIST_FIRST(&inodedep->id_bufwait));
15057 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
15058 	    LIST_FIRST(&inodedep->id_inowait),
15059 	    TAILQ_FIRST(&inodedep->id_inoupdt),
15060 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
15061 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
15062 	    TAILQ_FIRST(&inodedep->id_extupdt),
15063 	    TAILQ_FIRST(&inodedep->id_newextupdt),
15064 	    TAILQ_FIRST(&inodedep->id_freeblklst));
15065 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
15066 	    inodedep->id_savedino1,
15067 	    (intmax_t)inodedep->id_savedsize,
15068 	    (intmax_t)inodedep->id_savedextsize);
15069 }
15070 
15071 static void
15072 newblk_print(struct newblk *nbp)
15073 {
15074 
15075 	worklist_print(&nbp->nb_list, 0);
15076 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
15077 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
15078 	    &nbp->nb_jnewblk,
15079 	    &nbp->nb_bmsafemap,
15080 	    &nbp->nb_freefrag);
15081 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
15082 	    LIST_FIRST(&nbp->nb_indirdeps),
15083 	    LIST_FIRST(&nbp->nb_newdirblk),
15084 	    LIST_FIRST(&nbp->nb_jwork));
15085 }
15086 
15087 static void
15088 allocdirect_print(struct allocdirect *adp)
15089 {
15090 
15091 	newblk_print(&adp->ad_block);
15092 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
15093 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
15094 	db_printf("    offset %d, inodedep %p\n",
15095 	    adp->ad_offset, adp->ad_inodedep);
15096 }
15097 
15098 static void
15099 allocindir_print(struct allocindir *aip)
15100 {
15101 
15102 	newblk_print(&aip->ai_block);
15103 	db_printf("    oldblkno %jd, lbn %jd\n",
15104 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
15105 	db_printf("    offset %d, indirdep %p\n",
15106 	    aip->ai_offset, aip->ai_indirdep);
15107 }
15108 
15109 static void
15110 mkdir_print(struct mkdir *mkdir)
15111 {
15112 
15113 	worklist_print(&mkdir->md_list, 0);
15114 	db_printf("    diradd %p, jaddref %p, buf %p\n",
15115 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
15116 }
15117 
15118 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
15119 {
15120 
15121 	if (have_addr == 0) {
15122 		db_printf("inodedep address required\n");
15123 		return;
15124 	}
15125 	inodedep_print((struct inodedep*)addr, 1);
15126 }
15127 
15128 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
15129 {
15130 	struct inodedep_hashhead *inodedephd;
15131 	struct inodedep *inodedep;
15132 	struct ufsmount *ump;
15133 	int cnt;
15134 
15135 	if (have_addr == 0) {
15136 		db_printf("ufsmount address required\n");
15137 		return;
15138 	}
15139 	ump = (struct ufsmount *)addr;
15140 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
15141 		inodedephd = &ump->inodedep_hashtbl[cnt];
15142 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
15143 			inodedep_print(inodedep, 0);
15144 		}
15145 	}
15146 }
15147 
15148 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
15149 {
15150 
15151 	if (have_addr == 0) {
15152 		db_printf("worklist address required\n");
15153 		return;
15154 	}
15155 	worklist_print((struct worklist *)addr, 1);
15156 }
15157 
15158 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
15159 {
15160 	struct worklist *wk;
15161 	struct workhead *wkhd;
15162 
15163 	if (have_addr == 0) {
15164 		db_printf("worklist address required "
15165 		    "(for example value in bp->b_dep)\n");
15166 		return;
15167 	}
15168 	/*
15169 	 * We often do not have the address of the worklist head but
15170 	 * instead a pointer to its first entry (e.g., we have the
15171 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
15172 	 * pointer of bp->b_dep will point at the head of the list, so
15173 	 * we cheat and use that instead. If we are in the middle of
15174 	 * a list we will still get the same result, so nothing
15175 	 * unexpected will result.
15176 	 */
15177 	wk = (struct worklist *)addr;
15178 	if (wk == NULL)
15179 		return;
15180 	wkhd = (struct workhead *)wk->wk_list.le_prev;
15181 	LIST_FOREACH(wk, wkhd, wk_list) {
15182 		switch(wk->wk_type) {
15183 		case D_INODEDEP:
15184 			inodedep_print(WK_INODEDEP(wk), 0);
15185 			continue;
15186 		case D_ALLOCDIRECT:
15187 			allocdirect_print(WK_ALLOCDIRECT(wk));
15188 			continue;
15189 		case D_ALLOCINDIR:
15190 			allocindir_print(WK_ALLOCINDIR(wk));
15191 			continue;
15192 		case D_MKDIR:
15193 			mkdir_print(WK_MKDIR(wk));
15194 			continue;
15195 		default:
15196 			worklist_print(wk, 0);
15197 			continue;
15198 		}
15199 	}
15200 }
15201 
15202 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
15203 {
15204 	if (have_addr == 0) {
15205 		db_printf("mkdir address required\n");
15206 		return;
15207 	}
15208 	mkdir_print((struct mkdir *)addr);
15209 }
15210 
15211 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
15212 {
15213 	struct mkdirlist *mkdirlisthd;
15214 	struct mkdir *mkdir;
15215 
15216 	if (have_addr == 0) {
15217 		db_printf("mkdir listhead address required\n");
15218 		return;
15219 	}
15220 	mkdirlisthd = (struct mkdirlist *)addr;
15221 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
15222 		mkdir_print(mkdir);
15223 		if (mkdir->md_diradd != NULL) {
15224 			db_printf("    ");
15225 			worklist_print(&mkdir->md_diradd->da_list, 0);
15226 		}
15227 		if (mkdir->md_jaddref != NULL) {
15228 			db_printf("    ");
15229 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
15230 		}
15231 	}
15232 }
15233 
15234 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
15235 {
15236 	if (have_addr == 0) {
15237 		db_printf("allocdirect address required\n");
15238 		return;
15239 	}
15240 	allocdirect_print((struct allocdirect *)addr);
15241 }
15242 
15243 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
15244 {
15245 	if (have_addr == 0) {
15246 		db_printf("allocindir address required\n");
15247 		return;
15248 	}
15249 	allocindir_print((struct allocindir *)addr);
15250 }
15251 
15252 #endif /* DDB */
15253 
15254 #endif /* SOFTUPDATES */
15255