xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision cd8537910406e68d4719136a5b0cf6d23bb1b23b)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1998, 2000 Marshall Kirk McKusick.
5  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
6  * All rights reserved.
7  *
8  * The soft updates code is derived from the appendix of a University
9  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
10  * "Soft Updates: A Solution to the Metadata Update Problem in File
11  * Systems", CSE-TR-254-95, August 1995).
12  *
13  * Further information about soft updates can be obtained from:
14  *
15  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
16  *	1614 Oxford Street		mckusick@mckusick.com
17  *	Berkeley, CA 94709-1608		+1-510-843-9542
18  *	USA
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
35  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
36  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
42  */
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include "opt_ffs.h"
48 #include "opt_quota.h"
49 #include "opt_ddb.h"
50 
51 #include <sys/param.h>
52 #include <sys/kernel.h>
53 #include <sys/systm.h>
54 #include <sys/bio.h>
55 #include <sys/buf.h>
56 #include <sys/kdb.h>
57 #include <sys/kthread.h>
58 #include <sys/ktr.h>
59 #include <sys/limits.h>
60 #include <sys/lock.h>
61 #include <sys/malloc.h>
62 #include <sys/mount.h>
63 #include <sys/mutex.h>
64 #include <sys/namei.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/racct.h>
68 #include <sys/rwlock.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/syslog.h>
72 #include <sys/vnode.h>
73 #include <sys/conf.h>
74 
75 #include <ufs/ufs/dir.h>
76 #include <ufs/ufs/extattr.h>
77 #include <ufs/ufs/quota.h>
78 #include <ufs/ufs/inode.h>
79 #include <ufs/ufs/ufsmount.h>
80 #include <ufs/ffs/fs.h>
81 #include <ufs/ffs/softdep.h>
82 #include <ufs/ffs/ffs_extern.h>
83 #include <ufs/ufs/ufs_extern.h>
84 
85 #include <vm/vm.h>
86 #include <vm/vm_extern.h>
87 #include <vm/vm_object.h>
88 
89 #include <geom/geom.h>
90 #include <geom/geom_vfs.h>
91 
92 #include <ddb/ddb.h>
93 
94 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
95 
96 #ifndef SOFTUPDATES
97 
98 int
99 softdep_flushfiles(oldmnt, flags, td)
100 	struct mount *oldmnt;
101 	int flags;
102 	struct thread *td;
103 {
104 
105 	panic("softdep_flushfiles called");
106 }
107 
108 int
109 softdep_mount(devvp, mp, fs, cred)
110 	struct vnode *devvp;
111 	struct mount *mp;
112 	struct fs *fs;
113 	struct ucred *cred;
114 {
115 
116 	return (0);
117 }
118 
119 void
120 softdep_initialize()
121 {
122 
123 	return;
124 }
125 
126 void
127 softdep_uninitialize()
128 {
129 
130 	return;
131 }
132 
133 void
134 softdep_unmount(mp)
135 	struct mount *mp;
136 {
137 
138 	panic("softdep_unmount called");
139 }
140 
141 void
142 softdep_setup_sbupdate(ump, fs, bp)
143 	struct ufsmount *ump;
144 	struct fs *fs;
145 	struct buf *bp;
146 {
147 
148 	panic("softdep_setup_sbupdate called");
149 }
150 
151 void
152 softdep_setup_inomapdep(bp, ip, newinum, mode)
153 	struct buf *bp;
154 	struct inode *ip;
155 	ino_t newinum;
156 	int mode;
157 {
158 
159 	panic("softdep_setup_inomapdep called");
160 }
161 
162 void
163 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
164 	struct buf *bp;
165 	struct mount *mp;
166 	ufs2_daddr_t newblkno;
167 	int frags;
168 	int oldfrags;
169 {
170 
171 	panic("softdep_setup_blkmapdep called");
172 }
173 
174 void
175 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
176 	struct inode *ip;
177 	ufs_lbn_t lbn;
178 	ufs2_daddr_t newblkno;
179 	ufs2_daddr_t oldblkno;
180 	long newsize;
181 	long oldsize;
182 	struct buf *bp;
183 {
184 
185 	panic("softdep_setup_allocdirect called");
186 }
187 
188 void
189 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
190 	struct inode *ip;
191 	ufs_lbn_t lbn;
192 	ufs2_daddr_t newblkno;
193 	ufs2_daddr_t oldblkno;
194 	long newsize;
195 	long oldsize;
196 	struct buf *bp;
197 {
198 
199 	panic("softdep_setup_allocext called");
200 }
201 
202 void
203 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
204 	struct inode *ip;
205 	ufs_lbn_t lbn;
206 	struct buf *bp;
207 	int ptrno;
208 	ufs2_daddr_t newblkno;
209 	ufs2_daddr_t oldblkno;
210 	struct buf *nbp;
211 {
212 
213 	panic("softdep_setup_allocindir_page called");
214 }
215 
216 void
217 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
218 	struct buf *nbp;
219 	struct inode *ip;
220 	struct buf *bp;
221 	int ptrno;
222 	ufs2_daddr_t newblkno;
223 {
224 
225 	panic("softdep_setup_allocindir_meta called");
226 }
227 
228 void
229 softdep_journal_freeblocks(ip, cred, length, flags)
230 	struct inode *ip;
231 	struct ucred *cred;
232 	off_t length;
233 	int flags;
234 {
235 
236 	panic("softdep_journal_freeblocks called");
237 }
238 
239 void
240 softdep_journal_fsync(ip)
241 	struct inode *ip;
242 {
243 
244 	panic("softdep_journal_fsync called");
245 }
246 
247 void
248 softdep_setup_freeblocks(ip, length, flags)
249 	struct inode *ip;
250 	off_t length;
251 	int flags;
252 {
253 
254 	panic("softdep_setup_freeblocks called");
255 }
256 
257 void
258 softdep_freefile(pvp, ino, mode)
259 		struct vnode *pvp;
260 		ino_t ino;
261 		int mode;
262 {
263 
264 	panic("softdep_freefile called");
265 }
266 
267 int
268 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
269 	struct buf *bp;
270 	struct inode *dp;
271 	off_t diroffset;
272 	ino_t newinum;
273 	struct buf *newdirbp;
274 	int isnewblk;
275 {
276 
277 	panic("softdep_setup_directory_add called");
278 }
279 
280 void
281 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
282 	struct buf *bp;
283 	struct inode *dp;
284 	caddr_t base;
285 	caddr_t oldloc;
286 	caddr_t newloc;
287 	int entrysize;
288 {
289 
290 	panic("softdep_change_directoryentry_offset called");
291 }
292 
293 void
294 softdep_setup_remove(bp, dp, ip, isrmdir)
295 	struct buf *bp;
296 	struct inode *dp;
297 	struct inode *ip;
298 	int isrmdir;
299 {
300 
301 	panic("softdep_setup_remove called");
302 }
303 
304 void
305 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
306 	struct buf *bp;
307 	struct inode *dp;
308 	struct inode *ip;
309 	ino_t newinum;
310 	int isrmdir;
311 {
312 
313 	panic("softdep_setup_directory_change called");
314 }
315 
316 void
317 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
318 	struct mount *mp;
319 	struct buf *bp;
320 	ufs2_daddr_t blkno;
321 	int frags;
322 	struct workhead *wkhd;
323 {
324 
325 	panic("%s called", __FUNCTION__);
326 }
327 
328 void
329 softdep_setup_inofree(mp, bp, ino, wkhd)
330 	struct mount *mp;
331 	struct buf *bp;
332 	ino_t ino;
333 	struct workhead *wkhd;
334 {
335 
336 	panic("%s called", __FUNCTION__);
337 }
338 
339 void
340 softdep_setup_unlink(dp, ip)
341 	struct inode *dp;
342 	struct inode *ip;
343 {
344 
345 	panic("%s called", __FUNCTION__);
346 }
347 
348 void
349 softdep_setup_link(dp, ip)
350 	struct inode *dp;
351 	struct inode *ip;
352 {
353 
354 	panic("%s called", __FUNCTION__);
355 }
356 
357 void
358 softdep_revert_link(dp, ip)
359 	struct inode *dp;
360 	struct inode *ip;
361 {
362 
363 	panic("%s called", __FUNCTION__);
364 }
365 
366 void
367 softdep_setup_rmdir(dp, ip)
368 	struct inode *dp;
369 	struct inode *ip;
370 {
371 
372 	panic("%s called", __FUNCTION__);
373 }
374 
375 void
376 softdep_revert_rmdir(dp, ip)
377 	struct inode *dp;
378 	struct inode *ip;
379 {
380 
381 	panic("%s called", __FUNCTION__);
382 }
383 
384 void
385 softdep_setup_create(dp, ip)
386 	struct inode *dp;
387 	struct inode *ip;
388 {
389 
390 	panic("%s called", __FUNCTION__);
391 }
392 
393 void
394 softdep_revert_create(dp, ip)
395 	struct inode *dp;
396 	struct inode *ip;
397 {
398 
399 	panic("%s called", __FUNCTION__);
400 }
401 
402 void
403 softdep_setup_mkdir(dp, ip)
404 	struct inode *dp;
405 	struct inode *ip;
406 {
407 
408 	panic("%s called", __FUNCTION__);
409 }
410 
411 void
412 softdep_revert_mkdir(dp, ip)
413 	struct inode *dp;
414 	struct inode *ip;
415 {
416 
417 	panic("%s called", __FUNCTION__);
418 }
419 
420 void
421 softdep_setup_dotdot_link(dp, ip)
422 	struct inode *dp;
423 	struct inode *ip;
424 {
425 
426 	panic("%s called", __FUNCTION__);
427 }
428 
429 int
430 softdep_prealloc(vp, waitok)
431 	struct vnode *vp;
432 	int waitok;
433 {
434 
435 	panic("%s called", __FUNCTION__);
436 }
437 
438 int
439 softdep_journal_lookup(mp, vpp)
440 	struct mount *mp;
441 	struct vnode **vpp;
442 {
443 
444 	return (ENOENT);
445 }
446 
447 void
448 softdep_change_linkcnt(ip)
449 	struct inode *ip;
450 {
451 
452 	panic("softdep_change_linkcnt called");
453 }
454 
455 void
456 softdep_load_inodeblock(ip)
457 	struct inode *ip;
458 {
459 
460 	panic("softdep_load_inodeblock called");
461 }
462 
463 void
464 softdep_update_inodeblock(ip, bp, waitfor)
465 	struct inode *ip;
466 	struct buf *bp;
467 	int waitfor;
468 {
469 
470 	panic("softdep_update_inodeblock called");
471 }
472 
473 int
474 softdep_fsync(vp)
475 	struct vnode *vp;	/* the "in_core" copy of the inode */
476 {
477 
478 	return (0);
479 }
480 
481 void
482 softdep_fsync_mountdev(vp)
483 	struct vnode *vp;
484 {
485 
486 	return;
487 }
488 
489 int
490 softdep_flushworklist(oldmnt, countp, td)
491 	struct mount *oldmnt;
492 	int *countp;
493 	struct thread *td;
494 {
495 
496 	*countp = 0;
497 	return (0);
498 }
499 
500 int
501 softdep_sync_metadata(struct vnode *vp)
502 {
503 
504 	panic("softdep_sync_metadata called");
505 }
506 
507 int
508 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
509 {
510 
511 	panic("softdep_sync_buf called");
512 }
513 
514 int
515 softdep_slowdown(vp)
516 	struct vnode *vp;
517 {
518 
519 	panic("softdep_slowdown called");
520 }
521 
522 int
523 softdep_request_cleanup(fs, vp, cred, resource)
524 	struct fs *fs;
525 	struct vnode *vp;
526 	struct ucred *cred;
527 	int resource;
528 {
529 
530 	return (0);
531 }
532 
533 int
534 softdep_check_suspend(struct mount *mp,
535 		      struct vnode *devvp,
536 		      int softdep_depcnt,
537 		      int softdep_accdepcnt,
538 		      int secondary_writes,
539 		      int secondary_accwrites)
540 {
541 	struct bufobj *bo;
542 	int error;
543 
544 	(void) softdep_depcnt,
545 	(void) softdep_accdepcnt;
546 
547 	bo = &devvp->v_bufobj;
548 	ASSERT_BO_WLOCKED(bo);
549 
550 	MNT_ILOCK(mp);
551 	while (mp->mnt_secondary_writes != 0) {
552 		BO_UNLOCK(bo);
553 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
554 		    (PUSER - 1) | PDROP, "secwr", 0);
555 		BO_LOCK(bo);
556 		MNT_ILOCK(mp);
557 	}
558 
559 	/*
560 	 * Reasons for needing more work before suspend:
561 	 * - Dirty buffers on devvp.
562 	 * - Secondary writes occurred after start of vnode sync loop
563 	 */
564 	error = 0;
565 	if (bo->bo_numoutput > 0 ||
566 	    bo->bo_dirty.bv_cnt > 0 ||
567 	    secondary_writes != 0 ||
568 	    mp->mnt_secondary_writes != 0 ||
569 	    secondary_accwrites != mp->mnt_secondary_accwrites)
570 		error = EAGAIN;
571 	BO_UNLOCK(bo);
572 	return (error);
573 }
574 
575 void
576 softdep_get_depcounts(struct mount *mp,
577 		      int *softdepactivep,
578 		      int *softdepactiveaccp)
579 {
580 	(void) mp;
581 	*softdepactivep = 0;
582 	*softdepactiveaccp = 0;
583 }
584 
585 void
586 softdep_buf_append(bp, wkhd)
587 	struct buf *bp;
588 	struct workhead *wkhd;
589 {
590 
591 	panic("softdep_buf_appendwork called");
592 }
593 
594 void
595 softdep_inode_append(ip, cred, wkhd)
596 	struct inode *ip;
597 	struct ucred *cred;
598 	struct workhead *wkhd;
599 {
600 
601 	panic("softdep_inode_appendwork called");
602 }
603 
604 void
605 softdep_freework(wkhd)
606 	struct workhead *wkhd;
607 {
608 
609 	panic("softdep_freework called");
610 }
611 
612 int
613 softdep_prerename(fdvp, fvp, tdvp, tvp)
614 	struct vnode *fdvp;
615 	struct vnode *fvp;
616 	struct vnode *tdvp;
617 	struct vnode *tvp;
618 {
619 
620 	panic("softdep_prerename called");
621 }
622 
623 int
624 softdep_prelink(dvp, vp, will_direnter)
625 	struct vnode *dvp;
626 	struct vnode *vp;
627 	int will_direnter;
628 {
629 
630 	panic("softdep_prelink called");
631 }
632 
633 #else
634 
635 FEATURE(softupdates, "FFS soft-updates support");
636 
637 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
638     "soft updates stats");
639 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total,
640     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
641     "total dependencies allocated");
642 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse,
643     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
644     "high use dependencies allocated");
645 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current,
646     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
647     "current dependencies allocated");
648 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write,
649     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
650     "current dependencies written");
651 
652 unsigned long dep_current[D_LAST + 1];
653 unsigned long dep_highuse[D_LAST + 1];
654 unsigned long dep_total[D_LAST + 1];
655 unsigned long dep_write[D_LAST + 1];
656 
657 #define	SOFTDEP_TYPE(type, str, long)					\
658     static MALLOC_DEFINE(M_ ## type, #str, long);			\
659     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
660 	&dep_total[D_ ## type], 0, "");					\
661     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
662 	&dep_current[D_ ## type], 0, "");				\
663     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
664 	&dep_highuse[D_ ## type], 0, "");				\
665     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
666 	&dep_write[D_ ## type], 0, "");
667 
668 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
669 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
670 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
671     "Block or frag allocated from cyl group map");
672 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
673 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
674 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
675 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
676 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
677 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
678 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
679 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
680 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
681 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
682 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
683 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
684 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
685 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
686 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
687 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
688 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
689 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
690 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
691 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
692 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
693 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
694 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
695 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
696 
697 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
698 
699 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
700 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
701 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
702 
703 #define M_SOFTDEP_FLAGS	(M_WAITOK)
704 
705 /*
706  * translate from workitem type to memory type
707  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
708  */
709 static struct malloc_type *memtype[] = {
710 	NULL,
711 	M_PAGEDEP,
712 	M_INODEDEP,
713 	M_BMSAFEMAP,
714 	M_NEWBLK,
715 	M_ALLOCDIRECT,
716 	M_INDIRDEP,
717 	M_ALLOCINDIR,
718 	M_FREEFRAG,
719 	M_FREEBLKS,
720 	M_FREEFILE,
721 	M_DIRADD,
722 	M_MKDIR,
723 	M_DIRREM,
724 	M_NEWDIRBLK,
725 	M_FREEWORK,
726 	M_FREEDEP,
727 	M_JADDREF,
728 	M_JREMREF,
729 	M_JMVREF,
730 	M_JNEWBLK,
731 	M_JFREEBLK,
732 	M_JFREEFRAG,
733 	M_JSEG,
734 	M_JSEGDEP,
735 	M_SBDEP,
736 	M_JTRUNC,
737 	M_JFSYNC,
738 	M_SENTINEL
739 };
740 
741 #define DtoM(type) (memtype[type])
742 
743 /*
744  * Names of malloc types.
745  */
746 #define TYPENAME(type)  \
747 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
748 	memtype[type]->ks_shortdesc : "???")
749 /*
750  * End system adaptation definitions.
751  */
752 
753 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
754 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
755 
756 /*
757  * Internal function prototypes.
758  */
759 static	void check_clear_deps(struct mount *);
760 static	void softdep_error(char *, int);
761 static	int softdep_process_worklist(struct mount *, int);
762 static	int softdep_waitidle(struct mount *, int);
763 static	void drain_output(struct vnode *);
764 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
765 static	int check_inodedep_free(struct inodedep *);
766 static	void clear_remove(struct mount *);
767 static	void clear_inodedeps(struct mount *);
768 static	void unlinked_inodedep(struct mount *, struct inodedep *);
769 static	void clear_unlinked_inodedep(struct inodedep *);
770 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
771 static	int flush_pagedep_deps(struct vnode *, struct mount *,
772 	    struct diraddhd *, struct buf *);
773 static	int free_pagedep(struct pagedep *);
774 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
775 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
776 static	int flush_deplist(struct allocdirectlst *, int, int *);
777 static	int sync_cgs(struct mount *, int);
778 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
779 static	int handle_written_sbdep(struct sbdep *, struct buf *);
780 static	void initiate_write_sbdep(struct sbdep *);
781 static	void diradd_inode_written(struct diradd *, struct inodedep *);
782 static	int handle_written_indirdep(struct indirdep *, struct buf *,
783 	    struct buf**, int);
784 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
785 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
786 	    uint8_t *);
787 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
788 static	void handle_written_jaddref(struct jaddref *);
789 static	void handle_written_jremref(struct jremref *);
790 static	void handle_written_jseg(struct jseg *, struct buf *);
791 static	void handle_written_jnewblk(struct jnewblk *);
792 static	void handle_written_jblkdep(struct jblkdep *);
793 static	void handle_written_jfreefrag(struct jfreefrag *);
794 static	void complete_jseg(struct jseg *);
795 static	void complete_jsegs(struct jseg *);
796 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
797 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
798 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
799 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
800 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
801 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
802 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
803 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
804 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
805 static	inline void inoref_write(struct inoref *, struct jseg *,
806 	    struct jrefrec *);
807 static	void handle_allocdirect_partdone(struct allocdirect *,
808 	    struct workhead *);
809 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
810 	    struct workhead *);
811 static	void indirdep_complete(struct indirdep *);
812 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
813 static	void indirblk_insert(struct freework *);
814 static	void indirblk_remove(struct freework *);
815 static	void handle_allocindir_partdone(struct allocindir *);
816 static	void initiate_write_filepage(struct pagedep *, struct buf *);
817 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
818 static	void handle_written_mkdir(struct mkdir *, int);
819 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
820 	    uint8_t *);
821 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
822 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
823 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
824 static	void handle_workitem_freefile(struct freefile *);
825 static	int handle_workitem_remove(struct dirrem *, int);
826 static	struct dirrem *newdirrem(struct buf *, struct inode *,
827 	    struct inode *, int, struct dirrem **);
828 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
829 	    struct buf *);
830 static	void cancel_indirdep(struct indirdep *, struct buf *,
831 	    struct freeblks *);
832 static	void free_indirdep(struct indirdep *);
833 static	void free_diradd(struct diradd *, struct workhead *);
834 static	void merge_diradd(struct inodedep *, struct diradd *);
835 static	void complete_diradd(struct diradd *);
836 static	struct diradd *diradd_lookup(struct pagedep *, int);
837 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
838 	    struct jremref *);
839 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
840 	    struct jremref *);
841 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
842 	    struct jremref *, struct jremref *);
843 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
844 	    struct jremref *);
845 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
846 	    struct freeblks *, int);
847 static	int setup_trunc_indir(struct freeblks *, struct inode *,
848 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
849 static	void complete_trunc_indir(struct freework *);
850 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
851 	    int);
852 static	void complete_mkdir(struct mkdir *);
853 static	void free_newdirblk(struct newdirblk *);
854 static	void free_jremref(struct jremref *);
855 static	void free_jaddref(struct jaddref *);
856 static	void free_jsegdep(struct jsegdep *);
857 static	void free_jsegs(struct jblocks *);
858 static	void rele_jseg(struct jseg *);
859 static	void free_jseg(struct jseg *, struct jblocks *);
860 static	void free_jnewblk(struct jnewblk *);
861 static	void free_jblkdep(struct jblkdep *);
862 static	void free_jfreefrag(struct jfreefrag *);
863 static	void free_freedep(struct freedep *);
864 static	void journal_jremref(struct dirrem *, struct jremref *,
865 	    struct inodedep *);
866 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
867 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
868 	    struct workhead *);
869 static	void cancel_jfreefrag(struct jfreefrag *);
870 static	inline void setup_freedirect(struct freeblks *, struct inode *,
871 	    int, int);
872 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
873 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
874 	    ufs_lbn_t, int);
875 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
876 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
877 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
878 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
879 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
880 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
881 	    int, int);
882 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
883 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
884 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
885 static	void newblk_freefrag(struct newblk*);
886 static	void free_newblk(struct newblk *);
887 static	void cancel_allocdirect(struct allocdirectlst *,
888 	    struct allocdirect *, struct freeblks *);
889 static	int check_inode_unwritten(struct inodedep *);
890 static	int free_inodedep(struct inodedep *);
891 static	void freework_freeblock(struct freework *, u_long);
892 static	void freework_enqueue(struct freework *);
893 static	int handle_workitem_freeblocks(struct freeblks *, int);
894 static	int handle_complete_freeblocks(struct freeblks *, int);
895 static	void handle_workitem_indirblk(struct freework *);
896 static	void handle_written_freework(struct freework *);
897 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
898 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
899 	    struct workhead *);
900 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
901 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
902 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
903 	    ufs2_daddr_t, ufs_lbn_t);
904 static	void handle_workitem_freefrag(struct freefrag *);
905 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
906 	    ufs_lbn_t, u_long);
907 static	void allocdirect_merge(struct allocdirectlst *,
908 	    struct allocdirect *, struct allocdirect *);
909 static	struct freefrag *allocindir_merge(struct allocindir *,
910 	    struct allocindir *);
911 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
912 	    struct bmsafemap **);
913 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
914 	    int cg, struct bmsafemap *);
915 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
916 	    struct newblk **);
917 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
918 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
919 	    struct inodedep **);
920 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
921 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
922 	    int, struct pagedep **);
923 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
924 	    struct pagedep **);
925 static	void pause_timer(void *);
926 static	int request_cleanup(struct mount *, int);
927 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
928 static	void schedule_cleanup(struct mount *);
929 static void softdep_ast_cleanup_proc(struct thread *);
930 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
931 static	int process_worklist_item(struct mount *, int, int);
932 static	void process_removes(struct vnode *);
933 static	void process_truncates(struct vnode *);
934 static	void jwork_move(struct workhead *, struct workhead *);
935 static	void jwork_insert(struct workhead *, struct jsegdep *);
936 static	void add_to_worklist(struct worklist *, int);
937 static	void wake_worklist(struct worklist *);
938 static	void wait_worklist(struct worklist *, char *);
939 static	void remove_from_worklist(struct worklist *);
940 static	void softdep_flush(void *);
941 static	void softdep_flushjournal(struct mount *);
942 static	int softdep_speedup(struct ufsmount *);
943 static	void worklist_speedup(struct mount *);
944 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
945 static	void journal_unmount(struct ufsmount *);
946 static	int journal_space(struct ufsmount *, int);
947 static	void journal_suspend(struct ufsmount *);
948 static	int journal_unsuspend(struct ufsmount *ump);
949 static	void add_to_journal(struct worklist *);
950 static	void remove_from_journal(struct worklist *);
951 static	bool softdep_excess_items(struct ufsmount *, int);
952 static	void softdep_process_journal(struct mount *, struct worklist *, int);
953 static	struct jremref *newjremref(struct dirrem *, struct inode *,
954 	    struct inode *ip, off_t, nlink_t);
955 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
956 	    uint16_t);
957 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
958 	    uint16_t);
959 static	inline struct jsegdep *inoref_jseg(struct inoref *);
960 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
961 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
962 	    ufs2_daddr_t, int);
963 static	void adjust_newfreework(struct freeblks *, int);
964 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
965 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
966 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
967 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
968 	    ufs2_daddr_t, long, ufs_lbn_t);
969 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
970 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
971 static	int jwait(struct worklist *, int);
972 static	struct inodedep *inodedep_lookup_ip(struct inode *);
973 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
974 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
975 static	void handle_jwork(struct workhead *);
976 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
977 	    struct mkdir **);
978 static	struct jblocks *jblocks_create(void);
979 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
980 static	void jblocks_free(struct jblocks *, struct mount *, int);
981 static	void jblocks_destroy(struct jblocks *);
982 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
983 
984 /*
985  * Exported softdep operations.
986  */
987 static	void softdep_disk_io_initiation(struct buf *);
988 static	void softdep_disk_write_complete(struct buf *);
989 static	void softdep_deallocate_dependencies(struct buf *);
990 static	int softdep_count_dependencies(struct buf *bp, int);
991 
992 /*
993  * Global lock over all of soft updates.
994  */
995 static struct mtx lk;
996 MTX_SYSINIT(softdep_lock, &lk, "global softdep", MTX_DEF);
997 
998 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
999 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
1000 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
1001 
1002 /*
1003  * Per-filesystem soft-updates locking.
1004  */
1005 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
1006 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
1007 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
1008 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
1009 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
1010 				    RA_WLOCKED)
1011 
1012 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
1013 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
1014 
1015 /*
1016  * Worklist queue management.
1017  * These routines require that the lock be held.
1018  */
1019 #ifndef /* NOT */ INVARIANTS
1020 #define WORKLIST_INSERT(head, item) do {	\
1021 	(item)->wk_state |= ONWORKLIST;		\
1022 	LIST_INSERT_HEAD(head, item, wk_list);	\
1023 } while (0)
1024 #define WORKLIST_REMOVE(item) do {		\
1025 	(item)->wk_state &= ~ONWORKLIST;	\
1026 	LIST_REMOVE(item, wk_list);		\
1027 } while (0)
1028 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1029 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1030 
1031 #else /* INVARIANTS */
1032 static	void worklist_insert(struct workhead *, struct worklist *, int,
1033 	const char *, int);
1034 static	void worklist_remove(struct worklist *, int, const char *, int);
1035 
1036 #define WORKLIST_INSERT(head, item) \
1037 	worklist_insert(head, item, 1, __func__, __LINE__)
1038 #define WORKLIST_INSERT_UNLOCKED(head, item)\
1039 	worklist_insert(head, item, 0, __func__, __LINE__)
1040 #define WORKLIST_REMOVE(item)\
1041 	worklist_remove(item, 1, __func__, __LINE__)
1042 #define WORKLIST_REMOVE_UNLOCKED(item)\
1043 	worklist_remove(item, 0, __func__, __LINE__)
1044 
1045 static void
1046 worklist_insert(head, item, locked, func, line)
1047 	struct workhead *head;
1048 	struct worklist *item;
1049 	int locked;
1050 	const char *func;
1051 	int line;
1052 {
1053 
1054 	if (locked)
1055 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1056 	if (item->wk_state & ONWORKLIST)
1057 		panic("worklist_insert: %p %s(0x%X) already on list, "
1058 		    "added in function %s at line %d",
1059 		    item, TYPENAME(item->wk_type), item->wk_state,
1060 		    item->wk_func, item->wk_line);
1061 	item->wk_state |= ONWORKLIST;
1062 	item->wk_func = func;
1063 	item->wk_line = line;
1064 	LIST_INSERT_HEAD(head, item, wk_list);
1065 }
1066 
1067 static void
1068 worklist_remove(item, locked, func, line)
1069 	struct worklist *item;
1070 	int locked;
1071 	const char *func;
1072 	int line;
1073 {
1074 
1075 	if (locked)
1076 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1077 	if ((item->wk_state & ONWORKLIST) == 0)
1078 		panic("worklist_remove: %p %s(0x%X) not on list, "
1079 		    "removed in function %s at line %d",
1080 		    item, TYPENAME(item->wk_type), item->wk_state,
1081 		    item->wk_func, item->wk_line);
1082 	item->wk_state &= ~ONWORKLIST;
1083 	item->wk_func = func;
1084 	item->wk_line = line;
1085 	LIST_REMOVE(item, wk_list);
1086 }
1087 #endif /* INVARIANTS */
1088 
1089 /*
1090  * Merge two jsegdeps keeping only the oldest one as newer references
1091  * can't be discarded until after older references.
1092  */
1093 static inline struct jsegdep *
1094 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1095 {
1096 	struct jsegdep *swp;
1097 
1098 	if (two == NULL)
1099 		return (one);
1100 
1101 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1102 		swp = one;
1103 		one = two;
1104 		two = swp;
1105 	}
1106 	WORKLIST_REMOVE(&two->jd_list);
1107 	free_jsegdep(two);
1108 
1109 	return (one);
1110 }
1111 
1112 /*
1113  * If two freedeps are compatible free one to reduce list size.
1114  */
1115 static inline struct freedep *
1116 freedep_merge(struct freedep *one, struct freedep *two)
1117 {
1118 	if (two == NULL)
1119 		return (one);
1120 
1121 	if (one->fd_freework == two->fd_freework) {
1122 		WORKLIST_REMOVE(&two->fd_list);
1123 		free_freedep(two);
1124 	}
1125 	return (one);
1126 }
1127 
1128 /*
1129  * Move journal work from one list to another.  Duplicate freedeps and
1130  * jsegdeps are coalesced to keep the lists as small as possible.
1131  */
1132 static void
1133 jwork_move(dst, src)
1134 	struct workhead *dst;
1135 	struct workhead *src;
1136 {
1137 	struct freedep *freedep;
1138 	struct jsegdep *jsegdep;
1139 	struct worklist *wkn;
1140 	struct worklist *wk;
1141 
1142 	KASSERT(dst != src,
1143 	    ("jwork_move: dst == src"));
1144 	freedep = NULL;
1145 	jsegdep = NULL;
1146 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1147 		if (wk->wk_type == D_JSEGDEP)
1148 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1149 		else if (wk->wk_type == D_FREEDEP)
1150 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1151 	}
1152 
1153 	while ((wk = LIST_FIRST(src)) != NULL) {
1154 		WORKLIST_REMOVE(wk);
1155 		WORKLIST_INSERT(dst, wk);
1156 		if (wk->wk_type == D_JSEGDEP) {
1157 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1158 			continue;
1159 		}
1160 		if (wk->wk_type == D_FREEDEP)
1161 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1162 	}
1163 }
1164 
1165 static void
1166 jwork_insert(dst, jsegdep)
1167 	struct workhead *dst;
1168 	struct jsegdep *jsegdep;
1169 {
1170 	struct jsegdep *jsegdepn;
1171 	struct worklist *wk;
1172 
1173 	LIST_FOREACH(wk, dst, wk_list)
1174 		if (wk->wk_type == D_JSEGDEP)
1175 			break;
1176 	if (wk == NULL) {
1177 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1178 		return;
1179 	}
1180 	jsegdepn = WK_JSEGDEP(wk);
1181 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1182 		WORKLIST_REMOVE(wk);
1183 		free_jsegdep(jsegdepn);
1184 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1185 	} else
1186 		free_jsegdep(jsegdep);
1187 }
1188 
1189 /*
1190  * Routines for tracking and managing workitems.
1191  */
1192 static	void workitem_free(struct worklist *, int);
1193 static	void workitem_alloc(struct worklist *, int, struct mount *);
1194 static	void workitem_reassign(struct worklist *, int);
1195 
1196 #define	WORKITEM_FREE(item, type) \
1197 	workitem_free((struct worklist *)(item), (type))
1198 #define	WORKITEM_REASSIGN(item, type) \
1199 	workitem_reassign((struct worklist *)(item), (type))
1200 
1201 static void
1202 workitem_free(item, type)
1203 	struct worklist *item;
1204 	int type;
1205 {
1206 	struct ufsmount *ump;
1207 
1208 #ifdef INVARIANTS
1209 	if (item->wk_state & ONWORKLIST)
1210 		panic("workitem_free: %s(0x%X) still on list, "
1211 		    "added in function %s at line %d",
1212 		    TYPENAME(item->wk_type), item->wk_state,
1213 		    item->wk_func, item->wk_line);
1214 	if (item->wk_type != type && type != D_NEWBLK)
1215 		panic("workitem_free: type mismatch %s != %s",
1216 		    TYPENAME(item->wk_type), TYPENAME(type));
1217 #endif
1218 	if (item->wk_state & IOWAITING)
1219 		wakeup(item);
1220 	ump = VFSTOUFS(item->wk_mp);
1221 	LOCK_OWNED(ump);
1222 	KASSERT(ump->softdep_deps > 0,
1223 	    ("workitem_free: %s: softdep_deps going negative",
1224 	    ump->um_fs->fs_fsmnt));
1225 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1226 		wakeup(&ump->softdep_deps);
1227 	KASSERT(dep_current[item->wk_type] > 0,
1228 	    ("workitem_free: %s: dep_current[%s] going negative",
1229 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1230 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1231 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1232 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1233 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1234 	ump->softdep_curdeps[item->wk_type] -= 1;
1235 #ifdef INVARIANTS
1236 	LIST_REMOVE(item, wk_all);
1237 #endif
1238 	free(item, DtoM(type));
1239 }
1240 
1241 static void
1242 workitem_alloc(item, type, mp)
1243 	struct worklist *item;
1244 	int type;
1245 	struct mount *mp;
1246 {
1247 	struct ufsmount *ump;
1248 
1249 	item->wk_type = type;
1250 	item->wk_mp = mp;
1251 	item->wk_state = 0;
1252 
1253 	ump = VFSTOUFS(mp);
1254 	ACQUIRE_GBLLOCK(&lk);
1255 	dep_current[type]++;
1256 	if (dep_current[type] > dep_highuse[type])
1257 		dep_highuse[type] = dep_current[type];
1258 	dep_total[type]++;
1259 	FREE_GBLLOCK(&lk);
1260 	ACQUIRE_LOCK(ump);
1261 	ump->softdep_curdeps[type] += 1;
1262 	ump->softdep_deps++;
1263 	ump->softdep_accdeps++;
1264 #ifdef INVARIANTS
1265 	LIST_INSERT_HEAD(&ump->softdep_alldeps[type], item, wk_all);
1266 #endif
1267 	FREE_LOCK(ump);
1268 }
1269 
1270 static void
1271 workitem_reassign(item, newtype)
1272 	struct worklist *item;
1273 	int newtype;
1274 {
1275 	struct ufsmount *ump;
1276 
1277 	ump = VFSTOUFS(item->wk_mp);
1278 	LOCK_OWNED(ump);
1279 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1280 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1281 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1282 	ump->softdep_curdeps[item->wk_type] -= 1;
1283 	ump->softdep_curdeps[newtype] += 1;
1284 	KASSERT(dep_current[item->wk_type] > 0,
1285 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1286 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1287 	ACQUIRE_GBLLOCK(&lk);
1288 	dep_current[newtype]++;
1289 	dep_current[item->wk_type]--;
1290 	if (dep_current[newtype] > dep_highuse[newtype])
1291 		dep_highuse[newtype] = dep_current[newtype];
1292 	dep_total[newtype]++;
1293 	FREE_GBLLOCK(&lk);
1294 	item->wk_type = newtype;
1295 }
1296 
1297 /*
1298  * Workitem queue management
1299  */
1300 static int max_softdeps;	/* maximum number of structs before slowdown */
1301 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1302 static int proc_waiting;	/* tracks whether we have a timeout posted */
1303 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1304 static struct callout softdep_callout;
1305 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1306 static int req_clear_remove;	/* syncer process flush some freeblks */
1307 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1308 
1309 /*
1310  * runtime statistics
1311  */
1312 static int stat_flush_threads;	/* number of softdep flushing threads */
1313 static int stat_worklist_push;	/* number of worklist 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, blk_limit_push,
1348     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1349 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1350     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1351 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1352     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1353 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1354     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1355 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1356     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1357 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1358     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1359 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1360     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1361 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1362     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1363 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1364     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1365 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1366     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1367 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1368     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1369 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1370     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1371 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1372     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1373 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1374     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1375 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1376     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1377 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1378     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1379 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1380     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1381 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1382     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1383 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1384     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1385 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1386     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1387 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1388     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1389 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1390     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1391 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1392     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1393 
1394 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1395     &softdep_flushcache, 0, "");
1396 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1397     &stat_emptyjblocks, 0, "");
1398 
1399 SYSCTL_DECL(_vfs_ffs);
1400 
1401 /* Whether to recompute the summary at mount time */
1402 static int compute_summary_at_mount = 0;
1403 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1404 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1405 static int print_threads = 0;
1406 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1407     &print_threads, 0, "Notify flusher thread start/stop");
1408 
1409 /* List of all filesystems mounted with soft updates */
1410 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1411 
1412 static void
1413 get_parent_vp_unlock_bp(struct mount *mp, struct buf *bp,
1414     struct diraddhd *diraddhdp, struct diraddhd *unfinishedp)
1415 {
1416 	struct diradd *dap;
1417 
1418 	/*
1419 	 * Requeue unfinished dependencies before
1420 	 * unlocking buffer, which could make
1421 	 * diraddhdp invalid.
1422 	 */
1423 	ACQUIRE_LOCK(VFSTOUFS(mp));
1424 	while ((dap = LIST_FIRST(unfinishedp)) != NULL) {
1425 		LIST_REMOVE(dap, da_pdlist);
1426 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
1427 	}
1428 	FREE_LOCK(VFSTOUFS(mp));
1429 
1430 	bp->b_vflags &= ~BV_SCANNED;
1431 	BUF_NOREC(bp);
1432 	BUF_UNLOCK(bp);
1433 }
1434 
1435 /*
1436  * This function fetches inode inum on mount point mp.  We already
1437  * hold a locked vnode vp, and might have a locked buffer bp belonging
1438  * to vp.
1439 
1440  * We must not block on acquiring the new inode lock as we will get
1441  * into a lock-order reversal with the buffer lock and possibly get a
1442  * deadlock.  Thus if we cannot instantiate the requested vnode
1443  * without sleeping on its lock, we must unlock the vnode and the
1444  * buffer before doing a blocking on the vnode lock.  We return
1445  * ERELOOKUP if we have had to unlock either the vnode or the buffer so
1446  * that the caller can reassess its state.
1447  *
1448  * Top-level VFS code (for syscalls and other consumers, e.g. callers
1449  * of VOP_FSYNC() in syncer) check for ERELOOKUP and restart at safe
1450  * point.
1451  *
1452  * Since callers expect to operate on fully constructed vnode, we also
1453  * recheck v_data after relock, and return ENOENT if NULL.
1454  *
1455  * If unlocking bp, we must unroll dequeueing its unfinished
1456  * dependencies, and clear scan flag, before unlocking.  If unlocking
1457  * vp while it is under deactivation, we re-queue deactivation.
1458  */
1459 static int
1460 get_parent_vp(struct vnode *vp, struct mount *mp, ino_t inum, struct buf *bp,
1461     struct diraddhd *diraddhdp, struct diraddhd *unfinishedp,
1462     struct vnode **rvp)
1463 {
1464 	struct vnode *pvp;
1465 	int error;
1466 	bool bplocked;
1467 
1468 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked");
1469 	for (bplocked = true, pvp = NULL;;) {
1470 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE | LK_NOWAIT, &pvp,
1471 		    FFSV_FORCEINSMQ);
1472 		if (error == 0) {
1473 			/*
1474 			 * Since we could have unlocked vp, the inode
1475 			 * number could no longer indicate a
1476 			 * constructed node.  In this case, we must
1477 			 * restart the syscall.
1478 			 */
1479 			if (VTOI(pvp)->i_mode == 0 || !bplocked) {
1480 				if (bp != NULL && bplocked)
1481 					get_parent_vp_unlock_bp(mp, bp,
1482 					    diraddhdp, unfinishedp);
1483 				if (VTOI(pvp)->i_mode == 0)
1484 					vgone(pvp);
1485 				error = ERELOOKUP;
1486 				goto out2;
1487 			}
1488 			goto out1;
1489 		}
1490 		if (bp != NULL && bplocked) {
1491 			get_parent_vp_unlock_bp(mp, bp, diraddhdp, unfinishedp);
1492 			bplocked = false;
1493 		}
1494 
1495 		/*
1496 		 * Do not drop vnode lock while inactivating.  This
1497 		 * would result in leaks of the VI flags and
1498 		 * reclaiming of non-truncated vnode.  Instead,
1499 		 * re-schedule inactivation hoping that we would be
1500 		 * able to sync inode later.
1501 		 */
1502 		if ((vp->v_iflag & VI_DOINGINACT) != 0) {
1503 			VI_LOCK(vp);
1504 			vp->v_iflag |= VI_OWEINACT;
1505 			VI_UNLOCK(vp);
1506 			return (ERELOOKUP);
1507 		}
1508 
1509 		VOP_UNLOCK(vp);
1510 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &pvp,
1511 		    FFSV_FORCEINSMQ);
1512 		if (error != 0) {
1513 			MPASS(error != ERELOOKUP);
1514 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1515 			break;
1516 		}
1517 		if (VTOI(pvp)->i_mode == 0) {
1518 			vgone(pvp);
1519 			vput(pvp);
1520 			pvp = NULL;
1521 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1522 			error = ERELOOKUP;
1523 			break;
1524 		}
1525 		error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
1526 		if (error == 0)
1527 			break;
1528 		vput(pvp);
1529 		pvp = NULL;
1530 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1531 		if (vp->v_data == NULL) {
1532 			error = ENOENT;
1533 			break;
1534 		}
1535 	}
1536 	if (bp != NULL) {
1537 		MPASS(!bplocked);
1538 		error = ERELOOKUP;
1539 	}
1540 out2:
1541 	if (error != 0 && pvp != NULL) {
1542 		vput(pvp);
1543 		pvp = NULL;
1544 	}
1545 out1:
1546 	*rvp = pvp;
1547 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked on return");
1548 	return (error);
1549 }
1550 
1551 /*
1552  * This function cleans the worklist for a filesystem.
1553  * Each filesystem running with soft dependencies gets its own
1554  * thread to run in this function. The thread is started up in
1555  * softdep_mount and shutdown in softdep_unmount. They show up
1556  * as part of the kernel "bufdaemon" process whose process
1557  * entry is available in bufdaemonproc.
1558  */
1559 static int searchfailed;
1560 extern struct proc *bufdaemonproc;
1561 static void
1562 softdep_flush(addr)
1563 	void *addr;
1564 {
1565 	struct mount *mp;
1566 	struct thread *td;
1567 	struct ufsmount *ump;
1568 
1569 	td = curthread;
1570 	td->td_pflags |= TDP_NORUNNINGBUF;
1571 	mp = (struct mount *)addr;
1572 	ump = VFSTOUFS(mp);
1573 	atomic_add_int(&stat_flush_threads, 1);
1574 	ACQUIRE_LOCK(ump);
1575 	ump->softdep_flags &= ~FLUSH_STARTING;
1576 	wakeup(&ump->softdep_flushtd);
1577 	FREE_LOCK(ump);
1578 	if (print_threads) {
1579 		if (stat_flush_threads == 1)
1580 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1581 			    bufdaemonproc->p_pid);
1582 		printf("Start thread %s\n", td->td_name);
1583 	}
1584 	for (;;) {
1585 		while (softdep_process_worklist(mp, 0) > 0 ||
1586 		    (MOUNTEDSUJ(mp) &&
1587 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1588 			kthread_suspend_check();
1589 		ACQUIRE_LOCK(ump);
1590 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1591 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1592 			    "sdflush", hz / 2);
1593 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1594 		/*
1595 		 * Check to see if we are done and need to exit.
1596 		 */
1597 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1598 			FREE_LOCK(ump);
1599 			continue;
1600 		}
1601 		ump->softdep_flags &= ~FLUSH_EXIT;
1602 		FREE_LOCK(ump);
1603 		wakeup(&ump->softdep_flags);
1604 		if (print_threads)
1605 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1606 		atomic_subtract_int(&stat_flush_threads, 1);
1607 		kthread_exit();
1608 		panic("kthread_exit failed\n");
1609 	}
1610 }
1611 
1612 static void
1613 worklist_speedup(mp)
1614 	struct mount *mp;
1615 {
1616 	struct ufsmount *ump;
1617 
1618 	ump = VFSTOUFS(mp);
1619 	LOCK_OWNED(ump);
1620 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1621 		ump->softdep_flags |= FLUSH_CLEANUP;
1622 	wakeup(&ump->softdep_flushtd);
1623 }
1624 
1625 static void
1626 softdep_send_speedup(struct ufsmount *ump, off_t shortage, u_int flags)
1627 {
1628 	struct buf *bp;
1629 
1630 	if ((ump->um_flags & UM_CANSPEEDUP) == 0)
1631 		return;
1632 
1633 	bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
1634 	bp->b_iocmd = BIO_SPEEDUP;
1635 	bp->b_ioflags = flags;
1636 	bp->b_bcount = omin(shortage, LONG_MAX);
1637 	g_vfs_strategy(ump->um_bo, bp);
1638 	bufwait(bp);
1639 	free(bp, M_TRIM);
1640 }
1641 
1642 static int
1643 softdep_speedup(ump)
1644 	struct ufsmount *ump;
1645 {
1646 	struct ufsmount *altump;
1647 	struct mount_softdeps *sdp;
1648 
1649 	LOCK_OWNED(ump);
1650 	worklist_speedup(ump->um_mountp);
1651 	bd_speedup();
1652 	/*
1653 	 * If we have global shortages, then we need other
1654 	 * filesystems to help with the cleanup. Here we wakeup a
1655 	 * flusher thread for a filesystem that is over its fair
1656 	 * share of resources.
1657 	 */
1658 	if (req_clear_inodedeps || req_clear_remove) {
1659 		ACQUIRE_GBLLOCK(&lk);
1660 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1661 			if ((altump = sdp->sd_ump) == ump)
1662 				continue;
1663 			if (((req_clear_inodedeps &&
1664 			    altump->softdep_curdeps[D_INODEDEP] >
1665 			    max_softdeps / stat_flush_threads) ||
1666 			    (req_clear_remove &&
1667 			    altump->softdep_curdeps[D_DIRREM] >
1668 			    (max_softdeps / 2) / stat_flush_threads)) &&
1669 			    TRY_ACQUIRE_LOCK(altump))
1670 				break;
1671 		}
1672 		if (sdp == NULL) {
1673 			searchfailed++;
1674 			FREE_GBLLOCK(&lk);
1675 		} else {
1676 			/*
1677 			 * Move to the end of the list so we pick a
1678 			 * different one on out next try.
1679 			 */
1680 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1681 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1682 			FREE_GBLLOCK(&lk);
1683 			if ((altump->softdep_flags &
1684 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1685 				altump->softdep_flags |= FLUSH_CLEANUP;
1686 			altump->um_softdep->sd_cleanups++;
1687 			wakeup(&altump->softdep_flushtd);
1688 			FREE_LOCK(altump);
1689 		}
1690 	}
1691 	return (speedup_syncer());
1692 }
1693 
1694 /*
1695  * Add an item to the end of the work queue.
1696  * This routine requires that the lock be held.
1697  * This is the only routine that adds items to the list.
1698  * The following routine is the only one that removes items
1699  * and does so in order from first to last.
1700  */
1701 
1702 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1703 #define	WK_NODELAY	0x0002	/* Process immediately. */
1704 
1705 static void
1706 add_to_worklist(wk, flags)
1707 	struct worklist *wk;
1708 	int flags;
1709 {
1710 	struct ufsmount *ump;
1711 
1712 	ump = VFSTOUFS(wk->wk_mp);
1713 	LOCK_OWNED(ump);
1714 	if (wk->wk_state & ONWORKLIST)
1715 		panic("add_to_worklist: %s(0x%X) already on list",
1716 		    TYPENAME(wk->wk_type), wk->wk_state);
1717 	wk->wk_state |= ONWORKLIST;
1718 	if (ump->softdep_on_worklist == 0) {
1719 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1720 		ump->softdep_worklist_tail = wk;
1721 	} else if (flags & WK_HEAD) {
1722 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1723 	} else {
1724 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1725 		ump->softdep_worklist_tail = wk;
1726 	}
1727 	ump->softdep_on_worklist += 1;
1728 	if (flags & WK_NODELAY)
1729 		worklist_speedup(wk->wk_mp);
1730 }
1731 
1732 /*
1733  * Remove the item to be processed. If we are removing the last
1734  * item on the list, we need to recalculate the tail pointer.
1735  */
1736 static void
1737 remove_from_worklist(wk)
1738 	struct worklist *wk;
1739 {
1740 	struct ufsmount *ump;
1741 
1742 	ump = VFSTOUFS(wk->wk_mp);
1743 	if (ump->softdep_worklist_tail == wk)
1744 		ump->softdep_worklist_tail =
1745 		    (struct worklist *)wk->wk_list.le_prev;
1746 	WORKLIST_REMOVE(wk);
1747 	ump->softdep_on_worklist -= 1;
1748 }
1749 
1750 static void
1751 wake_worklist(wk)
1752 	struct worklist *wk;
1753 {
1754 	if (wk->wk_state & IOWAITING) {
1755 		wk->wk_state &= ~IOWAITING;
1756 		wakeup(wk);
1757 	}
1758 }
1759 
1760 static void
1761 wait_worklist(wk, wmesg)
1762 	struct worklist *wk;
1763 	char *wmesg;
1764 {
1765 	struct ufsmount *ump;
1766 
1767 	ump = VFSTOUFS(wk->wk_mp);
1768 	wk->wk_state |= IOWAITING;
1769 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1770 }
1771 
1772 /*
1773  * Process that runs once per second to handle items in the background queue.
1774  *
1775  * Note that we ensure that everything is done in the order in which they
1776  * appear in the queue. The code below depends on this property to ensure
1777  * that blocks of a file are freed before the inode itself is freed. This
1778  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1779  * until all the old ones have been purged from the dependency lists.
1780  */
1781 static int
1782 softdep_process_worklist(mp, full)
1783 	struct mount *mp;
1784 	int full;
1785 {
1786 	int cnt, matchcnt;
1787 	struct ufsmount *ump;
1788 	long starttime;
1789 
1790 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1791 	if (MOUNTEDSOFTDEP(mp) == 0)
1792 		return (0);
1793 	matchcnt = 0;
1794 	ump = VFSTOUFS(mp);
1795 	ACQUIRE_LOCK(ump);
1796 	starttime = time_second;
1797 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1798 	check_clear_deps(mp);
1799 	while (ump->softdep_on_worklist > 0) {
1800 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1801 			break;
1802 		else
1803 			matchcnt += cnt;
1804 		check_clear_deps(mp);
1805 		/*
1806 		 * We do not generally want to stop for buffer space, but if
1807 		 * we are really being a buffer hog, we will stop and wait.
1808 		 */
1809 		if (should_yield()) {
1810 			FREE_LOCK(ump);
1811 			kern_yield(PRI_USER);
1812 			bwillwrite();
1813 			ACQUIRE_LOCK(ump);
1814 		}
1815 		/*
1816 		 * Never allow processing to run for more than one
1817 		 * second. This gives the syncer thread the opportunity
1818 		 * to pause if appropriate.
1819 		 */
1820 		if (!full && starttime != time_second)
1821 			break;
1822 	}
1823 	if (full == 0)
1824 		journal_unsuspend(ump);
1825 	FREE_LOCK(ump);
1826 	return (matchcnt);
1827 }
1828 
1829 /*
1830  * Process all removes associated with a vnode if we are running out of
1831  * journal space.  Any other process which attempts to flush these will
1832  * be unable as we have the vnodes locked.
1833  */
1834 static void
1835 process_removes(vp)
1836 	struct vnode *vp;
1837 {
1838 	struct inodedep *inodedep;
1839 	struct dirrem *dirrem;
1840 	struct ufsmount *ump;
1841 	struct mount *mp;
1842 	ino_t inum;
1843 
1844 	mp = vp->v_mount;
1845 	ump = VFSTOUFS(mp);
1846 	LOCK_OWNED(ump);
1847 	inum = VTOI(vp)->i_number;
1848 	for (;;) {
1849 top:
1850 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1851 			return;
1852 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1853 			/*
1854 			 * If another thread is trying to lock this vnode
1855 			 * it will fail but we must wait for it to do so
1856 			 * before we can proceed.
1857 			 */
1858 			if (dirrem->dm_state & INPROGRESS) {
1859 				wait_worklist(&dirrem->dm_list, "pwrwait");
1860 				goto top;
1861 			}
1862 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1863 			    (COMPLETE | ONWORKLIST))
1864 				break;
1865 		}
1866 		if (dirrem == NULL)
1867 			return;
1868 		remove_from_worklist(&dirrem->dm_list);
1869 		FREE_LOCK(ump);
1870 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1871 			panic("process_removes: suspended filesystem");
1872 		handle_workitem_remove(dirrem, 0);
1873 		vn_finished_secondary_write(mp);
1874 		ACQUIRE_LOCK(ump);
1875 	}
1876 }
1877 
1878 /*
1879  * Process all truncations associated with a vnode if we are running out
1880  * of journal space.  This is called when the vnode lock is already held
1881  * and no other process can clear the truncation.  This function returns
1882  * a value greater than zero if it did any work.
1883  */
1884 static void
1885 process_truncates(vp)
1886 	struct vnode *vp;
1887 {
1888 	struct inodedep *inodedep;
1889 	struct freeblks *freeblks;
1890 	struct ufsmount *ump;
1891 	struct mount *mp;
1892 	ino_t inum;
1893 	int cgwait;
1894 
1895 	mp = vp->v_mount;
1896 	ump = VFSTOUFS(mp);
1897 	LOCK_OWNED(ump);
1898 	inum = VTOI(vp)->i_number;
1899 	for (;;) {
1900 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1901 			return;
1902 		cgwait = 0;
1903 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1904 			/* Journal entries not yet written.  */
1905 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1906 				jwait(&LIST_FIRST(
1907 				    &freeblks->fb_jblkdephd)->jb_list,
1908 				    MNT_WAIT);
1909 				break;
1910 			}
1911 			/* Another thread is executing this item. */
1912 			if (freeblks->fb_state & INPROGRESS) {
1913 				wait_worklist(&freeblks->fb_list, "ptrwait");
1914 				break;
1915 			}
1916 			/* Freeblks is waiting on a inode write. */
1917 			if ((freeblks->fb_state & COMPLETE) == 0) {
1918 				FREE_LOCK(ump);
1919 				ffs_update(vp, 1);
1920 				ACQUIRE_LOCK(ump);
1921 				break;
1922 			}
1923 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1924 			    (ALLCOMPLETE | ONWORKLIST)) {
1925 				remove_from_worklist(&freeblks->fb_list);
1926 				freeblks->fb_state |= INPROGRESS;
1927 				FREE_LOCK(ump);
1928 				if (vn_start_secondary_write(NULL, &mp,
1929 				    V_NOWAIT))
1930 					panic("process_truncates: "
1931 					    "suspended filesystem");
1932 				handle_workitem_freeblocks(freeblks, 0);
1933 				vn_finished_secondary_write(mp);
1934 				ACQUIRE_LOCK(ump);
1935 				break;
1936 			}
1937 			if (freeblks->fb_cgwait)
1938 				cgwait++;
1939 		}
1940 		if (cgwait) {
1941 			FREE_LOCK(ump);
1942 			sync_cgs(mp, MNT_WAIT);
1943 			ffs_sync_snap(mp, MNT_WAIT);
1944 			ACQUIRE_LOCK(ump);
1945 			continue;
1946 		}
1947 		if (freeblks == NULL)
1948 			break;
1949 	}
1950 	return;
1951 }
1952 
1953 /*
1954  * Process one item on the worklist.
1955  */
1956 static int
1957 process_worklist_item(mp, target, flags)
1958 	struct mount *mp;
1959 	int target;
1960 	int flags;
1961 {
1962 	struct worklist sentinel;
1963 	struct worklist *wk;
1964 	struct ufsmount *ump;
1965 	int matchcnt;
1966 	int error;
1967 
1968 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1969 	/*
1970 	 * If we are being called because of a process doing a
1971 	 * copy-on-write, then it is not safe to write as we may
1972 	 * recurse into the copy-on-write routine.
1973 	 */
1974 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1975 		return (-1);
1976 	PHOLD(curproc);	/* Don't let the stack go away. */
1977 	ump = VFSTOUFS(mp);
1978 	LOCK_OWNED(ump);
1979 	matchcnt = 0;
1980 	sentinel.wk_mp = NULL;
1981 	sentinel.wk_type = D_SENTINEL;
1982 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1983 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1984 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1985 		if (wk->wk_type == D_SENTINEL) {
1986 			LIST_REMOVE(&sentinel, wk_list);
1987 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1988 			continue;
1989 		}
1990 		if (wk->wk_state & INPROGRESS)
1991 			panic("process_worklist_item: %p already in progress.",
1992 			    wk);
1993 		wk->wk_state |= INPROGRESS;
1994 		remove_from_worklist(wk);
1995 		FREE_LOCK(ump);
1996 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1997 			panic("process_worklist_item: suspended filesystem");
1998 		switch (wk->wk_type) {
1999 		case D_DIRREM:
2000 			/* removal of a directory entry */
2001 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
2002 			break;
2003 
2004 		case D_FREEBLKS:
2005 			/* releasing blocks and/or fragments from a file */
2006 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
2007 			    flags);
2008 			break;
2009 
2010 		case D_FREEFRAG:
2011 			/* releasing a fragment when replaced as a file grows */
2012 			handle_workitem_freefrag(WK_FREEFRAG(wk));
2013 			error = 0;
2014 			break;
2015 
2016 		case D_FREEFILE:
2017 			/* releasing an inode when its link count drops to 0 */
2018 			handle_workitem_freefile(WK_FREEFILE(wk));
2019 			error = 0;
2020 			break;
2021 
2022 		default:
2023 			panic("%s_process_worklist: Unknown type %s",
2024 			    "softdep", TYPENAME(wk->wk_type));
2025 			/* NOTREACHED */
2026 		}
2027 		vn_finished_secondary_write(mp);
2028 		ACQUIRE_LOCK(ump);
2029 		if (error == 0) {
2030 			if (++matchcnt == target)
2031 				break;
2032 			continue;
2033 		}
2034 		/*
2035 		 * We have to retry the worklist item later.  Wake up any
2036 		 * waiters who may be able to complete it immediately and
2037 		 * add the item back to the head so we don't try to execute
2038 		 * it again.
2039 		 */
2040 		wk->wk_state &= ~INPROGRESS;
2041 		wake_worklist(wk);
2042 		add_to_worklist(wk, WK_HEAD);
2043 	}
2044 	/* Sentinal could've become the tail from remove_from_worklist. */
2045 	if (ump->softdep_worklist_tail == &sentinel)
2046 		ump->softdep_worklist_tail =
2047 		    (struct worklist *)sentinel.wk_list.le_prev;
2048 	LIST_REMOVE(&sentinel, wk_list);
2049 	PRELE(curproc);
2050 	return (matchcnt);
2051 }
2052 
2053 /*
2054  * Move dependencies from one buffer to another.
2055  */
2056 int
2057 softdep_move_dependencies(oldbp, newbp)
2058 	struct buf *oldbp;
2059 	struct buf *newbp;
2060 {
2061 	struct worklist *wk, *wktail;
2062 	struct ufsmount *ump;
2063 	int dirty;
2064 
2065 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
2066 		return (0);
2067 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
2068 	    ("softdep_move_dependencies called on non-softdep filesystem"));
2069 	dirty = 0;
2070 	wktail = NULL;
2071 	ump = VFSTOUFS(wk->wk_mp);
2072 	ACQUIRE_LOCK(ump);
2073 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
2074 		LIST_REMOVE(wk, wk_list);
2075 		if (wk->wk_type == D_BMSAFEMAP &&
2076 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
2077 			dirty = 1;
2078 		if (wktail == NULL)
2079 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
2080 		else
2081 			LIST_INSERT_AFTER(wktail, wk, wk_list);
2082 		wktail = wk;
2083 	}
2084 	FREE_LOCK(ump);
2085 
2086 	return (dirty);
2087 }
2088 
2089 /*
2090  * Purge the work list of all items associated with a particular mount point.
2091  */
2092 int
2093 softdep_flushworklist(oldmnt, countp, td)
2094 	struct mount *oldmnt;
2095 	int *countp;
2096 	struct thread *td;
2097 {
2098 	struct vnode *devvp;
2099 	struct ufsmount *ump;
2100 	int count, error;
2101 
2102 	/*
2103 	 * Alternately flush the block device associated with the mount
2104 	 * point and process any dependencies that the flushing
2105 	 * creates. We continue until no more worklist dependencies
2106 	 * are found.
2107 	 */
2108 	*countp = 0;
2109 	error = 0;
2110 	ump = VFSTOUFS(oldmnt);
2111 	devvp = ump->um_devvp;
2112 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
2113 		*countp += count;
2114 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2115 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2116 		VOP_UNLOCK(devvp);
2117 		if (error != 0)
2118 			break;
2119 	}
2120 	return (error);
2121 }
2122 
2123 #define	SU_WAITIDLE_RETRIES	20
2124 static int
2125 softdep_waitidle(struct mount *mp, int flags __unused)
2126 {
2127 	struct ufsmount *ump;
2128 	struct vnode *devvp;
2129 	struct thread *td;
2130 	int error, i;
2131 
2132 	ump = VFSTOUFS(mp);
2133 	devvp = ump->um_devvp;
2134 	td = curthread;
2135 	error = 0;
2136 	ACQUIRE_LOCK(ump);
2137 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
2138 		ump->softdep_req = 1;
2139 		KASSERT((flags & FORCECLOSE) == 0 ||
2140 		    ump->softdep_on_worklist == 0,
2141 		    ("softdep_waitidle: work added after flush"));
2142 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
2143 		    "softdeps", 10 * hz);
2144 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2145 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2146 		VOP_UNLOCK(devvp);
2147 		ACQUIRE_LOCK(ump);
2148 		if (error != 0)
2149 			break;
2150 	}
2151 	ump->softdep_req = 0;
2152 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
2153 		error = EBUSY;
2154 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
2155 		    mp);
2156 	}
2157 	FREE_LOCK(ump);
2158 	return (error);
2159 }
2160 
2161 /*
2162  * Flush all vnodes and worklist items associated with a specified mount point.
2163  */
2164 int
2165 softdep_flushfiles(oldmnt, flags, td)
2166 	struct mount *oldmnt;
2167 	int flags;
2168 	struct thread *td;
2169 {
2170 #ifdef QUOTA
2171 	struct ufsmount *ump;
2172 	int i;
2173 #endif
2174 	int error, early, depcount, loopcnt, retry_flush_count, retry;
2175 	int morework;
2176 
2177 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
2178 	    ("softdep_flushfiles called on non-softdep filesystem"));
2179 	loopcnt = 10;
2180 	retry_flush_count = 3;
2181 retry_flush:
2182 	error = 0;
2183 
2184 	/*
2185 	 * Alternately flush the vnodes associated with the mount
2186 	 * point and process any dependencies that the flushing
2187 	 * creates. In theory, this loop can happen at most twice,
2188 	 * but we give it a few extra just to be sure.
2189 	 */
2190 	for (; loopcnt > 0; loopcnt--) {
2191 		/*
2192 		 * Do another flush in case any vnodes were brought in
2193 		 * as part of the cleanup operations.
2194 		 */
2195 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2196 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2197 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2198 			break;
2199 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2200 		    depcount == 0)
2201 			break;
2202 	}
2203 	/*
2204 	 * If we are unmounting then it is an error to fail. If we
2205 	 * are simply trying to downgrade to read-only, then filesystem
2206 	 * activity can keep us busy forever, so we just fail with EBUSY.
2207 	 */
2208 	if (loopcnt == 0) {
2209 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2210 			panic("softdep_flushfiles: looping");
2211 		error = EBUSY;
2212 	}
2213 	if (!error)
2214 		error = softdep_waitidle(oldmnt, flags);
2215 	if (!error) {
2216 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2217 			retry = 0;
2218 			MNT_ILOCK(oldmnt);
2219 			morework = oldmnt->mnt_nvnodelistsize > 0;
2220 #ifdef QUOTA
2221 			ump = VFSTOUFS(oldmnt);
2222 			UFS_LOCK(ump);
2223 			for (i = 0; i < MAXQUOTAS; i++) {
2224 				if (ump->um_quotas[i] != NULLVP)
2225 					morework = 1;
2226 			}
2227 			UFS_UNLOCK(ump);
2228 #endif
2229 			if (morework) {
2230 				if (--retry_flush_count > 0) {
2231 					retry = 1;
2232 					loopcnt = 3;
2233 				} else
2234 					error = EBUSY;
2235 			}
2236 			MNT_IUNLOCK(oldmnt);
2237 			if (retry)
2238 				goto retry_flush;
2239 		}
2240 	}
2241 	return (error);
2242 }
2243 
2244 /*
2245  * Structure hashing.
2246  *
2247  * There are four types of structures that can be looked up:
2248  *	1) pagedep structures identified by mount point, inode number,
2249  *	   and logical block.
2250  *	2) inodedep structures identified by mount point and inode number.
2251  *	3) newblk structures identified by mount point and
2252  *	   physical block number.
2253  *	4) bmsafemap structures identified by mount point and
2254  *	   cylinder group number.
2255  *
2256  * The "pagedep" and "inodedep" dependency structures are hashed
2257  * separately from the file blocks and inodes to which they correspond.
2258  * This separation helps when the in-memory copy of an inode or
2259  * file block must be replaced. It also obviates the need to access
2260  * an inode or file page when simply updating (or de-allocating)
2261  * dependency structures. Lookup of newblk structures is needed to
2262  * find newly allocated blocks when trying to associate them with
2263  * their allocdirect or allocindir structure.
2264  *
2265  * The lookup routines optionally create and hash a new instance when
2266  * an existing entry is not found. The bmsafemap lookup routine always
2267  * allocates a new structure if an existing one is not found.
2268  */
2269 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2270 
2271 /*
2272  * Structures and routines associated with pagedep caching.
2273  */
2274 #define	PAGEDEP_HASH(ump, inum, lbn) \
2275 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2276 
2277 static int
2278 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2279 	struct pagedep_hashhead *pagedephd;
2280 	ino_t ino;
2281 	ufs_lbn_t lbn;
2282 	struct pagedep **pagedeppp;
2283 {
2284 	struct pagedep *pagedep;
2285 
2286 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2287 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2288 			*pagedeppp = pagedep;
2289 			return (1);
2290 		}
2291 	}
2292 	*pagedeppp = NULL;
2293 	return (0);
2294 }
2295 /*
2296  * Look up a pagedep. Return 1 if found, 0 otherwise.
2297  * If not found, allocate if DEPALLOC flag is passed.
2298  * Found or allocated entry is returned in pagedeppp.
2299  */
2300 static int
2301 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2302 	struct mount *mp;
2303 	struct buf *bp;
2304 	ino_t ino;
2305 	ufs_lbn_t lbn;
2306 	int flags;
2307 	struct pagedep **pagedeppp;
2308 {
2309 	struct pagedep *pagedep;
2310 	struct pagedep_hashhead *pagedephd;
2311 	struct worklist *wk;
2312 	struct ufsmount *ump;
2313 	int ret;
2314 	int i;
2315 
2316 	ump = VFSTOUFS(mp);
2317 	LOCK_OWNED(ump);
2318 	if (bp) {
2319 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2320 			if (wk->wk_type == D_PAGEDEP) {
2321 				*pagedeppp = WK_PAGEDEP(wk);
2322 				return (1);
2323 			}
2324 		}
2325 	}
2326 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2327 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2328 	if (ret) {
2329 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2330 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2331 		return (1);
2332 	}
2333 	if ((flags & DEPALLOC) == 0)
2334 		return (0);
2335 	FREE_LOCK(ump);
2336 	pagedep = malloc(sizeof(struct pagedep),
2337 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2338 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2339 	ACQUIRE_LOCK(ump);
2340 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2341 	if (*pagedeppp) {
2342 		/*
2343 		 * This should never happen since we only create pagedeps
2344 		 * with the vnode lock held.  Could be an assert.
2345 		 */
2346 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2347 		return (ret);
2348 	}
2349 	pagedep->pd_ino = ino;
2350 	pagedep->pd_lbn = lbn;
2351 	LIST_INIT(&pagedep->pd_dirremhd);
2352 	LIST_INIT(&pagedep->pd_pendinghd);
2353 	for (i = 0; i < DAHASHSZ; i++)
2354 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2355 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2356 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2357 	*pagedeppp = pagedep;
2358 	return (0);
2359 }
2360 
2361 /*
2362  * Structures and routines associated with inodedep caching.
2363  */
2364 #define	INODEDEP_HASH(ump, inum) \
2365       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2366 
2367 static int
2368 inodedep_find(inodedephd, inum, inodedeppp)
2369 	struct inodedep_hashhead *inodedephd;
2370 	ino_t inum;
2371 	struct inodedep **inodedeppp;
2372 {
2373 	struct inodedep *inodedep;
2374 
2375 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2376 		if (inum == inodedep->id_ino)
2377 			break;
2378 	if (inodedep) {
2379 		*inodedeppp = inodedep;
2380 		return (1);
2381 	}
2382 	*inodedeppp = NULL;
2383 
2384 	return (0);
2385 }
2386 /*
2387  * Look up an inodedep. Return 1 if found, 0 if not found.
2388  * If not found, allocate if DEPALLOC flag is passed.
2389  * Found or allocated entry is returned in inodedeppp.
2390  */
2391 static int
2392 inodedep_lookup(mp, inum, flags, inodedeppp)
2393 	struct mount *mp;
2394 	ino_t inum;
2395 	int flags;
2396 	struct inodedep **inodedeppp;
2397 {
2398 	struct inodedep *inodedep;
2399 	struct inodedep_hashhead *inodedephd;
2400 	struct ufsmount *ump;
2401 	struct fs *fs;
2402 
2403 	ump = VFSTOUFS(mp);
2404 	LOCK_OWNED(ump);
2405 	fs = ump->um_fs;
2406 	inodedephd = INODEDEP_HASH(ump, inum);
2407 
2408 	if (inodedep_find(inodedephd, inum, inodedeppp))
2409 		return (1);
2410 	if ((flags & DEPALLOC) == 0)
2411 		return (0);
2412 	/*
2413 	 * If the system is over its limit and our filesystem is
2414 	 * responsible for more than our share of that usage and
2415 	 * we are not in a rush, request some inodedep cleanup.
2416 	 */
2417 	if (softdep_excess_items(ump, D_INODEDEP))
2418 		schedule_cleanup(mp);
2419 	else
2420 		FREE_LOCK(ump);
2421 	inodedep = malloc(sizeof(struct inodedep),
2422 		M_INODEDEP, M_SOFTDEP_FLAGS);
2423 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2424 	ACQUIRE_LOCK(ump);
2425 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2426 		WORKITEM_FREE(inodedep, D_INODEDEP);
2427 		return (1);
2428 	}
2429 	inodedep->id_fs = fs;
2430 	inodedep->id_ino = inum;
2431 	inodedep->id_state = ALLCOMPLETE;
2432 	inodedep->id_nlinkdelta = 0;
2433 	inodedep->id_nlinkwrote = -1;
2434 	inodedep->id_savedino1 = NULL;
2435 	inodedep->id_savedsize = -1;
2436 	inodedep->id_savedextsize = -1;
2437 	inodedep->id_savednlink = -1;
2438 	inodedep->id_bmsafemap = NULL;
2439 	inodedep->id_mkdiradd = NULL;
2440 	LIST_INIT(&inodedep->id_dirremhd);
2441 	LIST_INIT(&inodedep->id_pendinghd);
2442 	LIST_INIT(&inodedep->id_inowait);
2443 	LIST_INIT(&inodedep->id_bufwait);
2444 	TAILQ_INIT(&inodedep->id_inoreflst);
2445 	TAILQ_INIT(&inodedep->id_inoupdt);
2446 	TAILQ_INIT(&inodedep->id_newinoupdt);
2447 	TAILQ_INIT(&inodedep->id_extupdt);
2448 	TAILQ_INIT(&inodedep->id_newextupdt);
2449 	TAILQ_INIT(&inodedep->id_freeblklst);
2450 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2451 	*inodedeppp = inodedep;
2452 	return (0);
2453 }
2454 
2455 /*
2456  * Structures and routines associated with newblk caching.
2457  */
2458 #define	NEWBLK_HASH(ump, inum) \
2459 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2460 
2461 static int
2462 newblk_find(newblkhd, newblkno, flags, newblkpp)
2463 	struct newblk_hashhead *newblkhd;
2464 	ufs2_daddr_t newblkno;
2465 	int flags;
2466 	struct newblk **newblkpp;
2467 {
2468 	struct newblk *newblk;
2469 
2470 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2471 		if (newblkno != newblk->nb_newblkno)
2472 			continue;
2473 		/*
2474 		 * If we're creating a new dependency don't match those that
2475 		 * have already been converted to allocdirects.  This is for
2476 		 * a frag extend.
2477 		 */
2478 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2479 			continue;
2480 		break;
2481 	}
2482 	if (newblk) {
2483 		*newblkpp = newblk;
2484 		return (1);
2485 	}
2486 	*newblkpp = NULL;
2487 	return (0);
2488 }
2489 
2490 /*
2491  * Look up a newblk. Return 1 if found, 0 if not found.
2492  * If not found, allocate if DEPALLOC flag is passed.
2493  * Found or allocated entry is returned in newblkpp.
2494  */
2495 static int
2496 newblk_lookup(mp, newblkno, flags, newblkpp)
2497 	struct mount *mp;
2498 	ufs2_daddr_t newblkno;
2499 	int flags;
2500 	struct newblk **newblkpp;
2501 {
2502 	struct newblk *newblk;
2503 	struct newblk_hashhead *newblkhd;
2504 	struct ufsmount *ump;
2505 
2506 	ump = VFSTOUFS(mp);
2507 	LOCK_OWNED(ump);
2508 	newblkhd = NEWBLK_HASH(ump, newblkno);
2509 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2510 		return (1);
2511 	if ((flags & DEPALLOC) == 0)
2512 		return (0);
2513 	if (softdep_excess_items(ump, D_NEWBLK) ||
2514 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2515 	    softdep_excess_items(ump, D_ALLOCINDIR))
2516 		schedule_cleanup(mp);
2517 	else
2518 		FREE_LOCK(ump);
2519 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2520 	    M_SOFTDEP_FLAGS | M_ZERO);
2521 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2522 	ACQUIRE_LOCK(ump);
2523 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2524 		WORKITEM_FREE(newblk, D_NEWBLK);
2525 		return (1);
2526 	}
2527 	newblk->nb_freefrag = NULL;
2528 	LIST_INIT(&newblk->nb_indirdeps);
2529 	LIST_INIT(&newblk->nb_newdirblk);
2530 	LIST_INIT(&newblk->nb_jwork);
2531 	newblk->nb_state = ATTACHED;
2532 	newblk->nb_newblkno = newblkno;
2533 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2534 	*newblkpp = newblk;
2535 	return (0);
2536 }
2537 
2538 /*
2539  * Structures and routines associated with freed indirect block caching.
2540  */
2541 #define	INDIR_HASH(ump, blkno) \
2542 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2543 
2544 /*
2545  * Lookup an indirect block in the indir hash table.  The freework is
2546  * removed and potentially freed.  The caller must do a blocking journal
2547  * write before writing to the blkno.
2548  */
2549 static int
2550 indirblk_lookup(mp, blkno)
2551 	struct mount *mp;
2552 	ufs2_daddr_t blkno;
2553 {
2554 	struct freework *freework;
2555 	struct indir_hashhead *wkhd;
2556 	struct ufsmount *ump;
2557 
2558 	ump = VFSTOUFS(mp);
2559 	wkhd = INDIR_HASH(ump, blkno);
2560 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2561 		if (freework->fw_blkno != blkno)
2562 			continue;
2563 		indirblk_remove(freework);
2564 		return (1);
2565 	}
2566 	return (0);
2567 }
2568 
2569 /*
2570  * Insert an indirect block represented by freework into the indirblk
2571  * hash table so that it may prevent the block from being re-used prior
2572  * to the journal being written.
2573  */
2574 static void
2575 indirblk_insert(freework)
2576 	struct freework *freework;
2577 {
2578 	struct jblocks *jblocks;
2579 	struct jseg *jseg;
2580 	struct ufsmount *ump;
2581 
2582 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2583 	jblocks = ump->softdep_jblocks;
2584 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2585 	if (jseg == NULL)
2586 		return;
2587 
2588 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2589 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2590 	    fw_next);
2591 	freework->fw_state &= ~DEPCOMPLETE;
2592 }
2593 
2594 static void
2595 indirblk_remove(freework)
2596 	struct freework *freework;
2597 {
2598 	struct ufsmount *ump;
2599 
2600 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2601 	LIST_REMOVE(freework, fw_segs);
2602 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2603 	freework->fw_state |= DEPCOMPLETE;
2604 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2605 		WORKITEM_FREE(freework, D_FREEWORK);
2606 }
2607 
2608 /*
2609  * Executed during filesystem system initialization before
2610  * mounting any filesystems.
2611  */
2612 void
2613 softdep_initialize()
2614 {
2615 
2616 	TAILQ_INIT(&softdepmounts);
2617 #ifdef __LP64__
2618 	max_softdeps = desiredvnodes * 4;
2619 #else
2620 	max_softdeps = desiredvnodes * 2;
2621 #endif
2622 
2623 	/* initialise bioops hack */
2624 	bioops.io_start = softdep_disk_io_initiation;
2625 	bioops.io_complete = softdep_disk_write_complete;
2626 	bioops.io_deallocate = softdep_deallocate_dependencies;
2627 	bioops.io_countdeps = softdep_count_dependencies;
2628 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2629 
2630 	/* Initialize the callout with an mtx. */
2631 	callout_init_mtx(&softdep_callout, &lk, 0);
2632 }
2633 
2634 /*
2635  * Executed after all filesystems have been unmounted during
2636  * filesystem module unload.
2637  */
2638 void
2639 softdep_uninitialize()
2640 {
2641 
2642 	/* clear bioops hack */
2643 	bioops.io_start = NULL;
2644 	bioops.io_complete = NULL;
2645 	bioops.io_deallocate = NULL;
2646 	bioops.io_countdeps = NULL;
2647 	softdep_ast_cleanup = NULL;
2648 
2649 	callout_drain(&softdep_callout);
2650 }
2651 
2652 /*
2653  * Called at mount time to notify the dependency code that a
2654  * filesystem wishes to use it.
2655  */
2656 int
2657 softdep_mount(devvp, mp, fs, cred)
2658 	struct vnode *devvp;
2659 	struct mount *mp;
2660 	struct fs *fs;
2661 	struct ucred *cred;
2662 {
2663 	struct csum_total cstotal;
2664 	struct mount_softdeps *sdp;
2665 	struct ufsmount *ump;
2666 	struct cg *cgp;
2667 	struct buf *bp;
2668 	u_int cyl, i;
2669 	int error;
2670 
2671 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2672 	    M_WAITOK | M_ZERO);
2673 	MNT_ILOCK(mp);
2674 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2675 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2676 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2677 			MNTK_SOFTDEP | MNTK_NOASYNC;
2678 	}
2679 	ump = VFSTOUFS(mp);
2680 	ump->um_softdep = sdp;
2681 	MNT_IUNLOCK(mp);
2682 	rw_init(LOCK_PTR(ump), "per-fs softdep");
2683 	sdp->sd_ump = ump;
2684 	LIST_INIT(&ump->softdep_workitem_pending);
2685 	LIST_INIT(&ump->softdep_journal_pending);
2686 	TAILQ_INIT(&ump->softdep_unlinked);
2687 	LIST_INIT(&ump->softdep_dirtycg);
2688 	ump->softdep_worklist_tail = NULL;
2689 	ump->softdep_on_worklist = 0;
2690 	ump->softdep_deps = 0;
2691 	LIST_INIT(&ump->softdep_mkdirlisthd);
2692 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2693 	    &ump->pagedep_hash_size);
2694 	ump->pagedep_nextclean = 0;
2695 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2696 	    &ump->inodedep_hash_size);
2697 	ump->inodedep_nextclean = 0;
2698 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2699 	    &ump->newblk_hash_size);
2700 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2701 	    &ump->bmsafemap_hash_size);
2702 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2703 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2704 	    M_FREEWORK, M_WAITOK);
2705 	ump->indir_hash_size = i - 1;
2706 	for (i = 0; i <= ump->indir_hash_size; i++)
2707 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2708 #ifdef INVARIANTS
2709 	for (i = 0; i <= D_LAST; i++)
2710 		LIST_INIT(&ump->softdep_alldeps[i]);
2711 #endif
2712 	ACQUIRE_GBLLOCK(&lk);
2713 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2714 	FREE_GBLLOCK(&lk);
2715 	if ((fs->fs_flags & FS_SUJ) &&
2716 	    (error = journal_mount(mp, fs, cred)) != 0) {
2717 		printf("Failed to start journal: %d\n", error);
2718 		softdep_unmount(mp);
2719 		return (error);
2720 	}
2721 	/*
2722 	 * Start our flushing thread in the bufdaemon process.
2723 	 */
2724 	ACQUIRE_LOCK(ump);
2725 	ump->softdep_flags |= FLUSH_STARTING;
2726 	FREE_LOCK(ump);
2727 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2728 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2729 	    mp->mnt_stat.f_mntonname);
2730 	ACQUIRE_LOCK(ump);
2731 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2732 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2733 		    hz / 2);
2734 	}
2735 	FREE_LOCK(ump);
2736 	/*
2737 	 * When doing soft updates, the counters in the
2738 	 * superblock may have gotten out of sync. Recomputation
2739 	 * can take a long time and can be deferred for background
2740 	 * fsck.  However, the old behavior of scanning the cylinder
2741 	 * groups and recalculating them at mount time is available
2742 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2743 	 */
2744 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2745 		return (0);
2746 	bzero(&cstotal, sizeof cstotal);
2747 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2748 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2749 		    fs->fs_cgsize, cred, &bp)) != 0) {
2750 			brelse(bp);
2751 			softdep_unmount(mp);
2752 			return (error);
2753 		}
2754 		cgp = (struct cg *)bp->b_data;
2755 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2756 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2757 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2758 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2759 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2760 		brelse(bp);
2761 	}
2762 #ifdef INVARIANTS
2763 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2764 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2765 #endif
2766 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2767 	return (0);
2768 }
2769 
2770 void
2771 softdep_unmount(mp)
2772 	struct mount *mp;
2773 {
2774 	struct ufsmount *ump;
2775 #ifdef INVARIANTS
2776 	int i;
2777 #endif
2778 
2779 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2780 	    ("softdep_unmount called on non-softdep filesystem"));
2781 	ump = VFSTOUFS(mp);
2782 	MNT_ILOCK(mp);
2783 	mp->mnt_flag &= ~MNT_SOFTDEP;
2784 	if (MOUNTEDSUJ(mp) == 0) {
2785 		MNT_IUNLOCK(mp);
2786 	} else {
2787 		mp->mnt_flag &= ~MNT_SUJ;
2788 		MNT_IUNLOCK(mp);
2789 		journal_unmount(ump);
2790 	}
2791 	/*
2792 	 * Shut down our flushing thread. Check for NULL is if
2793 	 * softdep_mount errors out before the thread has been created.
2794 	 */
2795 	if (ump->softdep_flushtd != NULL) {
2796 		ACQUIRE_LOCK(ump);
2797 		ump->softdep_flags |= FLUSH_EXIT;
2798 		wakeup(&ump->softdep_flushtd);
2799 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2800 		    "sdwait", 0);
2801 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2802 		    ("Thread shutdown failed"));
2803 	}
2804 	/*
2805 	 * Free up our resources.
2806 	 */
2807 	ACQUIRE_GBLLOCK(&lk);
2808 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2809 	FREE_GBLLOCK(&lk);
2810 	rw_destroy(LOCK_PTR(ump));
2811 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2812 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2813 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2814 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2815 	    ump->bmsafemap_hash_size);
2816 	free(ump->indir_hashtbl, M_FREEWORK);
2817 #ifdef INVARIANTS
2818 	for (i = 0; i <= D_LAST; i++) {
2819 		KASSERT(ump->softdep_curdeps[i] == 0,
2820 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2821 		    TYPENAME(i), ump->softdep_curdeps[i]));
2822 		KASSERT(LIST_EMPTY(&ump->softdep_alldeps[i]),
2823 		    ("Unmount %s: Dep type %s not empty (%p)", ump->um_fs->fs_fsmnt,
2824 		    TYPENAME(i), LIST_FIRST(&ump->softdep_alldeps[i])));
2825 	}
2826 #endif
2827 	free(ump->um_softdep, M_MOUNTDATA);
2828 }
2829 
2830 static struct jblocks *
2831 jblocks_create(void)
2832 {
2833 	struct jblocks *jblocks;
2834 
2835 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2836 	TAILQ_INIT(&jblocks->jb_segs);
2837 	jblocks->jb_avail = 10;
2838 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2839 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2840 
2841 	return (jblocks);
2842 }
2843 
2844 static ufs2_daddr_t
2845 jblocks_alloc(jblocks, bytes, actual)
2846 	struct jblocks *jblocks;
2847 	int bytes;
2848 	int *actual;
2849 {
2850 	ufs2_daddr_t daddr;
2851 	struct jextent *jext;
2852 	int freecnt;
2853 	int blocks;
2854 
2855 	blocks = bytes / DEV_BSIZE;
2856 	jext = &jblocks->jb_extent[jblocks->jb_head];
2857 	freecnt = jext->je_blocks - jblocks->jb_off;
2858 	if (freecnt == 0) {
2859 		jblocks->jb_off = 0;
2860 		if (++jblocks->jb_head > jblocks->jb_used)
2861 			jblocks->jb_head = 0;
2862 		jext = &jblocks->jb_extent[jblocks->jb_head];
2863 		freecnt = jext->je_blocks;
2864 	}
2865 	if (freecnt > blocks)
2866 		freecnt = blocks;
2867 	*actual = freecnt * DEV_BSIZE;
2868 	daddr = jext->je_daddr + jblocks->jb_off;
2869 	jblocks->jb_off += freecnt;
2870 	jblocks->jb_free -= freecnt;
2871 
2872 	return (daddr);
2873 }
2874 
2875 static void
2876 jblocks_free(jblocks, mp, bytes)
2877 	struct jblocks *jblocks;
2878 	struct mount *mp;
2879 	int bytes;
2880 {
2881 
2882 	LOCK_OWNED(VFSTOUFS(mp));
2883 	jblocks->jb_free += bytes / DEV_BSIZE;
2884 	if (jblocks->jb_suspended)
2885 		worklist_speedup(mp);
2886 	wakeup(jblocks);
2887 }
2888 
2889 static void
2890 jblocks_destroy(jblocks)
2891 	struct jblocks *jblocks;
2892 {
2893 
2894 	if (jblocks->jb_extent)
2895 		free(jblocks->jb_extent, M_JBLOCKS);
2896 	free(jblocks, M_JBLOCKS);
2897 }
2898 
2899 static void
2900 jblocks_add(jblocks, daddr, blocks)
2901 	struct jblocks *jblocks;
2902 	ufs2_daddr_t daddr;
2903 	int blocks;
2904 {
2905 	struct jextent *jext;
2906 
2907 	jblocks->jb_blocks += blocks;
2908 	jblocks->jb_free += blocks;
2909 	jext = &jblocks->jb_extent[jblocks->jb_used];
2910 	/* Adding the first block. */
2911 	if (jext->je_daddr == 0) {
2912 		jext->je_daddr = daddr;
2913 		jext->je_blocks = blocks;
2914 		return;
2915 	}
2916 	/* Extending the last extent. */
2917 	if (jext->je_daddr + jext->je_blocks == daddr) {
2918 		jext->je_blocks += blocks;
2919 		return;
2920 	}
2921 	/* Adding a new extent. */
2922 	if (++jblocks->jb_used == jblocks->jb_avail) {
2923 		jblocks->jb_avail *= 2;
2924 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2925 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2926 		memcpy(jext, jblocks->jb_extent,
2927 		    sizeof(struct jextent) * jblocks->jb_used);
2928 		free(jblocks->jb_extent, M_JBLOCKS);
2929 		jblocks->jb_extent = jext;
2930 	}
2931 	jext = &jblocks->jb_extent[jblocks->jb_used];
2932 	jext->je_daddr = daddr;
2933 	jext->je_blocks = blocks;
2934 	return;
2935 }
2936 
2937 int
2938 softdep_journal_lookup(mp, vpp)
2939 	struct mount *mp;
2940 	struct vnode **vpp;
2941 {
2942 	struct componentname cnp;
2943 	struct vnode *dvp;
2944 	ino_t sujournal;
2945 	int error;
2946 
2947 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2948 	if (error)
2949 		return (error);
2950 	bzero(&cnp, sizeof(cnp));
2951 	cnp.cn_nameiop = LOOKUP;
2952 	cnp.cn_flags = ISLASTCN;
2953 	cnp.cn_thread = curthread;
2954 	cnp.cn_cred = curthread->td_ucred;
2955 	cnp.cn_pnbuf = SUJ_FILE;
2956 	cnp.cn_nameptr = SUJ_FILE;
2957 	cnp.cn_namelen = strlen(SUJ_FILE);
2958 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2959 	vput(dvp);
2960 	if (error != 0)
2961 		return (error);
2962 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2963 	return (error);
2964 }
2965 
2966 /*
2967  * Open and verify the journal file.
2968  */
2969 static int
2970 journal_mount(mp, fs, cred)
2971 	struct mount *mp;
2972 	struct fs *fs;
2973 	struct ucred *cred;
2974 {
2975 	struct jblocks *jblocks;
2976 	struct ufsmount *ump;
2977 	struct vnode *vp;
2978 	struct inode *ip;
2979 	ufs2_daddr_t blkno;
2980 	int bcount;
2981 	int error;
2982 	int i;
2983 
2984 	ump = VFSTOUFS(mp);
2985 	ump->softdep_journal_tail = NULL;
2986 	ump->softdep_on_journal = 0;
2987 	ump->softdep_accdeps = 0;
2988 	ump->softdep_req = 0;
2989 	ump->softdep_jblocks = NULL;
2990 	error = softdep_journal_lookup(mp, &vp);
2991 	if (error != 0) {
2992 		printf("Failed to find journal.  Use tunefs to create one\n");
2993 		return (error);
2994 	}
2995 	ip = VTOI(vp);
2996 	if (ip->i_size < SUJ_MIN) {
2997 		error = ENOSPC;
2998 		goto out;
2999 	}
3000 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
3001 	jblocks = jblocks_create();
3002 	for (i = 0; i < bcount; i++) {
3003 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
3004 		if (error)
3005 			break;
3006 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
3007 	}
3008 	if (error) {
3009 		jblocks_destroy(jblocks);
3010 		goto out;
3011 	}
3012 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
3013 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
3014 	ump->softdep_jblocks = jblocks;
3015 out:
3016 	if (error == 0) {
3017 		MNT_ILOCK(mp);
3018 		mp->mnt_flag |= MNT_SUJ;
3019 		mp->mnt_flag &= ~MNT_SOFTDEP;
3020 		MNT_IUNLOCK(mp);
3021 		/*
3022 		 * Only validate the journal contents if the
3023 		 * filesystem is clean, otherwise we write the logs
3024 		 * but they'll never be used.  If the filesystem was
3025 		 * still dirty when we mounted it the journal is
3026 		 * invalid and a new journal can only be valid if it
3027 		 * starts from a clean mount.
3028 		 */
3029 		if (fs->fs_clean) {
3030 			DIP_SET(ip, i_modrev, fs->fs_mtime);
3031 			ip->i_flags |= IN_MODIFIED;
3032 			ffs_update(vp, 1);
3033 		}
3034 	}
3035 	vput(vp);
3036 	return (error);
3037 }
3038 
3039 static void
3040 journal_unmount(ump)
3041 	struct ufsmount *ump;
3042 {
3043 
3044 	if (ump->softdep_jblocks)
3045 		jblocks_destroy(ump->softdep_jblocks);
3046 	ump->softdep_jblocks = NULL;
3047 }
3048 
3049 /*
3050  * Called when a journal record is ready to be written.  Space is allocated
3051  * and the journal entry is created when the journal is flushed to stable
3052  * store.
3053  */
3054 static void
3055 add_to_journal(wk)
3056 	struct worklist *wk;
3057 {
3058 	struct ufsmount *ump;
3059 
3060 	ump = VFSTOUFS(wk->wk_mp);
3061 	LOCK_OWNED(ump);
3062 	if (wk->wk_state & ONWORKLIST)
3063 		panic("add_to_journal: %s(0x%X) already on list",
3064 		    TYPENAME(wk->wk_type), wk->wk_state);
3065 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
3066 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
3067 		ump->softdep_jblocks->jb_age = ticks;
3068 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
3069 	} else
3070 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
3071 	ump->softdep_journal_tail = wk;
3072 	ump->softdep_on_journal += 1;
3073 }
3074 
3075 /*
3076  * Remove an arbitrary item for the journal worklist maintain the tail
3077  * pointer.  This happens when a new operation obviates the need to
3078  * journal an old operation.
3079  */
3080 static void
3081 remove_from_journal(wk)
3082 	struct worklist *wk;
3083 {
3084 	struct ufsmount *ump;
3085 
3086 	ump = VFSTOUFS(wk->wk_mp);
3087 	LOCK_OWNED(ump);
3088 #ifdef INVARIANTS
3089 	{
3090 		struct worklist *wkn;
3091 
3092 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
3093 			if (wkn == wk)
3094 				break;
3095 		if (wkn == NULL)
3096 			panic("remove_from_journal: %p is not in journal", wk);
3097 	}
3098 #endif
3099 	/*
3100 	 * We emulate a TAILQ to save space in most structures which do not
3101 	 * require TAILQ semantics.  Here we must update the tail position
3102 	 * when removing the tail which is not the final entry. This works
3103 	 * only if the worklist linkage are at the beginning of the structure.
3104 	 */
3105 	if (ump->softdep_journal_tail == wk)
3106 		ump->softdep_journal_tail =
3107 		    (struct worklist *)wk->wk_list.le_prev;
3108 	WORKLIST_REMOVE(wk);
3109 	ump->softdep_on_journal -= 1;
3110 }
3111 
3112 /*
3113  * Check for journal space as well as dependency limits so the prelink
3114  * code can throttle both journaled and non-journaled filesystems.
3115  * Threshold is 0 for low and 1 for min.
3116  */
3117 static int
3118 journal_space(ump, thresh)
3119 	struct ufsmount *ump;
3120 	int thresh;
3121 {
3122 	struct jblocks *jblocks;
3123 	int limit, avail;
3124 
3125 	jblocks = ump->softdep_jblocks;
3126 	if (jblocks == NULL)
3127 		return (1);
3128 	/*
3129 	 * We use a tighter restriction here to prevent request_cleanup()
3130 	 * running in threads from running into locks we currently hold.
3131 	 * We have to be over the limit and our filesystem has to be
3132 	 * responsible for more than our share of that usage.
3133 	 */
3134 	limit = (max_softdeps / 10) * 9;
3135 	if (dep_current[D_INODEDEP] > limit &&
3136 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
3137 		return (0);
3138 	if (thresh)
3139 		thresh = jblocks->jb_min;
3140 	else
3141 		thresh = jblocks->jb_low;
3142 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
3143 	avail = jblocks->jb_free - avail;
3144 
3145 	return (avail > thresh);
3146 }
3147 
3148 static void
3149 journal_suspend(ump)
3150 	struct ufsmount *ump;
3151 {
3152 	struct jblocks *jblocks;
3153 	struct mount *mp;
3154 	bool set;
3155 
3156 	mp = UFSTOVFS(ump);
3157 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
3158 		return;
3159 
3160 	jblocks = ump->softdep_jblocks;
3161 	vfs_op_enter(mp);
3162 	set = false;
3163 	MNT_ILOCK(mp);
3164 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
3165 		stat_journal_min++;
3166 		mp->mnt_kern_flag |= MNTK_SUSPEND;
3167 		mp->mnt_susp_owner = ump->softdep_flushtd;
3168 		set = true;
3169 	}
3170 	jblocks->jb_suspended = 1;
3171 	MNT_IUNLOCK(mp);
3172 	if (!set)
3173 		vfs_op_exit(mp);
3174 }
3175 
3176 static int
3177 journal_unsuspend(struct ufsmount *ump)
3178 {
3179 	struct jblocks *jblocks;
3180 	struct mount *mp;
3181 
3182 	mp = UFSTOVFS(ump);
3183 	jblocks = ump->softdep_jblocks;
3184 
3185 	if (jblocks != NULL && jblocks->jb_suspended &&
3186 	    journal_space(ump, jblocks->jb_min)) {
3187 		jblocks->jb_suspended = 0;
3188 		FREE_LOCK(ump);
3189 		mp->mnt_susp_owner = curthread;
3190 		vfs_write_resume(mp, 0);
3191 		ACQUIRE_LOCK(ump);
3192 		return (1);
3193 	}
3194 	return (0);
3195 }
3196 
3197 /*
3198  * Called before any allocation function to be certain that there is
3199  * sufficient space in the journal prior to creating any new records.
3200  * Since in the case of block allocation we may have multiple locked
3201  * buffers at the time of the actual allocation we can not block
3202  * when the journal records are created.  Doing so would create a deadlock
3203  * if any of these buffers needed to be flushed to reclaim space.  Instead
3204  * we require a sufficiently large amount of available space such that
3205  * each thread in the system could have passed this allocation check and
3206  * still have sufficient free space.  With 20% of a minimum journal size
3207  * of 1MB we have 6553 records available.
3208  */
3209 int
3210 softdep_prealloc(vp, waitok)
3211 	struct vnode *vp;
3212 	int waitok;
3213 {
3214 	struct ufsmount *ump;
3215 
3216 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3217 	    ("softdep_prealloc called on non-softdep filesystem"));
3218 	/*
3219 	 * Nothing to do if we are not running journaled soft updates.
3220 	 * If we currently hold the snapshot lock, we must avoid
3221 	 * handling other resources that could cause deadlock.  Do not
3222 	 * touch quotas vnode since it is typically recursed with
3223 	 * other vnode locks held.
3224 	 */
3225 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3226 	    (vp->v_vflag & VV_SYSTEM) != 0)
3227 		return (0);
3228 	ump = VFSTOUFS(vp->v_mount);
3229 	ACQUIRE_LOCK(ump);
3230 	if (journal_space(ump, 0)) {
3231 		FREE_LOCK(ump);
3232 		return (0);
3233 	}
3234 	stat_journal_low++;
3235 	FREE_LOCK(ump);
3236 	if (waitok == MNT_NOWAIT)
3237 		return (ENOSPC);
3238 	/*
3239 	 * Attempt to sync this vnode once to flush any journal
3240 	 * work attached to it.
3241 	 */
3242 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3243 		ffs_syncvnode(vp, waitok, 0);
3244 	ACQUIRE_LOCK(ump);
3245 	process_removes(vp);
3246 	process_truncates(vp);
3247 	if (journal_space(ump, 0) == 0) {
3248 		softdep_speedup(ump);
3249 		if (journal_space(ump, 1) == 0)
3250 			journal_suspend(ump);
3251 	}
3252 	FREE_LOCK(ump);
3253 
3254 	return (0);
3255 }
3256 
3257 /*
3258  * Try hard to sync all data and metadata for the vnode, and workitems
3259  * flushing which might conflict with the vnode lock.  This is a
3260  * helper for softdep_prerename().
3261  */
3262 static int
3263 softdep_prerename_vnode(ump, vp)
3264 	struct ufsmount *ump;
3265 	struct vnode *vp;
3266 {
3267 	int error;
3268 
3269 	ASSERT_VOP_ELOCKED(vp, "prehandle");
3270 	if (vp->v_data == NULL)
3271 		return (0);
3272 	error = VOP_FSYNC(vp, MNT_WAIT, curthread);
3273 	if (error != 0)
3274 		return (error);
3275 	ACQUIRE_LOCK(ump);
3276 	process_removes(vp);
3277 	process_truncates(vp);
3278 	FREE_LOCK(ump);
3279 	return (0);
3280 }
3281 
3282 /*
3283  * Must be called from VOP_RENAME() after all vnodes are locked.
3284  * Ensures that there is enough journal space for rename.  It is
3285  * sufficiently different from softdep_prelink() by having to handle
3286  * four vnodes.
3287  */
3288 int
3289 softdep_prerename(fdvp, fvp, tdvp, tvp)
3290 	struct vnode *fdvp;
3291 	struct vnode *fvp;
3292 	struct vnode *tdvp;
3293 	struct vnode *tvp;
3294 {
3295 	struct ufsmount *ump;
3296 	int error;
3297 
3298 	ump = VFSTOUFS(fdvp->v_mount);
3299 
3300 	if (journal_space(ump, 0))
3301 		return (0);
3302 
3303 	VOP_UNLOCK(tdvp);
3304 	VOP_UNLOCK(fvp);
3305 	if (tvp != NULL && tvp != tdvp)
3306 		VOP_UNLOCK(tvp);
3307 
3308 	error = softdep_prerename_vnode(ump, fdvp);
3309 	VOP_UNLOCK(fdvp);
3310 	if (error != 0)
3311 		return (error);
3312 
3313 	VOP_LOCK(fvp, LK_EXCLUSIVE | LK_RETRY);
3314 	error = softdep_prerename_vnode(ump, fvp);
3315 	VOP_UNLOCK(fvp);
3316 	if (error != 0)
3317 		return (error);
3318 
3319 	if (tdvp != fdvp) {
3320 		VOP_LOCK(tdvp, LK_EXCLUSIVE | LK_RETRY);
3321 		error = softdep_prerename_vnode(ump, tdvp);
3322 		VOP_UNLOCK(tdvp);
3323 		if (error != 0)
3324 			return (error);
3325 	}
3326 
3327 	if (tvp != fvp && tvp != NULL) {
3328 		VOP_LOCK(tvp, LK_EXCLUSIVE | LK_RETRY);
3329 		error = softdep_prerename_vnode(ump, tvp);
3330 		VOP_UNLOCK(tvp);
3331 		if (error != 0)
3332 			return (error);
3333 	}
3334 
3335 	ACQUIRE_LOCK(ump);
3336 	softdep_speedup(ump);
3337 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3338 	if (journal_space(ump, 0) == 0) {
3339 		softdep_speedup(ump);
3340 		if (journal_space(ump, 1) == 0)
3341 			journal_suspend(ump);
3342 	}
3343 	FREE_LOCK(ump);
3344 	return (ERELOOKUP);
3345 }
3346 
3347 /*
3348  * Before adjusting a link count on a vnode verify that we have sufficient
3349  * journal space.  If not, process operations that depend on the currently
3350  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3351  * and softdep flush threads can not acquire these locks to reclaim space.
3352  *
3353  * Returns 0 if all owned locks are still valid and were not dropped
3354  * in the process, in other case it returns either an error from sync,
3355  * or ERELOOKUP if any of the locks were re-acquired.  In the later
3356  * case, the state of the vnodes cannot be relied upon and our VFS
3357  * syscall must be restarted at top level from the lookup.
3358  */
3359 int
3360 softdep_prelink(dvp, vp, will_direnter)
3361 	struct vnode *dvp;
3362 	struct vnode *vp;
3363 	int will_direnter;
3364 {
3365 	struct ufsmount *ump;
3366 	int error, error1;
3367 
3368 	ASSERT_VOP_ELOCKED(dvp, "prelink dvp");
3369 	if (vp != NULL)
3370 		ASSERT_VOP_ELOCKED(vp, "prelink vp");
3371 	ump = VFSTOUFS(dvp->v_mount);
3372 
3373 	/*
3374 	 * Nothing to do if we have sufficient journal space.
3375 	 * If we currently hold the snapshot lock, we must avoid
3376 	 * handling other resources that could cause deadlock.
3377 	 *
3378 	 * will_direnter == 1: In case allocated a directory block in
3379 	 * an indirect block, we must prevent holes in the directory
3380 	 * created if directory entries are written out of order.  To
3381 	 * accomplish this we fsync when we extend a directory into
3382 	 * indirects.  During rename it's not safe to drop the tvp
3383 	 * lock so sync must be delayed until it is.
3384 	 *
3385 	 * This synchronous step could be removed if fsck and the
3386 	 * kernel were taught to fill in sparse directories rather
3387 	 * than panic.
3388 	 */
3389 	if (journal_space(ump, 0) || (vp != NULL && IS_SNAPSHOT(VTOI(vp)))) {
3390 		error = 0;
3391 		if (will_direnter && (vp == NULL || !IS_SNAPSHOT(VTOI(vp)))) {
3392 			if (vp != NULL)
3393 				VOP_UNLOCK(vp);
3394 			error = ffs_syncvnode(dvp, MNT_WAIT, 0);
3395 			if (vp != NULL) {
3396 				error1 = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3397 				if (error1 != 0) {
3398 					vn_lock_pair(dvp, true, vp, false);
3399 					if (error == 0)
3400 						error = ERELOOKUP;
3401 				} else if (vp->v_data == NULL) {
3402 					error = ERELOOKUP;
3403 				}
3404 			}
3405 		}
3406 		return (error);
3407 	}
3408 
3409 	stat_journal_low++;
3410 	if (vp != NULL) {
3411 		VOP_UNLOCK(dvp);
3412 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3413 		vn_lock_pair(dvp, false, vp, true);
3414 		if (dvp->v_data == NULL)
3415 			return (ERELOOKUP);
3416 	}
3417 	if (vp != NULL)
3418 		VOP_UNLOCK(vp);
3419 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3420 	VOP_UNLOCK(dvp);
3421 
3422 	/* Process vp before dvp as it may create .. removes. */
3423 	if (vp != NULL) {
3424 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3425 		if (vp->v_data == NULL) {
3426 			vn_lock_pair(dvp, false, vp, true);
3427 			return (ERELOOKUP);
3428 		}
3429 		ACQUIRE_LOCK(ump);
3430 		process_removes(vp);
3431 		process_truncates(vp);
3432 		FREE_LOCK(ump);
3433 		VOP_UNLOCK(vp);
3434 	}
3435 
3436 	vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
3437 	if (dvp->v_data == NULL) {
3438 		vn_lock_pair(dvp, true, vp, false);
3439 		return (ERELOOKUP);
3440 	}
3441 
3442 	ACQUIRE_LOCK(ump);
3443 	process_removes(dvp);
3444 	process_truncates(dvp);
3445 	VOP_UNLOCK(dvp);
3446 	softdep_speedup(ump);
3447 
3448 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3449 	if (journal_space(ump, 0) == 0) {
3450 		softdep_speedup(ump);
3451 		if (journal_space(ump, 1) == 0)
3452 			journal_suspend(ump);
3453 	}
3454 	FREE_LOCK(ump);
3455 
3456 	vn_lock_pair(dvp, false, vp, false);
3457 	return (ERELOOKUP);
3458 }
3459 
3460 static void
3461 jseg_write(ump, jseg, data)
3462 	struct ufsmount *ump;
3463 	struct jseg *jseg;
3464 	uint8_t *data;
3465 {
3466 	struct jsegrec *rec;
3467 
3468 	rec = (struct jsegrec *)data;
3469 	rec->jsr_seq = jseg->js_seq;
3470 	rec->jsr_oldest = jseg->js_oldseq;
3471 	rec->jsr_cnt = jseg->js_cnt;
3472 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3473 	rec->jsr_crc = 0;
3474 	rec->jsr_time = ump->um_fs->fs_mtime;
3475 }
3476 
3477 static inline void
3478 inoref_write(inoref, jseg, rec)
3479 	struct inoref *inoref;
3480 	struct jseg *jseg;
3481 	struct jrefrec *rec;
3482 {
3483 
3484 	inoref->if_jsegdep->jd_seg = jseg;
3485 	rec->jr_ino = inoref->if_ino;
3486 	rec->jr_parent = inoref->if_parent;
3487 	rec->jr_nlink = inoref->if_nlink;
3488 	rec->jr_mode = inoref->if_mode;
3489 	rec->jr_diroff = inoref->if_diroff;
3490 }
3491 
3492 static void
3493 jaddref_write(jaddref, jseg, data)
3494 	struct jaddref *jaddref;
3495 	struct jseg *jseg;
3496 	uint8_t *data;
3497 {
3498 	struct jrefrec *rec;
3499 
3500 	rec = (struct jrefrec *)data;
3501 	rec->jr_op = JOP_ADDREF;
3502 	inoref_write(&jaddref->ja_ref, jseg, rec);
3503 }
3504 
3505 static void
3506 jremref_write(jremref, jseg, data)
3507 	struct jremref *jremref;
3508 	struct jseg *jseg;
3509 	uint8_t *data;
3510 {
3511 	struct jrefrec *rec;
3512 
3513 	rec = (struct jrefrec *)data;
3514 	rec->jr_op = JOP_REMREF;
3515 	inoref_write(&jremref->jr_ref, jseg, rec);
3516 }
3517 
3518 static void
3519 jmvref_write(jmvref, jseg, data)
3520 	struct jmvref *jmvref;
3521 	struct jseg *jseg;
3522 	uint8_t *data;
3523 {
3524 	struct jmvrec *rec;
3525 
3526 	rec = (struct jmvrec *)data;
3527 	rec->jm_op = JOP_MVREF;
3528 	rec->jm_ino = jmvref->jm_ino;
3529 	rec->jm_parent = jmvref->jm_parent;
3530 	rec->jm_oldoff = jmvref->jm_oldoff;
3531 	rec->jm_newoff = jmvref->jm_newoff;
3532 }
3533 
3534 static void
3535 jnewblk_write(jnewblk, jseg, data)
3536 	struct jnewblk *jnewblk;
3537 	struct jseg *jseg;
3538 	uint8_t *data;
3539 {
3540 	struct jblkrec *rec;
3541 
3542 	jnewblk->jn_jsegdep->jd_seg = jseg;
3543 	rec = (struct jblkrec *)data;
3544 	rec->jb_op = JOP_NEWBLK;
3545 	rec->jb_ino = jnewblk->jn_ino;
3546 	rec->jb_blkno = jnewblk->jn_blkno;
3547 	rec->jb_lbn = jnewblk->jn_lbn;
3548 	rec->jb_frags = jnewblk->jn_frags;
3549 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3550 }
3551 
3552 static void
3553 jfreeblk_write(jfreeblk, jseg, data)
3554 	struct jfreeblk *jfreeblk;
3555 	struct jseg *jseg;
3556 	uint8_t *data;
3557 {
3558 	struct jblkrec *rec;
3559 
3560 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3561 	rec = (struct jblkrec *)data;
3562 	rec->jb_op = JOP_FREEBLK;
3563 	rec->jb_ino = jfreeblk->jf_ino;
3564 	rec->jb_blkno = jfreeblk->jf_blkno;
3565 	rec->jb_lbn = jfreeblk->jf_lbn;
3566 	rec->jb_frags = jfreeblk->jf_frags;
3567 	rec->jb_oldfrags = 0;
3568 }
3569 
3570 static void
3571 jfreefrag_write(jfreefrag, jseg, data)
3572 	struct jfreefrag *jfreefrag;
3573 	struct jseg *jseg;
3574 	uint8_t *data;
3575 {
3576 	struct jblkrec *rec;
3577 
3578 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3579 	rec = (struct jblkrec *)data;
3580 	rec->jb_op = JOP_FREEBLK;
3581 	rec->jb_ino = jfreefrag->fr_ino;
3582 	rec->jb_blkno = jfreefrag->fr_blkno;
3583 	rec->jb_lbn = jfreefrag->fr_lbn;
3584 	rec->jb_frags = jfreefrag->fr_frags;
3585 	rec->jb_oldfrags = 0;
3586 }
3587 
3588 static void
3589 jtrunc_write(jtrunc, jseg, data)
3590 	struct jtrunc *jtrunc;
3591 	struct jseg *jseg;
3592 	uint8_t *data;
3593 {
3594 	struct jtrncrec *rec;
3595 
3596 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3597 	rec = (struct jtrncrec *)data;
3598 	rec->jt_op = JOP_TRUNC;
3599 	rec->jt_ino = jtrunc->jt_ino;
3600 	rec->jt_size = jtrunc->jt_size;
3601 	rec->jt_extsize = jtrunc->jt_extsize;
3602 }
3603 
3604 static void
3605 jfsync_write(jfsync, jseg, data)
3606 	struct jfsync *jfsync;
3607 	struct jseg *jseg;
3608 	uint8_t *data;
3609 {
3610 	struct jtrncrec *rec;
3611 
3612 	rec = (struct jtrncrec *)data;
3613 	rec->jt_op = JOP_SYNC;
3614 	rec->jt_ino = jfsync->jfs_ino;
3615 	rec->jt_size = jfsync->jfs_size;
3616 	rec->jt_extsize = jfsync->jfs_extsize;
3617 }
3618 
3619 static void
3620 softdep_flushjournal(mp)
3621 	struct mount *mp;
3622 {
3623 	struct jblocks *jblocks;
3624 	struct ufsmount *ump;
3625 
3626 	if (MOUNTEDSUJ(mp) == 0)
3627 		return;
3628 	ump = VFSTOUFS(mp);
3629 	jblocks = ump->softdep_jblocks;
3630 	ACQUIRE_LOCK(ump);
3631 	while (ump->softdep_on_journal) {
3632 		jblocks->jb_needseg = 1;
3633 		softdep_process_journal(mp, NULL, MNT_WAIT);
3634 	}
3635 	FREE_LOCK(ump);
3636 }
3637 
3638 static void softdep_synchronize_completed(struct bio *);
3639 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3640 
3641 static void
3642 softdep_synchronize_completed(bp)
3643         struct bio *bp;
3644 {
3645 	struct jseg *oldest;
3646 	struct jseg *jseg;
3647 	struct ufsmount *ump;
3648 
3649 	/*
3650 	 * caller1 marks the last segment written before we issued the
3651 	 * synchronize cache.
3652 	 */
3653 	jseg = bp->bio_caller1;
3654 	if (jseg == NULL) {
3655 		g_destroy_bio(bp);
3656 		return;
3657 	}
3658 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3659 	ACQUIRE_LOCK(ump);
3660 	oldest = NULL;
3661 	/*
3662 	 * Mark all the journal entries waiting on the synchronize cache
3663 	 * as completed so they may continue on.
3664 	 */
3665 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3666 		jseg->js_state |= COMPLETE;
3667 		oldest = jseg;
3668 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3669 	}
3670 	/*
3671 	 * Restart deferred journal entry processing from the oldest
3672 	 * completed jseg.
3673 	 */
3674 	if (oldest)
3675 		complete_jsegs(oldest);
3676 
3677 	FREE_LOCK(ump);
3678 	g_destroy_bio(bp);
3679 }
3680 
3681 /*
3682  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3683  * barriers.  The journal must be written prior to any blocks that depend
3684  * on it and the journal can not be released until the blocks have be
3685  * written.  This code handles both barriers simultaneously.
3686  */
3687 static void
3688 softdep_synchronize(bp, ump, caller1)
3689 	struct bio *bp;
3690 	struct ufsmount *ump;
3691 	void *caller1;
3692 {
3693 
3694 	bp->bio_cmd = BIO_FLUSH;
3695 	bp->bio_flags |= BIO_ORDERED;
3696 	bp->bio_data = NULL;
3697 	bp->bio_offset = ump->um_cp->provider->mediasize;
3698 	bp->bio_length = 0;
3699 	bp->bio_done = softdep_synchronize_completed;
3700 	bp->bio_caller1 = caller1;
3701 	g_io_request(bp, ump->um_cp);
3702 }
3703 
3704 /*
3705  * Flush some journal records to disk.
3706  */
3707 static void
3708 softdep_process_journal(mp, needwk, flags)
3709 	struct mount *mp;
3710 	struct worklist *needwk;
3711 	int flags;
3712 {
3713 	struct jblocks *jblocks;
3714 	struct ufsmount *ump;
3715 	struct worklist *wk;
3716 	struct jseg *jseg;
3717 	struct buf *bp;
3718 	struct bio *bio;
3719 	uint8_t *data;
3720 	struct fs *fs;
3721 	int shouldflush;
3722 	int segwritten;
3723 	int jrecmin;	/* Minimum records per block. */
3724 	int jrecmax;	/* Maximum records per block. */
3725 	int size;
3726 	int cnt;
3727 	int off;
3728 	int devbsize;
3729 
3730 	if (MOUNTEDSUJ(mp) == 0)
3731 		return;
3732 	shouldflush = softdep_flushcache;
3733 	bio = NULL;
3734 	jseg = NULL;
3735 	ump = VFSTOUFS(mp);
3736 	LOCK_OWNED(ump);
3737 	fs = ump->um_fs;
3738 	jblocks = ump->softdep_jblocks;
3739 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3740 	/*
3741 	 * We write anywhere between a disk block and fs block.  The upper
3742 	 * bound is picked to prevent buffer cache fragmentation and limit
3743 	 * processing time per I/O.
3744 	 */
3745 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3746 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3747 	segwritten = 0;
3748 	for (;;) {
3749 		cnt = ump->softdep_on_journal;
3750 		/*
3751 		 * Criteria for writing a segment:
3752 		 * 1) We have a full block.
3753 		 * 2) We're called from jwait() and haven't found the
3754 		 *    journal item yet.
3755 		 * 3) Always write if needseg is set.
3756 		 * 4) If we are called from process_worklist and have
3757 		 *    not yet written anything we write a partial block
3758 		 *    to enforce a 1 second maximum latency on journal
3759 		 *    entries.
3760 		 */
3761 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3762 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3763 			break;
3764 		cnt++;
3765 		/*
3766 		 * Verify some free journal space.  softdep_prealloc() should
3767 		 * guarantee that we don't run out so this is indicative of
3768 		 * a problem with the flow control.  Try to recover
3769 		 * gracefully in any event.
3770 		 */
3771 		while (jblocks->jb_free == 0) {
3772 			if (flags != MNT_WAIT)
3773 				break;
3774 			printf("softdep: Out of journal space!\n");
3775 			softdep_speedup(ump);
3776 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3777 		}
3778 		FREE_LOCK(ump);
3779 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3780 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3781 		LIST_INIT(&jseg->js_entries);
3782 		LIST_INIT(&jseg->js_indirs);
3783 		jseg->js_state = ATTACHED;
3784 		if (shouldflush == 0)
3785 			jseg->js_state |= COMPLETE;
3786 		else if (bio == NULL)
3787 			bio = g_alloc_bio();
3788 		jseg->js_jblocks = jblocks;
3789 		bp = geteblk(fs->fs_bsize, 0);
3790 		ACQUIRE_LOCK(ump);
3791 		/*
3792 		 * If there was a race while we were allocating the block
3793 		 * and jseg the entry we care about was likely written.
3794 		 * We bail out in both the WAIT and NOWAIT case and assume
3795 		 * the caller will loop if the entry it cares about is
3796 		 * not written.
3797 		 */
3798 		cnt = ump->softdep_on_journal;
3799 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3800 			bp->b_flags |= B_INVAL | B_NOCACHE;
3801 			WORKITEM_FREE(jseg, D_JSEG);
3802 			FREE_LOCK(ump);
3803 			brelse(bp);
3804 			ACQUIRE_LOCK(ump);
3805 			break;
3806 		}
3807 		/*
3808 		 * Calculate the disk block size required for the available
3809 		 * records rounded to the min size.
3810 		 */
3811 		if (cnt == 0)
3812 			size = devbsize;
3813 		else if (cnt < jrecmax)
3814 			size = howmany(cnt, jrecmin) * devbsize;
3815 		else
3816 			size = fs->fs_bsize;
3817 		/*
3818 		 * Allocate a disk block for this journal data and account
3819 		 * for truncation of the requested size if enough contiguous
3820 		 * space was not available.
3821 		 */
3822 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3823 		bp->b_lblkno = bp->b_blkno;
3824 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3825 		bp->b_bcount = size;
3826 		bp->b_flags &= ~B_INVAL;
3827 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3828 		/*
3829 		 * Initialize our jseg with cnt records.  Assign the next
3830 		 * sequence number to it and link it in-order.
3831 		 */
3832 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3833 		jseg->js_buf = bp;
3834 		jseg->js_cnt = cnt;
3835 		jseg->js_refs = cnt + 1;	/* Self ref. */
3836 		jseg->js_size = size;
3837 		jseg->js_seq = jblocks->jb_nextseq++;
3838 		if (jblocks->jb_oldestseg == NULL)
3839 			jblocks->jb_oldestseg = jseg;
3840 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3841 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3842 		if (jblocks->jb_writeseg == NULL)
3843 			jblocks->jb_writeseg = jseg;
3844 		/*
3845 		 * Start filling in records from the pending list.
3846 		 */
3847 		data = bp->b_data;
3848 		off = 0;
3849 
3850 		/*
3851 		 * Always put a header on the first block.
3852 		 * XXX As with below, there might not be a chance to get
3853 		 * into the loop.  Ensure that something valid is written.
3854 		 */
3855 		jseg_write(ump, jseg, data);
3856 		off += JREC_SIZE;
3857 		data = bp->b_data + off;
3858 
3859 		/*
3860 		 * XXX Something is wrong here.  There's no work to do,
3861 		 * but we need to perform and I/O and allow it to complete
3862 		 * anyways.
3863 		 */
3864 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3865 			stat_emptyjblocks++;
3866 
3867 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3868 		    != NULL) {
3869 			if (cnt == 0)
3870 				break;
3871 			/* Place a segment header on every device block. */
3872 			if ((off % devbsize) == 0) {
3873 				jseg_write(ump, jseg, data);
3874 				off += JREC_SIZE;
3875 				data = bp->b_data + off;
3876 			}
3877 			if (wk == needwk)
3878 				needwk = NULL;
3879 			remove_from_journal(wk);
3880 			wk->wk_state |= INPROGRESS;
3881 			WORKLIST_INSERT(&jseg->js_entries, wk);
3882 			switch (wk->wk_type) {
3883 			case D_JADDREF:
3884 				jaddref_write(WK_JADDREF(wk), jseg, data);
3885 				break;
3886 			case D_JREMREF:
3887 				jremref_write(WK_JREMREF(wk), jseg, data);
3888 				break;
3889 			case D_JMVREF:
3890 				jmvref_write(WK_JMVREF(wk), jseg, data);
3891 				break;
3892 			case D_JNEWBLK:
3893 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3894 				break;
3895 			case D_JFREEBLK:
3896 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3897 				break;
3898 			case D_JFREEFRAG:
3899 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3900 				break;
3901 			case D_JTRUNC:
3902 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3903 				break;
3904 			case D_JFSYNC:
3905 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3906 				break;
3907 			default:
3908 				panic("process_journal: Unknown type %s",
3909 				    TYPENAME(wk->wk_type));
3910 				/* NOTREACHED */
3911 			}
3912 			off += JREC_SIZE;
3913 			data = bp->b_data + off;
3914 			cnt--;
3915 		}
3916 
3917 		/* Clear any remaining space so we don't leak kernel data */
3918 		if (size > off)
3919 			bzero(data, size - off);
3920 
3921 		/*
3922 		 * Write this one buffer and continue.
3923 		 */
3924 		segwritten = 1;
3925 		jblocks->jb_needseg = 0;
3926 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3927 		FREE_LOCK(ump);
3928 		bp->b_xflags |= BX_CVTENXIO;
3929 		pbgetvp(ump->um_devvp, bp);
3930 		/*
3931 		 * We only do the blocking wait once we find the journal
3932 		 * entry we're looking for.
3933 		 */
3934 		if (needwk == NULL && flags == MNT_WAIT)
3935 			bwrite(bp);
3936 		else
3937 			bawrite(bp);
3938 		ACQUIRE_LOCK(ump);
3939 	}
3940 	/*
3941 	 * If we wrote a segment issue a synchronize cache so the journal
3942 	 * is reflected on disk before the data is written.  Since reclaiming
3943 	 * journal space also requires writing a journal record this
3944 	 * process also enforces a barrier before reclamation.
3945 	 */
3946 	if (segwritten && shouldflush) {
3947 		softdep_synchronize(bio, ump,
3948 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3949 	} else if (bio)
3950 		g_destroy_bio(bio);
3951 	/*
3952 	 * If we've suspended the filesystem because we ran out of journal
3953 	 * space either try to sync it here to make some progress or
3954 	 * unsuspend it if we already have.
3955 	 */
3956 	if (flags == 0 && jblocks->jb_suspended) {
3957 		if (journal_unsuspend(ump))
3958 			return;
3959 		FREE_LOCK(ump);
3960 		VFS_SYNC(mp, MNT_NOWAIT);
3961 		ffs_sbupdate(ump, MNT_WAIT, 0);
3962 		ACQUIRE_LOCK(ump);
3963 	}
3964 }
3965 
3966 /*
3967  * Complete a jseg, allowing all dependencies awaiting journal writes
3968  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3969  * structures so that the journal segment can be freed to reclaim space.
3970  */
3971 static void
3972 complete_jseg(jseg)
3973 	struct jseg *jseg;
3974 {
3975 	struct worklist *wk;
3976 	struct jmvref *jmvref;
3977 #ifdef INVARIANTS
3978 	int i = 0;
3979 #endif
3980 
3981 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3982 		WORKLIST_REMOVE(wk);
3983 		wk->wk_state &= ~INPROGRESS;
3984 		wk->wk_state |= COMPLETE;
3985 		KASSERT(i++ < jseg->js_cnt,
3986 		    ("handle_written_jseg: overflow %d >= %d",
3987 		    i - 1, jseg->js_cnt));
3988 		switch (wk->wk_type) {
3989 		case D_JADDREF:
3990 			handle_written_jaddref(WK_JADDREF(wk));
3991 			break;
3992 		case D_JREMREF:
3993 			handle_written_jremref(WK_JREMREF(wk));
3994 			break;
3995 		case D_JMVREF:
3996 			rele_jseg(jseg);	/* No jsegdep. */
3997 			jmvref = WK_JMVREF(wk);
3998 			LIST_REMOVE(jmvref, jm_deps);
3999 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
4000 				free_pagedep(jmvref->jm_pagedep);
4001 			WORKITEM_FREE(jmvref, D_JMVREF);
4002 			break;
4003 		case D_JNEWBLK:
4004 			handle_written_jnewblk(WK_JNEWBLK(wk));
4005 			break;
4006 		case D_JFREEBLK:
4007 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
4008 			break;
4009 		case D_JTRUNC:
4010 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
4011 			break;
4012 		case D_JFSYNC:
4013 			rele_jseg(jseg);	/* No jsegdep. */
4014 			WORKITEM_FREE(wk, D_JFSYNC);
4015 			break;
4016 		case D_JFREEFRAG:
4017 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
4018 			break;
4019 		default:
4020 			panic("handle_written_jseg: Unknown type %s",
4021 			    TYPENAME(wk->wk_type));
4022 			/* NOTREACHED */
4023 		}
4024 	}
4025 	/* Release the self reference so the structure may be freed. */
4026 	rele_jseg(jseg);
4027 }
4028 
4029 /*
4030  * Determine which jsegs are ready for completion processing.  Waits for
4031  * synchronize cache to complete as well as forcing in-order completion
4032  * of journal entries.
4033  */
4034 static void
4035 complete_jsegs(jseg)
4036 	struct jseg *jseg;
4037 {
4038 	struct jblocks *jblocks;
4039 	struct jseg *jsegn;
4040 
4041 	jblocks = jseg->js_jblocks;
4042 	/*
4043 	 * Don't allow out of order completions.  If this isn't the first
4044 	 * block wait for it to write before we're done.
4045 	 */
4046 	if (jseg != jblocks->jb_writeseg)
4047 		return;
4048 	/* Iterate through available jsegs processing their entries. */
4049 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
4050 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
4051 		jsegn = TAILQ_NEXT(jseg, js_next);
4052 		complete_jseg(jseg);
4053 		jseg = jsegn;
4054 	}
4055 	jblocks->jb_writeseg = jseg;
4056 	/*
4057 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
4058 	 */
4059 	free_jsegs(jblocks);
4060 }
4061 
4062 /*
4063  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
4064  * the final completions.
4065  */
4066 static void
4067 handle_written_jseg(jseg, bp)
4068 	struct jseg *jseg;
4069 	struct buf *bp;
4070 {
4071 
4072 	if (jseg->js_refs == 0)
4073 		panic("handle_written_jseg: No self-reference on %p", jseg);
4074 	jseg->js_state |= DEPCOMPLETE;
4075 	/*
4076 	 * We'll never need this buffer again, set flags so it will be
4077 	 * discarded.
4078 	 */
4079 	bp->b_flags |= B_INVAL | B_NOCACHE;
4080 	pbrelvp(bp);
4081 	complete_jsegs(jseg);
4082 }
4083 
4084 static inline struct jsegdep *
4085 inoref_jseg(inoref)
4086 	struct inoref *inoref;
4087 {
4088 	struct jsegdep *jsegdep;
4089 
4090 	jsegdep = inoref->if_jsegdep;
4091 	inoref->if_jsegdep = NULL;
4092 
4093 	return (jsegdep);
4094 }
4095 
4096 /*
4097  * Called once a jremref has made it to stable store.  The jremref is marked
4098  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
4099  * for the jremref to complete will be awoken by free_jremref.
4100  */
4101 static void
4102 handle_written_jremref(jremref)
4103 	struct jremref *jremref;
4104 {
4105 	struct inodedep *inodedep;
4106 	struct jsegdep *jsegdep;
4107 	struct dirrem *dirrem;
4108 
4109 	/* Grab the jsegdep. */
4110 	jsegdep = inoref_jseg(&jremref->jr_ref);
4111 	/*
4112 	 * Remove us from the inoref list.
4113 	 */
4114 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
4115 	    0, &inodedep) == 0)
4116 		panic("handle_written_jremref: Lost inodedep");
4117 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
4118 	/*
4119 	 * Complete the dirrem.
4120 	 */
4121 	dirrem = jremref->jr_dirrem;
4122 	jremref->jr_dirrem = NULL;
4123 	LIST_REMOVE(jremref, jr_deps);
4124 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
4125 	jwork_insert(&dirrem->dm_jwork, jsegdep);
4126 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
4127 	    (dirrem->dm_state & COMPLETE) != 0)
4128 		add_to_worklist(&dirrem->dm_list, 0);
4129 	free_jremref(jremref);
4130 }
4131 
4132 /*
4133  * Called once a jaddref has made it to stable store.  The dependency is
4134  * marked complete and any dependent structures are added to the inode
4135  * bufwait list to be completed as soon as it is written.  If a bitmap write
4136  * depends on this entry we move the inode into the inodedephd of the
4137  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
4138  */
4139 static void
4140 handle_written_jaddref(jaddref)
4141 	struct jaddref *jaddref;
4142 {
4143 	struct jsegdep *jsegdep;
4144 	struct inodedep *inodedep;
4145 	struct diradd *diradd;
4146 	struct mkdir *mkdir;
4147 
4148 	/* Grab the jsegdep. */
4149 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4150 	mkdir = NULL;
4151 	diradd = NULL;
4152 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4153 	    0, &inodedep) == 0)
4154 		panic("handle_written_jaddref: Lost inodedep.");
4155 	if (jaddref->ja_diradd == NULL)
4156 		panic("handle_written_jaddref: No dependency");
4157 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
4158 		diradd = jaddref->ja_diradd;
4159 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
4160 	} else if (jaddref->ja_state & MKDIR_PARENT) {
4161 		mkdir = jaddref->ja_mkdir;
4162 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
4163 	} else if (jaddref->ja_state & MKDIR_BODY)
4164 		mkdir = jaddref->ja_mkdir;
4165 	else
4166 		panic("handle_written_jaddref: Unknown dependency %p",
4167 		    jaddref->ja_diradd);
4168 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
4169 	/*
4170 	 * Remove us from the inode list.
4171 	 */
4172 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
4173 	/*
4174 	 * The mkdir may be waiting on the jaddref to clear before freeing.
4175 	 */
4176 	if (mkdir) {
4177 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
4178 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
4179 		    TYPENAME(mkdir->md_list.wk_type)));
4180 		mkdir->md_jaddref = NULL;
4181 		diradd = mkdir->md_diradd;
4182 		mkdir->md_state |= DEPCOMPLETE;
4183 		complete_mkdir(mkdir);
4184 	}
4185 	jwork_insert(&diradd->da_jwork, jsegdep);
4186 	if (jaddref->ja_state & NEWBLOCK) {
4187 		inodedep->id_state |= ONDEPLIST;
4188 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
4189 		    inodedep, id_deps);
4190 	}
4191 	free_jaddref(jaddref);
4192 }
4193 
4194 /*
4195  * Called once a jnewblk journal is written.  The allocdirect or allocindir
4196  * is placed in the bmsafemap to await notification of a written bitmap.  If
4197  * the operation was canceled we add the segdep to the appropriate
4198  * dependency to free the journal space once the canceling operation
4199  * completes.
4200  */
4201 static void
4202 handle_written_jnewblk(jnewblk)
4203 	struct jnewblk *jnewblk;
4204 {
4205 	struct bmsafemap *bmsafemap;
4206 	struct freefrag *freefrag;
4207 	struct freework *freework;
4208 	struct jsegdep *jsegdep;
4209 	struct newblk *newblk;
4210 
4211 	/* Grab the jsegdep. */
4212 	jsegdep = jnewblk->jn_jsegdep;
4213 	jnewblk->jn_jsegdep = NULL;
4214 	if (jnewblk->jn_dep == NULL)
4215 		panic("handle_written_jnewblk: No dependency for the segdep.");
4216 	switch (jnewblk->jn_dep->wk_type) {
4217 	case D_NEWBLK:
4218 	case D_ALLOCDIRECT:
4219 	case D_ALLOCINDIR:
4220 		/*
4221 		 * Add the written block to the bmsafemap so it can
4222 		 * be notified when the bitmap is on disk.
4223 		 */
4224 		newblk = WK_NEWBLK(jnewblk->jn_dep);
4225 		newblk->nb_jnewblk = NULL;
4226 		if ((newblk->nb_state & GOINGAWAY) == 0) {
4227 			bmsafemap = newblk->nb_bmsafemap;
4228 			newblk->nb_state |= ONDEPLIST;
4229 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
4230 			    nb_deps);
4231 		}
4232 		jwork_insert(&newblk->nb_jwork, jsegdep);
4233 		break;
4234 	case D_FREEFRAG:
4235 		/*
4236 		 * A newblock being removed by a freefrag when replaced by
4237 		 * frag extension.
4238 		 */
4239 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
4240 		freefrag->ff_jdep = NULL;
4241 		jwork_insert(&freefrag->ff_jwork, jsegdep);
4242 		break;
4243 	case D_FREEWORK:
4244 		/*
4245 		 * A direct block was removed by truncate.
4246 		 */
4247 		freework = WK_FREEWORK(jnewblk->jn_dep);
4248 		freework->fw_jnewblk = NULL;
4249 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
4250 		break;
4251 	default:
4252 		panic("handle_written_jnewblk: Unknown type %d.",
4253 		    jnewblk->jn_dep->wk_type);
4254 	}
4255 	jnewblk->jn_dep = NULL;
4256 	free_jnewblk(jnewblk);
4257 }
4258 
4259 /*
4260  * Cancel a jfreefrag that won't be needed, probably due to colliding with
4261  * an in-flight allocation that has not yet been committed.  Divorce us
4262  * from the freefrag and mark it DEPCOMPLETE so that it may be added
4263  * to the worklist.
4264  */
4265 static void
4266 cancel_jfreefrag(jfreefrag)
4267 	struct jfreefrag *jfreefrag;
4268 {
4269 	struct freefrag *freefrag;
4270 
4271 	if (jfreefrag->fr_jsegdep) {
4272 		free_jsegdep(jfreefrag->fr_jsegdep);
4273 		jfreefrag->fr_jsegdep = NULL;
4274 	}
4275 	freefrag = jfreefrag->fr_freefrag;
4276 	jfreefrag->fr_freefrag = NULL;
4277 	free_jfreefrag(jfreefrag);
4278 	freefrag->ff_state |= DEPCOMPLETE;
4279 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
4280 }
4281 
4282 /*
4283  * Free a jfreefrag when the parent freefrag is rendered obsolete.
4284  */
4285 static void
4286 free_jfreefrag(jfreefrag)
4287 	struct jfreefrag *jfreefrag;
4288 {
4289 
4290 	if (jfreefrag->fr_state & INPROGRESS)
4291 		WORKLIST_REMOVE(&jfreefrag->fr_list);
4292 	else if (jfreefrag->fr_state & ONWORKLIST)
4293 		remove_from_journal(&jfreefrag->fr_list);
4294 	if (jfreefrag->fr_freefrag != NULL)
4295 		panic("free_jfreefrag:  Still attached to a freefrag.");
4296 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
4297 }
4298 
4299 /*
4300  * Called when the journal write for a jfreefrag completes.  The parent
4301  * freefrag is added to the worklist if this completes its dependencies.
4302  */
4303 static void
4304 handle_written_jfreefrag(jfreefrag)
4305 	struct jfreefrag *jfreefrag;
4306 {
4307 	struct jsegdep *jsegdep;
4308 	struct freefrag *freefrag;
4309 
4310 	/* Grab the jsegdep. */
4311 	jsegdep = jfreefrag->fr_jsegdep;
4312 	jfreefrag->fr_jsegdep = NULL;
4313 	freefrag = jfreefrag->fr_freefrag;
4314 	if (freefrag == NULL)
4315 		panic("handle_written_jfreefrag: No freefrag.");
4316 	freefrag->ff_state |= DEPCOMPLETE;
4317 	freefrag->ff_jdep = NULL;
4318 	jwork_insert(&freefrag->ff_jwork, jsegdep);
4319 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
4320 		add_to_worklist(&freefrag->ff_list, 0);
4321 	jfreefrag->fr_freefrag = NULL;
4322 	free_jfreefrag(jfreefrag);
4323 }
4324 
4325 /*
4326  * Called when the journal write for a jfreeblk completes.  The jfreeblk
4327  * is removed from the freeblks list of pending journal writes and the
4328  * jsegdep is moved to the freeblks jwork to be completed when all blocks
4329  * have been reclaimed.
4330  */
4331 static void
4332 handle_written_jblkdep(jblkdep)
4333 	struct jblkdep *jblkdep;
4334 {
4335 	struct freeblks *freeblks;
4336 	struct jsegdep *jsegdep;
4337 
4338 	/* Grab the jsegdep. */
4339 	jsegdep = jblkdep->jb_jsegdep;
4340 	jblkdep->jb_jsegdep = NULL;
4341 	freeblks = jblkdep->jb_freeblks;
4342 	LIST_REMOVE(jblkdep, jb_deps);
4343 	jwork_insert(&freeblks->fb_jwork, jsegdep);
4344 	/*
4345 	 * If the freeblks is all journaled, we can add it to the worklist.
4346 	 */
4347 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4348 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4349 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4350 
4351 	free_jblkdep(jblkdep);
4352 }
4353 
4354 static struct jsegdep *
4355 newjsegdep(struct worklist *wk)
4356 {
4357 	struct jsegdep *jsegdep;
4358 
4359 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4360 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4361 	jsegdep->jd_seg = NULL;
4362 
4363 	return (jsegdep);
4364 }
4365 
4366 static struct jmvref *
4367 newjmvref(dp, ino, oldoff, newoff)
4368 	struct inode *dp;
4369 	ino_t ino;
4370 	off_t oldoff;
4371 	off_t newoff;
4372 {
4373 	struct jmvref *jmvref;
4374 
4375 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4376 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4377 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4378 	jmvref->jm_parent = dp->i_number;
4379 	jmvref->jm_ino = ino;
4380 	jmvref->jm_oldoff = oldoff;
4381 	jmvref->jm_newoff = newoff;
4382 
4383 	return (jmvref);
4384 }
4385 
4386 /*
4387  * Allocate a new jremref that tracks the removal of ip from dp with the
4388  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4389  * DEPCOMPLETE as we have all the information required for the journal write
4390  * and the directory has already been removed from the buffer.  The caller
4391  * is responsible for linking the jremref into the pagedep and adding it
4392  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4393  * a DOTDOT addition so handle_workitem_remove() can properly assign
4394  * the jsegdep when we're done.
4395  */
4396 static struct jremref *
4397 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4398     off_t diroff, nlink_t nlink)
4399 {
4400 	struct jremref *jremref;
4401 
4402 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4403 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4404 	jremref->jr_state = ATTACHED;
4405 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4406 	   nlink, ip->i_mode);
4407 	jremref->jr_dirrem = dirrem;
4408 
4409 	return (jremref);
4410 }
4411 
4412 static inline void
4413 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4414     nlink_t nlink, uint16_t mode)
4415 {
4416 
4417 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4418 	inoref->if_diroff = diroff;
4419 	inoref->if_ino = ino;
4420 	inoref->if_parent = parent;
4421 	inoref->if_nlink = nlink;
4422 	inoref->if_mode = mode;
4423 }
4424 
4425 /*
4426  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4427  * directory offset may not be known until later.  The caller is responsible
4428  * adding the entry to the journal when this information is available.  nlink
4429  * should be the link count prior to the addition and mode is only required
4430  * to have the correct FMT.
4431  */
4432 static struct jaddref *
4433 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4434     uint16_t mode)
4435 {
4436 	struct jaddref *jaddref;
4437 
4438 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4439 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4440 	jaddref->ja_state = ATTACHED;
4441 	jaddref->ja_mkdir = NULL;
4442 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4443 
4444 	return (jaddref);
4445 }
4446 
4447 /*
4448  * Create a new free dependency for a freework.  The caller is responsible
4449  * for adjusting the reference count when it has the lock held.  The freedep
4450  * will track an outstanding bitmap write that will ultimately clear the
4451  * freework to continue.
4452  */
4453 static struct freedep *
4454 newfreedep(struct freework *freework)
4455 {
4456 	struct freedep *freedep;
4457 
4458 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4459 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4460 	freedep->fd_freework = freework;
4461 
4462 	return (freedep);
4463 }
4464 
4465 /*
4466  * Free a freedep structure once the buffer it is linked to is written.  If
4467  * this is the last reference to the freework schedule it for completion.
4468  */
4469 static void
4470 free_freedep(freedep)
4471 	struct freedep *freedep;
4472 {
4473 	struct freework *freework;
4474 
4475 	freework = freedep->fd_freework;
4476 	freework->fw_freeblks->fb_cgwait--;
4477 	if (--freework->fw_ref == 0)
4478 		freework_enqueue(freework);
4479 	WORKITEM_FREE(freedep, D_FREEDEP);
4480 }
4481 
4482 /*
4483  * Allocate a new freework structure that may be a level in an indirect
4484  * when parent is not NULL or a top level block when it is.  The top level
4485  * freework structures are allocated without the per-filesystem lock held
4486  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4487  */
4488 static struct freework *
4489 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4490 	struct ufsmount *ump;
4491 	struct freeblks *freeblks;
4492 	struct freework *parent;
4493 	ufs_lbn_t lbn;
4494 	ufs2_daddr_t nb;
4495 	int frags;
4496 	int off;
4497 	int journal;
4498 {
4499 	struct freework *freework;
4500 
4501 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4502 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4503 	freework->fw_state = ATTACHED;
4504 	freework->fw_jnewblk = NULL;
4505 	freework->fw_freeblks = freeblks;
4506 	freework->fw_parent = parent;
4507 	freework->fw_lbn = lbn;
4508 	freework->fw_blkno = nb;
4509 	freework->fw_frags = frags;
4510 	freework->fw_indir = NULL;
4511 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4512 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4513 	freework->fw_start = freework->fw_off = off;
4514 	if (journal)
4515 		newjfreeblk(freeblks, lbn, nb, frags);
4516 	if (parent == NULL) {
4517 		ACQUIRE_LOCK(ump);
4518 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4519 		freeblks->fb_ref++;
4520 		FREE_LOCK(ump);
4521 	}
4522 
4523 	return (freework);
4524 }
4525 
4526 /*
4527  * Eliminate a jfreeblk for a block that does not need journaling.
4528  */
4529 static void
4530 cancel_jfreeblk(freeblks, blkno)
4531 	struct freeblks *freeblks;
4532 	ufs2_daddr_t blkno;
4533 {
4534 	struct jfreeblk *jfreeblk;
4535 	struct jblkdep *jblkdep;
4536 
4537 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4538 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4539 			continue;
4540 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4541 		if (jfreeblk->jf_blkno == blkno)
4542 			break;
4543 	}
4544 	if (jblkdep == NULL)
4545 		return;
4546 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4547 	free_jsegdep(jblkdep->jb_jsegdep);
4548 	LIST_REMOVE(jblkdep, jb_deps);
4549 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4550 }
4551 
4552 /*
4553  * Allocate a new jfreeblk to journal top level block pointer when truncating
4554  * a file.  The caller must add this to the worklist when the per-filesystem
4555  * lock is held.
4556  */
4557 static struct jfreeblk *
4558 newjfreeblk(freeblks, lbn, blkno, frags)
4559 	struct freeblks *freeblks;
4560 	ufs_lbn_t lbn;
4561 	ufs2_daddr_t blkno;
4562 	int frags;
4563 {
4564 	struct jfreeblk *jfreeblk;
4565 
4566 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4567 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4568 	    freeblks->fb_list.wk_mp);
4569 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4570 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4571 	jfreeblk->jf_ino = freeblks->fb_inum;
4572 	jfreeblk->jf_lbn = lbn;
4573 	jfreeblk->jf_blkno = blkno;
4574 	jfreeblk->jf_frags = frags;
4575 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4576 
4577 	return (jfreeblk);
4578 }
4579 
4580 /*
4581  * The journal is only prepared to handle full-size block numbers, so we
4582  * have to adjust the record to reflect the change to a full-size block.
4583  * For example, suppose we have a block made up of fragments 8-15 and
4584  * want to free its last two fragments. We are given a request that says:
4585  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4586  * where frags are the number of fragments to free and oldfrags are the
4587  * number of fragments to keep. To block align it, we have to change it to
4588  * have a valid full-size blkno, so it becomes:
4589  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4590  */
4591 static void
4592 adjust_newfreework(freeblks, frag_offset)
4593 	struct freeblks *freeblks;
4594 	int frag_offset;
4595 {
4596 	struct jfreeblk *jfreeblk;
4597 
4598 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4599 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4600 	    ("adjust_newfreework: Missing freeblks dependency"));
4601 
4602 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4603 	jfreeblk->jf_blkno -= frag_offset;
4604 	jfreeblk->jf_frags += frag_offset;
4605 }
4606 
4607 /*
4608  * Allocate a new jtrunc to track a partial truncation.
4609  */
4610 static struct jtrunc *
4611 newjtrunc(freeblks, size, extsize)
4612 	struct freeblks *freeblks;
4613 	off_t size;
4614 	int extsize;
4615 {
4616 	struct jtrunc *jtrunc;
4617 
4618 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4619 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4620 	    freeblks->fb_list.wk_mp);
4621 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4622 	jtrunc->jt_dep.jb_freeblks = freeblks;
4623 	jtrunc->jt_ino = freeblks->fb_inum;
4624 	jtrunc->jt_size = size;
4625 	jtrunc->jt_extsize = extsize;
4626 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4627 
4628 	return (jtrunc);
4629 }
4630 
4631 /*
4632  * If we're canceling a new bitmap we have to search for another ref
4633  * to move into the bmsafemap dep.  This might be better expressed
4634  * with another structure.
4635  */
4636 static void
4637 move_newblock_dep(jaddref, inodedep)
4638 	struct jaddref *jaddref;
4639 	struct inodedep *inodedep;
4640 {
4641 	struct inoref *inoref;
4642 	struct jaddref *jaddrefn;
4643 
4644 	jaddrefn = NULL;
4645 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4646 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4647 		if ((jaddref->ja_state & NEWBLOCK) &&
4648 		    inoref->if_list.wk_type == D_JADDREF) {
4649 			jaddrefn = (struct jaddref *)inoref;
4650 			break;
4651 		}
4652 	}
4653 	if (jaddrefn == NULL)
4654 		return;
4655 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4656 	jaddrefn->ja_state |= jaddref->ja_state &
4657 	    (ATTACHED | UNDONE | NEWBLOCK);
4658 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4659 	jaddref->ja_state |= ATTACHED;
4660 	LIST_REMOVE(jaddref, ja_bmdeps);
4661 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4662 	    ja_bmdeps);
4663 }
4664 
4665 /*
4666  * Cancel a jaddref either before it has been written or while it is being
4667  * written.  This happens when a link is removed before the add reaches
4668  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4669  * and inode to prevent the link count or bitmap from reaching the disk
4670  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4671  * required.
4672  *
4673  * Returns 1 if the canceled addref requires journaling of the remove and
4674  * 0 otherwise.
4675  */
4676 static int
4677 cancel_jaddref(jaddref, inodedep, wkhd)
4678 	struct jaddref *jaddref;
4679 	struct inodedep *inodedep;
4680 	struct workhead *wkhd;
4681 {
4682 	struct inoref *inoref;
4683 	struct jsegdep *jsegdep;
4684 	int needsj;
4685 
4686 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4687 	    ("cancel_jaddref: Canceling complete jaddref"));
4688 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4689 		needsj = 1;
4690 	else
4691 		needsj = 0;
4692 	if (inodedep == NULL)
4693 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4694 		    0, &inodedep) == 0)
4695 			panic("cancel_jaddref: Lost inodedep");
4696 	/*
4697 	 * We must adjust the nlink of any reference operation that follows
4698 	 * us so that it is consistent with the in-memory reference.  This
4699 	 * ensures that inode nlink rollbacks always have the correct link.
4700 	 */
4701 	if (needsj == 0) {
4702 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4703 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4704 			if (inoref->if_state & GOINGAWAY)
4705 				break;
4706 			inoref->if_nlink--;
4707 		}
4708 	}
4709 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4710 	if (jaddref->ja_state & NEWBLOCK)
4711 		move_newblock_dep(jaddref, inodedep);
4712 	wake_worklist(&jaddref->ja_list);
4713 	jaddref->ja_mkdir = NULL;
4714 	if (jaddref->ja_state & INPROGRESS) {
4715 		jaddref->ja_state &= ~INPROGRESS;
4716 		WORKLIST_REMOVE(&jaddref->ja_list);
4717 		jwork_insert(wkhd, jsegdep);
4718 	} else {
4719 		free_jsegdep(jsegdep);
4720 		if (jaddref->ja_state & DEPCOMPLETE)
4721 			remove_from_journal(&jaddref->ja_list);
4722 	}
4723 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4724 	/*
4725 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4726 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4727 	 * no longer need this addref attached to the inoreflst and it
4728 	 * will incorrectly adjust nlink if we leave it.
4729 	 */
4730 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4731 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4732 		    if_deps);
4733 		jaddref->ja_state |= COMPLETE;
4734 		free_jaddref(jaddref);
4735 		return (needsj);
4736 	}
4737 	/*
4738 	 * Leave the head of the list for jsegdeps for fast merging.
4739 	 */
4740 	if (LIST_FIRST(wkhd) != NULL) {
4741 		jaddref->ja_state |= ONWORKLIST;
4742 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4743 	} else
4744 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4745 
4746 	return (needsj);
4747 }
4748 
4749 /*
4750  * Attempt to free a jaddref structure when some work completes.  This
4751  * should only succeed once the entry is written and all dependencies have
4752  * been notified.
4753  */
4754 static void
4755 free_jaddref(jaddref)
4756 	struct jaddref *jaddref;
4757 {
4758 
4759 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4760 		return;
4761 	if (jaddref->ja_ref.if_jsegdep)
4762 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4763 		    jaddref, jaddref->ja_state);
4764 	if (jaddref->ja_state & NEWBLOCK)
4765 		LIST_REMOVE(jaddref, ja_bmdeps);
4766 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4767 		panic("free_jaddref: Bad state %p(0x%X)",
4768 		    jaddref, jaddref->ja_state);
4769 	if (jaddref->ja_mkdir != NULL)
4770 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4771 	WORKITEM_FREE(jaddref, D_JADDREF);
4772 }
4773 
4774 /*
4775  * Free a jremref structure once it has been written or discarded.
4776  */
4777 static void
4778 free_jremref(jremref)
4779 	struct jremref *jremref;
4780 {
4781 
4782 	if (jremref->jr_ref.if_jsegdep)
4783 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4784 	if (jremref->jr_state & INPROGRESS)
4785 		panic("free_jremref: IO still pending");
4786 	WORKITEM_FREE(jremref, D_JREMREF);
4787 }
4788 
4789 /*
4790  * Free a jnewblk structure.
4791  */
4792 static void
4793 free_jnewblk(jnewblk)
4794 	struct jnewblk *jnewblk;
4795 {
4796 
4797 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4798 		return;
4799 	LIST_REMOVE(jnewblk, jn_deps);
4800 	if (jnewblk->jn_dep != NULL)
4801 		panic("free_jnewblk: Dependency still attached.");
4802 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4803 }
4804 
4805 /*
4806  * Cancel a jnewblk which has been been made redundant by frag extension.
4807  */
4808 static void
4809 cancel_jnewblk(jnewblk, wkhd)
4810 	struct jnewblk *jnewblk;
4811 	struct workhead *wkhd;
4812 {
4813 	struct jsegdep *jsegdep;
4814 
4815 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4816 	jsegdep = jnewblk->jn_jsegdep;
4817 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4818 		panic("cancel_jnewblk: Invalid state");
4819 	jnewblk->jn_jsegdep  = NULL;
4820 	jnewblk->jn_dep = NULL;
4821 	jnewblk->jn_state |= GOINGAWAY;
4822 	if (jnewblk->jn_state & INPROGRESS) {
4823 		jnewblk->jn_state &= ~INPROGRESS;
4824 		WORKLIST_REMOVE(&jnewblk->jn_list);
4825 		jwork_insert(wkhd, jsegdep);
4826 	} else {
4827 		free_jsegdep(jsegdep);
4828 		remove_from_journal(&jnewblk->jn_list);
4829 	}
4830 	wake_worklist(&jnewblk->jn_list);
4831 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4832 }
4833 
4834 static void
4835 free_jblkdep(jblkdep)
4836 	struct jblkdep *jblkdep;
4837 {
4838 
4839 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4840 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4841 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4842 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4843 	else
4844 		panic("free_jblkdep: Unexpected type %s",
4845 		    TYPENAME(jblkdep->jb_list.wk_type));
4846 }
4847 
4848 /*
4849  * Free a single jseg once it is no longer referenced in memory or on
4850  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4851  * to disappear.
4852  */
4853 static void
4854 free_jseg(jseg, jblocks)
4855 	struct jseg *jseg;
4856 	struct jblocks *jblocks;
4857 {
4858 	struct freework *freework;
4859 
4860 	/*
4861 	 * Free freework structures that were lingering to indicate freed
4862 	 * indirect blocks that forced journal write ordering on reallocate.
4863 	 */
4864 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4865 		indirblk_remove(freework);
4866 	if (jblocks->jb_oldestseg == jseg)
4867 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4868 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4869 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4870 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4871 	    ("free_jseg: Freed jseg has valid entries."));
4872 	WORKITEM_FREE(jseg, D_JSEG);
4873 }
4874 
4875 /*
4876  * Free all jsegs that meet the criteria for being reclaimed and update
4877  * oldestseg.
4878  */
4879 static void
4880 free_jsegs(jblocks)
4881 	struct jblocks *jblocks;
4882 {
4883 	struct jseg *jseg;
4884 
4885 	/*
4886 	 * Free only those jsegs which have none allocated before them to
4887 	 * preserve the journal space ordering.
4888 	 */
4889 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4890 		/*
4891 		 * Only reclaim space when nothing depends on this journal
4892 		 * set and another set has written that it is no longer
4893 		 * valid.
4894 		 */
4895 		if (jseg->js_refs != 0) {
4896 			jblocks->jb_oldestseg = jseg;
4897 			return;
4898 		}
4899 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4900 			break;
4901 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4902 			break;
4903 		/*
4904 		 * We can free jsegs that didn't write entries when
4905 		 * oldestwrseq == js_seq.
4906 		 */
4907 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4908 		    jseg->js_cnt != 0)
4909 			break;
4910 		free_jseg(jseg, jblocks);
4911 	}
4912 	/*
4913 	 * If we exited the loop above we still must discover the
4914 	 * oldest valid segment.
4915 	 */
4916 	if (jseg)
4917 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4918 		     jseg = TAILQ_NEXT(jseg, js_next))
4919 			if (jseg->js_refs != 0)
4920 				break;
4921 	jblocks->jb_oldestseg = jseg;
4922 	/*
4923 	 * The journal has no valid records but some jsegs may still be
4924 	 * waiting on oldestwrseq to advance.  We force a small record
4925 	 * out to permit these lingering records to be reclaimed.
4926 	 */
4927 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4928 		jblocks->jb_needseg = 1;
4929 }
4930 
4931 /*
4932  * Release one reference to a jseg and free it if the count reaches 0.  This
4933  * should eventually reclaim journal space as well.
4934  */
4935 static void
4936 rele_jseg(jseg)
4937 	struct jseg *jseg;
4938 {
4939 
4940 	KASSERT(jseg->js_refs > 0,
4941 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4942 	if (--jseg->js_refs != 0)
4943 		return;
4944 	free_jsegs(jseg->js_jblocks);
4945 }
4946 
4947 /*
4948  * Release a jsegdep and decrement the jseg count.
4949  */
4950 static void
4951 free_jsegdep(jsegdep)
4952 	struct jsegdep *jsegdep;
4953 {
4954 
4955 	if (jsegdep->jd_seg)
4956 		rele_jseg(jsegdep->jd_seg);
4957 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4958 }
4959 
4960 /*
4961  * Wait for a journal item to make it to disk.  Initiate journal processing
4962  * if required.
4963  */
4964 static int
4965 jwait(wk, waitfor)
4966 	struct worklist *wk;
4967 	int waitfor;
4968 {
4969 
4970 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4971 	/*
4972 	 * Blocking journal waits cause slow synchronous behavior.  Record
4973 	 * stats on the frequency of these blocking operations.
4974 	 */
4975 	if (waitfor == MNT_WAIT) {
4976 		stat_journal_wait++;
4977 		switch (wk->wk_type) {
4978 		case D_JREMREF:
4979 		case D_JMVREF:
4980 			stat_jwait_filepage++;
4981 			break;
4982 		case D_JTRUNC:
4983 		case D_JFREEBLK:
4984 			stat_jwait_freeblks++;
4985 			break;
4986 		case D_JNEWBLK:
4987 			stat_jwait_newblk++;
4988 			break;
4989 		case D_JADDREF:
4990 			stat_jwait_inode++;
4991 			break;
4992 		default:
4993 			break;
4994 		}
4995 	}
4996 	/*
4997 	 * If IO has not started we process the journal.  We can't mark the
4998 	 * worklist item as IOWAITING because we drop the lock while
4999 	 * processing the journal and the worklist entry may be freed after
5000 	 * this point.  The caller may call back in and re-issue the request.
5001 	 */
5002 	if ((wk->wk_state & INPROGRESS) == 0) {
5003 		softdep_process_journal(wk->wk_mp, wk, waitfor);
5004 		if (waitfor != MNT_WAIT)
5005 			return (EBUSY);
5006 		return (0);
5007 	}
5008 	if (waitfor != MNT_WAIT)
5009 		return (EBUSY);
5010 	wait_worklist(wk, "jwait");
5011 	return (0);
5012 }
5013 
5014 /*
5015  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
5016  * appropriate.  This is a convenience function to reduce duplicate code
5017  * for the setup and revert functions below.
5018  */
5019 static struct inodedep *
5020 inodedep_lookup_ip(ip)
5021 	struct inode *ip;
5022 {
5023 	struct inodedep *inodedep;
5024 
5025 	KASSERT(ip->i_nlink >= ip->i_effnlink,
5026 	    ("inodedep_lookup_ip: bad delta"));
5027 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
5028 	    &inodedep);
5029 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
5030 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
5031 
5032 	return (inodedep);
5033 }
5034 
5035 /*
5036  * Called prior to creating a new inode and linking it to a directory.  The
5037  * jaddref structure must already be allocated by softdep_setup_inomapdep
5038  * and it is discovered here so we can initialize the mode and update
5039  * nlinkdelta.
5040  */
5041 void
5042 softdep_setup_create(dp, ip)
5043 	struct inode *dp;
5044 	struct inode *ip;
5045 {
5046 	struct inodedep *inodedep;
5047 	struct jaddref *jaddref;
5048 	struct vnode *dvp;
5049 
5050 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5051 	    ("softdep_setup_create called on non-softdep filesystem"));
5052 	KASSERT(ip->i_nlink == 1,
5053 	    ("softdep_setup_create: Invalid link count."));
5054 	dvp = ITOV(dp);
5055 	ACQUIRE_LOCK(ITOUMP(dp));
5056 	inodedep = inodedep_lookup_ip(ip);
5057 	if (DOINGSUJ(dvp)) {
5058 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5059 		    inoreflst);
5060 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
5061 		    ("softdep_setup_create: No addref structure present."));
5062 	}
5063 	FREE_LOCK(ITOUMP(dp));
5064 }
5065 
5066 /*
5067  * Create a jaddref structure to track the addition of a DOTDOT link when
5068  * we are reparenting an inode as part of a rename.  This jaddref will be
5069  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
5070  * non-journaling softdep.
5071  */
5072 void
5073 softdep_setup_dotdot_link(dp, ip)
5074 	struct inode *dp;
5075 	struct inode *ip;
5076 {
5077 	struct inodedep *inodedep;
5078 	struct jaddref *jaddref;
5079 	struct vnode *dvp;
5080 
5081 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5082 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
5083 	dvp = ITOV(dp);
5084 	jaddref = NULL;
5085 	/*
5086 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
5087 	 * is used as a normal link would be.
5088 	 */
5089 	if (DOINGSUJ(dvp))
5090 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5091 		    dp->i_effnlink - 1, dp->i_mode);
5092 	ACQUIRE_LOCK(ITOUMP(dp));
5093 	inodedep = inodedep_lookup_ip(dp);
5094 	if (jaddref)
5095 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5096 		    if_deps);
5097 	FREE_LOCK(ITOUMP(dp));
5098 }
5099 
5100 /*
5101  * Create a jaddref structure to track a new link to an inode.  The directory
5102  * offset is not known until softdep_setup_directory_add or
5103  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
5104  * softdep.
5105  */
5106 void
5107 softdep_setup_link(dp, ip)
5108 	struct inode *dp;
5109 	struct inode *ip;
5110 {
5111 	struct inodedep *inodedep;
5112 	struct jaddref *jaddref;
5113 	struct vnode *dvp;
5114 
5115 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5116 	    ("softdep_setup_link called on non-softdep filesystem"));
5117 	dvp = ITOV(dp);
5118 	jaddref = NULL;
5119 	if (DOINGSUJ(dvp))
5120 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
5121 		    ip->i_mode);
5122 	ACQUIRE_LOCK(ITOUMP(dp));
5123 	inodedep = inodedep_lookup_ip(ip);
5124 	if (jaddref)
5125 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5126 		    if_deps);
5127 	FREE_LOCK(ITOUMP(dp));
5128 }
5129 
5130 /*
5131  * Called to create the jaddref structures to track . and .. references as
5132  * well as lookup and further initialize the incomplete jaddref created
5133  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
5134  * nlinkdelta for non-journaling softdep.
5135  */
5136 void
5137 softdep_setup_mkdir(dp, ip)
5138 	struct inode *dp;
5139 	struct inode *ip;
5140 {
5141 	struct inodedep *inodedep;
5142 	struct jaddref *dotdotaddref;
5143 	struct jaddref *dotaddref;
5144 	struct jaddref *jaddref;
5145 	struct vnode *dvp;
5146 
5147 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5148 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
5149 	dvp = ITOV(dp);
5150 	dotaddref = dotdotaddref = NULL;
5151 	if (DOINGSUJ(dvp)) {
5152 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
5153 		    ip->i_mode);
5154 		dotaddref->ja_state |= MKDIR_BODY;
5155 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5156 		    dp->i_effnlink - 1, dp->i_mode);
5157 		dotdotaddref->ja_state |= MKDIR_PARENT;
5158 	}
5159 	ACQUIRE_LOCK(ITOUMP(dp));
5160 	inodedep = inodedep_lookup_ip(ip);
5161 	if (DOINGSUJ(dvp)) {
5162 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5163 		    inoreflst);
5164 		KASSERT(jaddref != NULL,
5165 		    ("softdep_setup_mkdir: No addref structure present."));
5166 		KASSERT(jaddref->ja_parent == dp->i_number,
5167 		    ("softdep_setup_mkdir: bad parent %ju",
5168 		    (uintmax_t)jaddref->ja_parent));
5169 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
5170 		    if_deps);
5171 	}
5172 	inodedep = inodedep_lookup_ip(dp);
5173 	if (DOINGSUJ(dvp))
5174 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
5175 		    &dotdotaddref->ja_ref, if_deps);
5176 	FREE_LOCK(ITOUMP(dp));
5177 }
5178 
5179 /*
5180  * Called to track nlinkdelta of the inode and parent directories prior to
5181  * unlinking a directory.
5182  */
5183 void
5184 softdep_setup_rmdir(dp, ip)
5185 	struct inode *dp;
5186 	struct inode *ip;
5187 {
5188 	struct vnode *dvp;
5189 
5190 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5191 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
5192 	dvp = ITOV(dp);
5193 	ACQUIRE_LOCK(ITOUMP(dp));
5194 	(void) inodedep_lookup_ip(ip);
5195 	(void) inodedep_lookup_ip(dp);
5196 	FREE_LOCK(ITOUMP(dp));
5197 }
5198 
5199 /*
5200  * Called to track nlinkdelta of the inode and parent directories prior to
5201  * unlink.
5202  */
5203 void
5204 softdep_setup_unlink(dp, ip)
5205 	struct inode *dp;
5206 	struct inode *ip;
5207 {
5208 	struct vnode *dvp;
5209 
5210 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5211 	    ("softdep_setup_unlink called on non-softdep filesystem"));
5212 	dvp = ITOV(dp);
5213 	ACQUIRE_LOCK(ITOUMP(dp));
5214 	(void) inodedep_lookup_ip(ip);
5215 	(void) inodedep_lookup_ip(dp);
5216 	FREE_LOCK(ITOUMP(dp));
5217 }
5218 
5219 /*
5220  * Called to release the journal structures created by a failed non-directory
5221  * creation.  Adjusts nlinkdelta for non-journaling softdep.
5222  */
5223 void
5224 softdep_revert_create(dp, ip)
5225 	struct inode *dp;
5226 	struct inode *ip;
5227 {
5228 	struct inodedep *inodedep;
5229 	struct jaddref *jaddref;
5230 	struct vnode *dvp;
5231 
5232 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
5233 	    ("softdep_revert_create called on non-softdep filesystem"));
5234 	dvp = ITOV(dp);
5235 	ACQUIRE_LOCK(ITOUMP(dp));
5236 	inodedep = inodedep_lookup_ip(ip);
5237 	if (DOINGSUJ(dvp)) {
5238 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5239 		    inoreflst);
5240 		KASSERT(jaddref->ja_parent == dp->i_number,
5241 		    ("softdep_revert_create: addref parent mismatch"));
5242 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5243 	}
5244 	FREE_LOCK(ITOUMP(dp));
5245 }
5246 
5247 /*
5248  * Called to release the journal structures created by a failed link
5249  * addition.  Adjusts nlinkdelta for non-journaling softdep.
5250  */
5251 void
5252 softdep_revert_link(dp, ip)
5253 	struct inode *dp;
5254 	struct inode *ip;
5255 {
5256 	struct inodedep *inodedep;
5257 	struct jaddref *jaddref;
5258 	struct vnode *dvp;
5259 
5260 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5261 	    ("softdep_revert_link called on non-softdep filesystem"));
5262 	dvp = ITOV(dp);
5263 	ACQUIRE_LOCK(ITOUMP(dp));
5264 	inodedep = inodedep_lookup_ip(ip);
5265 	if (DOINGSUJ(dvp)) {
5266 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5267 		    inoreflst);
5268 		KASSERT(jaddref->ja_parent == dp->i_number,
5269 		    ("softdep_revert_link: addref parent mismatch"));
5270 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5271 	}
5272 	FREE_LOCK(ITOUMP(dp));
5273 }
5274 
5275 /*
5276  * Called to release the journal structures created by a failed mkdir
5277  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
5278  */
5279 void
5280 softdep_revert_mkdir(dp, ip)
5281 	struct inode *dp;
5282 	struct inode *ip;
5283 {
5284 	struct inodedep *inodedep;
5285 	struct jaddref *jaddref;
5286 	struct jaddref *dotaddref;
5287 	struct vnode *dvp;
5288 
5289 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5290 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
5291 	dvp = ITOV(dp);
5292 
5293 	ACQUIRE_LOCK(ITOUMP(dp));
5294 	inodedep = inodedep_lookup_ip(dp);
5295 	if (DOINGSUJ(dvp)) {
5296 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5297 		    inoreflst);
5298 		KASSERT(jaddref->ja_parent == ip->i_number,
5299 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
5300 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5301 	}
5302 	inodedep = inodedep_lookup_ip(ip);
5303 	if (DOINGSUJ(dvp)) {
5304 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5305 		    inoreflst);
5306 		KASSERT(jaddref->ja_parent == dp->i_number,
5307 		    ("softdep_revert_mkdir: addref parent mismatch"));
5308 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
5309 		    inoreflst, if_deps);
5310 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5311 		KASSERT(dotaddref->ja_parent == ip->i_number,
5312 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
5313 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
5314 	}
5315 	FREE_LOCK(ITOUMP(dp));
5316 }
5317 
5318 /*
5319  * Called to correct nlinkdelta after a failed rmdir.
5320  */
5321 void
5322 softdep_revert_rmdir(dp, ip)
5323 	struct inode *dp;
5324 	struct inode *ip;
5325 {
5326 
5327 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5328 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
5329 	ACQUIRE_LOCK(ITOUMP(dp));
5330 	(void) inodedep_lookup_ip(ip);
5331 	(void) inodedep_lookup_ip(dp);
5332 	FREE_LOCK(ITOUMP(dp));
5333 }
5334 
5335 /*
5336  * Protecting the freemaps (or bitmaps).
5337  *
5338  * To eliminate the need to execute fsck before mounting a filesystem
5339  * after a power failure, one must (conservatively) guarantee that the
5340  * on-disk copy of the bitmaps never indicate that a live inode or block is
5341  * free.  So, when a block or inode is allocated, the bitmap should be
5342  * updated (on disk) before any new pointers.  When a block or inode is
5343  * freed, the bitmap should not be updated until all pointers have been
5344  * reset.  The latter dependency is handled by the delayed de-allocation
5345  * approach described below for block and inode de-allocation.  The former
5346  * dependency is handled by calling the following procedure when a block or
5347  * inode is allocated. When an inode is allocated an "inodedep" is created
5348  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5349  * Each "inodedep" is also inserted into the hash indexing structure so
5350  * that any additional link additions can be made dependent on the inode
5351  * allocation.
5352  *
5353  * The ufs filesystem maintains a number of free block counts (e.g., per
5354  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5355  * in addition to the bitmaps.  These counts are used to improve efficiency
5356  * during allocation and therefore must be consistent with the bitmaps.
5357  * There is no convenient way to guarantee post-crash consistency of these
5358  * counts with simple update ordering, for two main reasons: (1) The counts
5359  * and bitmaps for a single cylinder group block are not in the same disk
5360  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5361  * be written and the other not.  (2) Some of the counts are located in the
5362  * superblock rather than the cylinder group block. So, we focus our soft
5363  * updates implementation on protecting the bitmaps. When mounting a
5364  * filesystem, we recompute the auxiliary counts from the bitmaps.
5365  */
5366 
5367 /*
5368  * Called just after updating the cylinder group block to allocate an inode.
5369  */
5370 void
5371 softdep_setup_inomapdep(bp, ip, newinum, mode)
5372 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5373 	struct inode *ip;	/* inode related to allocation */
5374 	ino_t newinum;		/* new inode number being allocated */
5375 	int mode;
5376 {
5377 	struct inodedep *inodedep;
5378 	struct bmsafemap *bmsafemap;
5379 	struct jaddref *jaddref;
5380 	struct mount *mp;
5381 	struct fs *fs;
5382 
5383 	mp = ITOVFS(ip);
5384 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5385 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5386 	fs = VFSTOUFS(mp)->um_fs;
5387 	jaddref = NULL;
5388 
5389 	/*
5390 	 * Allocate the journal reference add structure so that the bitmap
5391 	 * can be dependent on it.
5392 	 */
5393 	if (MOUNTEDSUJ(mp)) {
5394 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5395 		jaddref->ja_state |= NEWBLOCK;
5396 	}
5397 
5398 	/*
5399 	 * Create a dependency for the newly allocated inode.
5400 	 * Panic if it already exists as something is seriously wrong.
5401 	 * Otherwise add it to the dependency list for the buffer holding
5402 	 * the cylinder group map from which it was allocated.
5403 	 *
5404 	 * We have to preallocate a bmsafemap entry in case it is needed
5405 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5406 	 * have to finish initializing it before we can FREE_LOCK().
5407 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5408 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5409 	 * creating the inodedep as it can be freed during the time
5410 	 * that we FREE_LOCK() while allocating the inodedep. We must
5411 	 * call workitem_alloc() before entering the locked section as
5412 	 * it also acquires the lock and we must avoid trying doing so
5413 	 * recursively.
5414 	 */
5415 	bmsafemap = malloc(sizeof(struct bmsafemap),
5416 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5417 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5418 	ACQUIRE_LOCK(ITOUMP(ip));
5419 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5420 		panic("softdep_setup_inomapdep: dependency %p for new"
5421 		    "inode already exists", inodedep);
5422 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5423 	if (jaddref) {
5424 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5425 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5426 		    if_deps);
5427 	} else {
5428 		inodedep->id_state |= ONDEPLIST;
5429 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5430 	}
5431 	inodedep->id_bmsafemap = bmsafemap;
5432 	inodedep->id_state &= ~DEPCOMPLETE;
5433 	FREE_LOCK(ITOUMP(ip));
5434 }
5435 
5436 /*
5437  * Called just after updating the cylinder group block to
5438  * allocate block or fragment.
5439  */
5440 void
5441 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5442 	struct buf *bp;		/* buffer for cylgroup block with block map */
5443 	struct mount *mp;	/* filesystem doing allocation */
5444 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5445 	int frags;		/* Number of fragments. */
5446 	int oldfrags;		/* Previous number of fragments for extend. */
5447 {
5448 	struct newblk *newblk;
5449 	struct bmsafemap *bmsafemap;
5450 	struct jnewblk *jnewblk;
5451 	struct ufsmount *ump;
5452 	struct fs *fs;
5453 
5454 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5455 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5456 	ump = VFSTOUFS(mp);
5457 	fs = ump->um_fs;
5458 	jnewblk = NULL;
5459 	/*
5460 	 * Create a dependency for the newly allocated block.
5461 	 * Add it to the dependency list for the buffer holding
5462 	 * the cylinder group map from which it was allocated.
5463 	 */
5464 	if (MOUNTEDSUJ(mp)) {
5465 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5466 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5467 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5468 		jnewblk->jn_state = ATTACHED;
5469 		jnewblk->jn_blkno = newblkno;
5470 		jnewblk->jn_frags = frags;
5471 		jnewblk->jn_oldfrags = oldfrags;
5472 #ifdef INVARIANTS
5473 		{
5474 			struct cg *cgp;
5475 			uint8_t *blksfree;
5476 			long bno;
5477 			int i;
5478 
5479 			cgp = (struct cg *)bp->b_data;
5480 			blksfree = cg_blksfree(cgp);
5481 			bno = dtogd(fs, jnewblk->jn_blkno);
5482 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5483 			    i++) {
5484 				if (isset(blksfree, bno + i))
5485 					panic("softdep_setup_blkmapdep: "
5486 					    "free fragment %d from %d-%d "
5487 					    "state 0x%X dep %p", i,
5488 					    jnewblk->jn_oldfrags,
5489 					    jnewblk->jn_frags,
5490 					    jnewblk->jn_state,
5491 					    jnewblk->jn_dep);
5492 			}
5493 		}
5494 #endif
5495 	}
5496 
5497 	CTR3(KTR_SUJ,
5498 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5499 	    newblkno, frags, oldfrags);
5500 	ACQUIRE_LOCK(ump);
5501 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5502 		panic("softdep_setup_blkmapdep: found block");
5503 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5504 	    dtog(fs, newblkno), NULL);
5505 	if (jnewblk) {
5506 		jnewblk->jn_dep = (struct worklist *)newblk;
5507 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5508 	} else {
5509 		newblk->nb_state |= ONDEPLIST;
5510 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5511 	}
5512 	newblk->nb_bmsafemap = bmsafemap;
5513 	newblk->nb_jnewblk = jnewblk;
5514 	FREE_LOCK(ump);
5515 }
5516 
5517 #define	BMSAFEMAP_HASH(ump, cg) \
5518       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5519 
5520 static int
5521 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5522 	struct bmsafemap_hashhead *bmsafemaphd;
5523 	int cg;
5524 	struct bmsafemap **bmsafemapp;
5525 {
5526 	struct bmsafemap *bmsafemap;
5527 
5528 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5529 		if (bmsafemap->sm_cg == cg)
5530 			break;
5531 	if (bmsafemap) {
5532 		*bmsafemapp = bmsafemap;
5533 		return (1);
5534 	}
5535 	*bmsafemapp = NULL;
5536 
5537 	return (0);
5538 }
5539 
5540 /*
5541  * Find the bmsafemap associated with a cylinder group buffer.
5542  * If none exists, create one. The buffer must be locked when
5543  * this routine is called and this routine must be called with
5544  * the softdep lock held. To avoid giving up the lock while
5545  * allocating a new bmsafemap, a preallocated bmsafemap may be
5546  * provided. If it is provided but not needed, it is freed.
5547  */
5548 static struct bmsafemap *
5549 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5550 	struct mount *mp;
5551 	struct buf *bp;
5552 	int cg;
5553 	struct bmsafemap *newbmsafemap;
5554 {
5555 	struct bmsafemap_hashhead *bmsafemaphd;
5556 	struct bmsafemap *bmsafemap, *collision;
5557 	struct worklist *wk;
5558 	struct ufsmount *ump;
5559 
5560 	ump = VFSTOUFS(mp);
5561 	LOCK_OWNED(ump);
5562 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5563 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5564 		if (wk->wk_type == D_BMSAFEMAP) {
5565 			if (newbmsafemap)
5566 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5567 			return (WK_BMSAFEMAP(wk));
5568 		}
5569 	}
5570 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5571 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5572 		if (newbmsafemap)
5573 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5574 		return (bmsafemap);
5575 	}
5576 	if (newbmsafemap) {
5577 		bmsafemap = newbmsafemap;
5578 	} else {
5579 		FREE_LOCK(ump);
5580 		bmsafemap = malloc(sizeof(struct bmsafemap),
5581 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5582 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5583 		ACQUIRE_LOCK(ump);
5584 	}
5585 	bmsafemap->sm_buf = bp;
5586 	LIST_INIT(&bmsafemap->sm_inodedephd);
5587 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5588 	LIST_INIT(&bmsafemap->sm_newblkhd);
5589 	LIST_INIT(&bmsafemap->sm_newblkwr);
5590 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5591 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5592 	LIST_INIT(&bmsafemap->sm_freehd);
5593 	LIST_INIT(&bmsafemap->sm_freewr);
5594 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5595 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5596 		return (collision);
5597 	}
5598 	bmsafemap->sm_cg = cg;
5599 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5600 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5601 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5602 	return (bmsafemap);
5603 }
5604 
5605 /*
5606  * Direct block allocation dependencies.
5607  *
5608  * When a new block is allocated, the corresponding disk locations must be
5609  * initialized (with zeros or new data) before the on-disk inode points to
5610  * them.  Also, the freemap from which the block was allocated must be
5611  * updated (on disk) before the inode's pointer. These two dependencies are
5612  * independent of each other and are needed for all file blocks and indirect
5613  * blocks that are pointed to directly by the inode.  Just before the
5614  * "in-core" version of the inode is updated with a newly allocated block
5615  * number, a procedure (below) is called to setup allocation dependency
5616  * structures.  These structures are removed when the corresponding
5617  * dependencies are satisfied or when the block allocation becomes obsolete
5618  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5619  * fragment that gets upgraded).  All of these cases are handled in
5620  * procedures described later.
5621  *
5622  * When a file extension causes a fragment to be upgraded, either to a larger
5623  * fragment or to a full block, the on-disk location may change (if the
5624  * previous fragment could not simply be extended). In this case, the old
5625  * fragment must be de-allocated, but not until after the inode's pointer has
5626  * been updated. In most cases, this is handled by later procedures, which
5627  * will construct a "freefrag" structure to be added to the workitem queue
5628  * when the inode update is complete (or obsolete).  The main exception to
5629  * this is when an allocation occurs while a pending allocation dependency
5630  * (for the same block pointer) remains.  This case is handled in the main
5631  * allocation dependency setup procedure by immediately freeing the
5632  * unreferenced fragments.
5633  */
5634 void
5635 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5636 	struct inode *ip;	/* inode to which block is being added */
5637 	ufs_lbn_t off;		/* block pointer within inode */
5638 	ufs2_daddr_t newblkno;	/* disk block number being added */
5639 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5640 	long newsize;		/* size of new block */
5641 	long oldsize;		/* size of new block */
5642 	struct buf *bp;		/* bp for allocated block */
5643 {
5644 	struct allocdirect *adp, *oldadp;
5645 	struct allocdirectlst *adphead;
5646 	struct freefrag *freefrag;
5647 	struct inodedep *inodedep;
5648 	struct pagedep *pagedep;
5649 	struct jnewblk *jnewblk;
5650 	struct newblk *newblk;
5651 	struct mount *mp;
5652 	ufs_lbn_t lbn;
5653 
5654 	lbn = bp->b_lblkno;
5655 	mp = ITOVFS(ip);
5656 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5657 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5658 	if (oldblkno && oldblkno != newblkno)
5659 		/*
5660 		 * The usual case is that a smaller fragment that
5661 		 * was just allocated has been replaced with a bigger
5662 		 * fragment or a full-size block. If it is marked as
5663 		 * B_DELWRI, the current contents have not been written
5664 		 * to disk. It is possible that the block was written
5665 		 * earlier, but very uncommon. If the block has never
5666 		 * been written, there is no need to send a BIO_DELETE
5667 		 * for it when it is freed. The gain from avoiding the
5668 		 * TRIMs for the common case of unwritten blocks far
5669 		 * exceeds the cost of the write amplification for the
5670 		 * uncommon case of failing to send a TRIM for a block
5671 		 * that had been written.
5672 		 */
5673 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5674 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5675 	else
5676 		freefrag = NULL;
5677 
5678 	CTR6(KTR_SUJ,
5679 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5680 	    "off %jd newsize %ld oldsize %d",
5681 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5682 	ACQUIRE_LOCK(ITOUMP(ip));
5683 	if (off >= UFS_NDADDR) {
5684 		if (lbn > 0)
5685 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5686 			    lbn, off);
5687 		/* allocating an indirect block */
5688 		if (oldblkno != 0)
5689 			panic("softdep_setup_allocdirect: non-zero indir");
5690 	} else {
5691 		if (off != lbn)
5692 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5693 			    lbn, off);
5694 		/*
5695 		 * Allocating a direct block.
5696 		 *
5697 		 * If we are allocating a directory block, then we must
5698 		 * allocate an associated pagedep to track additions and
5699 		 * deletions.
5700 		 */
5701 		if ((ip->i_mode & IFMT) == IFDIR)
5702 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5703 			    &pagedep);
5704 	}
5705 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5706 		panic("softdep_setup_allocdirect: lost block");
5707 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5708 	    ("softdep_setup_allocdirect: newblk already initialized"));
5709 	/*
5710 	 * Convert the newblk to an allocdirect.
5711 	 */
5712 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5713 	adp = (struct allocdirect *)newblk;
5714 	newblk->nb_freefrag = freefrag;
5715 	adp->ad_offset = off;
5716 	adp->ad_oldblkno = oldblkno;
5717 	adp->ad_newsize = newsize;
5718 	adp->ad_oldsize = oldsize;
5719 
5720 	/*
5721 	 * Finish initializing the journal.
5722 	 */
5723 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5724 		jnewblk->jn_ino = ip->i_number;
5725 		jnewblk->jn_lbn = lbn;
5726 		add_to_journal(&jnewblk->jn_list);
5727 	}
5728 	if (freefrag && freefrag->ff_jdep != NULL &&
5729 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5730 		add_to_journal(freefrag->ff_jdep);
5731 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5732 	adp->ad_inodedep = inodedep;
5733 
5734 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5735 	/*
5736 	 * The list of allocdirects must be kept in sorted and ascending
5737 	 * order so that the rollback routines can quickly determine the
5738 	 * first uncommitted block (the size of the file stored on disk
5739 	 * ends at the end of the lowest committed fragment, or if there
5740 	 * are no fragments, at the end of the highest committed block).
5741 	 * Since files generally grow, the typical case is that the new
5742 	 * block is to be added at the end of the list. We speed this
5743 	 * special case by checking against the last allocdirect in the
5744 	 * list before laboriously traversing the list looking for the
5745 	 * insertion point.
5746 	 */
5747 	adphead = &inodedep->id_newinoupdt;
5748 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5749 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5750 		/* insert at end of list */
5751 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5752 		if (oldadp != NULL && oldadp->ad_offset == off)
5753 			allocdirect_merge(adphead, adp, oldadp);
5754 		FREE_LOCK(ITOUMP(ip));
5755 		return;
5756 	}
5757 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5758 		if (oldadp->ad_offset >= off)
5759 			break;
5760 	}
5761 	if (oldadp == NULL)
5762 		panic("softdep_setup_allocdirect: lost entry");
5763 	/* insert in middle of list */
5764 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5765 	if (oldadp->ad_offset == off)
5766 		allocdirect_merge(adphead, adp, oldadp);
5767 
5768 	FREE_LOCK(ITOUMP(ip));
5769 }
5770 
5771 /*
5772  * Merge a newer and older journal record to be stored either in a
5773  * newblock or freefrag.  This handles aggregating journal records for
5774  * fragment allocation into a second record as well as replacing a
5775  * journal free with an aborted journal allocation.  A segment for the
5776  * oldest record will be placed on wkhd if it has been written.  If not
5777  * the segment for the newer record will suffice.
5778  */
5779 static struct worklist *
5780 jnewblk_merge(new, old, wkhd)
5781 	struct worklist *new;
5782 	struct worklist *old;
5783 	struct workhead *wkhd;
5784 {
5785 	struct jnewblk *njnewblk;
5786 	struct jnewblk *jnewblk;
5787 
5788 	/* Handle NULLs to simplify callers. */
5789 	if (new == NULL)
5790 		return (old);
5791 	if (old == NULL)
5792 		return (new);
5793 	/* Replace a jfreefrag with a jnewblk. */
5794 	if (new->wk_type == D_JFREEFRAG) {
5795 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5796 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5797 			    old, new);
5798 		cancel_jfreefrag(WK_JFREEFRAG(new));
5799 		return (old);
5800 	}
5801 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5802 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5803 		    old->wk_type, new->wk_type);
5804 	/*
5805 	 * Handle merging of two jnewblk records that describe
5806 	 * different sets of fragments in the same block.
5807 	 */
5808 	jnewblk = WK_JNEWBLK(old);
5809 	njnewblk = WK_JNEWBLK(new);
5810 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5811 		panic("jnewblk_merge: Merging disparate blocks.");
5812 	/*
5813 	 * The record may be rolled back in the cg.
5814 	 */
5815 	if (jnewblk->jn_state & UNDONE) {
5816 		jnewblk->jn_state &= ~UNDONE;
5817 		njnewblk->jn_state |= UNDONE;
5818 		njnewblk->jn_state &= ~ATTACHED;
5819 	}
5820 	/*
5821 	 * We modify the newer addref and free the older so that if neither
5822 	 * has been written the most up-to-date copy will be on disk.  If
5823 	 * both have been written but rolled back we only temporarily need
5824 	 * one of them to fix the bits when the cg write completes.
5825 	 */
5826 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5827 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5828 	cancel_jnewblk(jnewblk, wkhd);
5829 	WORKLIST_REMOVE(&jnewblk->jn_list);
5830 	free_jnewblk(jnewblk);
5831 	return (new);
5832 }
5833 
5834 /*
5835  * Replace an old allocdirect dependency with a newer one.
5836  */
5837 static void
5838 allocdirect_merge(adphead, newadp, oldadp)
5839 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5840 	struct allocdirect *newadp;	/* allocdirect being added */
5841 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5842 {
5843 	struct worklist *wk;
5844 	struct freefrag *freefrag;
5845 
5846 	freefrag = NULL;
5847 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5848 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5849 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5850 	    newadp->ad_offset >= UFS_NDADDR)
5851 		panic("%s %jd != new %jd || old size %ld != new %ld",
5852 		    "allocdirect_merge: old blkno",
5853 		    (intmax_t)newadp->ad_oldblkno,
5854 		    (intmax_t)oldadp->ad_newblkno,
5855 		    newadp->ad_oldsize, oldadp->ad_newsize);
5856 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5857 	newadp->ad_oldsize = oldadp->ad_oldsize;
5858 	/*
5859 	 * If the old dependency had a fragment to free or had never
5860 	 * previously had a block allocated, then the new dependency
5861 	 * can immediately post its freefrag and adopt the old freefrag.
5862 	 * This action is done by swapping the freefrag dependencies.
5863 	 * The new dependency gains the old one's freefrag, and the
5864 	 * old one gets the new one and then immediately puts it on
5865 	 * the worklist when it is freed by free_newblk. It is
5866 	 * not possible to do this swap when the old dependency had a
5867 	 * non-zero size but no previous fragment to free. This condition
5868 	 * arises when the new block is an extension of the old block.
5869 	 * Here, the first part of the fragment allocated to the new
5870 	 * dependency is part of the block currently claimed on disk by
5871 	 * the old dependency, so cannot legitimately be freed until the
5872 	 * conditions for the new dependency are fulfilled.
5873 	 */
5874 	freefrag = newadp->ad_freefrag;
5875 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5876 		newadp->ad_freefrag = oldadp->ad_freefrag;
5877 		oldadp->ad_freefrag = freefrag;
5878 	}
5879 	/*
5880 	 * If we are tracking a new directory-block allocation,
5881 	 * move it from the old allocdirect to the new allocdirect.
5882 	 */
5883 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5884 		WORKLIST_REMOVE(wk);
5885 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5886 			panic("allocdirect_merge: extra newdirblk");
5887 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5888 	}
5889 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5890 	/*
5891 	 * We need to move any journal dependencies over to the freefrag
5892 	 * that releases this block if it exists.  Otherwise we are
5893 	 * extending an existing block and we'll wait until that is
5894 	 * complete to release the journal space and extend the
5895 	 * new journal to cover this old space as well.
5896 	 */
5897 	if (freefrag == NULL) {
5898 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5899 			panic("allocdirect_merge: %jd != %jd",
5900 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5901 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5902 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5903 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5904 		    &newadp->ad_block.nb_jwork);
5905 		oldadp->ad_block.nb_jnewblk = NULL;
5906 		cancel_newblk(&oldadp->ad_block, NULL,
5907 		    &newadp->ad_block.nb_jwork);
5908 	} else {
5909 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5910 		    &freefrag->ff_list, &freefrag->ff_jwork);
5911 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5912 		    &freefrag->ff_jwork);
5913 	}
5914 	free_newblk(&oldadp->ad_block);
5915 }
5916 
5917 /*
5918  * Allocate a jfreefrag structure to journal a single block free.
5919  */
5920 static struct jfreefrag *
5921 newjfreefrag(freefrag, ip, blkno, size, lbn)
5922 	struct freefrag *freefrag;
5923 	struct inode *ip;
5924 	ufs2_daddr_t blkno;
5925 	long size;
5926 	ufs_lbn_t lbn;
5927 {
5928 	struct jfreefrag *jfreefrag;
5929 	struct fs *fs;
5930 
5931 	fs = ITOFS(ip);
5932 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5933 	    M_SOFTDEP_FLAGS);
5934 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5935 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5936 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5937 	jfreefrag->fr_ino = ip->i_number;
5938 	jfreefrag->fr_lbn = lbn;
5939 	jfreefrag->fr_blkno = blkno;
5940 	jfreefrag->fr_frags = numfrags(fs, size);
5941 	jfreefrag->fr_freefrag = freefrag;
5942 
5943 	return (jfreefrag);
5944 }
5945 
5946 /*
5947  * Allocate a new freefrag structure.
5948  */
5949 static struct freefrag *
5950 newfreefrag(ip, blkno, size, lbn, key)
5951 	struct inode *ip;
5952 	ufs2_daddr_t blkno;
5953 	long size;
5954 	ufs_lbn_t lbn;
5955 	u_long key;
5956 {
5957 	struct freefrag *freefrag;
5958 	struct ufsmount *ump;
5959 	struct fs *fs;
5960 
5961 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5962 	    ip->i_number, blkno, size, lbn);
5963 	ump = ITOUMP(ip);
5964 	fs = ump->um_fs;
5965 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5966 		panic("newfreefrag: frag size");
5967 	freefrag = malloc(sizeof(struct freefrag),
5968 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5969 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5970 	freefrag->ff_state = ATTACHED;
5971 	LIST_INIT(&freefrag->ff_jwork);
5972 	freefrag->ff_inum = ip->i_number;
5973 	freefrag->ff_vtype = ITOV(ip)->v_type;
5974 	freefrag->ff_blkno = blkno;
5975 	freefrag->ff_fragsize = size;
5976 	freefrag->ff_key = key;
5977 
5978 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5979 		freefrag->ff_jdep = (struct worklist *)
5980 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5981 	} else {
5982 		freefrag->ff_state |= DEPCOMPLETE;
5983 		freefrag->ff_jdep = NULL;
5984 	}
5985 
5986 	return (freefrag);
5987 }
5988 
5989 /*
5990  * This workitem de-allocates fragments that were replaced during
5991  * file block allocation.
5992  */
5993 static void
5994 handle_workitem_freefrag(freefrag)
5995 	struct freefrag *freefrag;
5996 {
5997 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5998 	struct workhead wkhd;
5999 
6000 	CTR3(KTR_SUJ,
6001 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
6002 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
6003 	/*
6004 	 * It would be illegal to add new completion items to the
6005 	 * freefrag after it was schedule to be done so it must be
6006 	 * safe to modify the list head here.
6007 	 */
6008 	LIST_INIT(&wkhd);
6009 	ACQUIRE_LOCK(ump);
6010 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
6011 	/*
6012 	 * If the journal has not been written we must cancel it here.
6013 	 */
6014 	if (freefrag->ff_jdep) {
6015 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
6016 			panic("handle_workitem_freefrag: Unexpected type %d\n",
6017 			    freefrag->ff_jdep->wk_type);
6018 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
6019 	}
6020 	FREE_LOCK(ump);
6021 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
6022 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
6023 	   &wkhd, freefrag->ff_key);
6024 	ACQUIRE_LOCK(ump);
6025 	WORKITEM_FREE(freefrag, D_FREEFRAG);
6026 	FREE_LOCK(ump);
6027 }
6028 
6029 /*
6030  * Set up a dependency structure for an external attributes data block.
6031  * This routine follows much of the structure of softdep_setup_allocdirect.
6032  * See the description of softdep_setup_allocdirect above for details.
6033  */
6034 void
6035 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
6036 	struct inode *ip;
6037 	ufs_lbn_t off;
6038 	ufs2_daddr_t newblkno;
6039 	ufs2_daddr_t oldblkno;
6040 	long newsize;
6041 	long oldsize;
6042 	struct buf *bp;
6043 {
6044 	struct allocdirect *adp, *oldadp;
6045 	struct allocdirectlst *adphead;
6046 	struct freefrag *freefrag;
6047 	struct inodedep *inodedep;
6048 	struct jnewblk *jnewblk;
6049 	struct newblk *newblk;
6050 	struct mount *mp;
6051 	struct ufsmount *ump;
6052 	ufs_lbn_t lbn;
6053 
6054 	mp = ITOVFS(ip);
6055 	ump = VFSTOUFS(mp);
6056 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6057 	    ("softdep_setup_allocext called on non-softdep filesystem"));
6058 	KASSERT(off < UFS_NXADDR,
6059 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
6060 
6061 	lbn = bp->b_lblkno;
6062 	if (oldblkno && oldblkno != newblkno)
6063 		/*
6064 		 * The usual case is that a smaller fragment that
6065 		 * was just allocated has been replaced with a bigger
6066 		 * fragment or a full-size block. If it is marked as
6067 		 * B_DELWRI, the current contents have not been written
6068 		 * to disk. It is possible that the block was written
6069 		 * earlier, but very uncommon. If the block has never
6070 		 * been written, there is no need to send a BIO_DELETE
6071 		 * for it when it is freed. The gain from avoiding the
6072 		 * TRIMs for the common case of unwritten blocks far
6073 		 * exceeds the cost of the write amplification for the
6074 		 * uncommon case of failing to send a TRIM for a block
6075 		 * that had been written.
6076 		 */
6077 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
6078 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
6079 	else
6080 		freefrag = NULL;
6081 
6082 	ACQUIRE_LOCK(ump);
6083 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
6084 		panic("softdep_setup_allocext: lost block");
6085 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6086 	    ("softdep_setup_allocext: newblk already initialized"));
6087 	/*
6088 	 * Convert the newblk to an allocdirect.
6089 	 */
6090 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
6091 	adp = (struct allocdirect *)newblk;
6092 	newblk->nb_freefrag = freefrag;
6093 	adp->ad_offset = off;
6094 	adp->ad_oldblkno = oldblkno;
6095 	adp->ad_newsize = newsize;
6096 	adp->ad_oldsize = oldsize;
6097 	adp->ad_state |=  EXTDATA;
6098 
6099 	/*
6100 	 * Finish initializing the journal.
6101 	 */
6102 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6103 		jnewblk->jn_ino = ip->i_number;
6104 		jnewblk->jn_lbn = lbn;
6105 		add_to_journal(&jnewblk->jn_list);
6106 	}
6107 	if (freefrag && freefrag->ff_jdep != NULL &&
6108 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6109 		add_to_journal(freefrag->ff_jdep);
6110 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6111 	adp->ad_inodedep = inodedep;
6112 
6113 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
6114 	/*
6115 	 * The list of allocdirects must be kept in sorted and ascending
6116 	 * order so that the rollback routines can quickly determine the
6117 	 * first uncommitted block (the size of the file stored on disk
6118 	 * ends at the end of the lowest committed fragment, or if there
6119 	 * are no fragments, at the end of the highest committed block).
6120 	 * Since files generally grow, the typical case is that the new
6121 	 * block is to be added at the end of the list. We speed this
6122 	 * special case by checking against the last allocdirect in the
6123 	 * list before laboriously traversing the list looking for the
6124 	 * insertion point.
6125 	 */
6126 	adphead = &inodedep->id_newextupdt;
6127 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
6128 	if (oldadp == NULL || oldadp->ad_offset <= off) {
6129 		/* insert at end of list */
6130 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
6131 		if (oldadp != NULL && oldadp->ad_offset == off)
6132 			allocdirect_merge(adphead, adp, oldadp);
6133 		FREE_LOCK(ump);
6134 		return;
6135 	}
6136 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
6137 		if (oldadp->ad_offset >= off)
6138 			break;
6139 	}
6140 	if (oldadp == NULL)
6141 		panic("softdep_setup_allocext: lost entry");
6142 	/* insert in middle of list */
6143 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
6144 	if (oldadp->ad_offset == off)
6145 		allocdirect_merge(adphead, adp, oldadp);
6146 	FREE_LOCK(ump);
6147 }
6148 
6149 /*
6150  * Indirect block allocation dependencies.
6151  *
6152  * The same dependencies that exist for a direct block also exist when
6153  * a new block is allocated and pointed to by an entry in a block of
6154  * indirect pointers. The undo/redo states described above are also
6155  * used here. Because an indirect block contains many pointers that
6156  * may have dependencies, a second copy of the entire in-memory indirect
6157  * block is kept. The buffer cache copy is always completely up-to-date.
6158  * The second copy, which is used only as a source for disk writes,
6159  * contains only the safe pointers (i.e., those that have no remaining
6160  * update dependencies). The second copy is freed when all pointers
6161  * are safe. The cache is not allowed to replace indirect blocks with
6162  * pending update dependencies. If a buffer containing an indirect
6163  * block with dependencies is written, these routines will mark it
6164  * dirty again. It can only be successfully written once all the
6165  * dependencies are removed. The ffs_fsync routine in conjunction with
6166  * softdep_sync_metadata work together to get all the dependencies
6167  * removed so that a file can be successfully written to disk. Three
6168  * procedures are used when setting up indirect block pointer
6169  * dependencies. The division is necessary because of the organization
6170  * of the "balloc" routine and because of the distinction between file
6171  * pages and file metadata blocks.
6172  */
6173 
6174 /*
6175  * Allocate a new allocindir structure.
6176  */
6177 static struct allocindir *
6178 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
6179 	struct inode *ip;	/* inode for file being extended */
6180 	int ptrno;		/* offset of pointer in indirect block */
6181 	ufs2_daddr_t newblkno;	/* disk block number being added */
6182 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
6183 	ufs_lbn_t lbn;
6184 {
6185 	struct newblk *newblk;
6186 	struct allocindir *aip;
6187 	struct freefrag *freefrag;
6188 	struct jnewblk *jnewblk;
6189 
6190 	if (oldblkno)
6191 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
6192 		    SINGLETON_KEY);
6193 	else
6194 		freefrag = NULL;
6195 	ACQUIRE_LOCK(ITOUMP(ip));
6196 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
6197 		panic("new_allocindir: lost block");
6198 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6199 	    ("newallocindir: newblk already initialized"));
6200 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
6201 	newblk->nb_freefrag = freefrag;
6202 	aip = (struct allocindir *)newblk;
6203 	aip->ai_offset = ptrno;
6204 	aip->ai_oldblkno = oldblkno;
6205 	aip->ai_lbn = lbn;
6206 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6207 		jnewblk->jn_ino = ip->i_number;
6208 		jnewblk->jn_lbn = lbn;
6209 		add_to_journal(&jnewblk->jn_list);
6210 	}
6211 	if (freefrag && freefrag->ff_jdep != NULL &&
6212 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6213 		add_to_journal(freefrag->ff_jdep);
6214 	return (aip);
6215 }
6216 
6217 /*
6218  * Called just before setting an indirect block pointer
6219  * to a newly allocated file page.
6220  */
6221 void
6222 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
6223 	struct inode *ip;	/* inode for file being extended */
6224 	ufs_lbn_t lbn;		/* allocated block number within file */
6225 	struct buf *bp;		/* buffer with indirect blk referencing page */
6226 	int ptrno;		/* offset of pointer in indirect block */
6227 	ufs2_daddr_t newblkno;	/* disk block number being added */
6228 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
6229 	struct buf *nbp;	/* buffer holding allocated page */
6230 {
6231 	struct inodedep *inodedep;
6232 	struct freefrag *freefrag;
6233 	struct allocindir *aip;
6234 	struct pagedep *pagedep;
6235 	struct mount *mp;
6236 	struct ufsmount *ump;
6237 
6238 	mp = ITOVFS(ip);
6239 	ump = VFSTOUFS(mp);
6240 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6241 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
6242 	KASSERT(lbn == nbp->b_lblkno,
6243 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
6244 	    lbn, bp->b_lblkno));
6245 	CTR4(KTR_SUJ,
6246 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
6247 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
6248 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
6249 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
6250 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6251 	/*
6252 	 * If we are allocating a directory page, then we must
6253 	 * allocate an associated pagedep to track additions and
6254 	 * deletions.
6255 	 */
6256 	if ((ip->i_mode & IFMT) == IFDIR)
6257 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
6258 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6259 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
6260 	FREE_LOCK(ump);
6261 	if (freefrag)
6262 		handle_workitem_freefrag(freefrag);
6263 }
6264 
6265 /*
6266  * Called just before setting an indirect block pointer to a
6267  * newly allocated indirect block.
6268  */
6269 void
6270 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
6271 	struct buf *nbp;	/* newly allocated indirect block */
6272 	struct inode *ip;	/* inode for file being extended */
6273 	struct buf *bp;		/* indirect block referencing allocated block */
6274 	int ptrno;		/* offset of pointer in indirect block */
6275 	ufs2_daddr_t newblkno;	/* disk block number being added */
6276 {
6277 	struct inodedep *inodedep;
6278 	struct allocindir *aip;
6279 	struct ufsmount *ump;
6280 	ufs_lbn_t lbn;
6281 
6282 	ump = ITOUMP(ip);
6283 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6284 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
6285 	CTR3(KTR_SUJ,
6286 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
6287 	    ip->i_number, newblkno, ptrno);
6288 	lbn = nbp->b_lblkno;
6289 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
6290 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
6291 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
6292 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6293 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
6294 		panic("softdep_setup_allocindir_meta: Block already existed");
6295 	FREE_LOCK(ump);
6296 }
6297 
6298 static void
6299 indirdep_complete(indirdep)
6300 	struct indirdep *indirdep;
6301 {
6302 	struct allocindir *aip;
6303 
6304 	LIST_REMOVE(indirdep, ir_next);
6305 	indirdep->ir_state |= DEPCOMPLETE;
6306 
6307 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
6308 		LIST_REMOVE(aip, ai_next);
6309 		free_newblk(&aip->ai_block);
6310 	}
6311 	/*
6312 	 * If this indirdep is not attached to a buf it was simply waiting
6313 	 * on completion to clear completehd.  free_indirdep() asserts
6314 	 * that nothing is dangling.
6315 	 */
6316 	if ((indirdep->ir_state & ONWORKLIST) == 0)
6317 		free_indirdep(indirdep);
6318 }
6319 
6320 static struct indirdep *
6321 indirdep_lookup(mp, ip, bp)
6322 	struct mount *mp;
6323 	struct inode *ip;
6324 	struct buf *bp;
6325 {
6326 	struct indirdep *indirdep, *newindirdep;
6327 	struct newblk *newblk;
6328 	struct ufsmount *ump;
6329 	struct worklist *wk;
6330 	struct fs *fs;
6331 	ufs2_daddr_t blkno;
6332 
6333 	ump = VFSTOUFS(mp);
6334 	LOCK_OWNED(ump);
6335 	indirdep = NULL;
6336 	newindirdep = NULL;
6337 	fs = ump->um_fs;
6338 	for (;;) {
6339 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6340 			if (wk->wk_type != D_INDIRDEP)
6341 				continue;
6342 			indirdep = WK_INDIRDEP(wk);
6343 			break;
6344 		}
6345 		/* Found on the buffer worklist, no new structure to free. */
6346 		if (indirdep != NULL && newindirdep == NULL)
6347 			return (indirdep);
6348 		if (indirdep != NULL && newindirdep != NULL)
6349 			panic("indirdep_lookup: simultaneous create");
6350 		/* None found on the buffer and a new structure is ready. */
6351 		if (indirdep == NULL && newindirdep != NULL)
6352 			break;
6353 		/* None found and no new structure available. */
6354 		FREE_LOCK(ump);
6355 		newindirdep = malloc(sizeof(struct indirdep),
6356 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
6357 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6358 		newindirdep->ir_state = ATTACHED;
6359 		if (I_IS_UFS1(ip))
6360 			newindirdep->ir_state |= UFS1FMT;
6361 		TAILQ_INIT(&newindirdep->ir_trunc);
6362 		newindirdep->ir_saveddata = NULL;
6363 		LIST_INIT(&newindirdep->ir_deplisthd);
6364 		LIST_INIT(&newindirdep->ir_donehd);
6365 		LIST_INIT(&newindirdep->ir_writehd);
6366 		LIST_INIT(&newindirdep->ir_completehd);
6367 		if (bp->b_blkno == bp->b_lblkno) {
6368 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6369 			    NULL, NULL);
6370 			bp->b_blkno = blkno;
6371 		}
6372 		newindirdep->ir_freeblks = NULL;
6373 		newindirdep->ir_savebp =
6374 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6375 		newindirdep->ir_bp = bp;
6376 		BUF_KERNPROC(newindirdep->ir_savebp);
6377 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6378 		ACQUIRE_LOCK(ump);
6379 	}
6380 	indirdep = newindirdep;
6381 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6382 	/*
6383 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6384 	 * that we don't free dependencies until the pointers are valid.
6385 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6386 	 * than using the hash.
6387 	 */
6388 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6389 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6390 	else
6391 		indirdep->ir_state |= DEPCOMPLETE;
6392 	return (indirdep);
6393 }
6394 
6395 /*
6396  * Called to finish the allocation of the "aip" allocated
6397  * by one of the two routines above.
6398  */
6399 static struct freefrag *
6400 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6401 	struct buf *bp;		/* in-memory copy of the indirect block */
6402 	struct inode *ip;	/* inode for file being extended */
6403 	struct inodedep *inodedep; /* Inodedep for ip */
6404 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6405 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6406 {
6407 	struct fs *fs;
6408 	struct indirdep *indirdep;
6409 	struct allocindir *oldaip;
6410 	struct freefrag *freefrag;
6411 	struct mount *mp;
6412 	struct ufsmount *ump;
6413 
6414 	mp = ITOVFS(ip);
6415 	ump = VFSTOUFS(mp);
6416 	LOCK_OWNED(ump);
6417 	fs = ump->um_fs;
6418 	if (bp->b_lblkno >= 0)
6419 		panic("setup_allocindir_phase2: not indir blk");
6420 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6421 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6422 	indirdep = indirdep_lookup(mp, ip, bp);
6423 	KASSERT(indirdep->ir_savebp != NULL,
6424 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6425 	aip->ai_indirdep = indirdep;
6426 	/*
6427 	 * Check for an unwritten dependency for this indirect offset.  If
6428 	 * there is, merge the old dependency into the new one.  This happens
6429 	 * as a result of reallocblk only.
6430 	 */
6431 	freefrag = NULL;
6432 	if (aip->ai_oldblkno != 0) {
6433 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6434 			if (oldaip->ai_offset == aip->ai_offset) {
6435 				freefrag = allocindir_merge(aip, oldaip);
6436 				goto done;
6437 			}
6438 		}
6439 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6440 			if (oldaip->ai_offset == aip->ai_offset) {
6441 				freefrag = allocindir_merge(aip, oldaip);
6442 				goto done;
6443 			}
6444 		}
6445 	}
6446 done:
6447 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6448 	return (freefrag);
6449 }
6450 
6451 /*
6452  * Merge two allocindirs which refer to the same block.  Move newblock
6453  * dependencies and setup the freefrags appropriately.
6454  */
6455 static struct freefrag *
6456 allocindir_merge(aip, oldaip)
6457 	struct allocindir *aip;
6458 	struct allocindir *oldaip;
6459 {
6460 	struct freefrag *freefrag;
6461 	struct worklist *wk;
6462 
6463 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6464 		panic("allocindir_merge: blkno");
6465 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6466 	freefrag = aip->ai_freefrag;
6467 	aip->ai_freefrag = oldaip->ai_freefrag;
6468 	oldaip->ai_freefrag = NULL;
6469 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6470 	/*
6471 	 * If we are tracking a new directory-block allocation,
6472 	 * move it from the old allocindir to the new allocindir.
6473 	 */
6474 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6475 		WORKLIST_REMOVE(wk);
6476 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6477 			panic("allocindir_merge: extra newdirblk");
6478 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6479 	}
6480 	/*
6481 	 * We can skip journaling for this freefrag and just complete
6482 	 * any pending journal work for the allocindir that is being
6483 	 * removed after the freefrag completes.
6484 	 */
6485 	if (freefrag->ff_jdep)
6486 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6487 	LIST_REMOVE(oldaip, ai_next);
6488 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6489 	    &freefrag->ff_list, &freefrag->ff_jwork);
6490 	free_newblk(&oldaip->ai_block);
6491 
6492 	return (freefrag);
6493 }
6494 
6495 static inline void
6496 setup_freedirect(freeblks, ip, i, needj)
6497 	struct freeblks *freeblks;
6498 	struct inode *ip;
6499 	int i;
6500 	int needj;
6501 {
6502 	struct ufsmount *ump;
6503 	ufs2_daddr_t blkno;
6504 	int frags;
6505 
6506 	blkno = DIP(ip, i_db[i]);
6507 	if (blkno == 0)
6508 		return;
6509 	DIP_SET(ip, i_db[i], 0);
6510 	ump = ITOUMP(ip);
6511 	frags = sblksize(ump->um_fs, ip->i_size, i);
6512 	frags = numfrags(ump->um_fs, frags);
6513 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6514 }
6515 
6516 static inline void
6517 setup_freeext(freeblks, ip, i, needj)
6518 	struct freeblks *freeblks;
6519 	struct inode *ip;
6520 	int i;
6521 	int needj;
6522 {
6523 	struct ufsmount *ump;
6524 	ufs2_daddr_t blkno;
6525 	int frags;
6526 
6527 	blkno = ip->i_din2->di_extb[i];
6528 	if (blkno == 0)
6529 		return;
6530 	ip->i_din2->di_extb[i] = 0;
6531 	ump = ITOUMP(ip);
6532 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6533 	frags = numfrags(ump->um_fs, frags);
6534 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6535 }
6536 
6537 static inline void
6538 setup_freeindir(freeblks, ip, i, lbn, needj)
6539 	struct freeblks *freeblks;
6540 	struct inode *ip;
6541 	int i;
6542 	ufs_lbn_t lbn;
6543 	int needj;
6544 {
6545 	struct ufsmount *ump;
6546 	ufs2_daddr_t blkno;
6547 
6548 	blkno = DIP(ip, i_ib[i]);
6549 	if (blkno == 0)
6550 		return;
6551 	DIP_SET(ip, i_ib[i], 0);
6552 	ump = ITOUMP(ip);
6553 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6554 	    0, needj);
6555 }
6556 
6557 static inline struct freeblks *
6558 newfreeblks(mp, ip)
6559 	struct mount *mp;
6560 	struct inode *ip;
6561 {
6562 	struct freeblks *freeblks;
6563 
6564 	freeblks = malloc(sizeof(struct freeblks),
6565 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6566 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6567 	LIST_INIT(&freeblks->fb_jblkdephd);
6568 	LIST_INIT(&freeblks->fb_jwork);
6569 	freeblks->fb_ref = 0;
6570 	freeblks->fb_cgwait = 0;
6571 	freeblks->fb_state = ATTACHED;
6572 	freeblks->fb_uid = ip->i_uid;
6573 	freeblks->fb_inum = ip->i_number;
6574 	freeblks->fb_vtype = ITOV(ip)->v_type;
6575 	freeblks->fb_modrev = DIP(ip, i_modrev);
6576 	freeblks->fb_devvp = ITODEVVP(ip);
6577 	freeblks->fb_chkcnt = 0;
6578 	freeblks->fb_len = 0;
6579 
6580 	return (freeblks);
6581 }
6582 
6583 static void
6584 trunc_indirdep(indirdep, freeblks, bp, off)
6585 	struct indirdep *indirdep;
6586 	struct freeblks *freeblks;
6587 	struct buf *bp;
6588 	int off;
6589 {
6590 	struct allocindir *aip, *aipn;
6591 
6592 	/*
6593 	 * The first set of allocindirs won't be in savedbp.
6594 	 */
6595 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6596 		if (aip->ai_offset > off)
6597 			cancel_allocindir(aip, bp, freeblks, 1);
6598 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6599 		if (aip->ai_offset > off)
6600 			cancel_allocindir(aip, bp, freeblks, 1);
6601 	/*
6602 	 * These will exist in savedbp.
6603 	 */
6604 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6605 		if (aip->ai_offset > off)
6606 			cancel_allocindir(aip, NULL, freeblks, 0);
6607 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6608 		if (aip->ai_offset > off)
6609 			cancel_allocindir(aip, NULL, freeblks, 0);
6610 }
6611 
6612 /*
6613  * Follow the chain of indirects down to lastlbn creating a freework
6614  * structure for each.  This will be used to start indir_trunc() at
6615  * the right offset and create the journal records for the parrtial
6616  * truncation.  A second step will handle the truncated dependencies.
6617  */
6618 static int
6619 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6620 	struct freeblks *freeblks;
6621 	struct inode *ip;
6622 	ufs_lbn_t lbn;
6623 	ufs_lbn_t lastlbn;
6624 	ufs2_daddr_t blkno;
6625 {
6626 	struct indirdep *indirdep;
6627 	struct indirdep *indirn;
6628 	struct freework *freework;
6629 	struct newblk *newblk;
6630 	struct mount *mp;
6631 	struct ufsmount *ump;
6632 	struct buf *bp;
6633 	uint8_t *start;
6634 	uint8_t *end;
6635 	ufs_lbn_t lbnadd;
6636 	int level;
6637 	int error;
6638 	int off;
6639 
6640 	freework = NULL;
6641 	if (blkno == 0)
6642 		return (0);
6643 	mp = freeblks->fb_list.wk_mp;
6644 	ump = VFSTOUFS(mp);
6645 	/*
6646 	 * Here, calls to VOP_BMAP() will fail.  However, we already have
6647 	 * the on-disk address, so we just pass it to bread() instead of
6648 	 * having bread() attempt to calculate it using VOP_BMAP().
6649 	 */
6650 	error = ffs_breadz(ump, ITOV(ip), lbn, blkptrtodb(ump, blkno),
6651 	    (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6652 	if (error)
6653 		return (error);
6654 	level = lbn_level(lbn);
6655 	lbnadd = lbn_offset(ump->um_fs, level);
6656 	/*
6657 	 * Compute the offset of the last block we want to keep.  Store
6658 	 * in the freework the first block we want to completely free.
6659 	 */
6660 	off = (lastlbn - -(lbn + level)) / lbnadd;
6661 	if (off + 1 == NINDIR(ump->um_fs))
6662 		goto nowork;
6663 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6664 	/*
6665 	 * Link the freework into the indirdep.  This will prevent any new
6666 	 * allocations from proceeding until we are finished with the
6667 	 * truncate and the block is written.
6668 	 */
6669 	ACQUIRE_LOCK(ump);
6670 	indirdep = indirdep_lookup(mp, ip, bp);
6671 	if (indirdep->ir_freeblks)
6672 		panic("setup_trunc_indir: indirdep already truncated.");
6673 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6674 	freework->fw_indir = indirdep;
6675 	/*
6676 	 * Cancel any allocindirs that will not make it to disk.
6677 	 * We have to do this for all copies of the indirdep that
6678 	 * live on this newblk.
6679 	 */
6680 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6681 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6682 		    &newblk) == 0)
6683 			panic("setup_trunc_indir: lost block");
6684 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6685 			trunc_indirdep(indirn, freeblks, bp, off);
6686 	} else
6687 		trunc_indirdep(indirdep, freeblks, bp, off);
6688 	FREE_LOCK(ump);
6689 	/*
6690 	 * Creation is protected by the buf lock. The saveddata is only
6691 	 * needed if a full truncation follows a partial truncation but it
6692 	 * is difficult to allocate in that case so we fetch it anyway.
6693 	 */
6694 	if (indirdep->ir_saveddata == NULL)
6695 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6696 		    M_SOFTDEP_FLAGS);
6697 nowork:
6698 	/* Fetch the blkno of the child and the zero start offset. */
6699 	if (I_IS_UFS1(ip)) {
6700 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6701 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6702 	} else {
6703 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6704 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6705 	}
6706 	if (freework) {
6707 		/* Zero the truncated pointers. */
6708 		end = bp->b_data + bp->b_bcount;
6709 		bzero(start, end - start);
6710 		bdwrite(bp);
6711 	} else
6712 		bqrelse(bp);
6713 	if (level == 0)
6714 		return (0);
6715 	lbn++; /* adjust level */
6716 	lbn -= (off * lbnadd);
6717 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6718 }
6719 
6720 /*
6721  * Complete the partial truncation of an indirect block setup by
6722  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6723  * copy and writes them to disk before the freeblks is allowed to complete.
6724  */
6725 static void
6726 complete_trunc_indir(freework)
6727 	struct freework *freework;
6728 {
6729 	struct freework *fwn;
6730 	struct indirdep *indirdep;
6731 	struct ufsmount *ump;
6732 	struct buf *bp;
6733 	uintptr_t start;
6734 	int count;
6735 
6736 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6737 	LOCK_OWNED(ump);
6738 	indirdep = freework->fw_indir;
6739 	for (;;) {
6740 		bp = indirdep->ir_bp;
6741 		/* See if the block was discarded. */
6742 		if (bp == NULL)
6743 			break;
6744 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6745 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6746 			break;
6747 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6748 		    LOCK_PTR(ump)) == 0)
6749 			BUF_UNLOCK(bp);
6750 		ACQUIRE_LOCK(ump);
6751 	}
6752 	freework->fw_state |= DEPCOMPLETE;
6753 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6754 	/*
6755 	 * Zero the pointers in the saved copy.
6756 	 */
6757 	if (indirdep->ir_state & UFS1FMT)
6758 		start = sizeof(ufs1_daddr_t);
6759 	else
6760 		start = sizeof(ufs2_daddr_t);
6761 	start *= freework->fw_start;
6762 	count = indirdep->ir_savebp->b_bcount - start;
6763 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6764 	bzero((char *)start, count);
6765 	/*
6766 	 * We need to start the next truncation in the list if it has not
6767 	 * been started yet.
6768 	 */
6769 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6770 	if (fwn != NULL) {
6771 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6772 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6773 		if ((fwn->fw_state & ONWORKLIST) == 0)
6774 			freework_enqueue(fwn);
6775 	}
6776 	/*
6777 	 * If bp is NULL the block was fully truncated, restore
6778 	 * the saved block list otherwise free it if it is no
6779 	 * longer needed.
6780 	 */
6781 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6782 		if (bp == NULL)
6783 			bcopy(indirdep->ir_saveddata,
6784 			    indirdep->ir_savebp->b_data,
6785 			    indirdep->ir_savebp->b_bcount);
6786 		free(indirdep->ir_saveddata, M_INDIRDEP);
6787 		indirdep->ir_saveddata = NULL;
6788 	}
6789 	/*
6790 	 * When bp is NULL there is a full truncation pending.  We
6791 	 * must wait for this full truncation to be journaled before
6792 	 * we can release this freework because the disk pointers will
6793 	 * never be written as zero.
6794 	 */
6795 	if (bp == NULL)  {
6796 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6797 			handle_written_freework(freework);
6798 		else
6799 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6800 			   &freework->fw_list);
6801 		if (fwn == NULL) {
6802 			freework->fw_indir = (void *)0x0000deadbeef0000;
6803 			bp = indirdep->ir_savebp;
6804 			indirdep->ir_savebp = NULL;
6805 			free_indirdep(indirdep);
6806 			FREE_LOCK(ump);
6807 			brelse(bp);
6808 			ACQUIRE_LOCK(ump);
6809 		}
6810 	} else {
6811 		/* Complete when the real copy is written. */
6812 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6813 		BUF_UNLOCK(bp);
6814 	}
6815 }
6816 
6817 /*
6818  * Calculate the number of blocks we are going to release where datablocks
6819  * is the current total and length is the new file size.
6820  */
6821 static ufs2_daddr_t
6822 blkcount(fs, datablocks, length)
6823 	struct fs *fs;
6824 	ufs2_daddr_t datablocks;
6825 	off_t length;
6826 {
6827 	off_t totblks, numblks;
6828 
6829 	totblks = 0;
6830 	numblks = howmany(length, fs->fs_bsize);
6831 	if (numblks <= UFS_NDADDR) {
6832 		totblks = howmany(length, fs->fs_fsize);
6833 		goto out;
6834 	}
6835         totblks = blkstofrags(fs, numblks);
6836 	numblks -= UFS_NDADDR;
6837 	/*
6838 	 * Count all single, then double, then triple indirects required.
6839 	 * Subtracting one indirects worth of blocks for each pass
6840 	 * acknowledges one of each pointed to by the inode.
6841 	 */
6842 	for (;;) {
6843 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6844 		numblks -= NINDIR(fs);
6845 		if (numblks <= 0)
6846 			break;
6847 		numblks = howmany(numblks, NINDIR(fs));
6848 	}
6849 out:
6850 	totblks = fsbtodb(fs, totblks);
6851 	/*
6852 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6853 	 * references.  We will correct it later in handle_complete_freeblks()
6854 	 * when we know the real count.
6855 	 */
6856 	if (totblks > datablocks)
6857 		return (0);
6858 	return (datablocks - totblks);
6859 }
6860 
6861 /*
6862  * Handle freeblocks for journaled softupdate filesystems.
6863  *
6864  * Contrary to normal softupdates, we must preserve the block pointers in
6865  * indirects until their subordinates are free.  This is to avoid journaling
6866  * every block that is freed which may consume more space than the journal
6867  * itself.  The recovery program will see the free block journals at the
6868  * base of the truncated area and traverse them to reclaim space.  The
6869  * pointers in the inode may be cleared immediately after the journal
6870  * records are written because each direct and indirect pointer in the
6871  * inode is recorded in a journal.  This permits full truncation to proceed
6872  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6873  *
6874  * The algorithm is as follows:
6875  * 1) Traverse the in-memory state and create journal entries to release
6876  *    the relevant blocks and full indirect trees.
6877  * 2) Traverse the indirect block chain adding partial truncation freework
6878  *    records to indirects in the path to lastlbn.  The freework will
6879  *    prevent new allocation dependencies from being satisfied in this
6880  *    indirect until the truncation completes.
6881  * 3) Read and lock the inode block, performing an update with the new size
6882  *    and pointers.  This prevents truncated data from becoming valid on
6883  *    disk through step 4.
6884  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6885  *    eliminate journal work for those records that do not require it.
6886  * 5) Schedule the journal records to be written followed by the inode block.
6887  * 6) Allocate any necessary frags for the end of file.
6888  * 7) Zero any partially truncated blocks.
6889  *
6890  * From this truncation proceeds asynchronously using the freework and
6891  * indir_trunc machinery.  The file will not be extended again into a
6892  * partially truncated indirect block until all work is completed but
6893  * the normal dependency mechanism ensures that it is rolled back/forward
6894  * as appropriate.  Further truncation may occur without delay and is
6895  * serialized in indir_trunc().
6896  */
6897 void
6898 softdep_journal_freeblocks(ip, cred, length, flags)
6899 	struct inode *ip;	/* The inode whose length is to be reduced */
6900 	struct ucred *cred;
6901 	off_t length;		/* The new length for the file */
6902 	int flags;		/* IO_EXT and/or IO_NORMAL */
6903 {
6904 	struct freeblks *freeblks, *fbn;
6905 	struct worklist *wk, *wkn;
6906 	struct inodedep *inodedep;
6907 	struct jblkdep *jblkdep;
6908 	struct allocdirect *adp, *adpn;
6909 	struct ufsmount *ump;
6910 	struct fs *fs;
6911 	struct buf *bp;
6912 	struct vnode *vp;
6913 	struct mount *mp;
6914 	daddr_t dbn;
6915 	ufs2_daddr_t extblocks, datablocks;
6916 	ufs_lbn_t tmpval, lbn, lastlbn;
6917 	int frags, lastoff, iboff, allocblock, needj, error, i;
6918 
6919 	ump = ITOUMP(ip);
6920 	mp = UFSTOVFS(ump);
6921 	fs = ump->um_fs;
6922 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6923 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6924 	vp = ITOV(ip);
6925 	needj = 1;
6926 	iboff = -1;
6927 	allocblock = 0;
6928 	extblocks = 0;
6929 	datablocks = 0;
6930 	frags = 0;
6931 	freeblks = newfreeblks(mp, ip);
6932 	ACQUIRE_LOCK(ump);
6933 	/*
6934 	 * If we're truncating a removed file that will never be written
6935 	 * we don't need to journal the block frees.  The canceled journals
6936 	 * for the allocations will suffice.
6937 	 */
6938 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6939 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6940 	    length == 0)
6941 		needj = 0;
6942 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6943 	    ip->i_number, length, needj);
6944 	FREE_LOCK(ump);
6945 	/*
6946 	 * Calculate the lbn that we are truncating to.  This results in -1
6947 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6948 	 * to keep, not the first lbn we want to truncate.
6949 	 */
6950 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6951 	lastoff = blkoff(fs, length);
6952 	/*
6953 	 * Compute frags we are keeping in lastlbn.  0 means all.
6954 	 */
6955 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6956 		frags = fragroundup(fs, lastoff);
6957 		/* adp offset of last valid allocdirect. */
6958 		iboff = lastlbn;
6959 	} else if (lastlbn > 0)
6960 		iboff = UFS_NDADDR;
6961 	if (fs->fs_magic == FS_UFS2_MAGIC)
6962 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6963 	/*
6964 	 * Handle normal data blocks and indirects.  This section saves
6965 	 * values used after the inode update to complete frag and indirect
6966 	 * truncation.
6967 	 */
6968 	if ((flags & IO_NORMAL) != 0) {
6969 		/*
6970 		 * Handle truncation of whole direct and indirect blocks.
6971 		 */
6972 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6973 			setup_freedirect(freeblks, ip, i, needj);
6974 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6975 		    i < UFS_NIADDR;
6976 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6977 			/* Release a whole indirect tree. */
6978 			if (lbn > lastlbn) {
6979 				setup_freeindir(freeblks, ip, i, -lbn -i,
6980 				    needj);
6981 				continue;
6982 			}
6983 			iboff = i + UFS_NDADDR;
6984 			/*
6985 			 * Traverse partially truncated indirect tree.
6986 			 */
6987 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6988 				setup_trunc_indir(freeblks, ip, -lbn - i,
6989 				    lastlbn, DIP(ip, i_ib[i]));
6990 		}
6991 		/*
6992 		 * Handle partial truncation to a frag boundary.
6993 		 */
6994 		if (frags) {
6995 			ufs2_daddr_t blkno;
6996 			long oldfrags;
6997 
6998 			oldfrags = blksize(fs, ip, lastlbn);
6999 			blkno = DIP(ip, i_db[lastlbn]);
7000 			if (blkno && oldfrags != frags) {
7001 				oldfrags -= frags;
7002 				oldfrags = numfrags(fs, oldfrags);
7003 				blkno += numfrags(fs, frags);
7004 				newfreework(ump, freeblks, NULL, lastlbn,
7005 				    blkno, oldfrags, 0, needj);
7006 				if (needj)
7007 					adjust_newfreework(freeblks,
7008 					    numfrags(fs, frags));
7009 			} else if (blkno == 0)
7010 				allocblock = 1;
7011 		}
7012 		/*
7013 		 * Add a journal record for partial truncate if we are
7014 		 * handling indirect blocks.  Non-indirects need no extra
7015 		 * journaling.
7016 		 */
7017 		if (length != 0 && lastlbn >= UFS_NDADDR) {
7018 			UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
7019 			newjtrunc(freeblks, length, 0);
7020 		}
7021 		ip->i_size = length;
7022 		DIP_SET(ip, i_size, ip->i_size);
7023 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7024 		datablocks = DIP(ip, i_blocks) - extblocks;
7025 		if (length != 0)
7026 			datablocks = blkcount(fs, datablocks, length);
7027 		freeblks->fb_len = length;
7028 	}
7029 	if ((flags & IO_EXT) != 0) {
7030 		for (i = 0; i < UFS_NXADDR; i++)
7031 			setup_freeext(freeblks, ip, i, needj);
7032 		ip->i_din2->di_extsize = 0;
7033 		datablocks += extblocks;
7034 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7035 	}
7036 #ifdef QUOTA
7037 	/* Reference the quotas in case the block count is wrong in the end. */
7038 	quotaref(vp, freeblks->fb_quota);
7039 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7040 #endif
7041 	freeblks->fb_chkcnt = -datablocks;
7042 	UFS_LOCK(ump);
7043 	fs->fs_pendingblocks += datablocks;
7044 	UFS_UNLOCK(ump);
7045 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7046 	/*
7047 	 * Handle truncation of incomplete alloc direct dependencies.  We
7048 	 * hold the inode block locked to prevent incomplete dependencies
7049 	 * from reaching the disk while we are eliminating those that
7050 	 * have been truncated.  This is a partially inlined ffs_update().
7051 	 */
7052 	ufs_itimes(vp);
7053 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
7054 	dbn = fsbtodb(fs, ino_to_fsba(fs, ip->i_number));
7055 	error = ffs_breadz(ump, ump->um_devvp, dbn, dbn, (int)fs->fs_bsize,
7056 	    NULL, NULL, 0, cred, 0, NULL, &bp);
7057 	if (error) {
7058 		softdep_error("softdep_journal_freeblocks", error);
7059 		return;
7060 	}
7061 	if (bp->b_bufsize == fs->fs_bsize)
7062 		bp->b_flags |= B_CLUSTEROK;
7063 	softdep_update_inodeblock(ip, bp, 0);
7064 	if (ump->um_fstype == UFS1) {
7065 		*((struct ufs1_dinode *)bp->b_data +
7066 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
7067 	} else {
7068 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7069 		*((struct ufs2_dinode *)bp->b_data +
7070 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
7071 	}
7072 	ACQUIRE_LOCK(ump);
7073 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7074 	if ((inodedep->id_state & IOSTARTED) != 0)
7075 		panic("softdep_setup_freeblocks: inode busy");
7076 	/*
7077 	 * Add the freeblks structure to the list of operations that
7078 	 * must await the zero'ed inode being written to disk. If we
7079 	 * still have a bitmap dependency (needj), then the inode
7080 	 * has never been written to disk, so we can process the
7081 	 * freeblks below once we have deleted the dependencies.
7082 	 */
7083 	if (needj)
7084 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7085 	else
7086 		freeblks->fb_state |= COMPLETE;
7087 	if ((flags & IO_NORMAL) != 0) {
7088 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
7089 			if (adp->ad_offset > iboff)
7090 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
7091 				    freeblks);
7092 			/*
7093 			 * Truncate the allocdirect.  We could eliminate
7094 			 * or modify journal records as well.
7095 			 */
7096 			else if (adp->ad_offset == iboff && frags)
7097 				adp->ad_newsize = frags;
7098 		}
7099 	}
7100 	if ((flags & IO_EXT) != 0)
7101 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7102 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7103 			    freeblks);
7104 	/*
7105 	 * Scan the bufwait list for newblock dependencies that will never
7106 	 * make it to disk.
7107 	 */
7108 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
7109 		if (wk->wk_type != D_ALLOCDIRECT)
7110 			continue;
7111 		adp = WK_ALLOCDIRECT(wk);
7112 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
7113 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
7114 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
7115 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
7116 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7117 		}
7118 	}
7119 	/*
7120 	 * Add journal work.
7121 	 */
7122 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
7123 		add_to_journal(&jblkdep->jb_list);
7124 	FREE_LOCK(ump);
7125 	bdwrite(bp);
7126 	/*
7127 	 * Truncate dependency structures beyond length.
7128 	 */
7129 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
7130 	/*
7131 	 * This is only set when we need to allocate a fragment because
7132 	 * none existed at the end of a frag-sized file.  It handles only
7133 	 * allocating a new, zero filled block.
7134 	 */
7135 	if (allocblock) {
7136 		ip->i_size = length - lastoff;
7137 		DIP_SET(ip, i_size, ip->i_size);
7138 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
7139 		if (error != 0) {
7140 			softdep_error("softdep_journal_freeblks", error);
7141 			return;
7142 		}
7143 		ip->i_size = length;
7144 		DIP_SET(ip, i_size, length);
7145 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
7146 		allocbuf(bp, frags);
7147 		ffs_update(vp, 0);
7148 		bawrite(bp);
7149 	} else if (lastoff != 0 && vp->v_type != VDIR) {
7150 		int size;
7151 
7152 		/*
7153 		 * Zero the end of a truncated frag or block.
7154 		 */
7155 		size = sblksize(fs, length, lastlbn);
7156 		error = bread(vp, lastlbn, size, cred, &bp);
7157 		if (error == 0) {
7158 			bzero((char *)bp->b_data + lastoff, size - lastoff);
7159 			bawrite(bp);
7160 		} else if (!ffs_fsfail_cleanup(ump, error)) {
7161 			softdep_error("softdep_journal_freeblks", error);
7162 			return;
7163 		}
7164 	}
7165 	ACQUIRE_LOCK(ump);
7166 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7167 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
7168 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
7169 	/*
7170 	 * We zero earlier truncations so they don't erroneously
7171 	 * update i_blocks.
7172 	 */
7173 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
7174 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
7175 			fbn->fb_len = 0;
7176 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
7177 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7178 		freeblks->fb_state |= INPROGRESS;
7179 	else
7180 		freeblks = NULL;
7181 	FREE_LOCK(ump);
7182 	if (freeblks)
7183 		handle_workitem_freeblocks(freeblks, 0);
7184 	trunc_pages(ip, length, extblocks, flags);
7185 
7186 }
7187 
7188 /*
7189  * Flush a JOP_SYNC to the journal.
7190  */
7191 void
7192 softdep_journal_fsync(ip)
7193 	struct inode *ip;
7194 {
7195 	struct jfsync *jfsync;
7196 	struct ufsmount *ump;
7197 
7198 	ump = ITOUMP(ip);
7199 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7200 	    ("softdep_journal_fsync called on non-softdep filesystem"));
7201 	if ((ip->i_flag & IN_TRUNCATED) == 0)
7202 		return;
7203 	ip->i_flag &= ~IN_TRUNCATED;
7204 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
7205 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
7206 	jfsync->jfs_size = ip->i_size;
7207 	jfsync->jfs_ino = ip->i_number;
7208 	ACQUIRE_LOCK(ump);
7209 	add_to_journal(&jfsync->jfs_list);
7210 	jwait(&jfsync->jfs_list, MNT_WAIT);
7211 	FREE_LOCK(ump);
7212 }
7213 
7214 /*
7215  * Block de-allocation dependencies.
7216  *
7217  * When blocks are de-allocated, the on-disk pointers must be nullified before
7218  * the blocks are made available for use by other files.  (The true
7219  * requirement is that old pointers must be nullified before new on-disk
7220  * pointers are set.  We chose this slightly more stringent requirement to
7221  * reduce complexity.) Our implementation handles this dependency by updating
7222  * the inode (or indirect block) appropriately but delaying the actual block
7223  * de-allocation (i.e., freemap and free space count manipulation) until
7224  * after the updated versions reach stable storage.  After the disk is
7225  * updated, the blocks can be safely de-allocated whenever it is convenient.
7226  * This implementation handles only the common case of reducing a file's
7227  * length to zero. Other cases are handled by the conventional synchronous
7228  * write approach.
7229  *
7230  * The ffs implementation with which we worked double-checks
7231  * the state of the block pointers and file size as it reduces
7232  * a file's length.  Some of this code is replicated here in our
7233  * soft updates implementation.  The freeblks->fb_chkcnt field is
7234  * used to transfer a part of this information to the procedure
7235  * that eventually de-allocates the blocks.
7236  *
7237  * This routine should be called from the routine that shortens
7238  * a file's length, before the inode's size or block pointers
7239  * are modified. It will save the block pointer information for
7240  * later release and zero the inode so that the calling routine
7241  * can release it.
7242  */
7243 void
7244 softdep_setup_freeblocks(ip, length, flags)
7245 	struct inode *ip;	/* The inode whose length is to be reduced */
7246 	off_t length;		/* The new length for the file */
7247 	int flags;		/* IO_EXT and/or IO_NORMAL */
7248 {
7249 	struct ufs1_dinode *dp1;
7250 	struct ufs2_dinode *dp2;
7251 	struct freeblks *freeblks;
7252 	struct inodedep *inodedep;
7253 	struct allocdirect *adp;
7254 	struct ufsmount *ump;
7255 	struct buf *bp;
7256 	struct fs *fs;
7257 	ufs2_daddr_t extblocks, datablocks;
7258 	struct mount *mp;
7259 	int i, delay, error;
7260 	ufs_lbn_t tmpval;
7261 	ufs_lbn_t lbn;
7262 
7263 	ump = ITOUMP(ip);
7264 	mp = UFSTOVFS(ump);
7265 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
7266 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
7267 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
7268 	    ip->i_number, length);
7269 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
7270 	fs = ump->um_fs;
7271 	if ((error = bread(ump->um_devvp,
7272 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
7273 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
7274 		if (!ffs_fsfail_cleanup(ump, error))
7275 			softdep_error("softdep_setup_freeblocks", error);
7276 		return;
7277 	}
7278 	freeblks = newfreeblks(mp, ip);
7279 	extblocks = 0;
7280 	datablocks = 0;
7281 	if (fs->fs_magic == FS_UFS2_MAGIC)
7282 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
7283 	if ((flags & IO_NORMAL) != 0) {
7284 		for (i = 0; i < UFS_NDADDR; i++)
7285 			setup_freedirect(freeblks, ip, i, 0);
7286 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
7287 		    i < UFS_NIADDR;
7288 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
7289 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
7290 		ip->i_size = 0;
7291 		DIP_SET(ip, i_size, 0);
7292 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7293 		datablocks = DIP(ip, i_blocks) - extblocks;
7294 	}
7295 	if ((flags & IO_EXT) != 0) {
7296 		for (i = 0; i < UFS_NXADDR; i++)
7297 			setup_freeext(freeblks, ip, i, 0);
7298 		ip->i_din2->di_extsize = 0;
7299 		datablocks += extblocks;
7300 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7301 	}
7302 #ifdef QUOTA
7303 	/* Reference the quotas in case the block count is wrong in the end. */
7304 	quotaref(ITOV(ip), freeblks->fb_quota);
7305 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7306 #endif
7307 	freeblks->fb_chkcnt = -datablocks;
7308 	UFS_LOCK(ump);
7309 	fs->fs_pendingblocks += datablocks;
7310 	UFS_UNLOCK(ump);
7311 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7312 	/*
7313 	 * Push the zero'ed inode to its disk buffer so that we are free
7314 	 * to delete its dependencies below. Once the dependencies are gone
7315 	 * the buffer can be safely released.
7316 	 */
7317 	if (ump->um_fstype == UFS1) {
7318 		dp1 = ((struct ufs1_dinode *)bp->b_data +
7319 		    ino_to_fsbo(fs, ip->i_number));
7320 		ip->i_din1->di_freelink = dp1->di_freelink;
7321 		*dp1 = *ip->i_din1;
7322 	} else {
7323 		dp2 = ((struct ufs2_dinode *)bp->b_data +
7324 		    ino_to_fsbo(fs, ip->i_number));
7325 		ip->i_din2->di_freelink = dp2->di_freelink;
7326 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7327 		*dp2 = *ip->i_din2;
7328 	}
7329 	/*
7330 	 * Find and eliminate any inode dependencies.
7331 	 */
7332 	ACQUIRE_LOCK(ump);
7333 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7334 	if ((inodedep->id_state & IOSTARTED) != 0)
7335 		panic("softdep_setup_freeblocks: inode busy");
7336 	/*
7337 	 * Add the freeblks structure to the list of operations that
7338 	 * must await the zero'ed inode being written to disk. If we
7339 	 * still have a bitmap dependency (delay == 0), then the inode
7340 	 * has never been written to disk, so we can process the
7341 	 * freeblks below once we have deleted the dependencies.
7342 	 */
7343 	delay = (inodedep->id_state & DEPCOMPLETE);
7344 	if (delay)
7345 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7346 	else
7347 		freeblks->fb_state |= COMPLETE;
7348 	/*
7349 	 * Because the file length has been truncated to zero, any
7350 	 * pending block allocation dependency structures associated
7351 	 * with this inode are obsolete and can simply be de-allocated.
7352 	 * We must first merge the two dependency lists to get rid of
7353 	 * any duplicate freefrag structures, then purge the merged list.
7354 	 * If we still have a bitmap dependency, then the inode has never
7355 	 * been written to disk, so we can free any fragments without delay.
7356 	 */
7357 	if (flags & IO_NORMAL) {
7358 		merge_inode_lists(&inodedep->id_newinoupdt,
7359 		    &inodedep->id_inoupdt);
7360 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7361 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7362 			    freeblks);
7363 	}
7364 	if (flags & IO_EXT) {
7365 		merge_inode_lists(&inodedep->id_newextupdt,
7366 		    &inodedep->id_extupdt);
7367 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7368 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7369 			    freeblks);
7370 	}
7371 	FREE_LOCK(ump);
7372 	bdwrite(bp);
7373 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7374 	ACQUIRE_LOCK(ump);
7375 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7376 		(void) free_inodedep(inodedep);
7377 	freeblks->fb_state |= DEPCOMPLETE;
7378 	/*
7379 	 * If the inode with zeroed block pointers is now on disk
7380 	 * we can start freeing blocks.
7381 	 */
7382 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7383 		freeblks->fb_state |= INPROGRESS;
7384 	else
7385 		freeblks = NULL;
7386 	FREE_LOCK(ump);
7387 	if (freeblks)
7388 		handle_workitem_freeblocks(freeblks, 0);
7389 	trunc_pages(ip, length, extblocks, flags);
7390 }
7391 
7392 /*
7393  * Eliminate pages from the page cache that back parts of this inode and
7394  * adjust the vnode pager's idea of our size.  This prevents stale data
7395  * from hanging around in the page cache.
7396  */
7397 static void
7398 trunc_pages(ip, length, extblocks, flags)
7399 	struct inode *ip;
7400 	off_t length;
7401 	ufs2_daddr_t extblocks;
7402 	int flags;
7403 {
7404 	struct vnode *vp;
7405 	struct fs *fs;
7406 	ufs_lbn_t lbn;
7407 	off_t end, extend;
7408 
7409 	vp = ITOV(ip);
7410 	fs = ITOFS(ip);
7411 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7412 	if ((flags & IO_EXT) != 0)
7413 		vn_pages_remove(vp, extend, 0);
7414 	if ((flags & IO_NORMAL) == 0)
7415 		return;
7416 	BO_LOCK(&vp->v_bufobj);
7417 	drain_output(vp);
7418 	BO_UNLOCK(&vp->v_bufobj);
7419 	/*
7420 	 * The vnode pager eliminates file pages we eliminate indirects
7421 	 * below.
7422 	 */
7423 	vnode_pager_setsize(vp, length);
7424 	/*
7425 	 * Calculate the end based on the last indirect we want to keep.  If
7426 	 * the block extends into indirects we can just use the negative of
7427 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7428 	 * be careful not to remove those, if they exist.  double and triple
7429 	 * indirect lbns do not overlap with others so it is not important
7430 	 * to verify how many levels are required.
7431 	 */
7432 	lbn = lblkno(fs, length);
7433 	if (lbn >= UFS_NDADDR) {
7434 		/* Calculate the virtual lbn of the triple indirect. */
7435 		lbn = -lbn - (UFS_NIADDR - 1);
7436 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7437 	} else
7438 		end = extend;
7439 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7440 }
7441 
7442 /*
7443  * See if the buf bp is in the range eliminated by truncation.
7444  */
7445 static int
7446 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7447 	struct buf *bp;
7448 	int *blkoffp;
7449 	ufs_lbn_t lastlbn;
7450 	int lastoff;
7451 	int flags;
7452 {
7453 	ufs_lbn_t lbn;
7454 
7455 	*blkoffp = 0;
7456 	/* Only match ext/normal blocks as appropriate. */
7457 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7458 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7459 		return (0);
7460 	/* ALTDATA is always a full truncation. */
7461 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7462 		return (1);
7463 	/* -1 is full truncation. */
7464 	if (lastlbn == -1)
7465 		return (1);
7466 	/*
7467 	 * If this is a partial truncate we only want those
7468 	 * blocks and indirect blocks that cover the range
7469 	 * we're after.
7470 	 */
7471 	lbn = bp->b_lblkno;
7472 	if (lbn < 0)
7473 		lbn = -(lbn + lbn_level(lbn));
7474 	if (lbn < lastlbn)
7475 		return (0);
7476 	/* Here we only truncate lblkno if it's partial. */
7477 	if (lbn == lastlbn) {
7478 		if (lastoff == 0)
7479 			return (0);
7480 		*blkoffp = lastoff;
7481 	}
7482 	return (1);
7483 }
7484 
7485 /*
7486  * Eliminate any dependencies that exist in memory beyond lblkno:off
7487  */
7488 static void
7489 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7490 	struct inode *ip;
7491 	struct freeblks *freeblks;
7492 	ufs_lbn_t lastlbn;
7493 	int lastoff;
7494 	int flags;
7495 {
7496 	struct bufobj *bo;
7497 	struct vnode *vp;
7498 	struct buf *bp;
7499 	int blkoff;
7500 
7501 	/*
7502 	 * We must wait for any I/O in progress to finish so that
7503 	 * all potential buffers on the dirty list will be visible.
7504 	 * Once they are all there, walk the list and get rid of
7505 	 * any dependencies.
7506 	 */
7507 	vp = ITOV(ip);
7508 	bo = &vp->v_bufobj;
7509 	BO_LOCK(bo);
7510 	drain_output(vp);
7511 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7512 		bp->b_vflags &= ~BV_SCANNED;
7513 restart:
7514 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7515 		if (bp->b_vflags & BV_SCANNED)
7516 			continue;
7517 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7518 			bp->b_vflags |= BV_SCANNED;
7519 			continue;
7520 		}
7521 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7522 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7523 			goto restart;
7524 		BO_UNLOCK(bo);
7525 		if (deallocate_dependencies(bp, freeblks, blkoff))
7526 			bqrelse(bp);
7527 		else
7528 			brelse(bp);
7529 		BO_LOCK(bo);
7530 		goto restart;
7531 	}
7532 	/*
7533 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7534 	 */
7535 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7536 		bp->b_vflags &= ~BV_SCANNED;
7537 cleanrestart:
7538 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7539 		if (bp->b_vflags & BV_SCANNED)
7540 			continue;
7541 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7542 			bp->b_vflags |= BV_SCANNED;
7543 			continue;
7544 		}
7545 		if (BUF_LOCK(bp,
7546 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7547 		    BO_LOCKPTR(bo)) == ENOLCK) {
7548 			BO_LOCK(bo);
7549 			goto cleanrestart;
7550 		}
7551 		bp->b_vflags |= BV_SCANNED;
7552 		bremfree(bp);
7553 		if (blkoff != 0) {
7554 			allocbuf(bp, blkoff);
7555 			bqrelse(bp);
7556 		} else {
7557 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7558 			brelse(bp);
7559 		}
7560 		BO_LOCK(bo);
7561 		goto cleanrestart;
7562 	}
7563 	drain_output(vp);
7564 	BO_UNLOCK(bo);
7565 }
7566 
7567 static int
7568 cancel_pagedep(pagedep, freeblks, blkoff)
7569 	struct pagedep *pagedep;
7570 	struct freeblks *freeblks;
7571 	int blkoff;
7572 {
7573 	struct jremref *jremref;
7574 	struct jmvref *jmvref;
7575 	struct dirrem *dirrem, *tmp;
7576 	int i;
7577 
7578 	/*
7579 	 * Copy any directory remove dependencies to the list
7580 	 * to be processed after the freeblks proceeds.  If
7581 	 * directory entry never made it to disk they
7582 	 * can be dumped directly onto the work list.
7583 	 */
7584 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7585 		/* Skip this directory removal if it is intended to remain. */
7586 		if (dirrem->dm_offset < blkoff)
7587 			continue;
7588 		/*
7589 		 * If there are any dirrems we wait for the journal write
7590 		 * to complete and then restart the buf scan as the lock
7591 		 * has been dropped.
7592 		 */
7593 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7594 			jwait(&jremref->jr_list, MNT_WAIT);
7595 			return (ERESTART);
7596 		}
7597 		LIST_REMOVE(dirrem, dm_next);
7598 		dirrem->dm_dirinum = pagedep->pd_ino;
7599 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7600 	}
7601 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7602 		jwait(&jmvref->jm_list, MNT_WAIT);
7603 		return (ERESTART);
7604 	}
7605 	/*
7606 	 * When we're partially truncating a pagedep we just want to flush
7607 	 * journal entries and return.  There can not be any adds in the
7608 	 * truncated portion of the directory and newblk must remain if
7609 	 * part of the block remains.
7610 	 */
7611 	if (blkoff != 0) {
7612 		struct diradd *dap;
7613 
7614 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7615 			if (dap->da_offset > blkoff)
7616 				panic("cancel_pagedep: diradd %p off %d > %d",
7617 				    dap, dap->da_offset, blkoff);
7618 		for (i = 0; i < DAHASHSZ; i++)
7619 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7620 				if (dap->da_offset > blkoff)
7621 					panic("cancel_pagedep: diradd %p off %d > %d",
7622 					    dap, dap->da_offset, blkoff);
7623 		return (0);
7624 	}
7625 	/*
7626 	 * There should be no directory add dependencies present
7627 	 * as the directory could not be truncated until all
7628 	 * children were removed.
7629 	 */
7630 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7631 	    ("deallocate_dependencies: pendinghd != NULL"));
7632 	for (i = 0; i < DAHASHSZ; i++)
7633 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7634 		    ("deallocate_dependencies: diraddhd != NULL"));
7635 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7636 		free_newdirblk(pagedep->pd_newdirblk);
7637 	if (free_pagedep(pagedep) == 0)
7638 		panic("Failed to free pagedep %p", pagedep);
7639 	return (0);
7640 }
7641 
7642 /*
7643  * Reclaim any dependency structures from a buffer that is about to
7644  * be reallocated to a new vnode. The buffer must be locked, thus,
7645  * no I/O completion operations can occur while we are manipulating
7646  * its associated dependencies. The mutex is held so that other I/O's
7647  * associated with related dependencies do not occur.
7648  */
7649 static int
7650 deallocate_dependencies(bp, freeblks, off)
7651 	struct buf *bp;
7652 	struct freeblks *freeblks;
7653 	int off;
7654 {
7655 	struct indirdep *indirdep;
7656 	struct pagedep *pagedep;
7657 	struct worklist *wk, *wkn;
7658 	struct ufsmount *ump;
7659 
7660 	ump = softdep_bp_to_mp(bp);
7661 	if (ump == NULL)
7662 		goto done;
7663 	ACQUIRE_LOCK(ump);
7664 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7665 		switch (wk->wk_type) {
7666 		case D_INDIRDEP:
7667 			indirdep = WK_INDIRDEP(wk);
7668 			if (bp->b_lblkno >= 0 ||
7669 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7670 				panic("deallocate_dependencies: not indir");
7671 			cancel_indirdep(indirdep, bp, freeblks);
7672 			continue;
7673 
7674 		case D_PAGEDEP:
7675 			pagedep = WK_PAGEDEP(wk);
7676 			if (cancel_pagedep(pagedep, freeblks, off)) {
7677 				FREE_LOCK(ump);
7678 				return (ERESTART);
7679 			}
7680 			continue;
7681 
7682 		case D_ALLOCINDIR:
7683 			/*
7684 			 * Simply remove the allocindir, we'll find it via
7685 			 * the indirdep where we can clear pointers if
7686 			 * needed.
7687 			 */
7688 			WORKLIST_REMOVE(wk);
7689 			continue;
7690 
7691 		case D_FREEWORK:
7692 			/*
7693 			 * A truncation is waiting for the zero'd pointers
7694 			 * to be written.  It can be freed when the freeblks
7695 			 * is journaled.
7696 			 */
7697 			WORKLIST_REMOVE(wk);
7698 			wk->wk_state |= ONDEPLIST;
7699 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7700 			break;
7701 
7702 		case D_ALLOCDIRECT:
7703 			if (off != 0)
7704 				continue;
7705 			/* FALLTHROUGH */
7706 		default:
7707 			panic("deallocate_dependencies: Unexpected type %s",
7708 			    TYPENAME(wk->wk_type));
7709 			/* NOTREACHED */
7710 		}
7711 	}
7712 	FREE_LOCK(ump);
7713 done:
7714 	/*
7715 	 * Don't throw away this buf, we were partially truncating and
7716 	 * some deps may always remain.
7717 	 */
7718 	if (off) {
7719 		allocbuf(bp, off);
7720 		bp->b_vflags |= BV_SCANNED;
7721 		return (EBUSY);
7722 	}
7723 	bp->b_flags |= B_INVAL | B_NOCACHE;
7724 
7725 	return (0);
7726 }
7727 
7728 /*
7729  * An allocdirect is being canceled due to a truncate.  We must make sure
7730  * the journal entry is released in concert with the blkfree that releases
7731  * the storage.  Completed journal entries must not be released until the
7732  * space is no longer pointed to by the inode or in the bitmap.
7733  */
7734 static void
7735 cancel_allocdirect(adphead, adp, freeblks)
7736 	struct allocdirectlst *adphead;
7737 	struct allocdirect *adp;
7738 	struct freeblks *freeblks;
7739 {
7740 	struct freework *freework;
7741 	struct newblk *newblk;
7742 	struct worklist *wk;
7743 
7744 	TAILQ_REMOVE(adphead, adp, ad_next);
7745 	newblk = (struct newblk *)adp;
7746 	freework = NULL;
7747 	/*
7748 	 * Find the correct freework structure.
7749 	 */
7750 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7751 		if (wk->wk_type != D_FREEWORK)
7752 			continue;
7753 		freework = WK_FREEWORK(wk);
7754 		if (freework->fw_blkno == newblk->nb_newblkno)
7755 			break;
7756 	}
7757 	if (freework == NULL)
7758 		panic("cancel_allocdirect: Freework not found");
7759 	/*
7760 	 * If a newblk exists at all we still have the journal entry that
7761 	 * initiated the allocation so we do not need to journal the free.
7762 	 */
7763 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7764 	/*
7765 	 * If the journal hasn't been written the jnewblk must be passed
7766 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7767 	 * this by linking the journal dependency into the freework to be
7768 	 * freed when freework_freeblock() is called.  If the journal has
7769 	 * been written we can simply reclaim the journal space when the
7770 	 * freeblks work is complete.
7771 	 */
7772 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7773 	    &freeblks->fb_jwork);
7774 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7775 }
7776 
7777 /*
7778  * Cancel a new block allocation.  May be an indirect or direct block.  We
7779  * remove it from various lists and return any journal record that needs to
7780  * be resolved by the caller.
7781  *
7782  * A special consideration is made for indirects which were never pointed
7783  * at on disk and will never be found once this block is released.
7784  */
7785 static struct jnewblk *
7786 cancel_newblk(newblk, wk, wkhd)
7787 	struct newblk *newblk;
7788 	struct worklist *wk;
7789 	struct workhead *wkhd;
7790 {
7791 	struct jnewblk *jnewblk;
7792 
7793 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7794 
7795 	newblk->nb_state |= GOINGAWAY;
7796 	/*
7797 	 * Previously we traversed the completedhd on each indirdep
7798 	 * attached to this newblk to cancel them and gather journal
7799 	 * work.  Since we need only the oldest journal segment and
7800 	 * the lowest point on the tree will always have the oldest
7801 	 * journal segment we are free to release the segments
7802 	 * of any subordinates and may leave the indirdep list to
7803 	 * indirdep_complete() when this newblk is freed.
7804 	 */
7805 	if (newblk->nb_state & ONDEPLIST) {
7806 		newblk->nb_state &= ~ONDEPLIST;
7807 		LIST_REMOVE(newblk, nb_deps);
7808 	}
7809 	if (newblk->nb_state & ONWORKLIST)
7810 		WORKLIST_REMOVE(&newblk->nb_list);
7811 	/*
7812 	 * If the journal entry hasn't been written we save a pointer to
7813 	 * the dependency that frees it until it is written or the
7814 	 * superseding operation completes.
7815 	 */
7816 	jnewblk = newblk->nb_jnewblk;
7817 	if (jnewblk != NULL && wk != NULL) {
7818 		newblk->nb_jnewblk = NULL;
7819 		jnewblk->jn_dep = wk;
7820 	}
7821 	if (!LIST_EMPTY(&newblk->nb_jwork))
7822 		jwork_move(wkhd, &newblk->nb_jwork);
7823 	/*
7824 	 * When truncating we must free the newdirblk early to remove
7825 	 * the pagedep from the hash before returning.
7826 	 */
7827 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7828 		free_newdirblk(WK_NEWDIRBLK(wk));
7829 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7830 		panic("cancel_newblk: extra newdirblk");
7831 
7832 	return (jnewblk);
7833 }
7834 
7835 /*
7836  * Schedule the freefrag associated with a newblk to be released once
7837  * the pointers are written and the previous block is no longer needed.
7838  */
7839 static void
7840 newblk_freefrag(newblk)
7841 	struct newblk *newblk;
7842 {
7843 	struct freefrag *freefrag;
7844 
7845 	if (newblk->nb_freefrag == NULL)
7846 		return;
7847 	freefrag = newblk->nb_freefrag;
7848 	newblk->nb_freefrag = NULL;
7849 	freefrag->ff_state |= COMPLETE;
7850 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7851 		add_to_worklist(&freefrag->ff_list, 0);
7852 }
7853 
7854 /*
7855  * Free a newblk. Generate a new freefrag work request if appropriate.
7856  * This must be called after the inode pointer and any direct block pointers
7857  * are valid or fully removed via truncate or frag extension.
7858  */
7859 static void
7860 free_newblk(newblk)
7861 	struct newblk *newblk;
7862 {
7863 	struct indirdep *indirdep;
7864 	struct worklist *wk;
7865 
7866 	KASSERT(newblk->nb_jnewblk == NULL,
7867 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7868 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7869 	    ("free_newblk: unclaimed newblk"));
7870 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7871 	newblk_freefrag(newblk);
7872 	if (newblk->nb_state & ONDEPLIST)
7873 		LIST_REMOVE(newblk, nb_deps);
7874 	if (newblk->nb_state & ONWORKLIST)
7875 		WORKLIST_REMOVE(&newblk->nb_list);
7876 	LIST_REMOVE(newblk, nb_hash);
7877 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7878 		free_newdirblk(WK_NEWDIRBLK(wk));
7879 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7880 		panic("free_newblk: extra newdirblk");
7881 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7882 		indirdep_complete(indirdep);
7883 	handle_jwork(&newblk->nb_jwork);
7884 	WORKITEM_FREE(newblk, D_NEWBLK);
7885 }
7886 
7887 /*
7888  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7889  */
7890 static void
7891 free_newdirblk(newdirblk)
7892 	struct newdirblk *newdirblk;
7893 {
7894 	struct pagedep *pagedep;
7895 	struct diradd *dap;
7896 	struct worklist *wk;
7897 
7898 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7899 	WORKLIST_REMOVE(&newdirblk->db_list);
7900 	/*
7901 	 * If the pagedep is still linked onto the directory buffer
7902 	 * dependency chain, then some of the entries on the
7903 	 * pd_pendinghd list may not be committed to disk yet. In
7904 	 * this case, we will simply clear the NEWBLOCK flag and
7905 	 * let the pd_pendinghd list be processed when the pagedep
7906 	 * is next written. If the pagedep is no longer on the buffer
7907 	 * dependency chain, then all the entries on the pd_pending
7908 	 * list are committed to disk and we can free them here.
7909 	 */
7910 	pagedep = newdirblk->db_pagedep;
7911 	pagedep->pd_state &= ~NEWBLOCK;
7912 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7913 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7914 			free_diradd(dap, NULL);
7915 		/*
7916 		 * If no dependencies remain, the pagedep will be freed.
7917 		 */
7918 		free_pagedep(pagedep);
7919 	}
7920 	/* Should only ever be one item in the list. */
7921 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7922 		WORKLIST_REMOVE(wk);
7923 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7924 	}
7925 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7926 }
7927 
7928 /*
7929  * Prepare an inode to be freed. The actual free operation is not
7930  * done until the zero'ed inode has been written to disk.
7931  */
7932 void
7933 softdep_freefile(pvp, ino, mode)
7934 	struct vnode *pvp;
7935 	ino_t ino;
7936 	int mode;
7937 {
7938 	struct inode *ip = VTOI(pvp);
7939 	struct inodedep *inodedep;
7940 	struct freefile *freefile;
7941 	struct freeblks *freeblks;
7942 	struct ufsmount *ump;
7943 
7944 	ump = ITOUMP(ip);
7945 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7946 	    ("softdep_freefile called on non-softdep filesystem"));
7947 	/*
7948 	 * This sets up the inode de-allocation dependency.
7949 	 */
7950 	freefile = malloc(sizeof(struct freefile),
7951 		M_FREEFILE, M_SOFTDEP_FLAGS);
7952 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7953 	freefile->fx_mode = mode;
7954 	freefile->fx_oldinum = ino;
7955 	freefile->fx_devvp = ump->um_devvp;
7956 	LIST_INIT(&freefile->fx_jwork);
7957 	UFS_LOCK(ump);
7958 	ump->um_fs->fs_pendinginodes += 1;
7959 	UFS_UNLOCK(ump);
7960 
7961 	/*
7962 	 * If the inodedep does not exist, then the zero'ed inode has
7963 	 * been written to disk. If the allocated inode has never been
7964 	 * written to disk, then the on-disk inode is zero'ed. In either
7965 	 * case we can free the file immediately.  If the journal was
7966 	 * canceled before being written the inode will never make it to
7967 	 * disk and we must send the canceled journal entrys to
7968 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7969 	 * Any blocks waiting on the inode to write can be safely freed
7970 	 * here as it will never been written.
7971 	 */
7972 	ACQUIRE_LOCK(ump);
7973 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7974 	if (inodedep) {
7975 		/*
7976 		 * Clear out freeblks that no longer need to reference
7977 		 * this inode.
7978 		 */
7979 		while ((freeblks =
7980 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7981 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7982 			    fb_next);
7983 			freeblks->fb_state &= ~ONDEPLIST;
7984 		}
7985 		/*
7986 		 * Remove this inode from the unlinked list.
7987 		 */
7988 		if (inodedep->id_state & UNLINKED) {
7989 			/*
7990 			 * Save the journal work to be freed with the bitmap
7991 			 * before we clear UNLINKED.  Otherwise it can be lost
7992 			 * if the inode block is written.
7993 			 */
7994 			handle_bufwait(inodedep, &freefile->fx_jwork);
7995 			clear_unlinked_inodedep(inodedep);
7996 			/*
7997 			 * Re-acquire inodedep as we've dropped the
7998 			 * per-filesystem lock in clear_unlinked_inodedep().
7999 			 */
8000 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
8001 		}
8002 	}
8003 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
8004 		FREE_LOCK(ump);
8005 		handle_workitem_freefile(freefile);
8006 		return;
8007 	}
8008 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
8009 		inodedep->id_state |= GOINGAWAY;
8010 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
8011 	FREE_LOCK(ump);
8012 	if (ip->i_number == ino)
8013 		UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
8014 }
8015 
8016 /*
8017  * Check to see if an inode has never been written to disk. If
8018  * so free the inodedep and return success, otherwise return failure.
8019  *
8020  * If we still have a bitmap dependency, then the inode has never
8021  * been written to disk. Drop the dependency as it is no longer
8022  * necessary since the inode is being deallocated. We set the
8023  * ALLCOMPLETE flags since the bitmap now properly shows that the
8024  * inode is not allocated. Even if the inode is actively being
8025  * written, it has been rolled back to its zero'ed state, so we
8026  * are ensured that a zero inode is what is on the disk. For short
8027  * lived files, this change will usually result in removing all the
8028  * dependencies from the inode so that it can be freed immediately.
8029  */
8030 static int
8031 check_inode_unwritten(inodedep)
8032 	struct inodedep *inodedep;
8033 {
8034 
8035 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8036 
8037 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
8038 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
8039 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
8040 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
8041 	    !LIST_EMPTY(&inodedep->id_inowait) ||
8042 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
8043 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
8044 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
8045 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
8046 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
8047 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
8048 	    inodedep->id_mkdiradd != NULL ||
8049 	    inodedep->id_nlinkdelta != 0)
8050 		return (0);
8051 	/*
8052 	 * Another process might be in initiate_write_inodeblock_ufs[12]
8053 	 * trying to allocate memory without holding "Softdep Lock".
8054 	 */
8055 	if ((inodedep->id_state & IOSTARTED) != 0 &&
8056 	    inodedep->id_savedino1 == NULL)
8057 		return (0);
8058 
8059 	if (inodedep->id_state & ONDEPLIST)
8060 		LIST_REMOVE(inodedep, id_deps);
8061 	inodedep->id_state &= ~ONDEPLIST;
8062 	inodedep->id_state |= ALLCOMPLETE;
8063 	inodedep->id_bmsafemap = NULL;
8064 	if (inodedep->id_state & ONWORKLIST)
8065 		WORKLIST_REMOVE(&inodedep->id_list);
8066 	if (inodedep->id_savedino1 != NULL) {
8067 		free(inodedep->id_savedino1, M_SAVEDINO);
8068 		inodedep->id_savedino1 = NULL;
8069 	}
8070 	if (free_inodedep(inodedep) == 0)
8071 		panic("check_inode_unwritten: busy inode");
8072 	return (1);
8073 }
8074 
8075 static int
8076 check_inodedep_free(inodedep)
8077 	struct inodedep *inodedep;
8078 {
8079 
8080 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8081 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
8082 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
8083 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
8084 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
8085 	    !LIST_EMPTY(&inodedep->id_inowait) ||
8086 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
8087 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
8088 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
8089 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
8090 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
8091 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
8092 	    inodedep->id_mkdiradd != NULL ||
8093 	    inodedep->id_nlinkdelta != 0 ||
8094 	    inodedep->id_savedino1 != NULL)
8095 		return (0);
8096 	return (1);
8097 }
8098 
8099 /*
8100  * Try to free an inodedep structure. Return 1 if it could be freed.
8101  */
8102 static int
8103 free_inodedep(inodedep)
8104 	struct inodedep *inodedep;
8105 {
8106 
8107 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8108 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
8109 	    !check_inodedep_free(inodedep))
8110 		return (0);
8111 	if (inodedep->id_state & ONDEPLIST)
8112 		LIST_REMOVE(inodedep, id_deps);
8113 	LIST_REMOVE(inodedep, id_hash);
8114 	WORKITEM_FREE(inodedep, D_INODEDEP);
8115 	return (1);
8116 }
8117 
8118 /*
8119  * Free the block referenced by a freework structure.  The parent freeblks
8120  * structure is released and completed when the final cg bitmap reaches
8121  * the disk.  This routine may be freeing a jnewblk which never made it to
8122  * disk in which case we do not have to wait as the operation is undone
8123  * in memory immediately.
8124  */
8125 static void
8126 freework_freeblock(freework, key)
8127 	struct freework *freework;
8128 	u_long key;
8129 {
8130 	struct freeblks *freeblks;
8131 	struct jnewblk *jnewblk;
8132 	struct ufsmount *ump;
8133 	struct workhead wkhd;
8134 	struct fs *fs;
8135 	int bsize;
8136 	int needj;
8137 
8138 	ump = VFSTOUFS(freework->fw_list.wk_mp);
8139 	LOCK_OWNED(ump);
8140 	/*
8141 	 * Handle partial truncate separately.
8142 	 */
8143 	if (freework->fw_indir) {
8144 		complete_trunc_indir(freework);
8145 		return;
8146 	}
8147 	freeblks = freework->fw_freeblks;
8148 	fs = ump->um_fs;
8149 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
8150 	bsize = lfragtosize(fs, freework->fw_frags);
8151 	LIST_INIT(&wkhd);
8152 	/*
8153 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
8154 	 * on the indirblk hashtable and prevents premature freeing.
8155 	 */
8156 	freework->fw_state |= DEPCOMPLETE;
8157 	/*
8158 	 * SUJ needs to wait for the segment referencing freed indirect
8159 	 * blocks to expire so that we know the checker will not confuse
8160 	 * a re-allocated indirect block with its old contents.
8161 	 */
8162 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
8163 		indirblk_insert(freework);
8164 	/*
8165 	 * If we are canceling an existing jnewblk pass it to the free
8166 	 * routine, otherwise pass the freeblk which will ultimately
8167 	 * release the freeblks.  If we're not journaling, we can just
8168 	 * free the freeblks immediately.
8169 	 */
8170 	jnewblk = freework->fw_jnewblk;
8171 	if (jnewblk != NULL) {
8172 		cancel_jnewblk(jnewblk, &wkhd);
8173 		needj = 0;
8174 	} else if (needj) {
8175 		freework->fw_state |= DELAYEDFREE;
8176 		freeblks->fb_cgwait++;
8177 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
8178 	}
8179 	FREE_LOCK(ump);
8180 	freeblks_free(ump, freeblks, btodb(bsize));
8181 	CTR4(KTR_SUJ,
8182 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
8183 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
8184 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
8185 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
8186 	ACQUIRE_LOCK(ump);
8187 	/*
8188 	 * The jnewblk will be discarded and the bits in the map never
8189 	 * made it to disk.  We can immediately free the freeblk.
8190 	 */
8191 	if (needj == 0)
8192 		handle_written_freework(freework);
8193 }
8194 
8195 /*
8196  * We enqueue freework items that need processing back on the freeblks and
8197  * add the freeblks to the worklist.  This makes it easier to find all work
8198  * required to flush a truncation in process_truncates().
8199  */
8200 static void
8201 freework_enqueue(freework)
8202 	struct freework *freework;
8203 {
8204 	struct freeblks *freeblks;
8205 
8206 	freeblks = freework->fw_freeblks;
8207 	if ((freework->fw_state & INPROGRESS) == 0)
8208 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
8209 	if ((freeblks->fb_state &
8210 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
8211 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
8212 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8213 }
8214 
8215 /*
8216  * Start, continue, or finish the process of freeing an indirect block tree.
8217  * The free operation may be paused at any point with fw_off containing the
8218  * offset to restart from.  This enables us to implement some flow control
8219  * for large truncates which may fan out and generate a huge number of
8220  * dependencies.
8221  */
8222 static void
8223 handle_workitem_indirblk(freework)
8224 	struct freework *freework;
8225 {
8226 	struct freeblks *freeblks;
8227 	struct ufsmount *ump;
8228 	struct fs *fs;
8229 
8230 	freeblks = freework->fw_freeblks;
8231 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8232 	fs = ump->um_fs;
8233 	if (freework->fw_state & DEPCOMPLETE) {
8234 		handle_written_freework(freework);
8235 		return;
8236 	}
8237 	if (freework->fw_off == NINDIR(fs)) {
8238 		freework_freeblock(freework, SINGLETON_KEY);
8239 		return;
8240 	}
8241 	freework->fw_state |= INPROGRESS;
8242 	FREE_LOCK(ump);
8243 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
8244 	    freework->fw_lbn);
8245 	ACQUIRE_LOCK(ump);
8246 }
8247 
8248 /*
8249  * Called when a freework structure attached to a cg buf is written.  The
8250  * ref on either the parent or the freeblks structure is released and
8251  * the freeblks is added back to the worklist if there is more work to do.
8252  */
8253 static void
8254 handle_written_freework(freework)
8255 	struct freework *freework;
8256 {
8257 	struct freeblks *freeblks;
8258 	struct freework *parent;
8259 
8260 	freeblks = freework->fw_freeblks;
8261 	parent = freework->fw_parent;
8262 	if (freework->fw_state & DELAYEDFREE)
8263 		freeblks->fb_cgwait--;
8264 	freework->fw_state |= COMPLETE;
8265 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
8266 		WORKITEM_FREE(freework, D_FREEWORK);
8267 	if (parent) {
8268 		if (--parent->fw_ref == 0)
8269 			freework_enqueue(parent);
8270 		return;
8271 	}
8272 	if (--freeblks->fb_ref != 0)
8273 		return;
8274 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
8275 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
8276 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8277 }
8278 
8279 /*
8280  * This workitem routine performs the block de-allocation.
8281  * The workitem is added to the pending list after the updated
8282  * inode block has been written to disk.  As mentioned above,
8283  * checks regarding the number of blocks de-allocated (compared
8284  * to the number of blocks allocated for the file) are also
8285  * performed in this function.
8286  */
8287 static int
8288 handle_workitem_freeblocks(freeblks, flags)
8289 	struct freeblks *freeblks;
8290 	int flags;
8291 {
8292 	struct freework *freework;
8293 	struct newblk *newblk;
8294 	struct allocindir *aip;
8295 	struct ufsmount *ump;
8296 	struct worklist *wk;
8297 	u_long key;
8298 
8299 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
8300 	    ("handle_workitem_freeblocks: Journal entries not written."));
8301 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8302 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8303 	ACQUIRE_LOCK(ump);
8304 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
8305 		WORKLIST_REMOVE(wk);
8306 		switch (wk->wk_type) {
8307 		case D_DIRREM:
8308 			wk->wk_state |= COMPLETE;
8309 			add_to_worklist(wk, 0);
8310 			continue;
8311 
8312 		case D_ALLOCDIRECT:
8313 			free_newblk(WK_NEWBLK(wk));
8314 			continue;
8315 
8316 		case D_ALLOCINDIR:
8317 			aip = WK_ALLOCINDIR(wk);
8318 			freework = NULL;
8319 			if (aip->ai_state & DELAYEDFREE) {
8320 				FREE_LOCK(ump);
8321 				freework = newfreework(ump, freeblks, NULL,
8322 				    aip->ai_lbn, aip->ai_newblkno,
8323 				    ump->um_fs->fs_frag, 0, 0);
8324 				ACQUIRE_LOCK(ump);
8325 			}
8326 			newblk = WK_NEWBLK(wk);
8327 			if (newblk->nb_jnewblk) {
8328 				freework->fw_jnewblk = newblk->nb_jnewblk;
8329 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
8330 				newblk->nb_jnewblk = NULL;
8331 			}
8332 			free_newblk(newblk);
8333 			continue;
8334 
8335 		case D_FREEWORK:
8336 			freework = WK_FREEWORK(wk);
8337 			if (freework->fw_lbn <= -UFS_NDADDR)
8338 				handle_workitem_indirblk(freework);
8339 			else
8340 				freework_freeblock(freework, key);
8341 			continue;
8342 		default:
8343 			panic("handle_workitem_freeblocks: Unknown type %s",
8344 			    TYPENAME(wk->wk_type));
8345 		}
8346 	}
8347 	if (freeblks->fb_ref != 0) {
8348 		freeblks->fb_state &= ~INPROGRESS;
8349 		wake_worklist(&freeblks->fb_list);
8350 		freeblks = NULL;
8351 	}
8352 	FREE_LOCK(ump);
8353 	ffs_blkrelease_finish(ump, key);
8354 	if (freeblks)
8355 		return handle_complete_freeblocks(freeblks, flags);
8356 	return (0);
8357 }
8358 
8359 /*
8360  * Handle completion of block free via truncate.  This allows fs_pending
8361  * to track the actual free block count more closely than if we only updated
8362  * it at the end.  We must be careful to handle cases where the block count
8363  * on free was incorrect.
8364  */
8365 static void
8366 freeblks_free(ump, freeblks, blocks)
8367 	struct ufsmount *ump;
8368 	struct freeblks *freeblks;
8369 	int blocks;
8370 {
8371 	struct fs *fs;
8372 	ufs2_daddr_t remain;
8373 
8374 	UFS_LOCK(ump);
8375 	remain = -freeblks->fb_chkcnt;
8376 	freeblks->fb_chkcnt += blocks;
8377 	if (remain > 0) {
8378 		if (remain < blocks)
8379 			blocks = remain;
8380 		fs = ump->um_fs;
8381 		fs->fs_pendingblocks -= blocks;
8382 	}
8383 	UFS_UNLOCK(ump);
8384 }
8385 
8386 /*
8387  * Once all of the freework workitems are complete we can retire the
8388  * freeblocks dependency and any journal work awaiting completion.  This
8389  * can not be called until all other dependencies are stable on disk.
8390  */
8391 static int
8392 handle_complete_freeblocks(freeblks, flags)
8393 	struct freeblks *freeblks;
8394 	int flags;
8395 {
8396 	struct inodedep *inodedep;
8397 	struct inode *ip;
8398 	struct vnode *vp;
8399 	struct fs *fs;
8400 	struct ufsmount *ump;
8401 	ufs2_daddr_t spare;
8402 
8403 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8404 	fs = ump->um_fs;
8405 	flags = LK_EXCLUSIVE | flags;
8406 	spare = freeblks->fb_chkcnt;
8407 
8408 	/*
8409 	 * If we did not release the expected number of blocks we may have
8410 	 * to adjust the inode block count here.  Only do so if it wasn't
8411 	 * a truncation to zero and the modrev still matches.
8412 	 */
8413 	if (spare && freeblks->fb_len != 0) {
8414 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8415 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8416 			return (EBUSY);
8417 		ip = VTOI(vp);
8418 		if (ip->i_mode == 0) {
8419 			vgone(vp);
8420 		} else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8421 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8422 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8423 			/*
8424 			 * We must wait so this happens before the
8425 			 * journal is reclaimed.
8426 			 */
8427 			ffs_update(vp, 1);
8428 		}
8429 		vput(vp);
8430 	}
8431 	if (spare < 0) {
8432 		UFS_LOCK(ump);
8433 		fs->fs_pendingblocks += spare;
8434 		UFS_UNLOCK(ump);
8435 	}
8436 #ifdef QUOTA
8437 	/* Handle spare. */
8438 	if (spare)
8439 		quotaadj(freeblks->fb_quota, ump, -spare);
8440 	quotarele(freeblks->fb_quota);
8441 #endif
8442 	ACQUIRE_LOCK(ump);
8443 	if (freeblks->fb_state & ONDEPLIST) {
8444 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8445 		    0, &inodedep);
8446 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8447 		freeblks->fb_state &= ~ONDEPLIST;
8448 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8449 			free_inodedep(inodedep);
8450 	}
8451 	/*
8452 	 * All of the freeblock deps must be complete prior to this call
8453 	 * so it's now safe to complete earlier outstanding journal entries.
8454 	 */
8455 	handle_jwork(&freeblks->fb_jwork);
8456 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8457 	FREE_LOCK(ump);
8458 	return (0);
8459 }
8460 
8461 /*
8462  * Release blocks associated with the freeblks and stored in the indirect
8463  * block dbn. If level is greater than SINGLE, the block is an indirect block
8464  * and recursive calls to indirtrunc must be used to cleanse other indirect
8465  * blocks.
8466  *
8467  * This handles partial and complete truncation of blocks.  Partial is noted
8468  * with goingaway == 0.  In this case the freework is completed after the
8469  * zero'd indirects are written to disk.  For full truncation the freework
8470  * is completed after the block is freed.
8471  */
8472 static void
8473 indir_trunc(freework, dbn, lbn)
8474 	struct freework *freework;
8475 	ufs2_daddr_t dbn;
8476 	ufs_lbn_t lbn;
8477 {
8478 	struct freework *nfreework;
8479 	struct workhead wkhd;
8480 	struct freeblks *freeblks;
8481 	struct buf *bp;
8482 	struct fs *fs;
8483 	struct indirdep *indirdep;
8484 	struct mount *mp;
8485 	struct ufsmount *ump;
8486 	ufs1_daddr_t *bap1;
8487 	ufs2_daddr_t nb, nnb, *bap2;
8488 	ufs_lbn_t lbnadd, nlbn;
8489 	u_long key;
8490 	int nblocks, ufs1fmt, freedblocks;
8491 	int goingaway, freedeps, needj, level, cnt, i, error;
8492 
8493 	freeblks = freework->fw_freeblks;
8494 	mp = freeblks->fb_list.wk_mp;
8495 	ump = VFSTOUFS(mp);
8496 	fs = ump->um_fs;
8497 	/*
8498 	 * Get buffer of block pointers to be freed.  There are three cases:
8499 	 *
8500 	 * 1) Partial truncate caches the indirdep pointer in the freework
8501 	 *    which provides us a back copy to the save bp which holds the
8502 	 *    pointers we want to clear.  When this completes the zero
8503 	 *    pointers are written to the real copy.
8504 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8505 	 *    eliminated the real copy and placed the indirdep on the saved
8506 	 *    copy.  The indirdep and buf are discarded when this completes.
8507 	 * 3) The indirect was not in memory, we read a copy off of the disk
8508 	 *    using the devvp and drop and invalidate the buffer when we're
8509 	 *    done.
8510 	 */
8511 	goingaway = 1;
8512 	indirdep = NULL;
8513 	if (freework->fw_indir != NULL) {
8514 		goingaway = 0;
8515 		indirdep = freework->fw_indir;
8516 		bp = indirdep->ir_savebp;
8517 		if (bp == NULL || bp->b_blkno != dbn)
8518 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8519 			    bp, (intmax_t)dbn);
8520 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8521 		/*
8522 		 * The lock prevents the buf dep list from changing and
8523 	 	 * indirects on devvp should only ever have one dependency.
8524 		 */
8525 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8526 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8527 			panic("indir_trunc: Bad indirdep %p from buf %p",
8528 			    indirdep, bp);
8529 	} else {
8530 		error = ffs_breadz(ump, freeblks->fb_devvp, dbn, dbn,
8531 		    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
8532 		if (error)
8533 			return;
8534 	}
8535 	ACQUIRE_LOCK(ump);
8536 	/* Protects against a race with complete_trunc_indir(). */
8537 	freework->fw_state &= ~INPROGRESS;
8538 	/*
8539 	 * If we have an indirdep we need to enforce the truncation order
8540 	 * and discard it when it is complete.
8541 	 */
8542 	if (indirdep) {
8543 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8544 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8545 			/*
8546 			 * Add the complete truncate to the list on the
8547 			 * indirdep to enforce in-order processing.
8548 			 */
8549 			if (freework->fw_indir == NULL)
8550 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8551 				    freework, fw_next);
8552 			FREE_LOCK(ump);
8553 			return;
8554 		}
8555 		/*
8556 		 * If we're goingaway, free the indirdep.  Otherwise it will
8557 		 * linger until the write completes.
8558 		 */
8559 		if (goingaway) {
8560 			KASSERT(indirdep->ir_savebp == bp,
8561 			    ("indir_trunc: losing ir_savebp %p",
8562 			    indirdep->ir_savebp));
8563 			indirdep->ir_savebp = NULL;
8564 			free_indirdep(indirdep);
8565 		}
8566 	}
8567 	FREE_LOCK(ump);
8568 	/* Initialize pointers depending on block size. */
8569 	if (ump->um_fstype == UFS1) {
8570 		bap1 = (ufs1_daddr_t *)bp->b_data;
8571 		nb = bap1[freework->fw_off];
8572 		ufs1fmt = 1;
8573 		bap2 = NULL;
8574 	} else {
8575 		bap2 = (ufs2_daddr_t *)bp->b_data;
8576 		nb = bap2[freework->fw_off];
8577 		ufs1fmt = 0;
8578 		bap1 = NULL;
8579 	}
8580 	level = lbn_level(lbn);
8581 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8582 	lbnadd = lbn_offset(fs, level);
8583 	nblocks = btodb(fs->fs_bsize);
8584 	nfreework = freework;
8585 	freedeps = 0;
8586 	cnt = 0;
8587 	/*
8588 	 * Reclaim blocks.  Traverses into nested indirect levels and
8589 	 * arranges for the current level to be freed when subordinates
8590 	 * are free when journaling.
8591 	 */
8592 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8593 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8594 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8595 		    fs->fs_bsize) != 0)
8596 			nb = 0;
8597 		if (i != NINDIR(fs) - 1) {
8598 			if (ufs1fmt)
8599 				nnb = bap1[i+1];
8600 			else
8601 				nnb = bap2[i+1];
8602 		} else
8603 			nnb = 0;
8604 		if (nb == 0)
8605 			continue;
8606 		cnt++;
8607 		if (level != 0) {
8608 			nlbn = (lbn + 1) - (i * lbnadd);
8609 			if (needj != 0) {
8610 				nfreework = newfreework(ump, freeblks, freework,
8611 				    nlbn, nb, fs->fs_frag, 0, 0);
8612 				freedeps++;
8613 			}
8614 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8615 		} else {
8616 			struct freedep *freedep;
8617 
8618 			/*
8619 			 * Attempt to aggregate freedep dependencies for
8620 			 * all blocks being released to the same CG.
8621 			 */
8622 			LIST_INIT(&wkhd);
8623 			if (needj != 0 &&
8624 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8625 				freedep = newfreedep(freework);
8626 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8627 				    &freedep->fd_list);
8628 				freedeps++;
8629 			}
8630 			CTR3(KTR_SUJ,
8631 			    "indir_trunc: ino %jd blkno %jd size %d",
8632 			    freeblks->fb_inum, nb, fs->fs_bsize);
8633 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8634 			    fs->fs_bsize, freeblks->fb_inum,
8635 			    freeblks->fb_vtype, &wkhd, key);
8636 		}
8637 	}
8638 	ffs_blkrelease_finish(ump, key);
8639 	if (goingaway) {
8640 		bp->b_flags |= B_INVAL | B_NOCACHE;
8641 		brelse(bp);
8642 	}
8643 	freedblocks = 0;
8644 	if (level == 0)
8645 		freedblocks = (nblocks * cnt);
8646 	if (needj == 0)
8647 		freedblocks += nblocks;
8648 	freeblks_free(ump, freeblks, freedblocks);
8649 	/*
8650 	 * If we are journaling set up the ref counts and offset so this
8651 	 * indirect can be completed when its children are free.
8652 	 */
8653 	if (needj) {
8654 		ACQUIRE_LOCK(ump);
8655 		freework->fw_off = i;
8656 		freework->fw_ref += freedeps;
8657 		freework->fw_ref -= NINDIR(fs) + 1;
8658 		if (level == 0)
8659 			freeblks->fb_cgwait += freedeps;
8660 		if (freework->fw_ref == 0)
8661 			freework_freeblock(freework, SINGLETON_KEY);
8662 		FREE_LOCK(ump);
8663 		return;
8664 	}
8665 	/*
8666 	 * If we're not journaling we can free the indirect now.
8667 	 */
8668 	dbn = dbtofsb(fs, dbn);
8669 	CTR3(KTR_SUJ,
8670 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8671 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8672 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8673 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8674 	/* Non SUJ softdep does single-threaded truncations. */
8675 	if (freework->fw_blkno == dbn) {
8676 		freework->fw_state |= ALLCOMPLETE;
8677 		ACQUIRE_LOCK(ump);
8678 		handle_written_freework(freework);
8679 		FREE_LOCK(ump);
8680 	}
8681 	return;
8682 }
8683 
8684 /*
8685  * Cancel an allocindir when it is removed via truncation.  When bp is not
8686  * NULL the indirect never appeared on disk and is scheduled to be freed
8687  * independently of the indir so we can more easily track journal work.
8688  */
8689 static void
8690 cancel_allocindir(aip, bp, freeblks, trunc)
8691 	struct allocindir *aip;
8692 	struct buf *bp;
8693 	struct freeblks *freeblks;
8694 	int trunc;
8695 {
8696 	struct indirdep *indirdep;
8697 	struct freefrag *freefrag;
8698 	struct newblk *newblk;
8699 
8700 	newblk = (struct newblk *)aip;
8701 	LIST_REMOVE(aip, ai_next);
8702 	/*
8703 	 * We must eliminate the pointer in bp if it must be freed on its
8704 	 * own due to partial truncate or pending journal work.
8705 	 */
8706 	if (bp && (trunc || newblk->nb_jnewblk)) {
8707 		/*
8708 		 * Clear the pointer and mark the aip to be freed
8709 		 * directly if it never existed on disk.
8710 		 */
8711 		aip->ai_state |= DELAYEDFREE;
8712 		indirdep = aip->ai_indirdep;
8713 		if (indirdep->ir_state & UFS1FMT)
8714 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8715 		else
8716 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8717 	}
8718 	/*
8719 	 * When truncating the previous pointer will be freed via
8720 	 * savedbp.  Eliminate the freefrag which would dup free.
8721 	 */
8722 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8723 		newblk->nb_freefrag = NULL;
8724 		if (freefrag->ff_jdep)
8725 			cancel_jfreefrag(
8726 			    WK_JFREEFRAG(freefrag->ff_jdep));
8727 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8728 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8729 	}
8730 	/*
8731 	 * If the journal hasn't been written the jnewblk must be passed
8732 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8733 	 * this by leaving the journal dependency on the newblk to be freed
8734 	 * when a freework is created in handle_workitem_freeblocks().
8735 	 */
8736 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8737 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8738 }
8739 
8740 /*
8741  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8742  * in to a newdirblk so any subsequent additions are tracked properly.  The
8743  * caller is responsible for adding the mkdir1 dependency to the journal
8744  * and updating id_mkdiradd.  This function returns with the per-filesystem
8745  * lock held.
8746  */
8747 static struct mkdir *
8748 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8749 	struct diradd *dap;
8750 	ino_t newinum;
8751 	ino_t dinum;
8752 	struct buf *newdirbp;
8753 	struct mkdir **mkdirp;
8754 {
8755 	struct newblk *newblk;
8756 	struct pagedep *pagedep;
8757 	struct inodedep *inodedep;
8758 	struct newdirblk *newdirblk;
8759 	struct mkdir *mkdir1, *mkdir2;
8760 	struct worklist *wk;
8761 	struct jaddref *jaddref;
8762 	struct ufsmount *ump;
8763 	struct mount *mp;
8764 
8765 	mp = dap->da_list.wk_mp;
8766 	ump = VFSTOUFS(mp);
8767 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8768 	    M_SOFTDEP_FLAGS);
8769 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8770 	LIST_INIT(&newdirblk->db_mkdir);
8771 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8772 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8773 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8774 	mkdir1->md_diradd = dap;
8775 	mkdir1->md_jaddref = NULL;
8776 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8777 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8778 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8779 	mkdir2->md_diradd = dap;
8780 	mkdir2->md_jaddref = NULL;
8781 	if (MOUNTEDSUJ(mp) == 0) {
8782 		mkdir1->md_state |= DEPCOMPLETE;
8783 		mkdir2->md_state |= DEPCOMPLETE;
8784 	}
8785 	/*
8786 	 * Dependency on "." and ".." being written to disk.
8787 	 */
8788 	mkdir1->md_buf = newdirbp;
8789 	ACQUIRE_LOCK(VFSTOUFS(mp));
8790 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8791 	/*
8792 	 * We must link the pagedep, allocdirect, and newdirblk for
8793 	 * the initial file page so the pointer to the new directory
8794 	 * is not written until the directory contents are live and
8795 	 * any subsequent additions are not marked live until the
8796 	 * block is reachable via the inode.
8797 	 */
8798 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8799 		panic("setup_newdir: lost pagedep");
8800 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8801 		if (wk->wk_type == D_ALLOCDIRECT)
8802 			break;
8803 	if (wk == NULL)
8804 		panic("setup_newdir: lost allocdirect");
8805 	if (pagedep->pd_state & NEWBLOCK)
8806 		panic("setup_newdir: NEWBLOCK already set");
8807 	newblk = WK_NEWBLK(wk);
8808 	pagedep->pd_state |= NEWBLOCK;
8809 	pagedep->pd_newdirblk = newdirblk;
8810 	newdirblk->db_pagedep = pagedep;
8811 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8812 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8813 	/*
8814 	 * Look up the inodedep for the parent directory so that we
8815 	 * can link mkdir2 into the pending dotdot jaddref or
8816 	 * the inode write if there is none.  If the inode is
8817 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8818 	 * been satisfied and mkdir2 can be freed.
8819 	 */
8820 	inodedep_lookup(mp, dinum, 0, &inodedep);
8821 	if (MOUNTEDSUJ(mp)) {
8822 		if (inodedep == NULL)
8823 			panic("setup_newdir: Lost parent.");
8824 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8825 		    inoreflst);
8826 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8827 		    (jaddref->ja_state & MKDIR_PARENT),
8828 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8829 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8830 		mkdir2->md_jaddref = jaddref;
8831 		jaddref->ja_mkdir = mkdir2;
8832 	} else if (inodedep == NULL ||
8833 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8834 		dap->da_state &= ~MKDIR_PARENT;
8835 		WORKITEM_FREE(mkdir2, D_MKDIR);
8836 		mkdir2 = NULL;
8837 	} else {
8838 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8839 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8840 	}
8841 	*mkdirp = mkdir2;
8842 
8843 	return (mkdir1);
8844 }
8845 
8846 /*
8847  * Directory entry addition dependencies.
8848  *
8849  * When adding a new directory entry, the inode (with its incremented link
8850  * count) must be written to disk before the directory entry's pointer to it.
8851  * Also, if the inode is newly allocated, the corresponding freemap must be
8852  * updated (on disk) before the directory entry's pointer. These requirements
8853  * are met via undo/redo on the directory entry's pointer, which consists
8854  * simply of the inode number.
8855  *
8856  * As directory entries are added and deleted, the free space within a
8857  * directory block can become fragmented.  The ufs filesystem will compact
8858  * a fragmented directory block to make space for a new entry. When this
8859  * occurs, the offsets of previously added entries change. Any "diradd"
8860  * dependency structures corresponding to these entries must be updated with
8861  * the new offsets.
8862  */
8863 
8864 /*
8865  * This routine is called after the in-memory inode's link
8866  * count has been incremented, but before the directory entry's
8867  * pointer to the inode has been set.
8868  */
8869 int
8870 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8871 	struct buf *bp;		/* buffer containing directory block */
8872 	struct inode *dp;	/* inode for directory */
8873 	off_t diroffset;	/* offset of new entry in directory */
8874 	ino_t newinum;		/* inode referenced by new directory entry */
8875 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8876 	int isnewblk;		/* entry is in a newly allocated block */
8877 {
8878 	int offset;		/* offset of new entry within directory block */
8879 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8880 	struct fs *fs;
8881 	struct diradd *dap;
8882 	struct newblk *newblk;
8883 	struct pagedep *pagedep;
8884 	struct inodedep *inodedep;
8885 	struct newdirblk *newdirblk;
8886 	struct mkdir *mkdir1, *mkdir2;
8887 	struct jaddref *jaddref;
8888 	struct ufsmount *ump;
8889 	struct mount *mp;
8890 	int isindir;
8891 
8892 	mp = ITOVFS(dp);
8893 	ump = VFSTOUFS(mp);
8894 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8895 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8896 	/*
8897 	 * Whiteouts have no dependencies.
8898 	 */
8899 	if (newinum == UFS_WINO) {
8900 		if (newdirbp != NULL)
8901 			bdwrite(newdirbp);
8902 		return (0);
8903 	}
8904 	jaddref = NULL;
8905 	mkdir1 = mkdir2 = NULL;
8906 	fs = ump->um_fs;
8907 	lbn = lblkno(fs, diroffset);
8908 	offset = blkoff(fs, diroffset);
8909 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8910 		M_SOFTDEP_FLAGS|M_ZERO);
8911 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8912 	dap->da_offset = offset;
8913 	dap->da_newinum = newinum;
8914 	dap->da_state = ATTACHED;
8915 	LIST_INIT(&dap->da_jwork);
8916 	isindir = bp->b_lblkno >= UFS_NDADDR;
8917 	newdirblk = NULL;
8918 	if (isnewblk &&
8919 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8920 		newdirblk = malloc(sizeof(struct newdirblk),
8921 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8922 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8923 		LIST_INIT(&newdirblk->db_mkdir);
8924 	}
8925 	/*
8926 	 * If we're creating a new directory setup the dependencies and set
8927 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8928 	 * we can move on.
8929 	 */
8930 	if (newdirbp == NULL) {
8931 		dap->da_state |= DEPCOMPLETE;
8932 		ACQUIRE_LOCK(ump);
8933 	} else {
8934 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8935 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8936 		    &mkdir2);
8937 	}
8938 	/*
8939 	 * Link into parent directory pagedep to await its being written.
8940 	 */
8941 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8942 #ifdef INVARIANTS
8943 	if (diradd_lookup(pagedep, offset) != NULL)
8944 		panic("softdep_setup_directory_add: %p already at off %d\n",
8945 		    diradd_lookup(pagedep, offset), offset);
8946 #endif
8947 	dap->da_pagedep = pagedep;
8948 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8949 	    da_pdlist);
8950 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8951 	/*
8952 	 * If we're journaling, link the diradd into the jaddref so it
8953 	 * may be completed after the journal entry is written.  Otherwise,
8954 	 * link the diradd into its inodedep.  If the inode is not yet
8955 	 * written place it on the bufwait list, otherwise do the post-inode
8956 	 * write processing to put it on the id_pendinghd list.
8957 	 */
8958 	if (MOUNTEDSUJ(mp)) {
8959 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8960 		    inoreflst);
8961 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8962 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8963 		jaddref->ja_diroff = diroffset;
8964 		jaddref->ja_diradd = dap;
8965 		add_to_journal(&jaddref->ja_list);
8966 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8967 		diradd_inode_written(dap, inodedep);
8968 	else
8969 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8970 	/*
8971 	 * Add the journal entries for . and .. links now that the primary
8972 	 * link is written.
8973 	 */
8974 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8975 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8976 		    inoreflst, if_deps);
8977 		KASSERT(jaddref != NULL &&
8978 		    jaddref->ja_ino == jaddref->ja_parent &&
8979 		    (jaddref->ja_state & MKDIR_BODY),
8980 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8981 		    jaddref));
8982 		mkdir1->md_jaddref = jaddref;
8983 		jaddref->ja_mkdir = mkdir1;
8984 		/*
8985 		 * It is important that the dotdot journal entry
8986 		 * is added prior to the dot entry since dot writes
8987 		 * both the dot and dotdot links.  These both must
8988 		 * be added after the primary link for the journal
8989 		 * to remain consistent.
8990 		 */
8991 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8992 		add_to_journal(&jaddref->ja_list);
8993 	}
8994 	/*
8995 	 * If we are adding a new directory remember this diradd so that if
8996 	 * we rename it we can keep the dot and dotdot dependencies.  If
8997 	 * we are adding a new name for an inode that has a mkdiradd we
8998 	 * must be in rename and we have to move the dot and dotdot
8999 	 * dependencies to this new name.  The old name is being orphaned
9000 	 * soon.
9001 	 */
9002 	if (mkdir1 != NULL) {
9003 		if (inodedep->id_mkdiradd != NULL)
9004 			panic("softdep_setup_directory_add: Existing mkdir");
9005 		inodedep->id_mkdiradd = dap;
9006 	} else if (inodedep->id_mkdiradd)
9007 		merge_diradd(inodedep, dap);
9008 	if (newdirblk != NULL) {
9009 		/*
9010 		 * There is nothing to do if we are already tracking
9011 		 * this block.
9012 		 */
9013 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
9014 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
9015 			FREE_LOCK(ump);
9016 			return (0);
9017 		}
9018 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
9019 		    == 0)
9020 			panic("softdep_setup_directory_add: lost entry");
9021 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
9022 		pagedep->pd_state |= NEWBLOCK;
9023 		pagedep->pd_newdirblk = newdirblk;
9024 		newdirblk->db_pagedep = pagedep;
9025 		FREE_LOCK(ump);
9026 		/*
9027 		 * If we extended into an indirect signal direnter to sync.
9028 		 */
9029 		if (isindir)
9030 			return (1);
9031 		return (0);
9032 	}
9033 	FREE_LOCK(ump);
9034 	return (0);
9035 }
9036 
9037 /*
9038  * This procedure is called to change the offset of a directory
9039  * entry when compacting a directory block which must be owned
9040  * exclusively by the caller. Note that the actual entry movement
9041  * must be done in this procedure to ensure that no I/O completions
9042  * occur while the move is in progress.
9043  */
9044 void
9045 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
9046 	struct buf *bp;		/* Buffer holding directory block. */
9047 	struct inode *dp;	/* inode for directory */
9048 	caddr_t base;		/* address of dp->i_offset */
9049 	caddr_t oldloc;		/* address of old directory location */
9050 	caddr_t newloc;		/* address of new directory location */
9051 	int entrysize;		/* size of directory entry */
9052 {
9053 	int offset, oldoffset, newoffset;
9054 	struct pagedep *pagedep;
9055 	struct jmvref *jmvref;
9056 	struct diradd *dap;
9057 	struct direct *de;
9058 	struct mount *mp;
9059 	struct ufsmount *ump;
9060 	ufs_lbn_t lbn;
9061 	int flags;
9062 
9063 	mp = ITOVFS(dp);
9064 	ump = VFSTOUFS(mp);
9065 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9066 	    ("softdep_change_directoryentry_offset called on "
9067 	     "non-softdep filesystem"));
9068 	de = (struct direct *)oldloc;
9069 	jmvref = NULL;
9070 	flags = 0;
9071 	/*
9072 	 * Moves are always journaled as it would be too complex to
9073 	 * determine if any affected adds or removes are present in the
9074 	 * journal.
9075 	 */
9076 	if (MOUNTEDSUJ(mp)) {
9077 		flags = DEPALLOC;
9078 		jmvref = newjmvref(dp, de->d_ino,
9079 		    I_OFFSET(dp) + (oldloc - base),
9080 		    I_OFFSET(dp) + (newloc - base));
9081 	}
9082 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9083 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9084 	oldoffset = offset + (oldloc - base);
9085 	newoffset = offset + (newloc - base);
9086 	ACQUIRE_LOCK(ump);
9087 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
9088 		goto done;
9089 	dap = diradd_lookup(pagedep, oldoffset);
9090 	if (dap) {
9091 		dap->da_offset = newoffset;
9092 		newoffset = DIRADDHASH(newoffset);
9093 		oldoffset = DIRADDHASH(oldoffset);
9094 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
9095 		    newoffset != oldoffset) {
9096 			LIST_REMOVE(dap, da_pdlist);
9097 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
9098 			    dap, da_pdlist);
9099 		}
9100 	}
9101 done:
9102 	if (jmvref) {
9103 		jmvref->jm_pagedep = pagedep;
9104 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
9105 		add_to_journal(&jmvref->jm_list);
9106 	}
9107 	bcopy(oldloc, newloc, entrysize);
9108 	FREE_LOCK(ump);
9109 }
9110 
9111 /*
9112  * Move the mkdir dependencies and journal work from one diradd to another
9113  * when renaming a directory.  The new name must depend on the mkdir deps
9114  * completing as the old name did.  Directories can only have one valid link
9115  * at a time so one must be canonical.
9116  */
9117 static void
9118 merge_diradd(inodedep, newdap)
9119 	struct inodedep *inodedep;
9120 	struct diradd *newdap;
9121 {
9122 	struct diradd *olddap;
9123 	struct mkdir *mkdir, *nextmd;
9124 	struct ufsmount *ump;
9125 	short state;
9126 
9127 	olddap = inodedep->id_mkdiradd;
9128 	inodedep->id_mkdiradd = newdap;
9129 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9130 		newdap->da_state &= ~DEPCOMPLETE;
9131 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
9132 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9133 		     mkdir = nextmd) {
9134 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9135 			if (mkdir->md_diradd != olddap)
9136 				continue;
9137 			mkdir->md_diradd = newdap;
9138 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
9139 			newdap->da_state |= state;
9140 			olddap->da_state &= ~state;
9141 			if ((olddap->da_state &
9142 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
9143 				break;
9144 		}
9145 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9146 			panic("merge_diradd: unfound ref");
9147 	}
9148 	/*
9149 	 * Any mkdir related journal items are not safe to be freed until
9150 	 * the new name is stable.
9151 	 */
9152 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
9153 	olddap->da_state |= DEPCOMPLETE;
9154 	complete_diradd(olddap);
9155 }
9156 
9157 /*
9158  * Move the diradd to the pending list when all diradd dependencies are
9159  * complete.
9160  */
9161 static void
9162 complete_diradd(dap)
9163 	struct diradd *dap;
9164 {
9165 	struct pagedep *pagedep;
9166 
9167 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
9168 		if (dap->da_state & DIRCHG)
9169 			pagedep = dap->da_previous->dm_pagedep;
9170 		else
9171 			pagedep = dap->da_pagedep;
9172 		LIST_REMOVE(dap, da_pdlist);
9173 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9174 	}
9175 }
9176 
9177 /*
9178  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
9179  * add entries and conditonally journal the remove.
9180  */
9181 static void
9182 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
9183 	struct diradd *dap;
9184 	struct dirrem *dirrem;
9185 	struct jremref *jremref;
9186 	struct jremref *dotremref;
9187 	struct jremref *dotdotremref;
9188 {
9189 	struct inodedep *inodedep;
9190 	struct jaddref *jaddref;
9191 	struct inoref *inoref;
9192 	struct ufsmount *ump;
9193 	struct mkdir *mkdir;
9194 
9195 	/*
9196 	 * If no remove references were allocated we're on a non-journaled
9197 	 * filesystem and can skip the cancel step.
9198 	 */
9199 	if (jremref == NULL) {
9200 		free_diradd(dap, NULL);
9201 		return;
9202 	}
9203 	/*
9204 	 * Cancel the primary name an free it if it does not require
9205 	 * journaling.
9206 	 */
9207 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
9208 	    0, &inodedep) != 0) {
9209 		/* Abort the addref that reference this diradd.  */
9210 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
9211 			if (inoref->if_list.wk_type != D_JADDREF)
9212 				continue;
9213 			jaddref = (struct jaddref *)inoref;
9214 			if (jaddref->ja_diradd != dap)
9215 				continue;
9216 			if (cancel_jaddref(jaddref, inodedep,
9217 			    &dirrem->dm_jwork) == 0) {
9218 				free_jremref(jremref);
9219 				jremref = NULL;
9220 			}
9221 			break;
9222 		}
9223 	}
9224 	/*
9225 	 * Cancel subordinate names and free them if they do not require
9226 	 * journaling.
9227 	 */
9228 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9229 		ump = VFSTOUFS(dap->da_list.wk_mp);
9230 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
9231 			if (mkdir->md_diradd != dap)
9232 				continue;
9233 			if ((jaddref = mkdir->md_jaddref) == NULL)
9234 				continue;
9235 			mkdir->md_jaddref = NULL;
9236 			if (mkdir->md_state & MKDIR_PARENT) {
9237 				if (cancel_jaddref(jaddref, NULL,
9238 				    &dirrem->dm_jwork) == 0) {
9239 					free_jremref(dotdotremref);
9240 					dotdotremref = NULL;
9241 				}
9242 			} else {
9243 				if (cancel_jaddref(jaddref, inodedep,
9244 				    &dirrem->dm_jwork) == 0) {
9245 					free_jremref(dotremref);
9246 					dotremref = NULL;
9247 				}
9248 			}
9249 		}
9250 	}
9251 
9252 	if (jremref)
9253 		journal_jremref(dirrem, jremref, inodedep);
9254 	if (dotremref)
9255 		journal_jremref(dirrem, dotremref, inodedep);
9256 	if (dotdotremref)
9257 		journal_jremref(dirrem, dotdotremref, NULL);
9258 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
9259 	free_diradd(dap, &dirrem->dm_jwork);
9260 }
9261 
9262 /*
9263  * Free a diradd dependency structure.
9264  */
9265 static void
9266 free_diradd(dap, wkhd)
9267 	struct diradd *dap;
9268 	struct workhead *wkhd;
9269 {
9270 	struct dirrem *dirrem;
9271 	struct pagedep *pagedep;
9272 	struct inodedep *inodedep;
9273 	struct mkdir *mkdir, *nextmd;
9274 	struct ufsmount *ump;
9275 
9276 	ump = VFSTOUFS(dap->da_list.wk_mp);
9277 	LOCK_OWNED(ump);
9278 	LIST_REMOVE(dap, da_pdlist);
9279 	if (dap->da_state & ONWORKLIST)
9280 		WORKLIST_REMOVE(&dap->da_list);
9281 	if ((dap->da_state & DIRCHG) == 0) {
9282 		pagedep = dap->da_pagedep;
9283 	} else {
9284 		dirrem = dap->da_previous;
9285 		pagedep = dirrem->dm_pagedep;
9286 		dirrem->dm_dirinum = pagedep->pd_ino;
9287 		dirrem->dm_state |= COMPLETE;
9288 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9289 			add_to_worklist(&dirrem->dm_list, 0);
9290 	}
9291 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
9292 	    0, &inodedep) != 0)
9293 		if (inodedep->id_mkdiradd == dap)
9294 			inodedep->id_mkdiradd = NULL;
9295 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9296 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9297 		     mkdir = nextmd) {
9298 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9299 			if (mkdir->md_diradd != dap)
9300 				continue;
9301 			dap->da_state &=
9302 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
9303 			LIST_REMOVE(mkdir, md_mkdirs);
9304 			if (mkdir->md_state & ONWORKLIST)
9305 				WORKLIST_REMOVE(&mkdir->md_list);
9306 			if (mkdir->md_jaddref != NULL)
9307 				panic("free_diradd: Unexpected jaddref");
9308 			WORKITEM_FREE(mkdir, D_MKDIR);
9309 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
9310 				break;
9311 		}
9312 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9313 			panic("free_diradd: unfound ref");
9314 	}
9315 	if (inodedep)
9316 		free_inodedep(inodedep);
9317 	/*
9318 	 * Free any journal segments waiting for the directory write.
9319 	 */
9320 	handle_jwork(&dap->da_jwork);
9321 	WORKITEM_FREE(dap, D_DIRADD);
9322 }
9323 
9324 /*
9325  * Directory entry removal dependencies.
9326  *
9327  * When removing a directory entry, the entry's inode pointer must be
9328  * zero'ed on disk before the corresponding inode's link count is decremented
9329  * (possibly freeing the inode for re-use). This dependency is handled by
9330  * updating the directory entry but delaying the inode count reduction until
9331  * after the directory block has been written to disk. After this point, the
9332  * inode count can be decremented whenever it is convenient.
9333  */
9334 
9335 /*
9336  * This routine should be called immediately after removing
9337  * a directory entry.  The inode's link count should not be
9338  * decremented by the calling procedure -- the soft updates
9339  * code will do this task when it is safe.
9340  */
9341 void
9342 softdep_setup_remove(bp, dp, ip, isrmdir)
9343 	struct buf *bp;		/* buffer containing directory block */
9344 	struct inode *dp;	/* inode for the directory being modified */
9345 	struct inode *ip;	/* inode for directory entry being removed */
9346 	int isrmdir;		/* indicates if doing RMDIR */
9347 {
9348 	struct dirrem *dirrem, *prevdirrem;
9349 	struct inodedep *inodedep;
9350 	struct ufsmount *ump;
9351 	int direct;
9352 
9353 	ump = ITOUMP(ip);
9354 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9355 	    ("softdep_setup_remove called on non-softdep filesystem"));
9356 	/*
9357 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9358 	 * newdirrem() to setup the full directory remove which requires
9359 	 * isrmdir > 1.
9360 	 */
9361 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9362 	/*
9363 	 * Add the dirrem to the inodedep's pending remove list for quick
9364 	 * discovery later.
9365 	 */
9366 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9367 		panic("softdep_setup_remove: Lost inodedep.");
9368 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9369 	dirrem->dm_state |= ONDEPLIST;
9370 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9371 
9372 	/*
9373 	 * If the COMPLETE flag is clear, then there were no active
9374 	 * entries and we want to roll back to a zeroed entry until
9375 	 * the new inode is committed to disk. If the COMPLETE flag is
9376 	 * set then we have deleted an entry that never made it to
9377 	 * disk. If the entry we deleted resulted from a name change,
9378 	 * then the old name still resides on disk. We cannot delete
9379 	 * its inode (returned to us in prevdirrem) until the zeroed
9380 	 * directory entry gets to disk. The new inode has never been
9381 	 * referenced on the disk, so can be deleted immediately.
9382 	 */
9383 	if ((dirrem->dm_state & COMPLETE) == 0) {
9384 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9385 		    dm_next);
9386 		FREE_LOCK(ump);
9387 	} else {
9388 		if (prevdirrem != NULL)
9389 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9390 			    prevdirrem, dm_next);
9391 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9392 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9393 		FREE_LOCK(ump);
9394 		if (direct)
9395 			handle_workitem_remove(dirrem, 0);
9396 	}
9397 }
9398 
9399 /*
9400  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9401  * pd_pendinghd list of a pagedep.
9402  */
9403 static struct diradd *
9404 diradd_lookup(pagedep, offset)
9405 	struct pagedep *pagedep;
9406 	int offset;
9407 {
9408 	struct diradd *dap;
9409 
9410 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9411 		if (dap->da_offset == offset)
9412 			return (dap);
9413 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9414 		if (dap->da_offset == offset)
9415 			return (dap);
9416 	return (NULL);
9417 }
9418 
9419 /*
9420  * Search for a .. diradd dependency in a directory that is being removed.
9421  * If the directory was renamed to a new parent we have a diradd rather
9422  * than a mkdir for the .. entry.  We need to cancel it now before
9423  * it is found in truncate().
9424  */
9425 static struct jremref *
9426 cancel_diradd_dotdot(ip, dirrem, jremref)
9427 	struct inode *ip;
9428 	struct dirrem *dirrem;
9429 	struct jremref *jremref;
9430 {
9431 	struct pagedep *pagedep;
9432 	struct diradd *dap;
9433 	struct worklist *wk;
9434 
9435 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9436 		return (jremref);
9437 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9438 	if (dap == NULL)
9439 		return (jremref);
9440 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9441 	/*
9442 	 * Mark any journal work as belonging to the parent so it is freed
9443 	 * with the .. reference.
9444 	 */
9445 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9446 		wk->wk_state |= MKDIR_PARENT;
9447 	return (NULL);
9448 }
9449 
9450 /*
9451  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9452  * replace it with a dirrem/diradd pair as a result of re-parenting a
9453  * directory.  This ensures that we don't simultaneously have a mkdir and
9454  * a diradd for the same .. entry.
9455  */
9456 static struct jremref *
9457 cancel_mkdir_dotdot(ip, dirrem, jremref)
9458 	struct inode *ip;
9459 	struct dirrem *dirrem;
9460 	struct jremref *jremref;
9461 {
9462 	struct inodedep *inodedep;
9463 	struct jaddref *jaddref;
9464 	struct ufsmount *ump;
9465 	struct mkdir *mkdir;
9466 	struct diradd *dap;
9467 	struct mount *mp;
9468 
9469 	mp = ITOVFS(ip);
9470 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9471 		return (jremref);
9472 	dap = inodedep->id_mkdiradd;
9473 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9474 		return (jremref);
9475 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9476 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9477 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9478 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9479 			break;
9480 	if (mkdir == NULL)
9481 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9482 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9483 		mkdir->md_jaddref = NULL;
9484 		jaddref->ja_state &= ~MKDIR_PARENT;
9485 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9486 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9487 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9488 			journal_jremref(dirrem, jremref, inodedep);
9489 			jremref = NULL;
9490 		}
9491 	}
9492 	if (mkdir->md_state & ONWORKLIST)
9493 		WORKLIST_REMOVE(&mkdir->md_list);
9494 	mkdir->md_state |= ALLCOMPLETE;
9495 	complete_mkdir(mkdir);
9496 	return (jremref);
9497 }
9498 
9499 static void
9500 journal_jremref(dirrem, jremref, inodedep)
9501 	struct dirrem *dirrem;
9502 	struct jremref *jremref;
9503 	struct inodedep *inodedep;
9504 {
9505 
9506 	if (inodedep == NULL)
9507 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9508 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9509 			panic("journal_jremref: Lost inodedep");
9510 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9511 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9512 	add_to_journal(&jremref->jr_list);
9513 }
9514 
9515 static void
9516 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9517 	struct dirrem *dirrem;
9518 	struct jremref *jremref;
9519 	struct jremref *dotremref;
9520 	struct jremref *dotdotremref;
9521 {
9522 	struct inodedep *inodedep;
9523 
9524 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9525 	    &inodedep) == 0)
9526 		panic("dirrem_journal: Lost inodedep");
9527 	journal_jremref(dirrem, jremref, inodedep);
9528 	if (dotremref)
9529 		journal_jremref(dirrem, dotremref, inodedep);
9530 	if (dotdotremref)
9531 		journal_jremref(dirrem, dotdotremref, NULL);
9532 }
9533 
9534 /*
9535  * Allocate a new dirrem if appropriate and return it along with
9536  * its associated pagedep. Called without a lock, returns with lock.
9537  */
9538 static struct dirrem *
9539 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9540 	struct buf *bp;		/* buffer containing directory block */
9541 	struct inode *dp;	/* inode for the directory being modified */
9542 	struct inode *ip;	/* inode for directory entry being removed */
9543 	int isrmdir;		/* indicates if doing RMDIR */
9544 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9545 {
9546 	int offset;
9547 	ufs_lbn_t lbn;
9548 	struct diradd *dap;
9549 	struct dirrem *dirrem;
9550 	struct pagedep *pagedep;
9551 	struct jremref *jremref;
9552 	struct jremref *dotremref;
9553 	struct jremref *dotdotremref;
9554 	struct vnode *dvp;
9555 	struct ufsmount *ump;
9556 
9557 	/*
9558 	 * Whiteouts have no deletion dependencies.
9559 	 */
9560 	if (ip == NULL)
9561 		panic("newdirrem: whiteout");
9562 	dvp = ITOV(dp);
9563 	ump = ITOUMP(dp);
9564 
9565 	/*
9566 	 * If the system is over its limit and our filesystem is
9567 	 * responsible for more than our share of that usage and
9568 	 * we are not a snapshot, request some inodedep cleanup.
9569 	 * Limiting the number of dirrem structures will also limit
9570 	 * the number of freefile and freeblks structures.
9571 	 */
9572 	ACQUIRE_LOCK(ump);
9573 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9574 		schedule_cleanup(UFSTOVFS(ump));
9575 	else
9576 		FREE_LOCK(ump);
9577 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9578 	    M_ZERO);
9579 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9580 	LIST_INIT(&dirrem->dm_jremrefhd);
9581 	LIST_INIT(&dirrem->dm_jwork);
9582 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9583 	dirrem->dm_oldinum = ip->i_number;
9584 	*prevdirremp = NULL;
9585 	/*
9586 	 * Allocate remove reference structures to track journal write
9587 	 * dependencies.  We will always have one for the link and
9588 	 * when doing directories we will always have one more for dot.
9589 	 * When renaming a directory we skip the dotdot link change so
9590 	 * this is not needed.
9591 	 */
9592 	jremref = dotremref = dotdotremref = NULL;
9593 	if (DOINGSUJ(dvp)) {
9594 		if (isrmdir) {
9595 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9596 			    ip->i_effnlink + 2);
9597 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9598 			    ip->i_effnlink + 1);
9599 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9600 			    dp->i_effnlink + 1);
9601 			dotdotremref->jr_state |= MKDIR_PARENT;
9602 		} else
9603 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9604 			    ip->i_effnlink + 1);
9605 	}
9606 	ACQUIRE_LOCK(ump);
9607 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9608 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9609 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9610 	    &pagedep);
9611 	dirrem->dm_pagedep = pagedep;
9612 	dirrem->dm_offset = offset;
9613 	/*
9614 	 * If we're renaming a .. link to a new directory, cancel any
9615 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9616 	 * the jremref is preserved for any potential diradd in this
9617 	 * location.  This can not coincide with a rmdir.
9618 	 */
9619 	if (I_OFFSET(dp) == DOTDOT_OFFSET) {
9620 		if (isrmdir)
9621 			panic("newdirrem: .. directory change during remove?");
9622 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9623 	}
9624 	/*
9625 	 * If we're removing a directory search for the .. dependency now and
9626 	 * cancel it.  Any pending journal work will be added to the dirrem
9627 	 * to be completed when the workitem remove completes.
9628 	 */
9629 	if (isrmdir)
9630 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9631 	/*
9632 	 * Check for a diradd dependency for the same directory entry.
9633 	 * If present, then both dependencies become obsolete and can
9634 	 * be de-allocated.
9635 	 */
9636 	dap = diradd_lookup(pagedep, offset);
9637 	if (dap == NULL) {
9638 		/*
9639 		 * Link the jremref structures into the dirrem so they are
9640 		 * written prior to the pagedep.
9641 		 */
9642 		if (jremref)
9643 			dirrem_journal(dirrem, jremref, dotremref,
9644 			    dotdotremref);
9645 		return (dirrem);
9646 	}
9647 	/*
9648 	 * Must be ATTACHED at this point.
9649 	 */
9650 	if ((dap->da_state & ATTACHED) == 0)
9651 		panic("newdirrem: not ATTACHED");
9652 	if (dap->da_newinum != ip->i_number)
9653 		panic("newdirrem: inum %ju should be %ju",
9654 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9655 	/*
9656 	 * If we are deleting a changed name that never made it to disk,
9657 	 * then return the dirrem describing the previous inode (which
9658 	 * represents the inode currently referenced from this entry on disk).
9659 	 */
9660 	if ((dap->da_state & DIRCHG) != 0) {
9661 		*prevdirremp = dap->da_previous;
9662 		dap->da_state &= ~DIRCHG;
9663 		dap->da_pagedep = pagedep;
9664 	}
9665 	/*
9666 	 * We are deleting an entry that never made it to disk.
9667 	 * Mark it COMPLETE so we can delete its inode immediately.
9668 	 */
9669 	dirrem->dm_state |= COMPLETE;
9670 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9671 #ifdef INVARIANTS
9672 	if (isrmdir == 0) {
9673 		struct worklist *wk;
9674 
9675 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9676 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9677 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9678 	}
9679 #endif
9680 
9681 	return (dirrem);
9682 }
9683 
9684 /*
9685  * Directory entry change dependencies.
9686  *
9687  * Changing an existing directory entry requires that an add operation
9688  * be completed first followed by a deletion. The semantics for the addition
9689  * are identical to the description of adding a new entry above except
9690  * that the rollback is to the old inode number rather than zero. Once
9691  * the addition dependency is completed, the removal is done as described
9692  * in the removal routine above.
9693  */
9694 
9695 /*
9696  * This routine should be called immediately after changing
9697  * a directory entry.  The inode's link count should not be
9698  * decremented by the calling procedure -- the soft updates
9699  * code will perform this task when it is safe.
9700  */
9701 void
9702 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9703 	struct buf *bp;		/* buffer containing directory block */
9704 	struct inode *dp;	/* inode for the directory being modified */
9705 	struct inode *ip;	/* inode for directory entry being removed */
9706 	ino_t newinum;		/* new inode number for changed entry */
9707 	int isrmdir;		/* indicates if doing RMDIR */
9708 {
9709 	int offset;
9710 	struct diradd *dap = NULL;
9711 	struct dirrem *dirrem, *prevdirrem;
9712 	struct pagedep *pagedep;
9713 	struct inodedep *inodedep;
9714 	struct jaddref *jaddref;
9715 	struct mount *mp;
9716 	struct ufsmount *ump;
9717 
9718 	mp = ITOVFS(dp);
9719 	ump = VFSTOUFS(mp);
9720 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9721 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9722 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9723 
9724 	/*
9725 	 * Whiteouts do not need diradd dependencies.
9726 	 */
9727 	if (newinum != UFS_WINO) {
9728 		dap = malloc(sizeof(struct diradd),
9729 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9730 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9731 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9732 		dap->da_offset = offset;
9733 		dap->da_newinum = newinum;
9734 		LIST_INIT(&dap->da_jwork);
9735 	}
9736 
9737 	/*
9738 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9739 	 */
9740 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9741 	pagedep = dirrem->dm_pagedep;
9742 	/*
9743 	 * The possible values for isrmdir:
9744 	 *	0 - non-directory file rename
9745 	 *	1 - directory rename within same directory
9746 	 *   inum - directory rename to new directory of given inode number
9747 	 * When renaming to a new directory, we are both deleting and
9748 	 * creating a new directory entry, so the link count on the new
9749 	 * directory should not change. Thus we do not need the followup
9750 	 * dirrem which is usually done in handle_workitem_remove. We set
9751 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9752 	 * followup dirrem.
9753 	 */
9754 	if (isrmdir > 1)
9755 		dirrem->dm_state |= DIRCHG;
9756 
9757 	/*
9758 	 * Whiteouts have no additional dependencies,
9759 	 * so just put the dirrem on the correct list.
9760 	 */
9761 	if (newinum == UFS_WINO) {
9762 		if ((dirrem->dm_state & COMPLETE) == 0) {
9763 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9764 			    dm_next);
9765 		} else {
9766 			dirrem->dm_dirinum = pagedep->pd_ino;
9767 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9768 				add_to_worklist(&dirrem->dm_list, 0);
9769 		}
9770 		FREE_LOCK(ump);
9771 		return;
9772 	}
9773 	/*
9774 	 * Add the dirrem to the inodedep's pending remove list for quick
9775 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9776 	 * will not fail.
9777 	 */
9778 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9779 		panic("softdep_setup_directory_change: Lost inodedep.");
9780 	dirrem->dm_state |= ONDEPLIST;
9781 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9782 
9783 	/*
9784 	 * If the COMPLETE flag is clear, then there were no active
9785 	 * entries and we want to roll back to the previous inode until
9786 	 * the new inode is committed to disk. If the COMPLETE flag is
9787 	 * set, then we have deleted an entry that never made it to disk.
9788 	 * If the entry we deleted resulted from a name change, then the old
9789 	 * inode reference still resides on disk. Any rollback that we do
9790 	 * needs to be to that old inode (returned to us in prevdirrem). If
9791 	 * the entry we deleted resulted from a create, then there is
9792 	 * no entry on the disk, so we want to roll back to zero rather
9793 	 * than the uncommitted inode. In either of the COMPLETE cases we
9794 	 * want to immediately free the unwritten and unreferenced inode.
9795 	 */
9796 	if ((dirrem->dm_state & COMPLETE) == 0) {
9797 		dap->da_previous = dirrem;
9798 	} else {
9799 		if (prevdirrem != NULL) {
9800 			dap->da_previous = prevdirrem;
9801 		} else {
9802 			dap->da_state &= ~DIRCHG;
9803 			dap->da_pagedep = pagedep;
9804 		}
9805 		dirrem->dm_dirinum = pagedep->pd_ino;
9806 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9807 			add_to_worklist(&dirrem->dm_list, 0);
9808 	}
9809 	/*
9810 	 * Lookup the jaddref for this journal entry.  We must finish
9811 	 * initializing it and make the diradd write dependent on it.
9812 	 * If we're not journaling, put it on the id_bufwait list if the
9813 	 * inode is not yet written. If it is written, do the post-inode
9814 	 * write processing to put it on the id_pendinghd list.
9815 	 */
9816 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9817 	if (MOUNTEDSUJ(mp)) {
9818 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9819 		    inoreflst);
9820 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9821 		    ("softdep_setup_directory_change: bad jaddref %p",
9822 		    jaddref));
9823 		jaddref->ja_diroff = I_OFFSET(dp);
9824 		jaddref->ja_diradd = dap;
9825 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9826 		    dap, da_pdlist);
9827 		add_to_journal(&jaddref->ja_list);
9828 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9829 		dap->da_state |= COMPLETE;
9830 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9831 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9832 	} else {
9833 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9834 		    dap, da_pdlist);
9835 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9836 	}
9837 	/*
9838 	 * If we're making a new name for a directory that has not been
9839 	 * committed when need to move the dot and dotdot references to
9840 	 * this new name.
9841 	 */
9842 	if (inodedep->id_mkdiradd && I_OFFSET(dp) != DOTDOT_OFFSET)
9843 		merge_diradd(inodedep, dap);
9844 	FREE_LOCK(ump);
9845 }
9846 
9847 /*
9848  * Called whenever the link count on an inode is changed.
9849  * It creates an inode dependency so that the new reference(s)
9850  * to the inode cannot be committed to disk until the updated
9851  * inode has been written.
9852  */
9853 void
9854 softdep_change_linkcnt(ip)
9855 	struct inode *ip;	/* the inode with the increased link count */
9856 {
9857 	struct inodedep *inodedep;
9858 	struct ufsmount *ump;
9859 
9860 	ump = ITOUMP(ip);
9861 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9862 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9863 	ACQUIRE_LOCK(ump);
9864 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9865 	if (ip->i_nlink < ip->i_effnlink)
9866 		panic("softdep_change_linkcnt: bad delta");
9867 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9868 	FREE_LOCK(ump);
9869 }
9870 
9871 /*
9872  * Attach a sbdep dependency to the superblock buf so that we can keep
9873  * track of the head of the linked list of referenced but unlinked inodes.
9874  */
9875 void
9876 softdep_setup_sbupdate(ump, fs, bp)
9877 	struct ufsmount *ump;
9878 	struct fs *fs;
9879 	struct buf *bp;
9880 {
9881 	struct sbdep *sbdep;
9882 	struct worklist *wk;
9883 
9884 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9885 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9886 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9887 		if (wk->wk_type == D_SBDEP)
9888 			break;
9889 	if (wk != NULL)
9890 		return;
9891 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9892 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9893 	sbdep->sb_fs = fs;
9894 	sbdep->sb_ump = ump;
9895 	ACQUIRE_LOCK(ump);
9896 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9897 	FREE_LOCK(ump);
9898 }
9899 
9900 /*
9901  * Return the first unlinked inodedep which is ready to be the head of the
9902  * list.  The inodedep and all those after it must have valid next pointers.
9903  */
9904 static struct inodedep *
9905 first_unlinked_inodedep(ump)
9906 	struct ufsmount *ump;
9907 {
9908 	struct inodedep *inodedep;
9909 	struct inodedep *idp;
9910 
9911 	LOCK_OWNED(ump);
9912 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9913 	    inodedep; inodedep = idp) {
9914 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9915 			return (NULL);
9916 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9917 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9918 			break;
9919 		if ((inodedep->id_state & UNLINKPREV) == 0)
9920 			break;
9921 	}
9922 	return (inodedep);
9923 }
9924 
9925 /*
9926  * Set the sujfree unlinked head pointer prior to writing a superblock.
9927  */
9928 static void
9929 initiate_write_sbdep(sbdep)
9930 	struct sbdep *sbdep;
9931 {
9932 	struct inodedep *inodedep;
9933 	struct fs *bpfs;
9934 	struct fs *fs;
9935 
9936 	bpfs = sbdep->sb_fs;
9937 	fs = sbdep->sb_ump->um_fs;
9938 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9939 	if (inodedep) {
9940 		fs->fs_sujfree = inodedep->id_ino;
9941 		inodedep->id_state |= UNLINKPREV;
9942 	} else
9943 		fs->fs_sujfree = 0;
9944 	bpfs->fs_sujfree = fs->fs_sujfree;
9945 	/*
9946 	 * Because we have made changes to the superblock, we need to
9947 	 * recompute its check-hash.
9948 	 */
9949 	bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9950 }
9951 
9952 /*
9953  * After a superblock is written determine whether it must be written again
9954  * due to a changing unlinked list head.
9955  */
9956 static int
9957 handle_written_sbdep(sbdep, bp)
9958 	struct sbdep *sbdep;
9959 	struct buf *bp;
9960 {
9961 	struct inodedep *inodedep;
9962 	struct fs *fs;
9963 
9964 	LOCK_OWNED(sbdep->sb_ump);
9965 	fs = sbdep->sb_fs;
9966 	/*
9967 	 * If the superblock doesn't match the in-memory list start over.
9968 	 */
9969 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9970 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9971 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9972 		bdirty(bp);
9973 		return (1);
9974 	}
9975 	WORKITEM_FREE(sbdep, D_SBDEP);
9976 	if (fs->fs_sujfree == 0)
9977 		return (0);
9978 	/*
9979 	 * Now that we have a record of this inode in stable store allow it
9980 	 * to be written to free up pending work.  Inodes may see a lot of
9981 	 * write activity after they are unlinked which we must not hold up.
9982 	 */
9983 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9984 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9985 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9986 			    inodedep, inodedep->id_state);
9987 		if (inodedep->id_state & UNLINKONLIST)
9988 			break;
9989 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9990 	}
9991 
9992 	return (0);
9993 }
9994 
9995 /*
9996  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9997  */
9998 static void
9999 unlinked_inodedep(mp, inodedep)
10000 	struct mount *mp;
10001 	struct inodedep *inodedep;
10002 {
10003 	struct ufsmount *ump;
10004 
10005 	ump = VFSTOUFS(mp);
10006 	LOCK_OWNED(ump);
10007 	if (MOUNTEDSUJ(mp) == 0)
10008 		return;
10009 	ump->um_fs->fs_fmod = 1;
10010 	if (inodedep->id_state & UNLINKED)
10011 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
10012 	inodedep->id_state |= UNLINKED;
10013 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
10014 }
10015 
10016 /*
10017  * Remove an inodedep from the unlinked inodedep list.  This may require
10018  * disk writes if the inode has made it that far.
10019  */
10020 static void
10021 clear_unlinked_inodedep(inodedep)
10022 	struct inodedep *inodedep;
10023 {
10024 	struct ufs2_dinode *dip;
10025 	struct ufsmount *ump;
10026 	struct inodedep *idp;
10027 	struct inodedep *idn;
10028 	struct fs *fs, *bpfs;
10029 	struct buf *bp;
10030 	daddr_t dbn;
10031 	ino_t ino;
10032 	ino_t nino;
10033 	ino_t pino;
10034 	int error;
10035 
10036 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10037 	fs = ump->um_fs;
10038 	ino = inodedep->id_ino;
10039 	error = 0;
10040 	for (;;) {
10041 		LOCK_OWNED(ump);
10042 		KASSERT((inodedep->id_state & UNLINKED) != 0,
10043 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
10044 		    inodedep));
10045 		/*
10046 		 * If nothing has yet been written simply remove us from
10047 		 * the in memory list and return.  This is the most common
10048 		 * case where handle_workitem_remove() loses the final
10049 		 * reference.
10050 		 */
10051 		if ((inodedep->id_state & UNLINKLINKS) == 0)
10052 			break;
10053 		/*
10054 		 * If we have a NEXT pointer and no PREV pointer we can simply
10055 		 * clear NEXT's PREV and remove ourselves from the list.  Be
10056 		 * careful not to clear PREV if the superblock points at
10057 		 * next as well.
10058 		 */
10059 		idn = TAILQ_NEXT(inodedep, id_unlinked);
10060 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
10061 			if (idn && fs->fs_sujfree != idn->id_ino)
10062 				idn->id_state &= ~UNLINKPREV;
10063 			break;
10064 		}
10065 		/*
10066 		 * Here we have an inodedep which is actually linked into
10067 		 * the list.  We must remove it by forcing a write to the
10068 		 * link before us, whether it be the superblock or an inode.
10069 		 * Unfortunately the list may change while we're waiting
10070 		 * on the buf lock for either resource so we must loop until
10071 		 * we lock the right one.  If both the superblock and an
10072 		 * inode point to this inode we must clear the inode first
10073 		 * followed by the superblock.
10074 		 */
10075 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
10076 		pino = 0;
10077 		if (idp && (idp->id_state & UNLINKNEXT))
10078 			pino = idp->id_ino;
10079 		FREE_LOCK(ump);
10080 		if (pino == 0) {
10081 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
10082 			    (int)fs->fs_sbsize, 0, 0, 0);
10083 		} else {
10084 			dbn = fsbtodb(fs, ino_to_fsba(fs, pino));
10085 			error = ffs_breadz(ump, ump->um_devvp, dbn, dbn,
10086 			    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL,
10087 			    &bp);
10088 		}
10089 		ACQUIRE_LOCK(ump);
10090 		if (error)
10091 			break;
10092 		/* If the list has changed restart the loop. */
10093 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
10094 		nino = 0;
10095 		if (idp && (idp->id_state & UNLINKNEXT))
10096 			nino = idp->id_ino;
10097 		if (nino != pino ||
10098 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
10099 			FREE_LOCK(ump);
10100 			brelse(bp);
10101 			ACQUIRE_LOCK(ump);
10102 			continue;
10103 		}
10104 		nino = 0;
10105 		idn = TAILQ_NEXT(inodedep, id_unlinked);
10106 		if (idn)
10107 			nino = idn->id_ino;
10108 		/*
10109 		 * Remove us from the in memory list.  After this we cannot
10110 		 * access the inodedep.
10111 		 */
10112 		KASSERT((inodedep->id_state & UNLINKED) != 0,
10113 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
10114 		    inodedep));
10115 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
10116 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
10117 		FREE_LOCK(ump);
10118 		/*
10119 		 * The predecessor's next pointer is manually updated here
10120 		 * so that the NEXT flag is never cleared for an element
10121 		 * that is in the list.
10122 		 */
10123 		if (pino == 0) {
10124 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
10125 			bpfs = (struct fs *)bp->b_data;
10126 			ffs_oldfscompat_write(bpfs, ump);
10127 			softdep_setup_sbupdate(ump, bpfs, bp);
10128 			/*
10129 			 * Because we may have made changes to the superblock,
10130 			 * we need to recompute its check-hash.
10131 			 */
10132 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
10133 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
10134 			((struct ufs1_dinode *)bp->b_data +
10135 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
10136 		} else {
10137 			dip = (struct ufs2_dinode *)bp->b_data +
10138 			    ino_to_fsbo(fs, pino);
10139 			dip->di_freelink = nino;
10140 			ffs_update_dinode_ckhash(fs, dip);
10141 		}
10142 		/*
10143 		 * If the bwrite fails we have no recourse to recover.  The
10144 		 * filesystem is corrupted already.
10145 		 */
10146 		bwrite(bp);
10147 		ACQUIRE_LOCK(ump);
10148 		/*
10149 		 * If the superblock pointer still needs to be cleared force
10150 		 * a write here.
10151 		 */
10152 		if (fs->fs_sujfree == ino) {
10153 			FREE_LOCK(ump);
10154 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
10155 			    (int)fs->fs_sbsize, 0, 0, 0);
10156 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
10157 			bpfs = (struct fs *)bp->b_data;
10158 			ffs_oldfscompat_write(bpfs, ump);
10159 			softdep_setup_sbupdate(ump, bpfs, bp);
10160 			/*
10161 			 * Because we may have made changes to the superblock,
10162 			 * we need to recompute its check-hash.
10163 			 */
10164 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
10165 			bwrite(bp);
10166 			ACQUIRE_LOCK(ump);
10167 		}
10168 
10169 		if (fs->fs_sujfree != ino)
10170 			return;
10171 		panic("clear_unlinked_inodedep: Failed to clear free head");
10172 	}
10173 	if (inodedep->id_ino == fs->fs_sujfree)
10174 		panic("clear_unlinked_inodedep: Freeing head of free list");
10175 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
10176 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
10177 	return;
10178 }
10179 
10180 /*
10181  * This workitem decrements the inode's link count.
10182  * If the link count reaches zero, the file is removed.
10183  */
10184 static int
10185 handle_workitem_remove(dirrem, flags)
10186 	struct dirrem *dirrem;
10187 	int flags;
10188 {
10189 	struct inodedep *inodedep;
10190 	struct workhead dotdotwk;
10191 	struct worklist *wk;
10192 	struct ufsmount *ump;
10193 	struct mount *mp;
10194 	struct vnode *vp;
10195 	struct inode *ip;
10196 	ino_t oldinum;
10197 
10198 	if (dirrem->dm_state & ONWORKLIST)
10199 		panic("handle_workitem_remove: dirrem %p still on worklist",
10200 		    dirrem);
10201 	oldinum = dirrem->dm_oldinum;
10202 	mp = dirrem->dm_list.wk_mp;
10203 	ump = VFSTOUFS(mp);
10204 	flags |= LK_EXCLUSIVE;
10205 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
10206 		return (EBUSY);
10207 	ip = VTOI(vp);
10208 	MPASS(ip->i_mode != 0);
10209 	ACQUIRE_LOCK(ump);
10210 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
10211 		panic("handle_workitem_remove: lost inodedep");
10212 	if (dirrem->dm_state & ONDEPLIST)
10213 		LIST_REMOVE(dirrem, dm_inonext);
10214 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
10215 	    ("handle_workitem_remove:  Journal entries not written."));
10216 
10217 	/*
10218 	 * Move all dependencies waiting on the remove to complete
10219 	 * from the dirrem to the inode inowait list to be completed
10220 	 * after the inode has been updated and written to disk.
10221 	 *
10222 	 * Any marked MKDIR_PARENT are saved to be completed when the
10223 	 * dotdot ref is removed unless DIRCHG is specified.  For
10224 	 * directory change operations there will be no further
10225 	 * directory writes and the jsegdeps need to be moved along
10226 	 * with the rest to be completed when the inode is free or
10227 	 * stable in the inode free list.
10228 	 */
10229 	LIST_INIT(&dotdotwk);
10230 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
10231 		WORKLIST_REMOVE(wk);
10232 		if ((dirrem->dm_state & DIRCHG) == 0 &&
10233 		    wk->wk_state & MKDIR_PARENT) {
10234 			wk->wk_state &= ~MKDIR_PARENT;
10235 			WORKLIST_INSERT(&dotdotwk, wk);
10236 			continue;
10237 		}
10238 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
10239 	}
10240 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
10241 	/*
10242 	 * Normal file deletion.
10243 	 */
10244 	if ((dirrem->dm_state & RMDIR) == 0) {
10245 		ip->i_nlink--;
10246 		KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
10247 		    "%ju negative i_nlink %d", (intmax_t)ip->i_number,
10248 		    ip->i_nlink));
10249 		DIP_SET(ip, i_nlink, ip->i_nlink);
10250 		UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10251 		if (ip->i_nlink < ip->i_effnlink)
10252 			panic("handle_workitem_remove: bad file delta");
10253 		if (ip->i_nlink == 0)
10254 			unlinked_inodedep(mp, inodedep);
10255 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10256 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10257 		    ("handle_workitem_remove: worklist not empty. %s",
10258 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
10259 		WORKITEM_FREE(dirrem, D_DIRREM);
10260 		FREE_LOCK(ump);
10261 		goto out;
10262 	}
10263 	/*
10264 	 * Directory deletion. Decrement reference count for both the
10265 	 * just deleted parent directory entry and the reference for ".".
10266 	 * Arrange to have the reference count on the parent decremented
10267 	 * to account for the loss of "..".
10268 	 */
10269 	ip->i_nlink -= 2;
10270 	KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
10271 	    "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
10272 	DIP_SET(ip, i_nlink, ip->i_nlink);
10273 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10274 	if (ip->i_nlink < ip->i_effnlink)
10275 		panic("handle_workitem_remove: bad dir delta");
10276 	if (ip->i_nlink == 0)
10277 		unlinked_inodedep(mp, inodedep);
10278 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10279 	/*
10280 	 * Rename a directory to a new parent. Since, we are both deleting
10281 	 * and creating a new directory entry, the link count on the new
10282 	 * directory should not change. Thus we skip the followup dirrem.
10283 	 */
10284 	if (dirrem->dm_state & DIRCHG) {
10285 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10286 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
10287 		WORKITEM_FREE(dirrem, D_DIRREM);
10288 		FREE_LOCK(ump);
10289 		goto out;
10290 	}
10291 	dirrem->dm_state = ONDEPLIST;
10292 	dirrem->dm_oldinum = dirrem->dm_dirinum;
10293 	/*
10294 	 * Place the dirrem on the parent's diremhd list.
10295 	 */
10296 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
10297 		panic("handle_workitem_remove: lost dir inodedep");
10298 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
10299 	/*
10300 	 * If the allocated inode has never been written to disk, then
10301 	 * the on-disk inode is zero'ed and we can remove the file
10302 	 * immediately.  When journaling if the inode has been marked
10303 	 * unlinked and not DEPCOMPLETE we know it can never be written.
10304 	 */
10305 	inodedep_lookup(mp, oldinum, 0, &inodedep);
10306 	if (inodedep == NULL ||
10307 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
10308 	    check_inode_unwritten(inodedep)) {
10309 		FREE_LOCK(ump);
10310 		vput(vp);
10311 		return handle_workitem_remove(dirrem, flags);
10312 	}
10313 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
10314 	FREE_LOCK(ump);
10315 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10316 out:
10317 	ffs_update(vp, 0);
10318 	vput(vp);
10319 	return (0);
10320 }
10321 
10322 /*
10323  * Inode de-allocation dependencies.
10324  *
10325  * When an inode's link count is reduced to zero, it can be de-allocated. We
10326  * found it convenient to postpone de-allocation until after the inode is
10327  * written to disk with its new link count (zero).  At this point, all of the
10328  * on-disk inode's block pointers are nullified and, with careful dependency
10329  * list ordering, all dependencies related to the inode will be satisfied and
10330  * the corresponding dependency structures de-allocated.  So, if/when the
10331  * inode is reused, there will be no mixing of old dependencies with new
10332  * ones.  This artificial dependency is set up by the block de-allocation
10333  * procedure above (softdep_setup_freeblocks) and completed by the
10334  * following procedure.
10335  */
10336 static void
10337 handle_workitem_freefile(freefile)
10338 	struct freefile *freefile;
10339 {
10340 	struct workhead wkhd;
10341 	struct fs *fs;
10342 	struct ufsmount *ump;
10343 	int error;
10344 #ifdef INVARIANTS
10345 	struct inodedep *idp;
10346 #endif
10347 
10348 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
10349 	fs = ump->um_fs;
10350 #ifdef INVARIANTS
10351 	ACQUIRE_LOCK(ump);
10352 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10353 	FREE_LOCK(ump);
10354 	if (error)
10355 		panic("handle_workitem_freefile: inodedep %p survived", idp);
10356 #endif
10357 	UFS_LOCK(ump);
10358 	fs->fs_pendinginodes -= 1;
10359 	UFS_UNLOCK(ump);
10360 	LIST_INIT(&wkhd);
10361 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10362 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10363 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10364 		softdep_error("handle_workitem_freefile", error);
10365 	ACQUIRE_LOCK(ump);
10366 	WORKITEM_FREE(freefile, D_FREEFILE);
10367 	FREE_LOCK(ump);
10368 }
10369 
10370 /*
10371  * Helper function which unlinks marker element from work list and returns
10372  * the next element on the list.
10373  */
10374 static __inline struct worklist *
10375 markernext(struct worklist *marker)
10376 {
10377 	struct worklist *next;
10378 
10379 	next = LIST_NEXT(marker, wk_list);
10380 	LIST_REMOVE(marker, wk_list);
10381 	return next;
10382 }
10383 
10384 /*
10385  * Disk writes.
10386  *
10387  * The dependency structures constructed above are most actively used when file
10388  * system blocks are written to disk.  No constraints are placed on when a
10389  * block can be written, but unsatisfied update dependencies are made safe by
10390  * modifying (or replacing) the source memory for the duration of the disk
10391  * write.  When the disk write completes, the memory block is again brought
10392  * up-to-date.
10393  *
10394  * In-core inode structure reclamation.
10395  *
10396  * Because there are a finite number of "in-core" inode structures, they are
10397  * reused regularly.  By transferring all inode-related dependencies to the
10398  * in-memory inode block and indexing them separately (via "inodedep"s), we
10399  * can allow "in-core" inode structures to be reused at any time and avoid
10400  * any increase in contention.
10401  *
10402  * Called just before entering the device driver to initiate a new disk I/O.
10403  * The buffer must be locked, thus, no I/O completion operations can occur
10404  * while we are manipulating its associated dependencies.
10405  */
10406 static void
10407 softdep_disk_io_initiation(bp)
10408 	struct buf *bp;		/* structure describing disk write to occur */
10409 {
10410 	struct worklist *wk;
10411 	struct worklist marker;
10412 	struct inodedep *inodedep;
10413 	struct freeblks *freeblks;
10414 	struct jblkdep *jblkdep;
10415 	struct newblk *newblk;
10416 	struct ufsmount *ump;
10417 
10418 	/*
10419 	 * We only care about write operations. There should never
10420 	 * be dependencies for reads.
10421 	 */
10422 	if (bp->b_iocmd != BIO_WRITE)
10423 		panic("softdep_disk_io_initiation: not write");
10424 
10425 	if (bp->b_vflags & BV_BKGRDINPROG)
10426 		panic("softdep_disk_io_initiation: Writing buffer with "
10427 		    "background write in progress: %p", bp);
10428 
10429 	ump = softdep_bp_to_mp(bp);
10430 	if (ump == NULL)
10431 		return;
10432 
10433 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10434 	PHOLD(curproc);			/* Don't swap out kernel stack */
10435 	ACQUIRE_LOCK(ump);
10436 	/*
10437 	 * Do any necessary pre-I/O processing.
10438 	 */
10439 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10440 	     wk = markernext(&marker)) {
10441 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10442 		switch (wk->wk_type) {
10443 		case D_PAGEDEP:
10444 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10445 			continue;
10446 
10447 		case D_INODEDEP:
10448 			inodedep = WK_INODEDEP(wk);
10449 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10450 				initiate_write_inodeblock_ufs1(inodedep, bp);
10451 			else
10452 				initiate_write_inodeblock_ufs2(inodedep, bp);
10453 			continue;
10454 
10455 		case D_INDIRDEP:
10456 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10457 			continue;
10458 
10459 		case D_BMSAFEMAP:
10460 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10461 			continue;
10462 
10463 		case D_JSEG:
10464 			WK_JSEG(wk)->js_buf = NULL;
10465 			continue;
10466 
10467 		case D_FREEBLKS:
10468 			freeblks = WK_FREEBLKS(wk);
10469 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10470 			/*
10471 			 * We have to wait for the freeblks to be journaled
10472 			 * before we can write an inodeblock with updated
10473 			 * pointers.  Be careful to arrange the marker so
10474 			 * we revisit the freeblks if it's not removed by
10475 			 * the first jwait().
10476 			 */
10477 			if (jblkdep != NULL) {
10478 				LIST_REMOVE(&marker, wk_list);
10479 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10480 				jwait(&jblkdep->jb_list, MNT_WAIT);
10481 			}
10482 			continue;
10483 		case D_ALLOCDIRECT:
10484 		case D_ALLOCINDIR:
10485 			/*
10486 			 * We have to wait for the jnewblk to be journaled
10487 			 * before we can write to a block if the contents
10488 			 * may be confused with an earlier file's indirect
10489 			 * at recovery time.  Handle the marker as described
10490 			 * above.
10491 			 */
10492 			newblk = WK_NEWBLK(wk);
10493 			if (newblk->nb_jnewblk != NULL &&
10494 			    indirblk_lookup(newblk->nb_list.wk_mp,
10495 			    newblk->nb_newblkno)) {
10496 				LIST_REMOVE(&marker, wk_list);
10497 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10498 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10499 			}
10500 			continue;
10501 
10502 		case D_SBDEP:
10503 			initiate_write_sbdep(WK_SBDEP(wk));
10504 			continue;
10505 
10506 		case D_MKDIR:
10507 		case D_FREEWORK:
10508 		case D_FREEDEP:
10509 		case D_JSEGDEP:
10510 			continue;
10511 
10512 		default:
10513 			panic("handle_disk_io_initiation: Unexpected type %s",
10514 			    TYPENAME(wk->wk_type));
10515 			/* NOTREACHED */
10516 		}
10517 	}
10518 	FREE_LOCK(ump);
10519 	PRELE(curproc);			/* Allow swapout of kernel stack */
10520 }
10521 
10522 /*
10523  * Called from within the procedure above to deal with unsatisfied
10524  * allocation dependencies in a directory. The buffer must be locked,
10525  * thus, no I/O completion operations can occur while we are
10526  * manipulating its associated dependencies.
10527  */
10528 static void
10529 initiate_write_filepage(pagedep, bp)
10530 	struct pagedep *pagedep;
10531 	struct buf *bp;
10532 {
10533 	struct jremref *jremref;
10534 	struct jmvref *jmvref;
10535 	struct dirrem *dirrem;
10536 	struct diradd *dap;
10537 	struct direct *ep;
10538 	int i;
10539 
10540 	if (pagedep->pd_state & IOSTARTED) {
10541 		/*
10542 		 * This can only happen if there is a driver that does not
10543 		 * understand chaining. Here biodone will reissue the call
10544 		 * to strategy for the incomplete buffers.
10545 		 */
10546 		printf("initiate_write_filepage: already started\n");
10547 		return;
10548 	}
10549 	pagedep->pd_state |= IOSTARTED;
10550 	/*
10551 	 * Wait for all journal remove dependencies to hit the disk.
10552 	 * We can not allow any potentially conflicting directory adds
10553 	 * to be visible before removes and rollback is too difficult.
10554 	 * The per-filesystem lock may be dropped and re-acquired, however
10555 	 * we hold the buf locked so the dependency can not go away.
10556 	 */
10557 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10558 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10559 			jwait(&jremref->jr_list, MNT_WAIT);
10560 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10561 		jwait(&jmvref->jm_list, MNT_WAIT);
10562 	for (i = 0; i < DAHASHSZ; i++) {
10563 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10564 			ep = (struct direct *)
10565 			    ((char *)bp->b_data + dap->da_offset);
10566 			if (ep->d_ino != dap->da_newinum)
10567 				panic("%s: dir inum %ju != new %ju",
10568 				    "initiate_write_filepage",
10569 				    (uintmax_t)ep->d_ino,
10570 				    (uintmax_t)dap->da_newinum);
10571 			if (dap->da_state & DIRCHG)
10572 				ep->d_ino = dap->da_previous->dm_oldinum;
10573 			else
10574 				ep->d_ino = 0;
10575 			dap->da_state &= ~ATTACHED;
10576 			dap->da_state |= UNDONE;
10577 		}
10578 	}
10579 }
10580 
10581 /*
10582  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10583  * Note that any bug fixes made to this routine must be done in the
10584  * version found below.
10585  *
10586  * Called from within the procedure above to deal with unsatisfied
10587  * allocation dependencies in an inodeblock. The buffer must be
10588  * locked, thus, no I/O completion operations can occur while we
10589  * are manipulating its associated dependencies.
10590  */
10591 static void
10592 initiate_write_inodeblock_ufs1(inodedep, bp)
10593 	struct inodedep *inodedep;
10594 	struct buf *bp;			/* The inode block */
10595 {
10596 	struct allocdirect *adp, *lastadp;
10597 	struct ufs1_dinode *dp;
10598 	struct ufs1_dinode *sip;
10599 	struct inoref *inoref;
10600 	struct ufsmount *ump;
10601 	struct fs *fs;
10602 	ufs_lbn_t i;
10603 #ifdef INVARIANTS
10604 	ufs_lbn_t prevlbn = 0;
10605 #endif
10606 	int deplist;
10607 
10608 	if (inodedep->id_state & IOSTARTED)
10609 		panic("initiate_write_inodeblock_ufs1: already started");
10610 	inodedep->id_state |= IOSTARTED;
10611 	fs = inodedep->id_fs;
10612 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10613 	LOCK_OWNED(ump);
10614 	dp = (struct ufs1_dinode *)bp->b_data +
10615 	    ino_to_fsbo(fs, inodedep->id_ino);
10616 
10617 	/*
10618 	 * If we're on the unlinked list but have not yet written our
10619 	 * next pointer initialize it here.
10620 	 */
10621 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10622 		struct inodedep *inon;
10623 
10624 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10625 		dp->di_freelink = inon ? inon->id_ino : 0;
10626 	}
10627 	/*
10628 	 * If the bitmap is not yet written, then the allocated
10629 	 * inode cannot be written to disk.
10630 	 */
10631 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10632 		if (inodedep->id_savedino1 != NULL)
10633 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10634 		FREE_LOCK(ump);
10635 		sip = malloc(sizeof(struct ufs1_dinode),
10636 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10637 		ACQUIRE_LOCK(ump);
10638 		inodedep->id_savedino1 = sip;
10639 		*inodedep->id_savedino1 = *dp;
10640 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10641 		dp->di_gen = inodedep->id_savedino1->di_gen;
10642 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10643 		return;
10644 	}
10645 	/*
10646 	 * If no dependencies, then there is nothing to roll back.
10647 	 */
10648 	inodedep->id_savedsize = dp->di_size;
10649 	inodedep->id_savedextsize = 0;
10650 	inodedep->id_savednlink = dp->di_nlink;
10651 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10652 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10653 		return;
10654 	/*
10655 	 * Revert the link count to that of the first unwritten journal entry.
10656 	 */
10657 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10658 	if (inoref)
10659 		dp->di_nlink = inoref->if_nlink;
10660 	/*
10661 	 * Set the dependencies to busy.
10662 	 */
10663 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10664 	     adp = TAILQ_NEXT(adp, ad_next)) {
10665 #ifdef INVARIANTS
10666 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10667 			panic("softdep_write_inodeblock: lbn order");
10668 		prevlbn = adp->ad_offset;
10669 		if (adp->ad_offset < UFS_NDADDR &&
10670 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10671 			panic("initiate_write_inodeblock_ufs1: "
10672 			    "direct pointer #%jd mismatch %d != %jd",
10673 			    (intmax_t)adp->ad_offset,
10674 			    dp->di_db[adp->ad_offset],
10675 			    (intmax_t)adp->ad_newblkno);
10676 		if (adp->ad_offset >= UFS_NDADDR &&
10677 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10678 			panic("initiate_write_inodeblock_ufs1: "
10679 			    "indirect pointer #%jd mismatch %d != %jd",
10680 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10681 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10682 			    (intmax_t)adp->ad_newblkno);
10683 		deplist |= 1 << adp->ad_offset;
10684 		if ((adp->ad_state & ATTACHED) == 0)
10685 			panic("initiate_write_inodeblock_ufs1: "
10686 			    "Unknown state 0x%x", adp->ad_state);
10687 #endif /* INVARIANTS */
10688 		adp->ad_state &= ~ATTACHED;
10689 		adp->ad_state |= UNDONE;
10690 	}
10691 	/*
10692 	 * The on-disk inode cannot claim to be any larger than the last
10693 	 * fragment that has been written. Otherwise, the on-disk inode
10694 	 * might have fragments that were not the last block in the file
10695 	 * which would corrupt the filesystem.
10696 	 */
10697 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10698 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10699 		if (adp->ad_offset >= UFS_NDADDR)
10700 			break;
10701 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10702 		/* keep going until hitting a rollback to a frag */
10703 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10704 			continue;
10705 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10706 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10707 #ifdef INVARIANTS
10708 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10709 				panic("initiate_write_inodeblock_ufs1: "
10710 				    "lost dep1");
10711 #endif /* INVARIANTS */
10712 			dp->di_db[i] = 0;
10713 		}
10714 		for (i = 0; i < UFS_NIADDR; i++) {
10715 #ifdef INVARIANTS
10716 			if (dp->di_ib[i] != 0 &&
10717 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10718 				panic("initiate_write_inodeblock_ufs1: "
10719 				    "lost dep2");
10720 #endif /* INVARIANTS */
10721 			dp->di_ib[i] = 0;
10722 		}
10723 		return;
10724 	}
10725 	/*
10726 	 * If we have zero'ed out the last allocated block of the file,
10727 	 * roll back the size to the last currently allocated block.
10728 	 * We know that this last allocated block is a full-sized as
10729 	 * we already checked for fragments in the loop above.
10730 	 */
10731 	if (lastadp != NULL &&
10732 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10733 		for (i = lastadp->ad_offset; i >= 0; i--)
10734 			if (dp->di_db[i] != 0)
10735 				break;
10736 		dp->di_size = (i + 1) * fs->fs_bsize;
10737 	}
10738 	/*
10739 	 * The only dependencies are for indirect blocks.
10740 	 *
10741 	 * The file size for indirect block additions is not guaranteed.
10742 	 * Such a guarantee would be non-trivial to achieve. The conventional
10743 	 * synchronous write implementation also does not make this guarantee.
10744 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10745 	 * can be over-estimated without destroying integrity when the file
10746 	 * moves into the indirect blocks (i.e., is large). If we want to
10747 	 * postpone fsck, we are stuck with this argument.
10748 	 */
10749 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10750 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10751 }
10752 
10753 /*
10754  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10755  * Note that any bug fixes made to this routine must be done in the
10756  * version found above.
10757  *
10758  * Called from within the procedure above to deal with unsatisfied
10759  * allocation dependencies in an inodeblock. The buffer must be
10760  * locked, thus, no I/O completion operations can occur while we
10761  * are manipulating its associated dependencies.
10762  */
10763 static void
10764 initiate_write_inodeblock_ufs2(inodedep, bp)
10765 	struct inodedep *inodedep;
10766 	struct buf *bp;			/* The inode block */
10767 {
10768 	struct allocdirect *adp, *lastadp;
10769 	struct ufs2_dinode *dp;
10770 	struct ufs2_dinode *sip;
10771 	struct inoref *inoref;
10772 	struct ufsmount *ump;
10773 	struct fs *fs;
10774 	ufs_lbn_t i;
10775 #ifdef INVARIANTS
10776 	ufs_lbn_t prevlbn = 0;
10777 #endif
10778 	int deplist;
10779 
10780 	if (inodedep->id_state & IOSTARTED)
10781 		panic("initiate_write_inodeblock_ufs2: already started");
10782 	inodedep->id_state |= IOSTARTED;
10783 	fs = inodedep->id_fs;
10784 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10785 	LOCK_OWNED(ump);
10786 	dp = (struct ufs2_dinode *)bp->b_data +
10787 	    ino_to_fsbo(fs, inodedep->id_ino);
10788 
10789 	/*
10790 	 * If we're on the unlinked list but have not yet written our
10791 	 * next pointer initialize it here.
10792 	 */
10793 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10794 		struct inodedep *inon;
10795 
10796 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10797 		dp->di_freelink = inon ? inon->id_ino : 0;
10798 		ffs_update_dinode_ckhash(fs, dp);
10799 	}
10800 	/*
10801 	 * If the bitmap is not yet written, then the allocated
10802 	 * inode cannot be written to disk.
10803 	 */
10804 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10805 		if (inodedep->id_savedino2 != NULL)
10806 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10807 		FREE_LOCK(ump);
10808 		sip = malloc(sizeof(struct ufs2_dinode),
10809 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10810 		ACQUIRE_LOCK(ump);
10811 		inodedep->id_savedino2 = sip;
10812 		*inodedep->id_savedino2 = *dp;
10813 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10814 		dp->di_gen = inodedep->id_savedino2->di_gen;
10815 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10816 		return;
10817 	}
10818 	/*
10819 	 * If no dependencies, then there is nothing to roll back.
10820 	 */
10821 	inodedep->id_savedsize = dp->di_size;
10822 	inodedep->id_savedextsize = dp->di_extsize;
10823 	inodedep->id_savednlink = dp->di_nlink;
10824 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10825 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10826 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10827 		return;
10828 	/*
10829 	 * Revert the link count to that of the first unwritten journal entry.
10830 	 */
10831 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10832 	if (inoref)
10833 		dp->di_nlink = inoref->if_nlink;
10834 
10835 	/*
10836 	 * Set the ext data dependencies to busy.
10837 	 */
10838 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10839 	     adp = TAILQ_NEXT(adp, ad_next)) {
10840 #ifdef INVARIANTS
10841 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10842 			panic("initiate_write_inodeblock_ufs2: lbn order");
10843 		prevlbn = adp->ad_offset;
10844 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10845 			panic("initiate_write_inodeblock_ufs2: "
10846 			    "ext pointer #%jd mismatch %jd != %jd",
10847 			    (intmax_t)adp->ad_offset,
10848 			    (intmax_t)dp->di_extb[adp->ad_offset],
10849 			    (intmax_t)adp->ad_newblkno);
10850 		deplist |= 1 << adp->ad_offset;
10851 		if ((adp->ad_state & ATTACHED) == 0)
10852 			panic("initiate_write_inodeblock_ufs2: Unknown "
10853 			    "state 0x%x", adp->ad_state);
10854 #endif /* INVARIANTS */
10855 		adp->ad_state &= ~ATTACHED;
10856 		adp->ad_state |= UNDONE;
10857 	}
10858 	/*
10859 	 * The on-disk inode cannot claim to be any larger than the last
10860 	 * fragment that has been written. Otherwise, the on-disk inode
10861 	 * might have fragments that were not the last block in the ext
10862 	 * data which would corrupt the filesystem.
10863 	 */
10864 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10865 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10866 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10867 		/* keep going until hitting a rollback to a frag */
10868 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10869 			continue;
10870 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10871 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10872 #ifdef INVARIANTS
10873 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10874 				panic("initiate_write_inodeblock_ufs2: "
10875 				    "lost dep1");
10876 #endif /* INVARIANTS */
10877 			dp->di_extb[i] = 0;
10878 		}
10879 		lastadp = NULL;
10880 		break;
10881 	}
10882 	/*
10883 	 * If we have zero'ed out the last allocated block of the ext
10884 	 * data, roll back the size to the last currently allocated block.
10885 	 * We know that this last allocated block is a full-sized as
10886 	 * we already checked for fragments in the loop above.
10887 	 */
10888 	if (lastadp != NULL &&
10889 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10890 		for (i = lastadp->ad_offset; i >= 0; i--)
10891 			if (dp->di_extb[i] != 0)
10892 				break;
10893 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10894 	}
10895 	/*
10896 	 * Set the file data dependencies to busy.
10897 	 */
10898 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10899 	     adp = TAILQ_NEXT(adp, ad_next)) {
10900 #ifdef INVARIANTS
10901 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10902 			panic("softdep_write_inodeblock: lbn order");
10903 		if ((adp->ad_state & ATTACHED) == 0)
10904 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10905 		prevlbn = adp->ad_offset;
10906 		if (!ffs_fsfail_cleanup(ump, 0) &&
10907 		    adp->ad_offset < UFS_NDADDR &&
10908 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10909 			panic("initiate_write_inodeblock_ufs2: "
10910 			    "direct pointer #%jd mismatch %jd != %jd",
10911 			    (intmax_t)adp->ad_offset,
10912 			    (intmax_t)dp->di_db[adp->ad_offset],
10913 			    (intmax_t)adp->ad_newblkno);
10914 		if (!ffs_fsfail_cleanup(ump, 0) &&
10915 		    adp->ad_offset >= UFS_NDADDR &&
10916 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10917 			panic("initiate_write_inodeblock_ufs2: "
10918 			    "indirect pointer #%jd mismatch %jd != %jd",
10919 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10920 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10921 			    (intmax_t)adp->ad_newblkno);
10922 		deplist |= 1 << adp->ad_offset;
10923 		if ((adp->ad_state & ATTACHED) == 0)
10924 			panic("initiate_write_inodeblock_ufs2: Unknown "
10925 			     "state 0x%x", adp->ad_state);
10926 #endif /* INVARIANTS */
10927 		adp->ad_state &= ~ATTACHED;
10928 		adp->ad_state |= UNDONE;
10929 	}
10930 	/*
10931 	 * The on-disk inode cannot claim to be any larger than the last
10932 	 * fragment that has been written. Otherwise, the on-disk inode
10933 	 * might have fragments that were not the last block in the file
10934 	 * which would corrupt the filesystem.
10935 	 */
10936 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10937 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10938 		if (adp->ad_offset >= UFS_NDADDR)
10939 			break;
10940 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10941 		/* keep going until hitting a rollback to a frag */
10942 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10943 			continue;
10944 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10945 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10946 #ifdef INVARIANTS
10947 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10948 				panic("initiate_write_inodeblock_ufs2: "
10949 				    "lost dep2");
10950 #endif /* INVARIANTS */
10951 			dp->di_db[i] = 0;
10952 		}
10953 		for (i = 0; i < UFS_NIADDR; i++) {
10954 #ifdef INVARIANTS
10955 			if (dp->di_ib[i] != 0 &&
10956 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10957 				panic("initiate_write_inodeblock_ufs2: "
10958 				    "lost dep3");
10959 #endif /* INVARIANTS */
10960 			dp->di_ib[i] = 0;
10961 		}
10962 		ffs_update_dinode_ckhash(fs, dp);
10963 		return;
10964 	}
10965 	/*
10966 	 * If we have zero'ed out the last allocated block of the file,
10967 	 * roll back the size to the last currently allocated block.
10968 	 * We know that this last allocated block is a full-sized as
10969 	 * we already checked for fragments in the loop above.
10970 	 */
10971 	if (lastadp != NULL &&
10972 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10973 		for (i = lastadp->ad_offset; i >= 0; i--)
10974 			if (dp->di_db[i] != 0)
10975 				break;
10976 		dp->di_size = (i + 1) * fs->fs_bsize;
10977 	}
10978 	/*
10979 	 * The only dependencies are for indirect blocks.
10980 	 *
10981 	 * The file size for indirect block additions is not guaranteed.
10982 	 * Such a guarantee would be non-trivial to achieve. The conventional
10983 	 * synchronous write implementation also does not make this guarantee.
10984 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10985 	 * can be over-estimated without destroying integrity when the file
10986 	 * moves into the indirect blocks (i.e., is large). If we want to
10987 	 * postpone fsck, we are stuck with this argument.
10988 	 */
10989 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10990 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10991 	ffs_update_dinode_ckhash(fs, dp);
10992 }
10993 
10994 /*
10995  * Cancel an indirdep as a result of truncation.  Release all of the
10996  * children allocindirs and place their journal work on the appropriate
10997  * list.
10998  */
10999 static void
11000 cancel_indirdep(indirdep, bp, freeblks)
11001 	struct indirdep *indirdep;
11002 	struct buf *bp;
11003 	struct freeblks *freeblks;
11004 {
11005 	struct allocindir *aip;
11006 
11007 	/*
11008 	 * None of the indirect pointers will ever be visible,
11009 	 * so they can simply be tossed. GOINGAWAY ensures
11010 	 * that allocated pointers will be saved in the buffer
11011 	 * cache until they are freed. Note that they will
11012 	 * only be able to be found by their physical address
11013 	 * since the inode mapping the logical address will
11014 	 * be gone. The save buffer used for the safe copy
11015 	 * was allocated in setup_allocindir_phase2 using
11016 	 * the physical address so it could be used for this
11017 	 * purpose. Hence we swap the safe copy with the real
11018 	 * copy, allowing the safe copy to be freed and holding
11019 	 * on to the real copy for later use in indir_trunc.
11020 	 */
11021 	if (indirdep->ir_state & GOINGAWAY)
11022 		panic("cancel_indirdep: already gone");
11023 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11024 		indirdep->ir_state |= DEPCOMPLETE;
11025 		LIST_REMOVE(indirdep, ir_next);
11026 	}
11027 	indirdep->ir_state |= GOINGAWAY;
11028 	/*
11029 	 * Pass in bp for blocks still have journal writes
11030 	 * pending so we can cancel them on their own.
11031 	 */
11032 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
11033 		cancel_allocindir(aip, bp, freeblks, 0);
11034 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
11035 		cancel_allocindir(aip, NULL, freeblks, 0);
11036 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
11037 		cancel_allocindir(aip, NULL, freeblks, 0);
11038 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
11039 		cancel_allocindir(aip, NULL, freeblks, 0);
11040 	/*
11041 	 * If there are pending partial truncations we need to keep the
11042 	 * old block copy around until they complete.  This is because
11043 	 * the current b_data is not a perfect superset of the available
11044 	 * blocks.
11045 	 */
11046 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
11047 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
11048 	else
11049 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
11050 	WORKLIST_REMOVE(&indirdep->ir_list);
11051 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
11052 	indirdep->ir_bp = NULL;
11053 	indirdep->ir_freeblks = freeblks;
11054 }
11055 
11056 /*
11057  * Free an indirdep once it no longer has new pointers to track.
11058  */
11059 static void
11060 free_indirdep(indirdep)
11061 	struct indirdep *indirdep;
11062 {
11063 
11064 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
11065 	    ("free_indirdep: Indir trunc list not empty."));
11066 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
11067 	    ("free_indirdep: Complete head not empty."));
11068 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
11069 	    ("free_indirdep: write head not empty."));
11070 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
11071 	    ("free_indirdep: done head not empty."));
11072 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
11073 	    ("free_indirdep: deplist head not empty."));
11074 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
11075 	    ("free_indirdep: %p still on newblk list.", indirdep));
11076 	KASSERT(indirdep->ir_saveddata == NULL,
11077 	    ("free_indirdep: %p still has saved data.", indirdep));
11078 	KASSERT(indirdep->ir_savebp == NULL,
11079 	    ("free_indirdep: %p still has savebp buffer.", indirdep));
11080 	if (indirdep->ir_state & ONWORKLIST)
11081 		WORKLIST_REMOVE(&indirdep->ir_list);
11082 	WORKITEM_FREE(indirdep, D_INDIRDEP);
11083 }
11084 
11085 /*
11086  * Called before a write to an indirdep.  This routine is responsible for
11087  * rolling back pointers to a safe state which includes only those
11088  * allocindirs which have been completed.
11089  */
11090 static void
11091 initiate_write_indirdep(indirdep, bp)
11092 	struct indirdep *indirdep;
11093 	struct buf *bp;
11094 {
11095 	struct ufsmount *ump;
11096 
11097 	indirdep->ir_state |= IOSTARTED;
11098 	if (indirdep->ir_state & GOINGAWAY)
11099 		panic("disk_io_initiation: indirdep gone");
11100 	/*
11101 	 * If there are no remaining dependencies, this will be writing
11102 	 * the real pointers.
11103 	 */
11104 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
11105 	    TAILQ_EMPTY(&indirdep->ir_trunc))
11106 		return;
11107 	/*
11108 	 * Replace up-to-date version with safe version.
11109 	 */
11110 	if (indirdep->ir_saveddata == NULL) {
11111 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
11112 		LOCK_OWNED(ump);
11113 		FREE_LOCK(ump);
11114 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
11115 		    M_SOFTDEP_FLAGS);
11116 		ACQUIRE_LOCK(ump);
11117 	}
11118 	indirdep->ir_state &= ~ATTACHED;
11119 	indirdep->ir_state |= UNDONE;
11120 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
11121 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
11122 	    bp->b_bcount);
11123 }
11124 
11125 /*
11126  * Called when an inode has been cleared in a cg bitmap.  This finally
11127  * eliminates any canceled jaddrefs
11128  */
11129 void
11130 softdep_setup_inofree(mp, bp, ino, wkhd)
11131 	struct mount *mp;
11132 	struct buf *bp;
11133 	ino_t ino;
11134 	struct workhead *wkhd;
11135 {
11136 	struct worklist *wk, *wkn;
11137 	struct inodedep *inodedep;
11138 	struct ufsmount *ump;
11139 	uint8_t *inosused;
11140 	struct cg *cgp;
11141 	struct fs *fs;
11142 
11143 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
11144 	    ("softdep_setup_inofree called on non-softdep filesystem"));
11145 	ump = VFSTOUFS(mp);
11146 	ACQUIRE_LOCK(ump);
11147 	if (!ffs_fsfail_cleanup(ump, 0)) {
11148 		fs = ump->um_fs;
11149 		cgp = (struct cg *)bp->b_data;
11150 		inosused = cg_inosused(cgp);
11151 		if (isset(inosused, ino % fs->fs_ipg))
11152 			panic("softdep_setup_inofree: inode %ju not freed.",
11153 			    (uintmax_t)ino);
11154 	}
11155 	if (inodedep_lookup(mp, ino, 0, &inodedep))
11156 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
11157 		    (uintmax_t)ino, inodedep);
11158 	if (wkhd) {
11159 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
11160 			if (wk->wk_type != D_JADDREF)
11161 				continue;
11162 			WORKLIST_REMOVE(wk);
11163 			/*
11164 			 * We can free immediately even if the jaddref
11165 			 * isn't attached in a background write as now
11166 			 * the bitmaps are reconciled.
11167 			 */
11168 			wk->wk_state |= COMPLETE | ATTACHED;
11169 			free_jaddref(WK_JADDREF(wk));
11170 		}
11171 		jwork_move(&bp->b_dep, wkhd);
11172 	}
11173 	FREE_LOCK(ump);
11174 }
11175 
11176 /*
11177  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
11178  * map.  Any dependencies waiting for the write to clear are added to the
11179  * buf's list and any jnewblks that are being canceled are discarded
11180  * immediately.
11181  */
11182 void
11183 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
11184 	struct mount *mp;
11185 	struct buf *bp;
11186 	ufs2_daddr_t blkno;
11187 	int frags;
11188 	struct workhead *wkhd;
11189 {
11190 	struct bmsafemap *bmsafemap;
11191 	struct jnewblk *jnewblk;
11192 	struct ufsmount *ump;
11193 	struct worklist *wk;
11194 	struct fs *fs;
11195 #ifdef INVARIANTS
11196 	uint8_t *blksfree;
11197 	struct cg *cgp;
11198 	ufs2_daddr_t jstart;
11199 	ufs2_daddr_t jend;
11200 	ufs2_daddr_t end;
11201 	long bno;
11202 	int i;
11203 #endif
11204 
11205 	CTR3(KTR_SUJ,
11206 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
11207 	    blkno, frags, wkhd);
11208 
11209 	ump = VFSTOUFS(mp);
11210 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
11211 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
11212 	ACQUIRE_LOCK(ump);
11213 	/* Lookup the bmsafemap so we track when it is dirty. */
11214 	fs = ump->um_fs;
11215 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11216 	/*
11217 	 * Detach any jnewblks which have been canceled.  They must linger
11218 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
11219 	 * an unjournaled allocation from hitting the disk.
11220 	 */
11221 	if (wkhd) {
11222 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
11223 			CTR2(KTR_SUJ,
11224 			    "softdep_setup_blkfree: blkno %jd wk type %d",
11225 			    blkno, wk->wk_type);
11226 			WORKLIST_REMOVE(wk);
11227 			if (wk->wk_type != D_JNEWBLK) {
11228 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
11229 				continue;
11230 			}
11231 			jnewblk = WK_JNEWBLK(wk);
11232 			KASSERT(jnewblk->jn_state & GOINGAWAY,
11233 			    ("softdep_setup_blkfree: jnewblk not canceled."));
11234 #ifdef INVARIANTS
11235 			/*
11236 			 * Assert that this block is free in the bitmap
11237 			 * before we discard the jnewblk.
11238 			 */
11239 			cgp = (struct cg *)bp->b_data;
11240 			blksfree = cg_blksfree(cgp);
11241 			bno = dtogd(fs, jnewblk->jn_blkno);
11242 			for (i = jnewblk->jn_oldfrags;
11243 			    i < jnewblk->jn_frags; i++) {
11244 				if (isset(blksfree, bno + i))
11245 					continue;
11246 				panic("softdep_setup_blkfree: not free");
11247 			}
11248 #endif
11249 			/*
11250 			 * Even if it's not attached we can free immediately
11251 			 * as the new bitmap is correct.
11252 			 */
11253 			wk->wk_state |= COMPLETE | ATTACHED;
11254 			free_jnewblk(jnewblk);
11255 		}
11256 	}
11257 
11258 #ifdef INVARIANTS
11259 	/*
11260 	 * Assert that we are not freeing a block which has an outstanding
11261 	 * allocation dependency.
11262 	 */
11263 	fs = VFSTOUFS(mp)->um_fs;
11264 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11265 	end = blkno + frags;
11266 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11267 		/*
11268 		 * Don't match against blocks that will be freed when the
11269 		 * background write is done.
11270 		 */
11271 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
11272 		    (COMPLETE | DEPCOMPLETE))
11273 			continue;
11274 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
11275 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
11276 		if ((blkno >= jstart && blkno < jend) ||
11277 		    (end > jstart && end <= jend)) {
11278 			printf("state 0x%X %jd - %d %d dep %p\n",
11279 			    jnewblk->jn_state, jnewblk->jn_blkno,
11280 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
11281 			    jnewblk->jn_dep);
11282 			panic("softdep_setup_blkfree: "
11283 			    "%jd-%jd(%d) overlaps with %jd-%jd",
11284 			    blkno, end, frags, jstart, jend);
11285 		}
11286 	}
11287 #endif
11288 	FREE_LOCK(ump);
11289 }
11290 
11291 /*
11292  * Revert a block allocation when the journal record that describes it
11293  * is not yet written.
11294  */
11295 static int
11296 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
11297 	struct jnewblk *jnewblk;
11298 	struct fs *fs;
11299 	struct cg *cgp;
11300 	uint8_t *blksfree;
11301 {
11302 	ufs1_daddr_t fragno;
11303 	long cgbno, bbase;
11304 	int frags, blk;
11305 	int i;
11306 
11307 	frags = 0;
11308 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11309 	/*
11310 	 * We have to test which frags need to be rolled back.  We may
11311 	 * be operating on a stale copy when doing background writes.
11312 	 */
11313 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
11314 		if (isclr(blksfree, cgbno + i))
11315 			frags++;
11316 	if (frags == 0)
11317 		return (0);
11318 	/*
11319 	 * This is mostly ffs_blkfree() sans some validation and
11320 	 * superblock updates.
11321 	 */
11322 	if (frags == fs->fs_frag) {
11323 		fragno = fragstoblks(fs, cgbno);
11324 		ffs_setblock(fs, blksfree, fragno);
11325 		ffs_clusteracct(fs, cgp, fragno, 1);
11326 		cgp->cg_cs.cs_nbfree++;
11327 	} else {
11328 		cgbno += jnewblk->jn_oldfrags;
11329 		bbase = cgbno - fragnum(fs, cgbno);
11330 		/* Decrement the old frags.  */
11331 		blk = blkmap(fs, blksfree, bbase);
11332 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11333 		/* Deallocate the fragment */
11334 		for (i = 0; i < frags; i++)
11335 			setbit(blksfree, cgbno + i);
11336 		cgp->cg_cs.cs_nffree += frags;
11337 		/* Add back in counts associated with the new frags */
11338 		blk = blkmap(fs, blksfree, bbase);
11339 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11340 		/* If a complete block has been reassembled, account for it. */
11341 		fragno = fragstoblks(fs, bbase);
11342 		if (ffs_isblock(fs, blksfree, fragno)) {
11343 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
11344 			ffs_clusteracct(fs, cgp, fragno, 1);
11345 			cgp->cg_cs.cs_nbfree++;
11346 		}
11347 	}
11348 	stat_jnewblk++;
11349 	jnewblk->jn_state &= ~ATTACHED;
11350 	jnewblk->jn_state |= UNDONE;
11351 
11352 	return (frags);
11353 }
11354 
11355 static void
11356 initiate_write_bmsafemap(bmsafemap, bp)
11357 	struct bmsafemap *bmsafemap;
11358 	struct buf *bp;			/* The cg block. */
11359 {
11360 	struct jaddref *jaddref;
11361 	struct jnewblk *jnewblk;
11362 	uint8_t *inosused;
11363 	uint8_t *blksfree;
11364 	struct cg *cgp;
11365 	struct fs *fs;
11366 	ino_t ino;
11367 
11368 	/*
11369 	 * If this is a background write, we did this at the time that
11370 	 * the copy was made, so do not need to do it again.
11371 	 */
11372 	if (bmsafemap->sm_state & IOSTARTED)
11373 		return;
11374 	bmsafemap->sm_state |= IOSTARTED;
11375 	/*
11376 	 * Clear any inode allocations which are pending journal writes.
11377 	 */
11378 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11379 		cgp = (struct cg *)bp->b_data;
11380 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11381 		inosused = cg_inosused(cgp);
11382 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11383 			ino = jaddref->ja_ino % fs->fs_ipg;
11384 			if (isset(inosused, ino)) {
11385 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11386 					cgp->cg_cs.cs_ndir--;
11387 				cgp->cg_cs.cs_nifree++;
11388 				clrbit(inosused, ino);
11389 				jaddref->ja_state &= ~ATTACHED;
11390 				jaddref->ja_state |= UNDONE;
11391 				stat_jaddref++;
11392 			} else
11393 				panic("initiate_write_bmsafemap: inode %ju "
11394 				    "marked free", (uintmax_t)jaddref->ja_ino);
11395 		}
11396 	}
11397 	/*
11398 	 * Clear any block allocations which are pending journal writes.
11399 	 */
11400 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11401 		cgp = (struct cg *)bp->b_data;
11402 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11403 		blksfree = cg_blksfree(cgp);
11404 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11405 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11406 				continue;
11407 			panic("initiate_write_bmsafemap: block %jd "
11408 			    "marked free", jnewblk->jn_blkno);
11409 		}
11410 	}
11411 	/*
11412 	 * Move allocation lists to the written lists so they can be
11413 	 * cleared once the block write is complete.
11414 	 */
11415 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11416 	    inodedep, id_deps);
11417 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11418 	    newblk, nb_deps);
11419 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11420 	    wk_list);
11421 }
11422 
11423 void
11424 softdep_handle_error(struct buf *bp)
11425 {
11426 	struct ufsmount *ump;
11427 
11428 	ump = softdep_bp_to_mp(bp);
11429 	if (ump == NULL)
11430 		return;
11431 
11432 	if (ffs_fsfail_cleanup(ump, bp->b_error)) {
11433 		/*
11434 		 * No future writes will succeed, so the on-disk image is safe.
11435 		 * Pretend that this write succeeded so that the softdep state
11436 		 * will be cleaned up naturally.
11437 		 */
11438 		bp->b_ioflags &= ~BIO_ERROR;
11439 		bp->b_error = 0;
11440 	}
11441 }
11442 
11443 /*
11444  * This routine is called during the completion interrupt
11445  * service routine for a disk write (from the procedure called
11446  * by the device driver to inform the filesystem caches of
11447  * a request completion).  It should be called early in this
11448  * procedure, before the block is made available to other
11449  * processes or other routines are called.
11450  *
11451  */
11452 static void
11453 softdep_disk_write_complete(bp)
11454 	struct buf *bp;		/* describes the completed disk write */
11455 {
11456 	struct worklist *wk;
11457 	struct worklist *owk;
11458 	struct ufsmount *ump;
11459 	struct workhead reattach;
11460 	struct freeblks *freeblks;
11461 	struct buf *sbp;
11462 
11463 	ump = softdep_bp_to_mp(bp);
11464 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11465 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11466 	     "with outstanding dependencies for buffer %p", bp));
11467 	if (ump == NULL)
11468 		return;
11469 	if ((bp->b_ioflags & BIO_ERROR) != 0)
11470 		softdep_handle_error(bp);
11471 	/*
11472 	 * If an error occurred while doing the write, then the data
11473 	 * has not hit the disk and the dependencies cannot be processed.
11474 	 * But we do have to go through and roll forward any dependencies
11475 	 * that were rolled back before the disk write.
11476 	 */
11477 	sbp = NULL;
11478 	ACQUIRE_LOCK(ump);
11479 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11480 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11481 			switch (wk->wk_type) {
11482 			case D_PAGEDEP:
11483 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11484 				continue;
11485 
11486 			case D_INODEDEP:
11487 				handle_written_inodeblock(WK_INODEDEP(wk),
11488 				    bp, 0);
11489 				continue;
11490 
11491 			case D_BMSAFEMAP:
11492 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11493 				    bp, 0);
11494 				continue;
11495 
11496 			case D_INDIRDEP:
11497 				handle_written_indirdep(WK_INDIRDEP(wk),
11498 				    bp, &sbp, 0);
11499 				continue;
11500 			default:
11501 				/* nothing to roll forward */
11502 				continue;
11503 			}
11504 		}
11505 		FREE_LOCK(ump);
11506 		if (sbp)
11507 			brelse(sbp);
11508 		return;
11509 	}
11510 	LIST_INIT(&reattach);
11511 
11512 	/*
11513 	 * Ump SU lock must not be released anywhere in this code segment.
11514 	 */
11515 	owk = NULL;
11516 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11517 		WORKLIST_REMOVE(wk);
11518 		atomic_add_long(&dep_write[wk->wk_type], 1);
11519 		if (wk == owk)
11520 			panic("duplicate worklist: %p\n", wk);
11521 		owk = wk;
11522 		switch (wk->wk_type) {
11523 		case D_PAGEDEP:
11524 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11525 			    WRITESUCCEEDED))
11526 				WORKLIST_INSERT(&reattach, wk);
11527 			continue;
11528 
11529 		case D_INODEDEP:
11530 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11531 			    WRITESUCCEEDED))
11532 				WORKLIST_INSERT(&reattach, wk);
11533 			continue;
11534 
11535 		case D_BMSAFEMAP:
11536 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11537 			    WRITESUCCEEDED))
11538 				WORKLIST_INSERT(&reattach, wk);
11539 			continue;
11540 
11541 		case D_MKDIR:
11542 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11543 			continue;
11544 
11545 		case D_ALLOCDIRECT:
11546 			wk->wk_state |= COMPLETE;
11547 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11548 			continue;
11549 
11550 		case D_ALLOCINDIR:
11551 			wk->wk_state |= COMPLETE;
11552 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11553 			continue;
11554 
11555 		case D_INDIRDEP:
11556 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11557 			    WRITESUCCEEDED))
11558 				WORKLIST_INSERT(&reattach, wk);
11559 			continue;
11560 
11561 		case D_FREEBLKS:
11562 			wk->wk_state |= COMPLETE;
11563 			freeblks = WK_FREEBLKS(wk);
11564 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11565 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11566 				add_to_worklist(wk, WK_NODELAY);
11567 			continue;
11568 
11569 		case D_FREEWORK:
11570 			handle_written_freework(WK_FREEWORK(wk));
11571 			break;
11572 
11573 		case D_JSEGDEP:
11574 			free_jsegdep(WK_JSEGDEP(wk));
11575 			continue;
11576 
11577 		case D_JSEG:
11578 			handle_written_jseg(WK_JSEG(wk), bp);
11579 			continue;
11580 
11581 		case D_SBDEP:
11582 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11583 				WORKLIST_INSERT(&reattach, wk);
11584 			continue;
11585 
11586 		case D_FREEDEP:
11587 			free_freedep(WK_FREEDEP(wk));
11588 			continue;
11589 
11590 		default:
11591 			panic("handle_disk_write_complete: Unknown type %s",
11592 			    TYPENAME(wk->wk_type));
11593 			/* NOTREACHED */
11594 		}
11595 	}
11596 	/*
11597 	 * Reattach any requests that must be redone.
11598 	 */
11599 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11600 		WORKLIST_REMOVE(wk);
11601 		WORKLIST_INSERT(&bp->b_dep, wk);
11602 	}
11603 	FREE_LOCK(ump);
11604 	if (sbp)
11605 		brelse(sbp);
11606 }
11607 
11608 /*
11609  * Called from within softdep_disk_write_complete above.
11610  */
11611 static void
11612 handle_allocdirect_partdone(adp, wkhd)
11613 	struct allocdirect *adp;	/* the completed allocdirect */
11614 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11615 {
11616 	struct allocdirectlst *listhead;
11617 	struct allocdirect *listadp;
11618 	struct inodedep *inodedep;
11619 	long bsize;
11620 
11621 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11622 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11623 		return;
11624 	/*
11625 	 * The on-disk inode cannot claim to be any larger than the last
11626 	 * fragment that has been written. Otherwise, the on-disk inode
11627 	 * might have fragments that were not the last block in the file
11628 	 * which would corrupt the filesystem. Thus, we cannot free any
11629 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11630 	 * these blocks must be rolled back to zero before writing the inode.
11631 	 * We check the currently active set of allocdirects in id_inoupdt
11632 	 * or id_extupdt as appropriate.
11633 	 */
11634 	inodedep = adp->ad_inodedep;
11635 	bsize = inodedep->id_fs->fs_bsize;
11636 	if (adp->ad_state & EXTDATA)
11637 		listhead = &inodedep->id_extupdt;
11638 	else
11639 		listhead = &inodedep->id_inoupdt;
11640 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11641 		/* found our block */
11642 		if (listadp == adp)
11643 			break;
11644 		/* continue if ad_oldlbn is not a fragment */
11645 		if (listadp->ad_oldsize == 0 ||
11646 		    listadp->ad_oldsize == bsize)
11647 			continue;
11648 		/* hit a fragment */
11649 		return;
11650 	}
11651 	/*
11652 	 * If we have reached the end of the current list without
11653 	 * finding the just finished dependency, then it must be
11654 	 * on the future dependency list. Future dependencies cannot
11655 	 * be freed until they are moved to the current list.
11656 	 */
11657 	if (listadp == NULL) {
11658 #ifdef INVARIANTS
11659 		if (adp->ad_state & EXTDATA)
11660 			listhead = &inodedep->id_newextupdt;
11661 		else
11662 			listhead = &inodedep->id_newinoupdt;
11663 		TAILQ_FOREACH(listadp, listhead, ad_next)
11664 			/* found our block */
11665 			if (listadp == adp)
11666 				break;
11667 		if (listadp == NULL)
11668 			panic("handle_allocdirect_partdone: lost dep");
11669 #endif /* INVARIANTS */
11670 		return;
11671 	}
11672 	/*
11673 	 * If we have found the just finished dependency, then queue
11674 	 * it along with anything that follows it that is complete.
11675 	 * Since the pointer has not yet been written in the inode
11676 	 * as the dependency prevents it, place the allocdirect on the
11677 	 * bufwait list where it will be freed once the pointer is
11678 	 * valid.
11679 	 */
11680 	if (wkhd == NULL)
11681 		wkhd = &inodedep->id_bufwait;
11682 	for (; adp; adp = listadp) {
11683 		listadp = TAILQ_NEXT(adp, ad_next);
11684 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11685 			return;
11686 		TAILQ_REMOVE(listhead, adp, ad_next);
11687 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11688 	}
11689 }
11690 
11691 /*
11692  * Called from within softdep_disk_write_complete above.  This routine
11693  * completes successfully written allocindirs.
11694  */
11695 static void
11696 handle_allocindir_partdone(aip)
11697 	struct allocindir *aip;		/* the completed allocindir */
11698 {
11699 	struct indirdep *indirdep;
11700 
11701 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11702 		return;
11703 	indirdep = aip->ai_indirdep;
11704 	LIST_REMOVE(aip, ai_next);
11705 	/*
11706 	 * Don't set a pointer while the buffer is undergoing IO or while
11707 	 * we have active truncations.
11708 	 */
11709 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11710 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11711 		return;
11712 	}
11713 	if (indirdep->ir_state & UFS1FMT)
11714 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11715 		    aip->ai_newblkno;
11716 	else
11717 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11718 		    aip->ai_newblkno;
11719 	/*
11720 	 * Await the pointer write before freeing the allocindir.
11721 	 */
11722 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11723 }
11724 
11725 /*
11726  * Release segments held on a jwork list.
11727  */
11728 static void
11729 handle_jwork(wkhd)
11730 	struct workhead *wkhd;
11731 {
11732 	struct worklist *wk;
11733 
11734 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11735 		WORKLIST_REMOVE(wk);
11736 		switch (wk->wk_type) {
11737 		case D_JSEGDEP:
11738 			free_jsegdep(WK_JSEGDEP(wk));
11739 			continue;
11740 		case D_FREEDEP:
11741 			free_freedep(WK_FREEDEP(wk));
11742 			continue;
11743 		case D_FREEFRAG:
11744 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11745 			WORKITEM_FREE(wk, D_FREEFRAG);
11746 			continue;
11747 		case D_FREEWORK:
11748 			handle_written_freework(WK_FREEWORK(wk));
11749 			continue;
11750 		default:
11751 			panic("handle_jwork: Unknown type %s\n",
11752 			    TYPENAME(wk->wk_type));
11753 		}
11754 	}
11755 }
11756 
11757 /*
11758  * Handle the bufwait list on an inode when it is safe to release items
11759  * held there.  This normally happens after an inode block is written but
11760  * may be delayed and handled later if there are pending journal items that
11761  * are not yet safe to be released.
11762  */
11763 static struct freefile *
11764 handle_bufwait(inodedep, refhd)
11765 	struct inodedep *inodedep;
11766 	struct workhead *refhd;
11767 {
11768 	struct jaddref *jaddref;
11769 	struct freefile *freefile;
11770 	struct worklist *wk;
11771 
11772 	freefile = NULL;
11773 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11774 		WORKLIST_REMOVE(wk);
11775 		switch (wk->wk_type) {
11776 		case D_FREEFILE:
11777 			/*
11778 			 * We defer adding freefile to the worklist
11779 			 * until all other additions have been made to
11780 			 * ensure that it will be done after all the
11781 			 * old blocks have been freed.
11782 			 */
11783 			if (freefile != NULL)
11784 				panic("handle_bufwait: freefile");
11785 			freefile = WK_FREEFILE(wk);
11786 			continue;
11787 
11788 		case D_MKDIR:
11789 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11790 			continue;
11791 
11792 		case D_DIRADD:
11793 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11794 			continue;
11795 
11796 		case D_FREEFRAG:
11797 			wk->wk_state |= COMPLETE;
11798 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11799 				add_to_worklist(wk, 0);
11800 			continue;
11801 
11802 		case D_DIRREM:
11803 			wk->wk_state |= COMPLETE;
11804 			add_to_worklist(wk, 0);
11805 			continue;
11806 
11807 		case D_ALLOCDIRECT:
11808 		case D_ALLOCINDIR:
11809 			free_newblk(WK_NEWBLK(wk));
11810 			continue;
11811 
11812 		case D_JNEWBLK:
11813 			wk->wk_state |= COMPLETE;
11814 			free_jnewblk(WK_JNEWBLK(wk));
11815 			continue;
11816 
11817 		/*
11818 		 * Save freed journal segments and add references on
11819 		 * the supplied list which will delay their release
11820 		 * until the cg bitmap is cleared on disk.
11821 		 */
11822 		case D_JSEGDEP:
11823 			if (refhd == NULL)
11824 				free_jsegdep(WK_JSEGDEP(wk));
11825 			else
11826 				WORKLIST_INSERT(refhd, wk);
11827 			continue;
11828 
11829 		case D_JADDREF:
11830 			jaddref = WK_JADDREF(wk);
11831 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11832 			    if_deps);
11833 			/*
11834 			 * Transfer any jaddrefs to the list to be freed with
11835 			 * the bitmap if we're handling a removed file.
11836 			 */
11837 			if (refhd == NULL) {
11838 				wk->wk_state |= COMPLETE;
11839 				free_jaddref(jaddref);
11840 			} else
11841 				WORKLIST_INSERT(refhd, wk);
11842 			continue;
11843 
11844 		default:
11845 			panic("handle_bufwait: Unknown type %p(%s)",
11846 			    wk, TYPENAME(wk->wk_type));
11847 			/* NOTREACHED */
11848 		}
11849 	}
11850 	return (freefile);
11851 }
11852 /*
11853  * Called from within softdep_disk_write_complete above to restore
11854  * in-memory inode block contents to their most up-to-date state. Note
11855  * that this routine is always called from interrupt level with further
11856  * interrupts from this device blocked.
11857  *
11858  * If the write did not succeed, we will do all the roll-forward
11859  * operations, but we will not take the actions that will allow its
11860  * dependencies to be processed.
11861  */
11862 static int
11863 handle_written_inodeblock(inodedep, bp, flags)
11864 	struct inodedep *inodedep;
11865 	struct buf *bp;		/* buffer containing the inode block */
11866 	int flags;
11867 {
11868 	struct freefile *freefile;
11869 	struct allocdirect *adp, *nextadp;
11870 	struct ufs1_dinode *dp1 = NULL;
11871 	struct ufs2_dinode *dp2 = NULL;
11872 	struct workhead wkhd;
11873 	int hadchanges, fstype;
11874 	ino_t freelink;
11875 
11876 	LIST_INIT(&wkhd);
11877 	hadchanges = 0;
11878 	freefile = NULL;
11879 	if ((inodedep->id_state & IOSTARTED) == 0)
11880 		panic("handle_written_inodeblock: not started");
11881 	inodedep->id_state &= ~IOSTARTED;
11882 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11883 		fstype = UFS1;
11884 		dp1 = (struct ufs1_dinode *)bp->b_data +
11885 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11886 		freelink = dp1->di_freelink;
11887 	} else {
11888 		fstype = UFS2;
11889 		dp2 = (struct ufs2_dinode *)bp->b_data +
11890 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11891 		freelink = dp2->di_freelink;
11892 	}
11893 	/*
11894 	 * Leave this inodeblock dirty until it's in the list.
11895 	 */
11896 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11897 	    (flags & WRITESUCCEEDED)) {
11898 		struct inodedep *inon;
11899 
11900 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11901 		if ((inon == NULL && freelink == 0) ||
11902 		    (inon && inon->id_ino == freelink)) {
11903 			if (inon)
11904 				inon->id_state |= UNLINKPREV;
11905 			inodedep->id_state |= UNLINKNEXT;
11906 		}
11907 		hadchanges = 1;
11908 	}
11909 	/*
11910 	 * If we had to rollback the inode allocation because of
11911 	 * bitmaps being incomplete, then simply restore it.
11912 	 * Keep the block dirty so that it will not be reclaimed until
11913 	 * all associated dependencies have been cleared and the
11914 	 * corresponding updates written to disk.
11915 	 */
11916 	if (inodedep->id_savedino1 != NULL) {
11917 		hadchanges = 1;
11918 		if (fstype == UFS1)
11919 			*dp1 = *inodedep->id_savedino1;
11920 		else
11921 			*dp2 = *inodedep->id_savedino2;
11922 		free(inodedep->id_savedino1, M_SAVEDINO);
11923 		inodedep->id_savedino1 = NULL;
11924 		if ((bp->b_flags & B_DELWRI) == 0)
11925 			stat_inode_bitmap++;
11926 		bdirty(bp);
11927 		/*
11928 		 * If the inode is clear here and GOINGAWAY it will never
11929 		 * be written.  Process the bufwait and clear any pending
11930 		 * work which may include the freefile.
11931 		 */
11932 		if (inodedep->id_state & GOINGAWAY)
11933 			goto bufwait;
11934 		return (1);
11935 	}
11936 	if (flags & WRITESUCCEEDED)
11937 		inodedep->id_state |= COMPLETE;
11938 	/*
11939 	 * Roll forward anything that had to be rolled back before
11940 	 * the inode could be updated.
11941 	 */
11942 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11943 		nextadp = TAILQ_NEXT(adp, ad_next);
11944 		if (adp->ad_state & ATTACHED)
11945 			panic("handle_written_inodeblock: new entry");
11946 		if (fstype == UFS1) {
11947 			if (adp->ad_offset < UFS_NDADDR) {
11948 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11949 					panic("%s %s #%jd mismatch %d != %jd",
11950 					    "handle_written_inodeblock:",
11951 					    "direct pointer",
11952 					    (intmax_t)adp->ad_offset,
11953 					    dp1->di_db[adp->ad_offset],
11954 					    (intmax_t)adp->ad_oldblkno);
11955 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11956 			} else {
11957 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11958 				    0)
11959 					panic("%s: %s #%jd allocated as %d",
11960 					    "handle_written_inodeblock",
11961 					    "indirect pointer",
11962 					    (intmax_t)adp->ad_offset -
11963 					    UFS_NDADDR,
11964 					    dp1->di_ib[adp->ad_offset -
11965 					    UFS_NDADDR]);
11966 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11967 				    adp->ad_newblkno;
11968 			}
11969 		} else {
11970 			if (adp->ad_offset < UFS_NDADDR) {
11971 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11972 					panic("%s: %s #%jd %s %jd != %jd",
11973 					    "handle_written_inodeblock",
11974 					    "direct pointer",
11975 					    (intmax_t)adp->ad_offset, "mismatch",
11976 					    (intmax_t)dp2->di_db[adp->ad_offset],
11977 					    (intmax_t)adp->ad_oldblkno);
11978 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11979 			} else {
11980 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11981 				    0)
11982 					panic("%s: %s #%jd allocated as %jd",
11983 					    "handle_written_inodeblock",
11984 					    "indirect pointer",
11985 					    (intmax_t)adp->ad_offset -
11986 					    UFS_NDADDR,
11987 					    (intmax_t)
11988 					    dp2->di_ib[adp->ad_offset -
11989 					    UFS_NDADDR]);
11990 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11991 				    adp->ad_newblkno;
11992 			}
11993 		}
11994 		adp->ad_state &= ~UNDONE;
11995 		adp->ad_state |= ATTACHED;
11996 		hadchanges = 1;
11997 	}
11998 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11999 		nextadp = TAILQ_NEXT(adp, ad_next);
12000 		if (adp->ad_state & ATTACHED)
12001 			panic("handle_written_inodeblock: new entry");
12002 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
12003 			panic("%s: direct pointers #%jd %s %jd != %jd",
12004 			    "handle_written_inodeblock",
12005 			    (intmax_t)adp->ad_offset, "mismatch",
12006 			    (intmax_t)dp2->di_extb[adp->ad_offset],
12007 			    (intmax_t)adp->ad_oldblkno);
12008 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
12009 		adp->ad_state &= ~UNDONE;
12010 		adp->ad_state |= ATTACHED;
12011 		hadchanges = 1;
12012 	}
12013 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
12014 		stat_direct_blk_ptrs++;
12015 	/*
12016 	 * Reset the file size to its most up-to-date value.
12017 	 */
12018 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
12019 		panic("handle_written_inodeblock: bad size");
12020 	if (inodedep->id_savednlink > UFS_LINK_MAX)
12021 		panic("handle_written_inodeblock: Invalid link count "
12022 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
12023 		    inodedep);
12024 	if (fstype == UFS1) {
12025 		if (dp1->di_nlink != inodedep->id_savednlink) {
12026 			dp1->di_nlink = inodedep->id_savednlink;
12027 			hadchanges = 1;
12028 		}
12029 		if (dp1->di_size != inodedep->id_savedsize) {
12030 			dp1->di_size = inodedep->id_savedsize;
12031 			hadchanges = 1;
12032 		}
12033 	} else {
12034 		if (dp2->di_nlink != inodedep->id_savednlink) {
12035 			dp2->di_nlink = inodedep->id_savednlink;
12036 			hadchanges = 1;
12037 		}
12038 		if (dp2->di_size != inodedep->id_savedsize) {
12039 			dp2->di_size = inodedep->id_savedsize;
12040 			hadchanges = 1;
12041 		}
12042 		if (dp2->di_extsize != inodedep->id_savedextsize) {
12043 			dp2->di_extsize = inodedep->id_savedextsize;
12044 			hadchanges = 1;
12045 		}
12046 	}
12047 	inodedep->id_savedsize = -1;
12048 	inodedep->id_savedextsize = -1;
12049 	inodedep->id_savednlink = -1;
12050 	/*
12051 	 * If there were any rollbacks in the inode block, then it must be
12052 	 * marked dirty so that its will eventually get written back in
12053 	 * its correct form.
12054 	 */
12055 	if (hadchanges) {
12056 		if (fstype == UFS2)
12057 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
12058 		bdirty(bp);
12059 	}
12060 bufwait:
12061 	/*
12062 	 * If the write did not succeed, we have done all the roll-forward
12063 	 * operations, but we cannot take the actions that will allow its
12064 	 * dependencies to be processed.
12065 	 */
12066 	if ((flags & WRITESUCCEEDED) == 0)
12067 		return (hadchanges);
12068 	/*
12069 	 * Process any allocdirects that completed during the update.
12070 	 */
12071 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
12072 		handle_allocdirect_partdone(adp, &wkhd);
12073 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
12074 		handle_allocdirect_partdone(adp, &wkhd);
12075 	/*
12076 	 * Process deallocations that were held pending until the
12077 	 * inode had been written to disk. Freeing of the inode
12078 	 * is delayed until after all blocks have been freed to
12079 	 * avoid creation of new <vfsid, inum, lbn> triples
12080 	 * before the old ones have been deleted.  Completely
12081 	 * unlinked inodes are not processed until the unlinked
12082 	 * inode list is written or the last reference is removed.
12083 	 */
12084 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
12085 		freefile = handle_bufwait(inodedep, NULL);
12086 		if (freefile && !LIST_EMPTY(&wkhd)) {
12087 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
12088 			freefile = NULL;
12089 		}
12090 	}
12091 	/*
12092 	 * Move rolled forward dependency completions to the bufwait list
12093 	 * now that those that were already written have been processed.
12094 	 */
12095 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
12096 		panic("handle_written_inodeblock: bufwait but no changes");
12097 	jwork_move(&inodedep->id_bufwait, &wkhd);
12098 
12099 	if (freefile != NULL) {
12100 		/*
12101 		 * If the inode is goingaway it was never written.  Fake up
12102 		 * the state here so free_inodedep() can succeed.
12103 		 */
12104 		if (inodedep->id_state & GOINGAWAY)
12105 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
12106 		if (free_inodedep(inodedep) == 0)
12107 			panic("handle_written_inodeblock: live inodedep %p",
12108 			    inodedep);
12109 		add_to_worklist(&freefile->fx_list, 0);
12110 		return (0);
12111 	}
12112 
12113 	/*
12114 	 * If no outstanding dependencies, free it.
12115 	 */
12116 	if (free_inodedep(inodedep) ||
12117 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
12118 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
12119 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
12120 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
12121 		return (0);
12122 	return (hadchanges);
12123 }
12124 
12125 /*
12126  * Perform needed roll-forwards and kick off any dependencies that
12127  * can now be processed.
12128  *
12129  * If the write did not succeed, we will do all the roll-forward
12130  * operations, but we will not take the actions that will allow its
12131  * dependencies to be processed.
12132  */
12133 static int
12134 handle_written_indirdep(indirdep, bp, bpp, flags)
12135 	struct indirdep *indirdep;
12136 	struct buf *bp;
12137 	struct buf **bpp;
12138 	int flags;
12139 {
12140 	struct allocindir *aip;
12141 	struct buf *sbp;
12142 	int chgs;
12143 
12144 	if (indirdep->ir_state & GOINGAWAY)
12145 		panic("handle_written_indirdep: indirdep gone");
12146 	if ((indirdep->ir_state & IOSTARTED) == 0)
12147 		panic("handle_written_indirdep: IO not started");
12148 	chgs = 0;
12149 	/*
12150 	 * If there were rollbacks revert them here.
12151 	 */
12152 	if (indirdep->ir_saveddata) {
12153 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
12154 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
12155 			free(indirdep->ir_saveddata, M_INDIRDEP);
12156 			indirdep->ir_saveddata = NULL;
12157 		}
12158 		chgs = 1;
12159 	}
12160 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
12161 	indirdep->ir_state |= ATTACHED;
12162 	/*
12163 	 * If the write did not succeed, we have done all the roll-forward
12164 	 * operations, but we cannot take the actions that will allow its
12165 	 * dependencies to be processed.
12166 	 */
12167 	if ((flags & WRITESUCCEEDED) == 0) {
12168 		stat_indir_blk_ptrs++;
12169 		bdirty(bp);
12170 		return (1);
12171 	}
12172 	/*
12173 	 * Move allocindirs with written pointers to the completehd if
12174 	 * the indirdep's pointer is not yet written.  Otherwise
12175 	 * free them here.
12176 	 */
12177 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
12178 		LIST_REMOVE(aip, ai_next);
12179 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
12180 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
12181 			    ai_next);
12182 			newblk_freefrag(&aip->ai_block);
12183 			continue;
12184 		}
12185 		free_newblk(&aip->ai_block);
12186 	}
12187 	/*
12188 	 * Move allocindirs that have finished dependency processing from
12189 	 * the done list to the write list after updating the pointers.
12190 	 */
12191 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
12192 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
12193 			handle_allocindir_partdone(aip);
12194 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
12195 				panic("disk_write_complete: not gone");
12196 			chgs = 1;
12197 		}
12198 	}
12199 	/*
12200 	 * Preserve the indirdep if there were any changes or if it is not
12201 	 * yet valid on disk.
12202 	 */
12203 	if (chgs) {
12204 		stat_indir_blk_ptrs++;
12205 		bdirty(bp);
12206 		return (1);
12207 	}
12208 	/*
12209 	 * If there were no changes we can discard the savedbp and detach
12210 	 * ourselves from the buf.  We are only carrying completed pointers
12211 	 * in this case.
12212 	 */
12213 	sbp = indirdep->ir_savebp;
12214 	sbp->b_flags |= B_INVAL | B_NOCACHE;
12215 	indirdep->ir_savebp = NULL;
12216 	indirdep->ir_bp = NULL;
12217 	if (*bpp != NULL)
12218 		panic("handle_written_indirdep: bp already exists.");
12219 	*bpp = sbp;
12220 	/*
12221 	 * The indirdep may not be freed until its parent points at it.
12222 	 */
12223 	if (indirdep->ir_state & DEPCOMPLETE)
12224 		free_indirdep(indirdep);
12225 
12226 	return (0);
12227 }
12228 
12229 /*
12230  * Process a diradd entry after its dependent inode has been written.
12231  */
12232 static void
12233 diradd_inode_written(dap, inodedep)
12234 	struct diradd *dap;
12235 	struct inodedep *inodedep;
12236 {
12237 
12238 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
12239 	dap->da_state |= COMPLETE;
12240 	complete_diradd(dap);
12241 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
12242 }
12243 
12244 /*
12245  * Returns true if the bmsafemap will have rollbacks when written.  Must only
12246  * be called with the per-filesystem lock and the buf lock on the cg held.
12247  */
12248 static int
12249 bmsafemap_backgroundwrite(bmsafemap, bp)
12250 	struct bmsafemap *bmsafemap;
12251 	struct buf *bp;
12252 {
12253 	int dirty;
12254 
12255 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
12256 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
12257 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
12258 	/*
12259 	 * If we're initiating a background write we need to process the
12260 	 * rollbacks as they exist now, not as they exist when IO starts.
12261 	 * No other consumers will look at the contents of the shadowed
12262 	 * buf so this is safe to do here.
12263 	 */
12264 	if (bp->b_xflags & BX_BKGRDMARKER)
12265 		initiate_write_bmsafemap(bmsafemap, bp);
12266 
12267 	return (dirty);
12268 }
12269 
12270 /*
12271  * Re-apply an allocation when a cg write is complete.
12272  */
12273 static int
12274 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
12275 	struct jnewblk *jnewblk;
12276 	struct fs *fs;
12277 	struct cg *cgp;
12278 	uint8_t *blksfree;
12279 {
12280 	ufs1_daddr_t fragno;
12281 	ufs2_daddr_t blkno;
12282 	long cgbno, bbase;
12283 	int frags, blk;
12284 	int i;
12285 
12286 	frags = 0;
12287 	cgbno = dtogd(fs, jnewblk->jn_blkno);
12288 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
12289 		if (isclr(blksfree, cgbno + i))
12290 			panic("jnewblk_rollforward: re-allocated fragment");
12291 		frags++;
12292 	}
12293 	if (frags == fs->fs_frag) {
12294 		blkno = fragstoblks(fs, cgbno);
12295 		ffs_clrblock(fs, blksfree, (long)blkno);
12296 		ffs_clusteracct(fs, cgp, blkno, -1);
12297 		cgp->cg_cs.cs_nbfree--;
12298 	} else {
12299 		bbase = cgbno - fragnum(fs, cgbno);
12300 		cgbno += jnewblk->jn_oldfrags;
12301                 /* If a complete block had been reassembled, account for it. */
12302 		fragno = fragstoblks(fs, bbase);
12303 		if (ffs_isblock(fs, blksfree, fragno)) {
12304 			cgp->cg_cs.cs_nffree += fs->fs_frag;
12305 			ffs_clusteracct(fs, cgp, fragno, -1);
12306 			cgp->cg_cs.cs_nbfree--;
12307 		}
12308 		/* Decrement the old frags.  */
12309 		blk = blkmap(fs, blksfree, bbase);
12310 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
12311 		/* Allocate the fragment */
12312 		for (i = 0; i < frags; i++)
12313 			clrbit(blksfree, cgbno + i);
12314 		cgp->cg_cs.cs_nffree -= frags;
12315 		/* Add back in counts associated with the new frags */
12316 		blk = blkmap(fs, blksfree, bbase);
12317 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
12318 	}
12319 	return (frags);
12320 }
12321 
12322 /*
12323  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
12324  * changes if it's not a background write.  Set all written dependencies
12325  * to DEPCOMPLETE and free the structure if possible.
12326  *
12327  * If the write did not succeed, we will do all the roll-forward
12328  * operations, but we will not take the actions that will allow its
12329  * dependencies to be processed.
12330  */
12331 static int
12332 handle_written_bmsafemap(bmsafemap, bp, flags)
12333 	struct bmsafemap *bmsafemap;
12334 	struct buf *bp;
12335 	int flags;
12336 {
12337 	struct newblk *newblk;
12338 	struct inodedep *inodedep;
12339 	struct jaddref *jaddref, *jatmp;
12340 	struct jnewblk *jnewblk, *jntmp;
12341 	struct ufsmount *ump;
12342 	uint8_t *inosused;
12343 	uint8_t *blksfree;
12344 	struct cg *cgp;
12345 	struct fs *fs;
12346 	ino_t ino;
12347 	int foreground;
12348 	int chgs;
12349 
12350 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
12351 		panic("handle_written_bmsafemap: Not started\n");
12352 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
12353 	chgs = 0;
12354 	bmsafemap->sm_state &= ~IOSTARTED;
12355 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
12356 	/*
12357 	 * If write was successful, release journal work that was waiting
12358 	 * on the write. Otherwise move the work back.
12359 	 */
12360 	if (flags & WRITESUCCEEDED)
12361 		handle_jwork(&bmsafemap->sm_freewr);
12362 	else
12363 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12364 		    worklist, wk_list);
12365 
12366 	/*
12367 	 * Restore unwritten inode allocation pending jaddref writes.
12368 	 */
12369 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
12370 		cgp = (struct cg *)bp->b_data;
12371 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12372 		inosused = cg_inosused(cgp);
12373 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
12374 		    ja_bmdeps, jatmp) {
12375 			if ((jaddref->ja_state & UNDONE) == 0)
12376 				continue;
12377 			ino = jaddref->ja_ino % fs->fs_ipg;
12378 			if (isset(inosused, ino))
12379 				panic("handle_written_bmsafemap: "
12380 				    "re-allocated inode");
12381 			/* Do the roll-forward only if it's a real copy. */
12382 			if (foreground) {
12383 				if ((jaddref->ja_mode & IFMT) == IFDIR)
12384 					cgp->cg_cs.cs_ndir++;
12385 				cgp->cg_cs.cs_nifree--;
12386 				setbit(inosused, ino);
12387 				chgs = 1;
12388 			}
12389 			jaddref->ja_state &= ~UNDONE;
12390 			jaddref->ja_state |= ATTACHED;
12391 			free_jaddref(jaddref);
12392 		}
12393 	}
12394 	/*
12395 	 * Restore any block allocations which are pending journal writes.
12396 	 */
12397 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12398 		cgp = (struct cg *)bp->b_data;
12399 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12400 		blksfree = cg_blksfree(cgp);
12401 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12402 		    jntmp) {
12403 			if ((jnewblk->jn_state & UNDONE) == 0)
12404 				continue;
12405 			/* Do the roll-forward only if it's a real copy. */
12406 			if (foreground &&
12407 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12408 				chgs = 1;
12409 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12410 			jnewblk->jn_state |= ATTACHED;
12411 			free_jnewblk(jnewblk);
12412 		}
12413 	}
12414 	/*
12415 	 * If the write did not succeed, we have done all the roll-forward
12416 	 * operations, but we cannot take the actions that will allow its
12417 	 * dependencies to be processed.
12418 	 */
12419 	if ((flags & WRITESUCCEEDED) == 0) {
12420 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12421 		    newblk, nb_deps);
12422 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12423 		    worklist, wk_list);
12424 		if (foreground)
12425 			bdirty(bp);
12426 		return (1);
12427 	}
12428 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12429 		newblk->nb_state |= DEPCOMPLETE;
12430 		newblk->nb_state &= ~ONDEPLIST;
12431 		newblk->nb_bmsafemap = NULL;
12432 		LIST_REMOVE(newblk, nb_deps);
12433 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12434 			handle_allocdirect_partdone(
12435 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12436 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12437 			handle_allocindir_partdone(
12438 			    WK_ALLOCINDIR(&newblk->nb_list));
12439 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12440 			panic("handle_written_bmsafemap: Unexpected type: %s",
12441 			    TYPENAME(newblk->nb_list.wk_type));
12442 	}
12443 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12444 		inodedep->id_state |= DEPCOMPLETE;
12445 		inodedep->id_state &= ~ONDEPLIST;
12446 		LIST_REMOVE(inodedep, id_deps);
12447 		inodedep->id_bmsafemap = NULL;
12448 	}
12449 	LIST_REMOVE(bmsafemap, sm_next);
12450 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12451 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12452 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12453 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12454 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12455 		LIST_REMOVE(bmsafemap, sm_hash);
12456 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12457 		return (0);
12458 	}
12459 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12460 	if (foreground)
12461 		bdirty(bp);
12462 	return (1);
12463 }
12464 
12465 /*
12466  * Try to free a mkdir dependency.
12467  */
12468 static void
12469 complete_mkdir(mkdir)
12470 	struct mkdir *mkdir;
12471 {
12472 	struct diradd *dap;
12473 
12474 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12475 		return;
12476 	LIST_REMOVE(mkdir, md_mkdirs);
12477 	dap = mkdir->md_diradd;
12478 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12479 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12480 		dap->da_state |= DEPCOMPLETE;
12481 		complete_diradd(dap);
12482 	}
12483 	WORKITEM_FREE(mkdir, D_MKDIR);
12484 }
12485 
12486 /*
12487  * Handle the completion of a mkdir dependency.
12488  */
12489 static void
12490 handle_written_mkdir(mkdir, type)
12491 	struct mkdir *mkdir;
12492 	int type;
12493 {
12494 
12495 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12496 		panic("handle_written_mkdir: bad type");
12497 	mkdir->md_state |= COMPLETE;
12498 	complete_mkdir(mkdir);
12499 }
12500 
12501 static int
12502 free_pagedep(pagedep)
12503 	struct pagedep *pagedep;
12504 {
12505 	int i;
12506 
12507 	if (pagedep->pd_state & NEWBLOCK)
12508 		return (0);
12509 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12510 		return (0);
12511 	for (i = 0; i < DAHASHSZ; i++)
12512 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12513 			return (0);
12514 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12515 		return (0);
12516 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12517 		return (0);
12518 	if (pagedep->pd_state & ONWORKLIST)
12519 		WORKLIST_REMOVE(&pagedep->pd_list);
12520 	LIST_REMOVE(pagedep, pd_hash);
12521 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12522 
12523 	return (1);
12524 }
12525 
12526 /*
12527  * Called from within softdep_disk_write_complete above.
12528  * A write operation was just completed. Removed inodes can
12529  * now be freed and associated block pointers may be committed.
12530  * Note that this routine is always called from interrupt level
12531  * with further interrupts from this device blocked.
12532  *
12533  * If the write did not succeed, we will do all the roll-forward
12534  * operations, but we will not take the actions that will allow its
12535  * dependencies to be processed.
12536  */
12537 static int
12538 handle_written_filepage(pagedep, bp, flags)
12539 	struct pagedep *pagedep;
12540 	struct buf *bp;		/* buffer containing the written page */
12541 	int flags;
12542 {
12543 	struct dirrem *dirrem;
12544 	struct diradd *dap, *nextdap;
12545 	struct direct *ep;
12546 	int i, chgs;
12547 
12548 	if ((pagedep->pd_state & IOSTARTED) == 0)
12549 		panic("handle_written_filepage: not started");
12550 	pagedep->pd_state &= ~IOSTARTED;
12551 	if ((flags & WRITESUCCEEDED) == 0)
12552 		goto rollforward;
12553 	/*
12554 	 * Process any directory removals that have been committed.
12555 	 */
12556 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12557 		LIST_REMOVE(dirrem, dm_next);
12558 		dirrem->dm_state |= COMPLETE;
12559 		dirrem->dm_dirinum = pagedep->pd_ino;
12560 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12561 		    ("handle_written_filepage: Journal entries not written."));
12562 		add_to_worklist(&dirrem->dm_list, 0);
12563 	}
12564 	/*
12565 	 * Free any directory additions that have been committed.
12566 	 * If it is a newly allocated block, we have to wait until
12567 	 * the on-disk directory inode claims the new block.
12568 	 */
12569 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12570 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12571 			free_diradd(dap, NULL);
12572 rollforward:
12573 	/*
12574 	 * Uncommitted directory entries must be restored.
12575 	 */
12576 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12577 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12578 		     dap = nextdap) {
12579 			nextdap = LIST_NEXT(dap, da_pdlist);
12580 			if (dap->da_state & ATTACHED)
12581 				panic("handle_written_filepage: attached");
12582 			ep = (struct direct *)
12583 			    ((char *)bp->b_data + dap->da_offset);
12584 			ep->d_ino = dap->da_newinum;
12585 			dap->da_state &= ~UNDONE;
12586 			dap->da_state |= ATTACHED;
12587 			chgs = 1;
12588 			/*
12589 			 * If the inode referenced by the directory has
12590 			 * been written out, then the dependency can be
12591 			 * moved to the pending list.
12592 			 */
12593 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12594 				LIST_REMOVE(dap, da_pdlist);
12595 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12596 				    da_pdlist);
12597 			}
12598 		}
12599 	}
12600 	/*
12601 	 * If there were any rollbacks in the directory, then it must be
12602 	 * marked dirty so that its will eventually get written back in
12603 	 * its correct form.
12604 	 */
12605 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12606 		if ((bp->b_flags & B_DELWRI) == 0)
12607 			stat_dir_entry++;
12608 		bdirty(bp);
12609 		return (1);
12610 	}
12611 	/*
12612 	 * If we are not waiting for a new directory block to be
12613 	 * claimed by its inode, then the pagedep will be freed.
12614 	 * Otherwise it will remain to track any new entries on
12615 	 * the page in case they are fsync'ed.
12616 	 */
12617 	free_pagedep(pagedep);
12618 	return (0);
12619 }
12620 
12621 /*
12622  * Writing back in-core inode structures.
12623  *
12624  * The filesystem only accesses an inode's contents when it occupies an
12625  * "in-core" inode structure.  These "in-core" structures are separate from
12626  * the page frames used to cache inode blocks.  Only the latter are
12627  * transferred to/from the disk.  So, when the updated contents of the
12628  * "in-core" inode structure are copied to the corresponding in-memory inode
12629  * block, the dependencies are also transferred.  The following procedure is
12630  * called when copying a dirty "in-core" inode to a cached inode block.
12631  */
12632 
12633 /*
12634  * Called when an inode is loaded from disk. If the effective link count
12635  * differed from the actual link count when it was last flushed, then we
12636  * need to ensure that the correct effective link count is put back.
12637  */
12638 void
12639 softdep_load_inodeblock(ip)
12640 	struct inode *ip;	/* the "in_core" copy of the inode */
12641 {
12642 	struct inodedep *inodedep;
12643 	struct ufsmount *ump;
12644 
12645 	ump = ITOUMP(ip);
12646 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12647 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12648 	/*
12649 	 * Check for alternate nlink count.
12650 	 */
12651 	ip->i_effnlink = ip->i_nlink;
12652 	ACQUIRE_LOCK(ump);
12653 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12654 		FREE_LOCK(ump);
12655 		return;
12656 	}
12657 	if (ip->i_nlink != inodedep->id_nlinkwrote &&
12658 	    inodedep->id_nlinkwrote != -1) {
12659 		KASSERT(ip->i_nlink == 0 &&
12660 		    (ump->um_flags & UM_FSFAIL_CLEANUP) != 0,
12661 		    ("read bad i_nlink value"));
12662 		ip->i_effnlink = ip->i_nlink = inodedep->id_nlinkwrote;
12663 	}
12664 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12665 	KASSERT(ip->i_effnlink >= 0,
12666 	    ("softdep_load_inodeblock: negative i_effnlink"));
12667 	FREE_LOCK(ump);
12668 }
12669 
12670 /*
12671  * This routine is called just before the "in-core" inode
12672  * information is to be copied to the in-memory inode block.
12673  * Recall that an inode block contains several inodes. If
12674  * the force flag is set, then the dependencies will be
12675  * cleared so that the update can always be made. Note that
12676  * the buffer is locked when this routine is called, so we
12677  * will never be in the middle of writing the inode block
12678  * to disk.
12679  */
12680 void
12681 softdep_update_inodeblock(ip, bp, waitfor)
12682 	struct inode *ip;	/* the "in_core" copy of the inode */
12683 	struct buf *bp;		/* the buffer containing the inode block */
12684 	int waitfor;		/* nonzero => update must be allowed */
12685 {
12686 	struct inodedep *inodedep;
12687 	struct inoref *inoref;
12688 	struct ufsmount *ump;
12689 	struct worklist *wk;
12690 	struct mount *mp;
12691 	struct buf *ibp;
12692 	struct fs *fs;
12693 	int error;
12694 
12695 	ump = ITOUMP(ip);
12696 	mp = UFSTOVFS(ump);
12697 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12698 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12699 	fs = ump->um_fs;
12700 	/*
12701 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12702 	 * does not have access to the in-core ip so must write directly into
12703 	 * the inode block buffer when setting freelink.
12704 	 */
12705 	if (fs->fs_magic == FS_UFS1_MAGIC)
12706 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12707 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12708 	else
12709 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12710 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12711 	/*
12712 	 * If the effective link count is not equal to the actual link
12713 	 * count, then we must track the difference in an inodedep while
12714 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12715 	 * if there is no existing inodedep, then there are no dependencies
12716 	 * to track.
12717 	 */
12718 	ACQUIRE_LOCK(ump);
12719 again:
12720 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12721 		FREE_LOCK(ump);
12722 		if (ip->i_effnlink != ip->i_nlink)
12723 			panic("softdep_update_inodeblock: bad link count");
12724 		return;
12725 	}
12726 	KASSERT(ip->i_nlink >= inodedep->id_nlinkdelta,
12727 	    ("softdep_update_inodeblock inconsistent ip %p i_nlink %d "
12728 	    "inodedep %p id_nlinkdelta %jd",
12729 	    ip, ip->i_nlink, inodedep, (intmax_t)inodedep->id_nlinkdelta));
12730 	inodedep->id_nlinkwrote = ip->i_nlink;
12731 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12732 		panic("softdep_update_inodeblock: bad delta");
12733 	/*
12734 	 * If we're flushing all dependencies we must also move any waiting
12735 	 * for journal writes onto the bufwait list prior to I/O.
12736 	 */
12737 	if (waitfor) {
12738 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12739 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12740 			    == DEPCOMPLETE) {
12741 				jwait(&inoref->if_list, MNT_WAIT);
12742 				goto again;
12743 			}
12744 		}
12745 	}
12746 	/*
12747 	 * Changes have been initiated. Anything depending on these
12748 	 * changes cannot occur until this inode has been written.
12749 	 */
12750 	inodedep->id_state &= ~COMPLETE;
12751 	if ((inodedep->id_state & ONWORKLIST) == 0)
12752 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12753 	/*
12754 	 * Any new dependencies associated with the incore inode must
12755 	 * now be moved to the list associated with the buffer holding
12756 	 * the in-memory copy of the inode. Once merged process any
12757 	 * allocdirects that are completed by the merger.
12758 	 */
12759 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12760 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12761 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12762 		    NULL);
12763 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12764 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12765 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12766 		    NULL);
12767 	/*
12768 	 * Now that the inode has been pushed into the buffer, the
12769 	 * operations dependent on the inode being written to disk
12770 	 * can be moved to the id_bufwait so that they will be
12771 	 * processed when the buffer I/O completes.
12772 	 */
12773 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12774 		WORKLIST_REMOVE(wk);
12775 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12776 	}
12777 	/*
12778 	 * Newly allocated inodes cannot be written until the bitmap
12779 	 * that allocates them have been written (indicated by
12780 	 * DEPCOMPLETE being set in id_state). If we are doing a
12781 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12782 	 * to be written so that the update can be done.
12783 	 */
12784 	if (waitfor == 0) {
12785 		FREE_LOCK(ump);
12786 		return;
12787 	}
12788 retry:
12789 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12790 		FREE_LOCK(ump);
12791 		return;
12792 	}
12793 	ibp = inodedep->id_bmsafemap->sm_buf;
12794 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12795 	if (ibp == NULL) {
12796 		/*
12797 		 * If ibp came back as NULL, the dependency could have been
12798 		 * freed while we slept.  Look it up again, and check to see
12799 		 * that it has completed.
12800 		 */
12801 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12802 			goto retry;
12803 		FREE_LOCK(ump);
12804 		return;
12805 	}
12806 	FREE_LOCK(ump);
12807 	if ((error = bwrite(ibp)) != 0)
12808 		softdep_error("softdep_update_inodeblock: bwrite", error);
12809 }
12810 
12811 /*
12812  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12813  * old inode dependency list (such as id_inoupdt).
12814  */
12815 static void
12816 merge_inode_lists(newlisthead, oldlisthead)
12817 	struct allocdirectlst *newlisthead;
12818 	struct allocdirectlst *oldlisthead;
12819 {
12820 	struct allocdirect *listadp, *newadp;
12821 
12822 	newadp = TAILQ_FIRST(newlisthead);
12823 	if (newadp != NULL)
12824 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12825 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12826 		if (listadp->ad_offset < newadp->ad_offset) {
12827 			listadp = TAILQ_NEXT(listadp, ad_next);
12828 			continue;
12829 		}
12830 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12831 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12832 		if (listadp->ad_offset == newadp->ad_offset) {
12833 			allocdirect_merge(oldlisthead, newadp,
12834 			    listadp);
12835 			listadp = newadp;
12836 		}
12837 		newadp = TAILQ_FIRST(newlisthead);
12838 	}
12839 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12840 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12841 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12842 	}
12843 }
12844 
12845 /*
12846  * If we are doing an fsync, then we must ensure that any directory
12847  * entries for the inode have been written after the inode gets to disk.
12848  */
12849 int
12850 softdep_fsync(vp)
12851 	struct vnode *vp;	/* the "in_core" copy of the inode */
12852 {
12853 	struct inodedep *inodedep;
12854 	struct pagedep *pagedep;
12855 	struct inoref *inoref;
12856 	struct ufsmount *ump;
12857 	struct worklist *wk;
12858 	struct diradd *dap;
12859 	struct mount *mp;
12860 	struct vnode *pvp;
12861 	struct inode *ip;
12862 	struct buf *bp;
12863 	struct fs *fs;
12864 	struct thread *td = curthread;
12865 	int error, flushparent, pagedep_new_block;
12866 	ino_t parentino;
12867 	ufs_lbn_t lbn;
12868 
12869 	ip = VTOI(vp);
12870 	mp = vp->v_mount;
12871 	ump = VFSTOUFS(mp);
12872 	fs = ump->um_fs;
12873 	if (MOUNTEDSOFTDEP(mp) == 0)
12874 		return (0);
12875 	ACQUIRE_LOCK(ump);
12876 restart:
12877 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12878 		FREE_LOCK(ump);
12879 		return (0);
12880 	}
12881 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12882 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12883 		    == DEPCOMPLETE) {
12884 			jwait(&inoref->if_list, MNT_WAIT);
12885 			goto restart;
12886 		}
12887 	}
12888 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12889 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12890 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12891 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12892 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12893 		panic("softdep_fsync: pending ops %p", inodedep);
12894 	for (error = 0, flushparent = 0; ; ) {
12895 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12896 			break;
12897 		if (wk->wk_type != D_DIRADD)
12898 			panic("softdep_fsync: Unexpected type %s",
12899 			    TYPENAME(wk->wk_type));
12900 		dap = WK_DIRADD(wk);
12901 		/*
12902 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12903 		 * dependency or is contained in a newly allocated block.
12904 		 */
12905 		if (dap->da_state & DIRCHG)
12906 			pagedep = dap->da_previous->dm_pagedep;
12907 		else
12908 			pagedep = dap->da_pagedep;
12909 		parentino = pagedep->pd_ino;
12910 		lbn = pagedep->pd_lbn;
12911 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12912 			panic("softdep_fsync: dirty");
12913 		if ((dap->da_state & MKDIR_PARENT) ||
12914 		    (pagedep->pd_state & NEWBLOCK))
12915 			flushparent = 1;
12916 		else
12917 			flushparent = 0;
12918 		/*
12919 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12920 		 * then we will not be able to release and recover the
12921 		 * vnode below, so we just have to give up on writing its
12922 		 * directory entry out. It will eventually be written, just
12923 		 * not now, but then the user was not asking to have it
12924 		 * written, so we are not breaking any promises.
12925 		 */
12926 		if (VN_IS_DOOMED(vp))
12927 			break;
12928 		/*
12929 		 * We prevent deadlock by always fetching inodes from the
12930 		 * root, moving down the directory tree. Thus, when fetching
12931 		 * our parent directory, we first try to get the lock. If
12932 		 * that fails, we must unlock ourselves before requesting
12933 		 * the lock on our parent. See the comment in ufs_lookup
12934 		 * for details on possible races.
12935 		 */
12936 		FREE_LOCK(ump);
12937 		error = get_parent_vp(vp, mp, parentino, NULL, NULL, NULL,
12938 		    &pvp);
12939 		if (error == ERELOOKUP)
12940 			error = 0;
12941 		if (error != 0)
12942 			return (error);
12943 		/*
12944 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12945 		 * that are contained in direct blocks will be resolved by
12946 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12947 		 * may require a complete sync'ing of the directory. So, we
12948 		 * try the cheap and fast ffs_update first, and if that fails,
12949 		 * then we do the slower ffs_syncvnode of the directory.
12950 		 */
12951 		if (flushparent) {
12952 			int locked;
12953 
12954 			if ((error = ffs_update(pvp, 1)) != 0) {
12955 				vput(pvp);
12956 				return (error);
12957 			}
12958 			ACQUIRE_LOCK(ump);
12959 			locked = 1;
12960 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12961 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12962 					if (wk->wk_type != D_DIRADD)
12963 						panic("softdep_fsync: Unexpected type %s",
12964 						      TYPENAME(wk->wk_type));
12965 					dap = WK_DIRADD(wk);
12966 					if (dap->da_state & DIRCHG)
12967 						pagedep = dap->da_previous->dm_pagedep;
12968 					else
12969 						pagedep = dap->da_pagedep;
12970 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12971 					FREE_LOCK(ump);
12972 					locked = 0;
12973 					if (pagedep_new_block && (error =
12974 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12975 						vput(pvp);
12976 						return (error);
12977 					}
12978 				}
12979 			}
12980 			if (locked)
12981 				FREE_LOCK(ump);
12982 		}
12983 		/*
12984 		 * Flush directory page containing the inode's name.
12985 		 */
12986 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12987 		    &bp);
12988 		if (error == 0)
12989 			error = bwrite(bp);
12990 		else
12991 			brelse(bp);
12992 		vput(pvp);
12993 		if (!ffs_fsfail_cleanup(ump, error))
12994 			return (error);
12995 		ACQUIRE_LOCK(ump);
12996 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12997 			break;
12998 	}
12999 	FREE_LOCK(ump);
13000 	return (0);
13001 }
13002 
13003 /*
13004  * Flush all the dirty bitmaps associated with the block device
13005  * before flushing the rest of the dirty blocks so as to reduce
13006  * the number of dependencies that will have to be rolled back.
13007  *
13008  * XXX Unused?
13009  */
13010 void
13011 softdep_fsync_mountdev(vp)
13012 	struct vnode *vp;
13013 {
13014 	struct buf *bp, *nbp;
13015 	struct worklist *wk;
13016 	struct bufobj *bo;
13017 
13018 	if (!vn_isdisk(vp))
13019 		panic("softdep_fsync_mountdev: vnode not a disk");
13020 	bo = &vp->v_bufobj;
13021 restart:
13022 	BO_LOCK(bo);
13023 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
13024 		/*
13025 		 * If it is already scheduled, skip to the next buffer.
13026 		 */
13027 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
13028 			continue;
13029 
13030 		if ((bp->b_flags & B_DELWRI) == 0)
13031 			panic("softdep_fsync_mountdev: not dirty");
13032 		/*
13033 		 * We are only interested in bitmaps with outstanding
13034 		 * dependencies.
13035 		 */
13036 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
13037 		    wk->wk_type != D_BMSAFEMAP ||
13038 		    (bp->b_vflags & BV_BKGRDINPROG)) {
13039 			BUF_UNLOCK(bp);
13040 			continue;
13041 		}
13042 		BO_UNLOCK(bo);
13043 		bremfree(bp);
13044 		(void) bawrite(bp);
13045 		goto restart;
13046 	}
13047 	drain_output(vp);
13048 	BO_UNLOCK(bo);
13049 }
13050 
13051 /*
13052  * Sync all cylinder groups that were dirty at the time this function is
13053  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
13054  * is used to flush freedep activity that may be holding up writes to a
13055  * indirect block.
13056  */
13057 static int
13058 sync_cgs(mp, waitfor)
13059 	struct mount *mp;
13060 	int waitfor;
13061 {
13062 	struct bmsafemap *bmsafemap;
13063 	struct bmsafemap *sentinel;
13064 	struct ufsmount *ump;
13065 	struct buf *bp;
13066 	int error;
13067 
13068 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
13069 	sentinel->sm_cg = -1;
13070 	ump = VFSTOUFS(mp);
13071 	error = 0;
13072 	ACQUIRE_LOCK(ump);
13073 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
13074 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
13075 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
13076 		/* Skip sentinels and cgs with no work to release. */
13077 		if (bmsafemap->sm_cg == -1 ||
13078 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
13079 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
13080 			LIST_REMOVE(sentinel, sm_next);
13081 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
13082 			continue;
13083 		}
13084 		/*
13085 		 * If we don't get the lock and we're waiting try again, if
13086 		 * not move on to the next buf and try to sync it.
13087 		 */
13088 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
13089 		if (bp == NULL && waitfor == MNT_WAIT)
13090 			continue;
13091 		LIST_REMOVE(sentinel, sm_next);
13092 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
13093 		if (bp == NULL)
13094 			continue;
13095 		FREE_LOCK(ump);
13096 		if (waitfor == MNT_NOWAIT)
13097 			bawrite(bp);
13098 		else
13099 			error = bwrite(bp);
13100 		ACQUIRE_LOCK(ump);
13101 		if (error)
13102 			break;
13103 	}
13104 	LIST_REMOVE(sentinel, sm_next);
13105 	FREE_LOCK(ump);
13106 	free(sentinel, M_BMSAFEMAP);
13107 	return (error);
13108 }
13109 
13110 /*
13111  * This routine is called when we are trying to synchronously flush a
13112  * file. This routine must eliminate any filesystem metadata dependencies
13113  * so that the syncing routine can succeed.
13114  */
13115 int
13116 softdep_sync_metadata(struct vnode *vp)
13117 {
13118 	struct inode *ip;
13119 	int error;
13120 
13121 	ip = VTOI(vp);
13122 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13123 	    ("softdep_sync_metadata called on non-softdep filesystem"));
13124 	/*
13125 	 * Ensure that any direct block dependencies have been cleared,
13126 	 * truncations are started, and inode references are journaled.
13127 	 */
13128 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
13129 	/*
13130 	 * Write all journal records to prevent rollbacks on devvp.
13131 	 */
13132 	if (vp->v_type == VCHR)
13133 		softdep_flushjournal(vp->v_mount);
13134 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
13135 	/*
13136 	 * Ensure that all truncates are written so we won't find deps on
13137 	 * indirect blocks.
13138 	 */
13139 	process_truncates(vp);
13140 	FREE_LOCK(VFSTOUFS(vp->v_mount));
13141 
13142 	return (error);
13143 }
13144 
13145 /*
13146  * This routine is called when we are attempting to sync a buf with
13147  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
13148  * other IO it can but returns EBUSY if the buffer is not yet able to
13149  * be written.  Dependencies which will not cause rollbacks will always
13150  * return 0.
13151  */
13152 int
13153 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
13154 {
13155 	struct indirdep *indirdep;
13156 	struct pagedep *pagedep;
13157 	struct allocindir *aip;
13158 	struct newblk *newblk;
13159 	struct ufsmount *ump;
13160 	struct buf *nbp;
13161 	struct worklist *wk;
13162 	int i, error;
13163 
13164 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13165 	    ("softdep_sync_buf called on non-softdep filesystem"));
13166 	/*
13167 	 * For VCHR we just don't want to force flush any dependencies that
13168 	 * will cause rollbacks.
13169 	 */
13170 	if (vp->v_type == VCHR) {
13171 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
13172 			return (EBUSY);
13173 		return (0);
13174 	}
13175 	ump = VFSTOUFS(vp->v_mount);
13176 	ACQUIRE_LOCK(ump);
13177 	/*
13178 	 * As we hold the buffer locked, none of its dependencies
13179 	 * will disappear.
13180 	 */
13181 	error = 0;
13182 top:
13183 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13184 		switch (wk->wk_type) {
13185 		case D_ALLOCDIRECT:
13186 		case D_ALLOCINDIR:
13187 			newblk = WK_NEWBLK(wk);
13188 			if (newblk->nb_jnewblk != NULL) {
13189 				if (waitfor == MNT_NOWAIT) {
13190 					error = EBUSY;
13191 					goto out_unlock;
13192 				}
13193 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
13194 				goto top;
13195 			}
13196 			if (newblk->nb_state & DEPCOMPLETE ||
13197 			    waitfor == MNT_NOWAIT)
13198 				continue;
13199 			nbp = newblk->nb_bmsafemap->sm_buf;
13200 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13201 			if (nbp == NULL)
13202 				goto top;
13203 			FREE_LOCK(ump);
13204 			if ((error = bwrite(nbp)) != 0)
13205 				goto out;
13206 			ACQUIRE_LOCK(ump);
13207 			continue;
13208 
13209 		case D_INDIRDEP:
13210 			indirdep = WK_INDIRDEP(wk);
13211 			if (waitfor == MNT_NOWAIT) {
13212 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
13213 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
13214 					error = EBUSY;
13215 					goto out_unlock;
13216 				}
13217 			}
13218 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
13219 				panic("softdep_sync_buf: truncation pending.");
13220 		restart:
13221 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13222 				newblk = (struct newblk *)aip;
13223 				if (newblk->nb_jnewblk != NULL) {
13224 					jwait(&newblk->nb_jnewblk->jn_list,
13225 					    waitfor);
13226 					goto restart;
13227 				}
13228 				if (newblk->nb_state & DEPCOMPLETE)
13229 					continue;
13230 				nbp = newblk->nb_bmsafemap->sm_buf;
13231 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13232 				if (nbp == NULL)
13233 					goto restart;
13234 				FREE_LOCK(ump);
13235 				if ((error = bwrite(nbp)) != 0)
13236 					goto out;
13237 				ACQUIRE_LOCK(ump);
13238 				goto restart;
13239 			}
13240 			continue;
13241 
13242 		case D_PAGEDEP:
13243 			/*
13244 			 * Only flush directory entries in synchronous passes.
13245 			 */
13246 			if (waitfor != MNT_WAIT) {
13247 				error = EBUSY;
13248 				goto out_unlock;
13249 			}
13250 			/*
13251 			 * While syncing snapshots, we must allow recursive
13252 			 * lookups.
13253 			 */
13254 			BUF_AREC(bp);
13255 			/*
13256 			 * We are trying to sync a directory that may
13257 			 * have dependencies on both its own metadata
13258 			 * and/or dependencies on the inodes of any
13259 			 * recently allocated files. We walk its diradd
13260 			 * lists pushing out the associated inode.
13261 			 */
13262 			pagedep = WK_PAGEDEP(wk);
13263 			for (i = 0; i < DAHASHSZ; i++) {
13264 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
13265 					continue;
13266 				error = flush_pagedep_deps(vp, wk->wk_mp,
13267 				    &pagedep->pd_diraddhd[i], bp);
13268 				if (error != 0) {
13269 					if (error != ERELOOKUP)
13270 						BUF_NOREC(bp);
13271 					goto out_unlock;
13272 				}
13273 			}
13274 			BUF_NOREC(bp);
13275 			continue;
13276 
13277 		case D_FREEWORK:
13278 		case D_FREEDEP:
13279 		case D_JSEGDEP:
13280 		case D_JNEWBLK:
13281 			continue;
13282 
13283 		default:
13284 			panic("softdep_sync_buf: Unknown type %s",
13285 			    TYPENAME(wk->wk_type));
13286 			/* NOTREACHED */
13287 		}
13288 	}
13289 out_unlock:
13290 	FREE_LOCK(ump);
13291 out:
13292 	return (error);
13293 }
13294 
13295 /*
13296  * Flush the dependencies associated with an inodedep.
13297  */
13298 static int
13299 flush_inodedep_deps(vp, mp, ino)
13300 	struct vnode *vp;
13301 	struct mount *mp;
13302 	ino_t ino;
13303 {
13304 	struct inodedep *inodedep;
13305 	struct inoref *inoref;
13306 	struct ufsmount *ump;
13307 	int error, waitfor;
13308 
13309 	/*
13310 	 * This work is done in two passes. The first pass grabs most
13311 	 * of the buffers and begins asynchronously writing them. The
13312 	 * only way to wait for these asynchronous writes is to sleep
13313 	 * on the filesystem vnode which may stay busy for a long time
13314 	 * if the filesystem is active. So, instead, we make a second
13315 	 * pass over the dependencies blocking on each write. In the
13316 	 * usual case we will be blocking against a write that we
13317 	 * initiated, so when it is done the dependency will have been
13318 	 * resolved. Thus the second pass is expected to end quickly.
13319 	 * We give a brief window at the top of the loop to allow
13320 	 * any pending I/O to complete.
13321 	 */
13322 	ump = VFSTOUFS(mp);
13323 	LOCK_OWNED(ump);
13324 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
13325 		if (error)
13326 			return (error);
13327 		FREE_LOCK(ump);
13328 		ACQUIRE_LOCK(ump);
13329 restart:
13330 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13331 			return (0);
13332 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13333 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13334 			    == DEPCOMPLETE) {
13335 				jwait(&inoref->if_list, MNT_WAIT);
13336 				goto restart;
13337 			}
13338 		}
13339 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
13340 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
13341 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
13342 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
13343 			continue;
13344 		/*
13345 		 * If pass2, we are done, otherwise do pass 2.
13346 		 */
13347 		if (waitfor == MNT_WAIT)
13348 			break;
13349 		waitfor = MNT_WAIT;
13350 	}
13351 	/*
13352 	 * Try freeing inodedep in case all dependencies have been removed.
13353 	 */
13354 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
13355 		(void) free_inodedep(inodedep);
13356 	return (0);
13357 }
13358 
13359 /*
13360  * Flush an inode dependency list.
13361  */
13362 static int
13363 flush_deplist(listhead, waitfor, errorp)
13364 	struct allocdirectlst *listhead;
13365 	int waitfor;
13366 	int *errorp;
13367 {
13368 	struct allocdirect *adp;
13369 	struct newblk *newblk;
13370 	struct ufsmount *ump;
13371 	struct buf *bp;
13372 
13373 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
13374 		return (0);
13375 	ump = VFSTOUFS(adp->ad_list.wk_mp);
13376 	LOCK_OWNED(ump);
13377 	TAILQ_FOREACH(adp, listhead, ad_next) {
13378 		newblk = (struct newblk *)adp;
13379 		if (newblk->nb_jnewblk != NULL) {
13380 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13381 			return (1);
13382 		}
13383 		if (newblk->nb_state & DEPCOMPLETE)
13384 			continue;
13385 		bp = newblk->nb_bmsafemap->sm_buf;
13386 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13387 		if (bp == NULL) {
13388 			if (waitfor == MNT_NOWAIT)
13389 				continue;
13390 			return (1);
13391 		}
13392 		FREE_LOCK(ump);
13393 		if (waitfor == MNT_NOWAIT)
13394 			bawrite(bp);
13395 		else
13396 			*errorp = bwrite(bp);
13397 		ACQUIRE_LOCK(ump);
13398 		return (1);
13399 	}
13400 	return (0);
13401 }
13402 
13403 /*
13404  * Flush dependencies associated with an allocdirect block.
13405  */
13406 static int
13407 flush_newblk_dep(vp, mp, lbn)
13408 	struct vnode *vp;
13409 	struct mount *mp;
13410 	ufs_lbn_t lbn;
13411 {
13412 	struct newblk *newblk;
13413 	struct ufsmount *ump;
13414 	struct bufobj *bo;
13415 	struct inode *ip;
13416 	struct buf *bp;
13417 	ufs2_daddr_t blkno;
13418 	int error;
13419 
13420 	error = 0;
13421 	bo = &vp->v_bufobj;
13422 	ip = VTOI(vp);
13423 	blkno = DIP(ip, i_db[lbn]);
13424 	if (blkno == 0)
13425 		panic("flush_newblk_dep: Missing block");
13426 	ump = VFSTOUFS(mp);
13427 	ACQUIRE_LOCK(ump);
13428 	/*
13429 	 * Loop until all dependencies related to this block are satisfied.
13430 	 * We must be careful to restart after each sleep in case a write
13431 	 * completes some part of this process for us.
13432 	 */
13433 	for (;;) {
13434 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13435 			FREE_LOCK(ump);
13436 			break;
13437 		}
13438 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13439 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13440 		/*
13441 		 * Flush the journal.
13442 		 */
13443 		if (newblk->nb_jnewblk != NULL) {
13444 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13445 			continue;
13446 		}
13447 		/*
13448 		 * Write the bitmap dependency.
13449 		 */
13450 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13451 			bp = newblk->nb_bmsafemap->sm_buf;
13452 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13453 			if (bp == NULL)
13454 				continue;
13455 			FREE_LOCK(ump);
13456 			error = bwrite(bp);
13457 			if (error)
13458 				break;
13459 			ACQUIRE_LOCK(ump);
13460 			continue;
13461 		}
13462 		/*
13463 		 * Write the buffer.
13464 		 */
13465 		FREE_LOCK(ump);
13466 		BO_LOCK(bo);
13467 		bp = gbincore(bo, lbn);
13468 		if (bp != NULL) {
13469 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13470 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13471 			if (error == ENOLCK) {
13472 				ACQUIRE_LOCK(ump);
13473 				error = 0;
13474 				continue; /* Slept, retry */
13475 			}
13476 			if (error != 0)
13477 				break;	/* Failed */
13478 			if (bp->b_flags & B_DELWRI) {
13479 				bremfree(bp);
13480 				error = bwrite(bp);
13481 				if (error)
13482 					break;
13483 			} else
13484 				BUF_UNLOCK(bp);
13485 		} else
13486 			BO_UNLOCK(bo);
13487 		/*
13488 		 * We have to wait for the direct pointers to
13489 		 * point at the newdirblk before the dependency
13490 		 * will go away.
13491 		 */
13492 		error = ffs_update(vp, 1);
13493 		if (error)
13494 			break;
13495 		ACQUIRE_LOCK(ump);
13496 	}
13497 	return (error);
13498 }
13499 
13500 /*
13501  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13502  */
13503 static int
13504 flush_pagedep_deps(pvp, mp, diraddhdp, locked_bp)
13505 	struct vnode *pvp;
13506 	struct mount *mp;
13507 	struct diraddhd *diraddhdp;
13508 	struct buf *locked_bp;
13509 {
13510 	struct inodedep *inodedep;
13511 	struct inoref *inoref;
13512 	struct ufsmount *ump;
13513 	struct diradd *dap;
13514 	struct vnode *vp;
13515 	int error = 0;
13516 	struct buf *bp;
13517 	ino_t inum;
13518 	struct diraddhd unfinished;
13519 
13520 	LIST_INIT(&unfinished);
13521 	ump = VFSTOUFS(mp);
13522 	LOCK_OWNED(ump);
13523 restart:
13524 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13525 		/*
13526 		 * Flush ourselves if this directory entry
13527 		 * has a MKDIR_PARENT dependency.
13528 		 */
13529 		if (dap->da_state & MKDIR_PARENT) {
13530 			FREE_LOCK(ump);
13531 			if ((error = ffs_update(pvp, 1)) != 0)
13532 				break;
13533 			ACQUIRE_LOCK(ump);
13534 			/*
13535 			 * If that cleared dependencies, go on to next.
13536 			 */
13537 			if (dap != LIST_FIRST(diraddhdp))
13538 				continue;
13539 			/*
13540 			 * All MKDIR_PARENT dependencies and all the
13541 			 * NEWBLOCK pagedeps that are contained in direct
13542 			 * blocks were resolved by doing above ffs_update.
13543 			 * Pagedeps contained in indirect blocks may
13544 			 * require a complete sync'ing of the directory.
13545 			 * We are in the midst of doing a complete sync,
13546 			 * so if they are not resolved in this pass we
13547 			 * defer them for now as they will be sync'ed by
13548 			 * our caller shortly.
13549 			 */
13550 			LIST_REMOVE(dap, da_pdlist);
13551 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13552 			continue;
13553 		}
13554 		/*
13555 		 * A newly allocated directory must have its "." and
13556 		 * ".." entries written out before its name can be
13557 		 * committed in its parent.
13558 		 */
13559 		inum = dap->da_newinum;
13560 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13561 			panic("flush_pagedep_deps: lost inode1");
13562 		/*
13563 		 * Wait for any pending journal adds to complete so we don't
13564 		 * cause rollbacks while syncing.
13565 		 */
13566 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13567 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13568 			    == DEPCOMPLETE) {
13569 				jwait(&inoref->if_list, MNT_WAIT);
13570 				goto restart;
13571 			}
13572 		}
13573 		if (dap->da_state & MKDIR_BODY) {
13574 			FREE_LOCK(ump);
13575 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13576 			    diraddhdp, &unfinished, &vp);
13577 			if (error != 0)
13578 				break;
13579 			error = flush_newblk_dep(vp, mp, 0);
13580 			/*
13581 			 * If we still have the dependency we might need to
13582 			 * update the vnode to sync the new link count to
13583 			 * disk.
13584 			 */
13585 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13586 				error = ffs_update(vp, 1);
13587 			vput(vp);
13588 			if (error != 0)
13589 				break;
13590 			ACQUIRE_LOCK(ump);
13591 			/*
13592 			 * If that cleared dependencies, go on to next.
13593 			 */
13594 			if (dap != LIST_FIRST(diraddhdp))
13595 				continue;
13596 			if (dap->da_state & MKDIR_BODY) {
13597 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13598 				    &inodedep);
13599 				panic("flush_pagedep_deps: MKDIR_BODY "
13600 				    "inodedep %p dap %p vp %p",
13601 				    inodedep, dap, vp);
13602 			}
13603 		}
13604 		/*
13605 		 * Flush the inode on which the directory entry depends.
13606 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13607 		 * the only remaining dependency is that the updated inode
13608 		 * count must get pushed to disk. The inode has already
13609 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13610 		 * the time of the reference count change. So we need only
13611 		 * locate that buffer, ensure that there will be no rollback
13612 		 * caused by a bitmap dependency, then write the inode buffer.
13613 		 */
13614 retry:
13615 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13616 			panic("flush_pagedep_deps: lost inode");
13617 		/*
13618 		 * If the inode still has bitmap dependencies,
13619 		 * push them to disk.
13620 		 */
13621 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13622 			bp = inodedep->id_bmsafemap->sm_buf;
13623 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13624 			if (bp == NULL)
13625 				goto retry;
13626 			FREE_LOCK(ump);
13627 			if ((error = bwrite(bp)) != 0)
13628 				break;
13629 			ACQUIRE_LOCK(ump);
13630 			if (dap != LIST_FIRST(diraddhdp))
13631 				continue;
13632 		}
13633 		/*
13634 		 * If the inode is still sitting in a buffer waiting
13635 		 * to be written or waiting for the link count to be
13636 		 * adjusted update it here to flush it to disk.
13637 		 */
13638 		if (dap == LIST_FIRST(diraddhdp)) {
13639 			FREE_LOCK(ump);
13640 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13641 			    diraddhdp, &unfinished, &vp);
13642 			if (error != 0)
13643 				break;
13644 			error = ffs_update(vp, 1);
13645 			vput(vp);
13646 			if (error)
13647 				break;
13648 			ACQUIRE_LOCK(ump);
13649 		}
13650 		/*
13651 		 * If we have failed to get rid of all the dependencies
13652 		 * then something is seriously wrong.
13653 		 */
13654 		if (dap == LIST_FIRST(diraddhdp)) {
13655 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13656 			panic("flush_pagedep_deps: failed to flush "
13657 			    "inodedep %p ino %ju dap %p",
13658 			    inodedep, (uintmax_t)inum, dap);
13659 		}
13660 	}
13661 	if (error)
13662 		ACQUIRE_LOCK(ump);
13663 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13664 		LIST_REMOVE(dap, da_pdlist);
13665 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13666 	}
13667 	return (error);
13668 }
13669 
13670 /*
13671  * A large burst of file addition or deletion activity can drive the
13672  * memory load excessively high. First attempt to slow things down
13673  * using the techniques below. If that fails, this routine requests
13674  * the offending operations to fall back to running synchronously
13675  * until the memory load returns to a reasonable level.
13676  */
13677 int
13678 softdep_slowdown(vp)
13679 	struct vnode *vp;
13680 {
13681 	struct ufsmount *ump;
13682 	int jlow;
13683 	int max_softdeps_hard;
13684 
13685 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13686 	    ("softdep_slowdown called on non-softdep filesystem"));
13687 	ump = VFSTOUFS(vp->v_mount);
13688 	ACQUIRE_LOCK(ump);
13689 	jlow = 0;
13690 	/*
13691 	 * Check for journal space if needed.
13692 	 */
13693 	if (DOINGSUJ(vp)) {
13694 		if (journal_space(ump, 0) == 0)
13695 			jlow = 1;
13696 	}
13697 	/*
13698 	 * If the system is under its limits and our filesystem is
13699 	 * not responsible for more than our share of the usage and
13700 	 * we are not low on journal space, then no need to slow down.
13701 	 */
13702 	max_softdeps_hard = max_softdeps * 11 / 10;
13703 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13704 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13705 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13706 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13707 	    ump->softdep_curdeps[D_DIRREM] <
13708 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13709 	    ump->softdep_curdeps[D_INODEDEP] <
13710 	    max_softdeps_hard / stat_flush_threads &&
13711 	    ump->softdep_curdeps[D_INDIRDEP] <
13712 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13713 	    ump->softdep_curdeps[D_FREEBLKS] <
13714 	    max_softdeps_hard / stat_flush_threads) {
13715 		FREE_LOCK(ump);
13716   		return (0);
13717 	}
13718 	/*
13719 	 * If the journal is low or our filesystem is over its limit
13720 	 * then speedup the cleanup.
13721 	 */
13722 	if (ump->softdep_curdeps[D_INDIRDEP] <
13723 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13724 		softdep_speedup(ump);
13725 	stat_sync_limit_hit += 1;
13726 	FREE_LOCK(ump);
13727 	/*
13728 	 * We only slow down the rate at which new dependencies are
13729 	 * generated if we are not using journaling. With journaling,
13730 	 * the cleanup should always be sufficient to keep things
13731 	 * under control.
13732 	 */
13733 	if (DOINGSUJ(vp))
13734 		return (0);
13735 	return (1);
13736 }
13737 
13738 /*
13739  * Called by the allocation routines when they are about to fail
13740  * in the hope that we can free up the requested resource (inodes
13741  * or disk space).
13742  *
13743  * First check to see if the work list has anything on it. If it has,
13744  * clean up entries until we successfully free the requested resource.
13745  * Because this process holds inodes locked, we cannot handle any remove
13746  * requests that might block on a locked inode as that could lead to
13747  * deadlock. If the worklist yields none of the requested resource,
13748  * start syncing out vnodes to free up the needed space.
13749  */
13750 int
13751 softdep_request_cleanup(fs, vp, cred, resource)
13752 	struct fs *fs;
13753 	struct vnode *vp;
13754 	struct ucred *cred;
13755 	int resource;
13756 {
13757 	struct ufsmount *ump;
13758 	struct mount *mp;
13759 	long starttime;
13760 	ufs2_daddr_t needed;
13761 	int error, failed_vnode;
13762 
13763 	/*
13764 	 * If we are being called because of a process doing a
13765 	 * copy-on-write, then it is not safe to process any
13766 	 * worklist items as we will recurse into the copyonwrite
13767 	 * routine.  This will result in an incoherent snapshot.
13768 	 * If the vnode that we hold is a snapshot, we must avoid
13769 	 * handling other resources that could cause deadlock.
13770 	 */
13771 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13772 		return (0);
13773 
13774 	if (resource == FLUSH_BLOCKS_WAIT)
13775 		stat_cleanup_blkrequests += 1;
13776 	else
13777 		stat_cleanup_inorequests += 1;
13778 
13779 	mp = vp->v_mount;
13780 	ump = VFSTOUFS(mp);
13781 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13782 	UFS_UNLOCK(ump);
13783 	error = ffs_update(vp, 1);
13784 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13785 		UFS_LOCK(ump);
13786 		return (0);
13787 	}
13788 	/*
13789 	 * If we are in need of resources, start by cleaning up
13790 	 * any block removals associated with our inode.
13791 	 */
13792 	ACQUIRE_LOCK(ump);
13793 	process_removes(vp);
13794 	process_truncates(vp);
13795 	FREE_LOCK(ump);
13796 	/*
13797 	 * Now clean up at least as many resources as we will need.
13798 	 *
13799 	 * When requested to clean up inodes, the number that are needed
13800 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13801 	 * plus a bit of slop (2) in case some more writers show up while
13802 	 * we are cleaning.
13803 	 *
13804 	 * When requested to free up space, the amount of space that
13805 	 * we need is enough blocks to allocate a full-sized segment
13806 	 * (fs_contigsumsize). The number of such segments that will
13807 	 * be needed is set by the number of simultaneous writers
13808 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13809 	 * writers show up while we are cleaning.
13810 	 *
13811 	 * Additionally, if we are unpriviledged and allocating space,
13812 	 * we need to ensure that we clean up enough blocks to get the
13813 	 * needed number of blocks over the threshold of the minimum
13814 	 * number of blocks required to be kept free by the filesystem
13815 	 * (fs_minfree).
13816 	 */
13817 	if (resource == FLUSH_INODES_WAIT) {
13818 		needed = vfs_mount_fetch_counter(vp->v_mount,
13819 		    MNT_COUNT_WRITEOPCOUNT) + 2;
13820 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13821 		needed = (vfs_mount_fetch_counter(vp->v_mount,
13822 		    MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13823 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13824 			needed += fragstoblks(fs,
13825 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13826 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13827 	} else {
13828 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13829 		    resource);
13830 		UFS_LOCK(ump);
13831 		return (0);
13832 	}
13833 	starttime = time_second;
13834 retry:
13835 	if (resource == FLUSH_BLOCKS_WAIT &&
13836 	    fs->fs_cstotal.cs_nbfree <= needed)
13837 		softdep_send_speedup(ump, needed * fs->fs_bsize,
13838 		    BIO_SPEEDUP_TRIM);
13839 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13840 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13841 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13842 	    fs->fs_cstotal.cs_nifree <= needed)) {
13843 		ACQUIRE_LOCK(ump);
13844 		if (ump->softdep_on_worklist > 0 &&
13845 		    process_worklist_item(UFSTOVFS(ump),
13846 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13847 			stat_worklist_push += 1;
13848 		FREE_LOCK(ump);
13849 	}
13850 	/*
13851 	 * If we still need resources and there are no more worklist
13852 	 * entries to process to obtain them, we have to start flushing
13853 	 * the dirty vnodes to force the release of additional requests
13854 	 * to the worklist that we can then process to reap addition
13855 	 * resources. We walk the vnodes associated with the mount point
13856 	 * until we get the needed worklist requests that we can reap.
13857 	 *
13858 	 * If there are several threads all needing to clean the same
13859 	 * mount point, only one is allowed to walk the mount list.
13860 	 * When several threads all try to walk the same mount list,
13861 	 * they end up competing with each other and often end up in
13862 	 * livelock. This approach ensures that forward progress is
13863 	 * made at the cost of occational ENOSPC errors being returned
13864 	 * that might otherwise have been avoided.
13865 	 */
13866 	error = 1;
13867 	if ((resource == FLUSH_BLOCKS_WAIT &&
13868 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13869 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13870 	     fs->fs_cstotal.cs_nifree <= needed)) {
13871 		ACQUIRE_LOCK(ump);
13872 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13873 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13874 			FREE_LOCK(ump);
13875 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13876 			ACQUIRE_LOCK(ump);
13877 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13878 			FREE_LOCK(ump);
13879 			if (ump->softdep_on_worklist > 0) {
13880 				stat_cleanup_retries += 1;
13881 				if (!failed_vnode)
13882 					goto retry;
13883 			}
13884 		} else {
13885 			FREE_LOCK(ump);
13886 			error = 0;
13887 		}
13888 		stat_cleanup_failures += 1;
13889 	}
13890 	if (time_second - starttime > stat_cleanup_high_delay)
13891 		stat_cleanup_high_delay = time_second - starttime;
13892 	UFS_LOCK(ump);
13893 	return (error);
13894 }
13895 
13896 /*
13897  * Scan the vnodes for the specified mount point flushing out any
13898  * vnodes that can be locked without waiting. Finally, try to flush
13899  * the device associated with the mount point if it can be locked
13900  * without waiting.
13901  *
13902  * We return 0 if we were able to lock every vnode in our scan.
13903  * If we had to skip one or more vnodes, we return 1.
13904  */
13905 static int
13906 softdep_request_cleanup_flush(mp, ump)
13907 	struct mount *mp;
13908 	struct ufsmount *ump;
13909 {
13910 	struct thread *td;
13911 	struct vnode *lvp, *mvp;
13912 	int failed_vnode;
13913 
13914 	failed_vnode = 0;
13915 	td = curthread;
13916 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13917 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13918 			VI_UNLOCK(lvp);
13919 			continue;
13920 		}
13921 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT) != 0) {
13922 			failed_vnode = 1;
13923 			continue;
13924 		}
13925 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13926 			vput(lvp);
13927 			continue;
13928 		}
13929 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13930 		vput(lvp);
13931 	}
13932 	lvp = ump->um_devvp;
13933 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13934 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13935 		VOP_UNLOCK(lvp);
13936 	}
13937 	return (failed_vnode);
13938 }
13939 
13940 static bool
13941 softdep_excess_items(struct ufsmount *ump, int item)
13942 {
13943 
13944 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13945 	return (dep_current[item] > max_softdeps &&
13946 	    ump->softdep_curdeps[item] > max_softdeps /
13947 	    stat_flush_threads);
13948 }
13949 
13950 static void
13951 schedule_cleanup(struct mount *mp)
13952 {
13953 	struct ufsmount *ump;
13954 	struct thread *td;
13955 
13956 	ump = VFSTOUFS(mp);
13957 	LOCK_OWNED(ump);
13958 	FREE_LOCK(ump);
13959 	td = curthread;
13960 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13961 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13962 		/*
13963 		 * No ast is delivered to kernel threads, so nobody
13964 		 * would deref the mp.  Some kernel threads
13965 		 * explicitely check for AST, e.g. NFS daemon does
13966 		 * this in the serving loop.
13967 		 */
13968 		return;
13969 	}
13970 	if (td->td_su != NULL)
13971 		vfs_rel(td->td_su);
13972 	vfs_ref(mp);
13973 	td->td_su = mp;
13974 	thread_lock(td);
13975 	td->td_flags |= TDF_ASTPENDING;
13976 	thread_unlock(td);
13977 }
13978 
13979 static void
13980 softdep_ast_cleanup_proc(struct thread *td)
13981 {
13982 	struct mount *mp;
13983 	struct ufsmount *ump;
13984 	int error;
13985 	bool req;
13986 
13987 	while ((mp = td->td_su) != NULL) {
13988 		td->td_su = NULL;
13989 		error = vfs_busy(mp, MBF_NOWAIT);
13990 		vfs_rel(mp);
13991 		if (error != 0)
13992 			return;
13993 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13994 			ump = VFSTOUFS(mp);
13995 			for (;;) {
13996 				req = false;
13997 				ACQUIRE_LOCK(ump);
13998 				if (softdep_excess_items(ump, D_INODEDEP)) {
13999 					req = true;
14000 					request_cleanup(mp, FLUSH_INODES);
14001 				}
14002 				if (softdep_excess_items(ump, D_DIRREM)) {
14003 					req = true;
14004 					request_cleanup(mp, FLUSH_BLOCKS);
14005 				}
14006 				FREE_LOCK(ump);
14007 				if (softdep_excess_items(ump, D_NEWBLK) ||
14008 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
14009 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
14010 					error = vn_start_write(NULL, &mp,
14011 					    V_WAIT);
14012 					if (error == 0) {
14013 						req = true;
14014 						VFS_SYNC(mp, MNT_WAIT);
14015 						vn_finished_write(mp);
14016 					}
14017 				}
14018 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
14019 					break;
14020 			}
14021 		}
14022 		vfs_unbusy(mp);
14023 	}
14024 	if ((mp = td->td_su) != NULL) {
14025 		td->td_su = NULL;
14026 		vfs_rel(mp);
14027 	}
14028 }
14029 
14030 /*
14031  * If memory utilization has gotten too high, deliberately slow things
14032  * down and speed up the I/O processing.
14033  */
14034 static int
14035 request_cleanup(mp, resource)
14036 	struct mount *mp;
14037 	int resource;
14038 {
14039 	struct thread *td = curthread;
14040 	struct ufsmount *ump;
14041 
14042 	ump = VFSTOUFS(mp);
14043 	LOCK_OWNED(ump);
14044 	/*
14045 	 * We never hold up the filesystem syncer or buf daemon.
14046 	 */
14047 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
14048 		return (0);
14049 	/*
14050 	 * First check to see if the work list has gotten backlogged.
14051 	 * If it has, co-opt this process to help clean up two entries.
14052 	 * Because this process may hold inodes locked, we cannot
14053 	 * handle any remove requests that might block on a locked
14054 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
14055 	 * to avoid recursively processing the worklist.
14056 	 */
14057 	if (ump->softdep_on_worklist > max_softdeps / 10) {
14058 		td->td_pflags |= TDP_SOFTDEP;
14059 		process_worklist_item(mp, 2, LK_NOWAIT);
14060 		td->td_pflags &= ~TDP_SOFTDEP;
14061 		stat_worklist_push += 2;
14062 		return(1);
14063 	}
14064 	/*
14065 	 * Next, we attempt to speed up the syncer process. If that
14066 	 * is successful, then we allow the process to continue.
14067 	 */
14068 	if (softdep_speedup(ump) &&
14069 	    resource != FLUSH_BLOCKS_WAIT &&
14070 	    resource != FLUSH_INODES_WAIT)
14071 		return(0);
14072 	/*
14073 	 * If we are resource constrained on inode dependencies, try
14074 	 * flushing some dirty inodes. Otherwise, we are constrained
14075 	 * by file deletions, so try accelerating flushes of directories
14076 	 * with removal dependencies. We would like to do the cleanup
14077 	 * here, but we probably hold an inode locked at this point and
14078 	 * that might deadlock against one that we try to clean. So,
14079 	 * the best that we can do is request the syncer daemon to do
14080 	 * the cleanup for us.
14081 	 */
14082 	switch (resource) {
14083 	case FLUSH_INODES:
14084 	case FLUSH_INODES_WAIT:
14085 		ACQUIRE_GBLLOCK(&lk);
14086 		stat_ino_limit_push += 1;
14087 		req_clear_inodedeps += 1;
14088 		FREE_GBLLOCK(&lk);
14089 		stat_countp = &stat_ino_limit_hit;
14090 		break;
14091 
14092 	case FLUSH_BLOCKS:
14093 	case FLUSH_BLOCKS_WAIT:
14094 		ACQUIRE_GBLLOCK(&lk);
14095 		stat_blk_limit_push += 1;
14096 		req_clear_remove += 1;
14097 		FREE_GBLLOCK(&lk);
14098 		stat_countp = &stat_blk_limit_hit;
14099 		break;
14100 
14101 	default:
14102 		panic("request_cleanup: unknown type");
14103 	}
14104 	/*
14105 	 * Hopefully the syncer daemon will catch up and awaken us.
14106 	 * We wait at most tickdelay before proceeding in any case.
14107 	 */
14108 	ACQUIRE_GBLLOCK(&lk);
14109 	FREE_LOCK(ump);
14110 	proc_waiting += 1;
14111 	if (callout_pending(&softdep_callout) == FALSE)
14112 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
14113 		    pause_timer, 0);
14114 
14115 	if ((td->td_pflags & TDP_KTHREAD) == 0)
14116 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
14117 	proc_waiting -= 1;
14118 	FREE_GBLLOCK(&lk);
14119 	ACQUIRE_LOCK(ump);
14120 	return (1);
14121 }
14122 
14123 /*
14124  * Awaken processes pausing in request_cleanup and clear proc_waiting
14125  * to indicate that there is no longer a timer running. Pause_timer
14126  * will be called with the global softdep mutex (&lk) locked.
14127  */
14128 static void
14129 pause_timer(arg)
14130 	void *arg;
14131 {
14132 
14133 	GBLLOCK_OWNED(&lk);
14134 	/*
14135 	 * The callout_ API has acquired mtx and will hold it around this
14136 	 * function call.
14137 	 */
14138 	*stat_countp += proc_waiting;
14139 	wakeup(&proc_waiting);
14140 }
14141 
14142 /*
14143  * If requested, try removing inode or removal dependencies.
14144  */
14145 static void
14146 check_clear_deps(mp)
14147 	struct mount *mp;
14148 {
14149 	struct ufsmount *ump;
14150 	bool suj_susp;
14151 
14152 	/*
14153 	 * Tell the lower layers that any TRIM or WRITE transactions that have
14154 	 * been delayed for performance reasons should proceed to help alleviate
14155 	 * the shortage faster. The race between checking req_* and the softdep
14156 	 * mutex (lk) is fine since this is an advisory operation that at most
14157 	 * causes deferred work to be done sooner.
14158 	 */
14159 	ump = VFSTOUFS(mp);
14160 	suj_susp = MOUNTEDSUJ(mp) && ump->softdep_jblocks->jb_suspended;
14161 	if (req_clear_remove || req_clear_inodedeps || suj_susp) {
14162 		FREE_LOCK(ump);
14163 		softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
14164 		ACQUIRE_LOCK(ump);
14165 	}
14166 
14167 	/*
14168 	 * If we are suspended, it may be because of our using
14169 	 * too many inodedeps, so help clear them out.
14170 	 */
14171 	if (suj_susp)
14172 		clear_inodedeps(mp);
14173 
14174 	/*
14175 	 * General requests for cleanup of backed up dependencies
14176 	 */
14177 	ACQUIRE_GBLLOCK(&lk);
14178 	if (req_clear_inodedeps) {
14179 		req_clear_inodedeps -= 1;
14180 		FREE_GBLLOCK(&lk);
14181 		clear_inodedeps(mp);
14182 		ACQUIRE_GBLLOCK(&lk);
14183 		wakeup(&proc_waiting);
14184 	}
14185 	if (req_clear_remove) {
14186 		req_clear_remove -= 1;
14187 		FREE_GBLLOCK(&lk);
14188 		clear_remove(mp);
14189 		ACQUIRE_GBLLOCK(&lk);
14190 		wakeup(&proc_waiting);
14191 	}
14192 	FREE_GBLLOCK(&lk);
14193 }
14194 
14195 /*
14196  * Flush out a directory with at least one removal dependency in an effort to
14197  * reduce the number of dirrem, freefile, and freeblks dependency structures.
14198  */
14199 static void
14200 clear_remove(mp)
14201 	struct mount *mp;
14202 {
14203 	struct pagedep_hashhead *pagedephd;
14204 	struct pagedep *pagedep;
14205 	struct ufsmount *ump;
14206 	struct vnode *vp;
14207 	struct bufobj *bo;
14208 	int error, cnt;
14209 	ino_t ino;
14210 
14211 	ump = VFSTOUFS(mp);
14212 	LOCK_OWNED(ump);
14213 
14214 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
14215 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
14216 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
14217 			ump->pagedep_nextclean = 0;
14218 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
14219 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
14220 				continue;
14221 			ino = pagedep->pd_ino;
14222 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14223 				continue;
14224 			FREE_LOCK(ump);
14225 
14226 			/*
14227 			 * Let unmount clear deps
14228 			 */
14229 			error = vfs_busy(mp, MBF_NOWAIT);
14230 			if (error != 0)
14231 				goto finish_write;
14232 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14233 			     FFSV_FORCEINSMQ);
14234 			vfs_unbusy(mp);
14235 			if (error != 0) {
14236 				softdep_error("clear_remove: vget", error);
14237 				goto finish_write;
14238 			}
14239 			MPASS(VTOI(vp)->i_mode != 0);
14240 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14241 				softdep_error("clear_remove: fsync", error);
14242 			bo = &vp->v_bufobj;
14243 			BO_LOCK(bo);
14244 			drain_output(vp);
14245 			BO_UNLOCK(bo);
14246 			vput(vp);
14247 		finish_write:
14248 			vn_finished_write(mp);
14249 			ACQUIRE_LOCK(ump);
14250 			return;
14251 		}
14252 	}
14253 }
14254 
14255 /*
14256  * Clear out a block of dirty inodes in an effort to reduce
14257  * the number of inodedep dependency structures.
14258  */
14259 static void
14260 clear_inodedeps(mp)
14261 	struct mount *mp;
14262 {
14263 	struct inodedep_hashhead *inodedephd;
14264 	struct inodedep *inodedep;
14265 	struct ufsmount *ump;
14266 	struct vnode *vp;
14267 	struct fs *fs;
14268 	int error, cnt;
14269 	ino_t firstino, lastino, ino;
14270 
14271 	ump = VFSTOUFS(mp);
14272 	fs = ump->um_fs;
14273 	LOCK_OWNED(ump);
14274 	/*
14275 	 * Pick a random inode dependency to be cleared.
14276 	 * We will then gather up all the inodes in its block
14277 	 * that have dependencies and flush them out.
14278 	 */
14279 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
14280 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
14281 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
14282 			ump->inodedep_nextclean = 0;
14283 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
14284 			break;
14285 	}
14286 	if (inodedep == NULL)
14287 		return;
14288 	/*
14289 	 * Find the last inode in the block with dependencies.
14290 	 */
14291 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
14292 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
14293 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
14294 			break;
14295 	/*
14296 	 * Asynchronously push all but the last inode with dependencies.
14297 	 * Synchronously push the last inode with dependencies to ensure
14298 	 * that the inode block gets written to free up the inodedeps.
14299 	 */
14300 	for (ino = firstino; ino <= lastino; ino++) {
14301 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
14302 			continue;
14303 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14304 			continue;
14305 		FREE_LOCK(ump);
14306 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
14307 		if (error != 0) {
14308 			vn_finished_write(mp);
14309 			ACQUIRE_LOCK(ump);
14310 			return;
14311 		}
14312 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14313 		    FFSV_FORCEINSMQ)) != 0) {
14314 			softdep_error("clear_inodedeps: vget", error);
14315 			vfs_unbusy(mp);
14316 			vn_finished_write(mp);
14317 			ACQUIRE_LOCK(ump);
14318 			return;
14319 		}
14320 		vfs_unbusy(mp);
14321 		if (VTOI(vp)->i_mode == 0) {
14322 			vgone(vp);
14323 		} else if (ino == lastino) {
14324 			do {
14325 				error = ffs_syncvnode(vp, MNT_WAIT, 0);
14326 			} while (error == ERELOOKUP);
14327 			if (error != 0)
14328 				softdep_error("clear_inodedeps: fsync1", error);
14329 		} else {
14330 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14331 				softdep_error("clear_inodedeps: fsync2", error);
14332 			BO_LOCK(&vp->v_bufobj);
14333 			drain_output(vp);
14334 			BO_UNLOCK(&vp->v_bufobj);
14335 		}
14336 		vput(vp);
14337 		vn_finished_write(mp);
14338 		ACQUIRE_LOCK(ump);
14339 	}
14340 }
14341 
14342 void
14343 softdep_buf_append(bp, wkhd)
14344 	struct buf *bp;
14345 	struct workhead *wkhd;
14346 {
14347 	struct worklist *wk;
14348 	struct ufsmount *ump;
14349 
14350 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14351 		return;
14352 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14353 	    ("softdep_buf_append called on non-softdep filesystem"));
14354 	ump = VFSTOUFS(wk->wk_mp);
14355 	ACQUIRE_LOCK(ump);
14356 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
14357 		WORKLIST_REMOVE(wk);
14358 		WORKLIST_INSERT(&bp->b_dep, wk);
14359 	}
14360 	FREE_LOCK(ump);
14361 
14362 }
14363 
14364 void
14365 softdep_inode_append(ip, cred, wkhd)
14366 	struct inode *ip;
14367 	struct ucred *cred;
14368 	struct workhead *wkhd;
14369 {
14370 	struct buf *bp;
14371 	struct fs *fs;
14372 	struct ufsmount *ump;
14373 	int error;
14374 
14375 	ump = ITOUMP(ip);
14376 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
14377 	    ("softdep_inode_append called on non-softdep filesystem"));
14378 	fs = ump->um_fs;
14379 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14380 	    (int)fs->fs_bsize, cred, &bp);
14381 	if (error) {
14382 		bqrelse(bp);
14383 		softdep_freework(wkhd);
14384 		return;
14385 	}
14386 	softdep_buf_append(bp, wkhd);
14387 	bqrelse(bp);
14388 }
14389 
14390 void
14391 softdep_freework(wkhd)
14392 	struct workhead *wkhd;
14393 {
14394 	struct worklist *wk;
14395 	struct ufsmount *ump;
14396 
14397 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14398 		return;
14399 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14400 	    ("softdep_freework called on non-softdep filesystem"));
14401 	ump = VFSTOUFS(wk->wk_mp);
14402 	ACQUIRE_LOCK(ump);
14403 	handle_jwork(wkhd);
14404 	FREE_LOCK(ump);
14405 }
14406 
14407 static struct ufsmount *
14408 softdep_bp_to_mp(bp)
14409 	struct buf *bp;
14410 {
14411 	struct mount *mp;
14412 	struct vnode *vp;
14413 
14414 	if (LIST_EMPTY(&bp->b_dep))
14415 		return (NULL);
14416 	vp = bp->b_vp;
14417 	KASSERT(vp != NULL,
14418 	    ("%s, buffer with dependencies lacks vnode", __func__));
14419 
14420 	/*
14421 	 * The ump mount point is stable after we get a correct
14422 	 * pointer, since bp is locked and this prevents unmount from
14423 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
14424 	 * head wk_mp, because we do not yet own SU ump lock and
14425 	 * workitem might be freed while dereferenced.
14426 	 */
14427 retry:
14428 	switch (vp->v_type) {
14429 	case VCHR:
14430 		VI_LOCK(vp);
14431 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14432 		VI_UNLOCK(vp);
14433 		if (mp == NULL)
14434 			goto retry;
14435 		break;
14436 	case VREG:
14437 	case VDIR:
14438 	case VLNK:
14439 	case VFIFO:
14440 	case VSOCK:
14441 		mp = vp->v_mount;
14442 		break;
14443 	case VBLK:
14444 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14445 		/* FALLTHROUGH */
14446 	case VNON:
14447 	case VBAD:
14448 	case VMARKER:
14449 		mp = NULL;
14450 		break;
14451 	default:
14452 		vn_printf(vp, "unknown vnode type");
14453 		mp = NULL;
14454 		break;
14455 	}
14456 	return (VFSTOUFS(mp));
14457 }
14458 
14459 /*
14460  * Function to determine if the buffer has outstanding dependencies
14461  * that will cause a roll-back if the buffer is written. If wantcount
14462  * is set, return number of dependencies, otherwise just yes or no.
14463  */
14464 static int
14465 softdep_count_dependencies(bp, wantcount)
14466 	struct buf *bp;
14467 	int wantcount;
14468 {
14469 	struct worklist *wk;
14470 	struct ufsmount *ump;
14471 	struct bmsafemap *bmsafemap;
14472 	struct freework *freework;
14473 	struct inodedep *inodedep;
14474 	struct indirdep *indirdep;
14475 	struct freeblks *freeblks;
14476 	struct allocindir *aip;
14477 	struct pagedep *pagedep;
14478 	struct dirrem *dirrem;
14479 	struct newblk *newblk;
14480 	struct mkdir *mkdir;
14481 	struct diradd *dap;
14482 	int i, retval;
14483 
14484 	ump = softdep_bp_to_mp(bp);
14485 	if (ump == NULL)
14486 		return (0);
14487 	retval = 0;
14488 	ACQUIRE_LOCK(ump);
14489 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14490 		switch (wk->wk_type) {
14491 		case D_INODEDEP:
14492 			inodedep = WK_INODEDEP(wk);
14493 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14494 				/* bitmap allocation dependency */
14495 				retval += 1;
14496 				if (!wantcount)
14497 					goto out;
14498 			}
14499 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14500 				/* direct block pointer dependency */
14501 				retval += 1;
14502 				if (!wantcount)
14503 					goto out;
14504 			}
14505 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14506 				/* direct block pointer dependency */
14507 				retval += 1;
14508 				if (!wantcount)
14509 					goto out;
14510 			}
14511 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14512 				/* Add reference dependency. */
14513 				retval += 1;
14514 				if (!wantcount)
14515 					goto out;
14516 			}
14517 			continue;
14518 
14519 		case D_INDIRDEP:
14520 			indirdep = WK_INDIRDEP(wk);
14521 
14522 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14523 				/* indirect truncation dependency */
14524 				retval += 1;
14525 				if (!wantcount)
14526 					goto out;
14527 			}
14528 
14529 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14530 				/* indirect block pointer dependency */
14531 				retval += 1;
14532 				if (!wantcount)
14533 					goto out;
14534 			}
14535 			continue;
14536 
14537 		case D_PAGEDEP:
14538 			pagedep = WK_PAGEDEP(wk);
14539 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14540 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14541 					/* Journal remove ref dependency. */
14542 					retval += 1;
14543 					if (!wantcount)
14544 						goto out;
14545 				}
14546 			}
14547 			for (i = 0; i < DAHASHSZ; i++) {
14548 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14549 					/* directory entry dependency */
14550 					retval += 1;
14551 					if (!wantcount)
14552 						goto out;
14553 				}
14554 			}
14555 			continue;
14556 
14557 		case D_BMSAFEMAP:
14558 			bmsafemap = WK_BMSAFEMAP(wk);
14559 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14560 				/* Add reference dependency. */
14561 				retval += 1;
14562 				if (!wantcount)
14563 					goto out;
14564 			}
14565 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14566 				/* Allocate block dependency. */
14567 				retval += 1;
14568 				if (!wantcount)
14569 					goto out;
14570 			}
14571 			continue;
14572 
14573 		case D_FREEBLKS:
14574 			freeblks = WK_FREEBLKS(wk);
14575 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14576 				/* Freeblk journal dependency. */
14577 				retval += 1;
14578 				if (!wantcount)
14579 					goto out;
14580 			}
14581 			continue;
14582 
14583 		case D_ALLOCDIRECT:
14584 		case D_ALLOCINDIR:
14585 			newblk = WK_NEWBLK(wk);
14586 			if (newblk->nb_jnewblk) {
14587 				/* Journal allocate dependency. */
14588 				retval += 1;
14589 				if (!wantcount)
14590 					goto out;
14591 			}
14592 			continue;
14593 
14594 		case D_MKDIR:
14595 			mkdir = WK_MKDIR(wk);
14596 			if (mkdir->md_jaddref) {
14597 				/* Journal reference dependency. */
14598 				retval += 1;
14599 				if (!wantcount)
14600 					goto out;
14601 			}
14602 			continue;
14603 
14604 		case D_FREEWORK:
14605 		case D_FREEDEP:
14606 		case D_JSEGDEP:
14607 		case D_JSEG:
14608 		case D_SBDEP:
14609 			/* never a dependency on these blocks */
14610 			continue;
14611 
14612 		default:
14613 			panic("softdep_count_dependencies: Unexpected type %s",
14614 			    TYPENAME(wk->wk_type));
14615 			/* NOTREACHED */
14616 		}
14617 	}
14618 out:
14619 	FREE_LOCK(ump);
14620 	return (retval);
14621 }
14622 
14623 /*
14624  * Acquire exclusive access to a buffer.
14625  * Must be called with a locked mtx parameter.
14626  * Return acquired buffer or NULL on failure.
14627  */
14628 static struct buf *
14629 getdirtybuf(bp, lock, waitfor)
14630 	struct buf *bp;
14631 	struct rwlock *lock;
14632 	int waitfor;
14633 {
14634 	int error;
14635 
14636 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14637 		if (waitfor != MNT_WAIT)
14638 			return (NULL);
14639 		error = BUF_LOCK(bp,
14640 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14641 		/*
14642 		 * Even if we successfully acquire bp here, we have dropped
14643 		 * lock, which may violates our guarantee.
14644 		 */
14645 		if (error == 0)
14646 			BUF_UNLOCK(bp);
14647 		else if (error != ENOLCK)
14648 			panic("getdirtybuf: inconsistent lock: %d", error);
14649 		rw_wlock(lock);
14650 		return (NULL);
14651 	}
14652 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14653 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14654 			rw_wunlock(lock);
14655 			BO_LOCK(bp->b_bufobj);
14656 			BUF_UNLOCK(bp);
14657 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14658 				bp->b_vflags |= BV_BKGRDWAIT;
14659 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14660 				       PRIBIO | PDROP, "getbuf", 0);
14661 			} else
14662 				BO_UNLOCK(bp->b_bufobj);
14663 			rw_wlock(lock);
14664 			return (NULL);
14665 		}
14666 		BUF_UNLOCK(bp);
14667 		if (waitfor != MNT_WAIT)
14668 			return (NULL);
14669 #ifdef DEBUG_VFS_LOCKS
14670 		if (bp->b_vp->v_type != VCHR)
14671 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14672 #endif
14673 		bp->b_vflags |= BV_BKGRDWAIT;
14674 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14675 		return (NULL);
14676 	}
14677 	if ((bp->b_flags & B_DELWRI) == 0) {
14678 		BUF_UNLOCK(bp);
14679 		return (NULL);
14680 	}
14681 	bremfree(bp);
14682 	return (bp);
14683 }
14684 
14685 /*
14686  * Check if it is safe to suspend the file system now.  On entry,
14687  * the vnode interlock for devvp should be held.  Return 0 with
14688  * the mount interlock held if the file system can be suspended now,
14689  * otherwise return EAGAIN with the mount interlock held.
14690  */
14691 int
14692 softdep_check_suspend(struct mount *mp,
14693 		      struct vnode *devvp,
14694 		      int softdep_depcnt,
14695 		      int softdep_accdepcnt,
14696 		      int secondary_writes,
14697 		      int secondary_accwrites)
14698 {
14699 	struct bufobj *bo;
14700 	struct ufsmount *ump;
14701 	struct inodedep *inodedep;
14702 	int error, unlinked;
14703 
14704 	bo = &devvp->v_bufobj;
14705 	ASSERT_BO_WLOCKED(bo);
14706 
14707 	/*
14708 	 * If we are not running with soft updates, then we need only
14709 	 * deal with secondary writes as we try to suspend.
14710 	 */
14711 	if (MOUNTEDSOFTDEP(mp) == 0) {
14712 		MNT_ILOCK(mp);
14713 		while (mp->mnt_secondary_writes != 0) {
14714 			BO_UNLOCK(bo);
14715 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14716 			    (PUSER - 1) | PDROP, "secwr", 0);
14717 			BO_LOCK(bo);
14718 			MNT_ILOCK(mp);
14719 		}
14720 
14721 		/*
14722 		 * Reasons for needing more work before suspend:
14723 		 * - Dirty buffers on devvp.
14724 		 * - Secondary writes occurred after start of vnode sync loop
14725 		 */
14726 		error = 0;
14727 		if (bo->bo_numoutput > 0 ||
14728 		    bo->bo_dirty.bv_cnt > 0 ||
14729 		    secondary_writes != 0 ||
14730 		    mp->mnt_secondary_writes != 0 ||
14731 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14732 			error = EAGAIN;
14733 		BO_UNLOCK(bo);
14734 		return (error);
14735 	}
14736 
14737 	/*
14738 	 * If we are running with soft updates, then we need to coordinate
14739 	 * with them as we try to suspend.
14740 	 */
14741 	ump = VFSTOUFS(mp);
14742 	for (;;) {
14743 		if (!TRY_ACQUIRE_LOCK(ump)) {
14744 			BO_UNLOCK(bo);
14745 			ACQUIRE_LOCK(ump);
14746 			FREE_LOCK(ump);
14747 			BO_LOCK(bo);
14748 			continue;
14749 		}
14750 		MNT_ILOCK(mp);
14751 		if (mp->mnt_secondary_writes != 0) {
14752 			FREE_LOCK(ump);
14753 			BO_UNLOCK(bo);
14754 			msleep(&mp->mnt_secondary_writes,
14755 			       MNT_MTX(mp),
14756 			       (PUSER - 1) | PDROP, "secwr", 0);
14757 			BO_LOCK(bo);
14758 			continue;
14759 		}
14760 		break;
14761 	}
14762 
14763 	unlinked = 0;
14764 	if (MOUNTEDSUJ(mp)) {
14765 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14766 		    inodedep != NULL;
14767 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14768 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14769 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14770 			    UNLINKONLIST) ||
14771 			    !check_inodedep_free(inodedep))
14772 				continue;
14773 			unlinked++;
14774 		}
14775 	}
14776 
14777 	/*
14778 	 * Reasons for needing more work before suspend:
14779 	 * - Dirty buffers on devvp.
14780 	 * - Softdep activity occurred after start of vnode sync loop
14781 	 * - Secondary writes occurred after start of vnode sync loop
14782 	 */
14783 	error = 0;
14784 	if (bo->bo_numoutput > 0 ||
14785 	    bo->bo_dirty.bv_cnt > 0 ||
14786 	    softdep_depcnt != unlinked ||
14787 	    ump->softdep_deps != unlinked ||
14788 	    softdep_accdepcnt != ump->softdep_accdeps ||
14789 	    secondary_writes != 0 ||
14790 	    mp->mnt_secondary_writes != 0 ||
14791 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14792 		error = EAGAIN;
14793 	FREE_LOCK(ump);
14794 	BO_UNLOCK(bo);
14795 	return (error);
14796 }
14797 
14798 /*
14799  * Get the number of dependency structures for the file system, both
14800  * the current number and the total number allocated.  These will
14801  * later be used to detect that softdep processing has occurred.
14802  */
14803 void
14804 softdep_get_depcounts(struct mount *mp,
14805 		      int *softdep_depsp,
14806 		      int *softdep_accdepsp)
14807 {
14808 	struct ufsmount *ump;
14809 
14810 	if (MOUNTEDSOFTDEP(mp) == 0) {
14811 		*softdep_depsp = 0;
14812 		*softdep_accdepsp = 0;
14813 		return;
14814 	}
14815 	ump = VFSTOUFS(mp);
14816 	ACQUIRE_LOCK(ump);
14817 	*softdep_depsp = ump->softdep_deps;
14818 	*softdep_accdepsp = ump->softdep_accdeps;
14819 	FREE_LOCK(ump);
14820 }
14821 
14822 /*
14823  * Wait for pending output on a vnode to complete.
14824  */
14825 static void
14826 drain_output(vp)
14827 	struct vnode *vp;
14828 {
14829 
14830 	ASSERT_VOP_LOCKED(vp, "drain_output");
14831 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14832 }
14833 
14834 /*
14835  * Called whenever a buffer that is being invalidated or reallocated
14836  * contains dependencies. This should only happen if an I/O error has
14837  * occurred. The routine is called with the buffer locked.
14838  */
14839 static void
14840 softdep_deallocate_dependencies(bp)
14841 	struct buf *bp;
14842 {
14843 
14844 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14845 		panic("softdep_deallocate_dependencies: dangling deps");
14846 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14847 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14848 	else
14849 		printf("softdep_deallocate_dependencies: "
14850 		    "got error %d while accessing filesystem\n", bp->b_error);
14851 	if (bp->b_error != ENXIO)
14852 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14853 }
14854 
14855 /*
14856  * Function to handle asynchronous write errors in the filesystem.
14857  */
14858 static void
14859 softdep_error(func, error)
14860 	char *func;
14861 	int error;
14862 {
14863 
14864 	/* XXX should do something better! */
14865 	printf("%s: got error %d while accessing filesystem\n", func, error);
14866 }
14867 
14868 #ifdef DDB
14869 
14870 /* exported to ffs_vfsops.c */
14871 extern void db_print_ffs(struct ufsmount *ump);
14872 void
14873 db_print_ffs(struct ufsmount *ump)
14874 {
14875 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14876 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14877 	db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14878 	    ump->um_fs, ump->softdep_on_worklist,
14879 	    ump->softdep_deps, ump->softdep_req);
14880 }
14881 
14882 static void
14883 worklist_print(struct worklist *wk, int verbose)
14884 {
14885 
14886 	if (!verbose) {
14887 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14888 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14889 		return;
14890 	}
14891 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14892 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14893 	    LIST_NEXT(wk, wk_list));
14894 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14895 }
14896 
14897 static void
14898 inodedep_print(struct inodedep *inodedep, int verbose)
14899 {
14900 
14901 	worklist_print(&inodedep->id_list, 0);
14902 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14903 	    inodedep->id_fs,
14904 	    (intmax_t)inodedep->id_ino,
14905 	    (intmax_t)fsbtodb(inodedep->id_fs,
14906 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14907 	    (intmax_t)inodedep->id_nlinkdelta,
14908 	    (intmax_t)inodedep->id_savednlink);
14909 
14910 	if (verbose == 0)
14911 		return;
14912 
14913 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14914 	    inodedep->id_bmsafemap,
14915 	    inodedep->id_mkdiradd,
14916 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14917 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14918 	    LIST_FIRST(&inodedep->id_dirremhd),
14919 	    LIST_FIRST(&inodedep->id_pendinghd),
14920 	    LIST_FIRST(&inodedep->id_bufwait));
14921 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14922 	    LIST_FIRST(&inodedep->id_inowait),
14923 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14924 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14925 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14926 	    TAILQ_FIRST(&inodedep->id_extupdt),
14927 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14928 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14929 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14930 	    inodedep->id_savedino1,
14931 	    (intmax_t)inodedep->id_savedsize,
14932 	    (intmax_t)inodedep->id_savedextsize);
14933 }
14934 
14935 static void
14936 newblk_print(struct newblk *nbp)
14937 {
14938 
14939 	worklist_print(&nbp->nb_list, 0);
14940 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14941 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14942 	    &nbp->nb_jnewblk,
14943 	    &nbp->nb_bmsafemap,
14944 	    &nbp->nb_freefrag);
14945 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14946 	    LIST_FIRST(&nbp->nb_indirdeps),
14947 	    LIST_FIRST(&nbp->nb_newdirblk),
14948 	    LIST_FIRST(&nbp->nb_jwork));
14949 }
14950 
14951 static void
14952 allocdirect_print(struct allocdirect *adp)
14953 {
14954 
14955 	newblk_print(&adp->ad_block);
14956 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14957 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14958 	db_printf("    offset %d, inodedep %p\n",
14959 	    adp->ad_offset, adp->ad_inodedep);
14960 }
14961 
14962 static void
14963 allocindir_print(struct allocindir *aip)
14964 {
14965 
14966 	newblk_print(&aip->ai_block);
14967 	db_printf("    oldblkno %jd, lbn %jd\n",
14968 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14969 	db_printf("    offset %d, indirdep %p\n",
14970 	    aip->ai_offset, aip->ai_indirdep);
14971 }
14972 
14973 static void
14974 mkdir_print(struct mkdir *mkdir)
14975 {
14976 
14977 	worklist_print(&mkdir->md_list, 0);
14978 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14979 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14980 }
14981 
14982 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14983 {
14984 
14985 	if (have_addr == 0) {
14986 		db_printf("inodedep address required\n");
14987 		return;
14988 	}
14989 	inodedep_print((struct inodedep*)addr, 1);
14990 }
14991 
14992 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14993 {
14994 	struct inodedep_hashhead *inodedephd;
14995 	struct inodedep *inodedep;
14996 	struct ufsmount *ump;
14997 	int cnt;
14998 
14999 	if (have_addr == 0) {
15000 		db_printf("ufsmount address required\n");
15001 		return;
15002 	}
15003 	ump = (struct ufsmount *)addr;
15004 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
15005 		inodedephd = &ump->inodedep_hashtbl[cnt];
15006 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
15007 			inodedep_print(inodedep, 0);
15008 		}
15009 	}
15010 }
15011 
15012 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
15013 {
15014 
15015 	if (have_addr == 0) {
15016 		db_printf("worklist address required\n");
15017 		return;
15018 	}
15019 	worklist_print((struct worklist *)addr, 1);
15020 }
15021 
15022 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
15023 {
15024 	struct worklist *wk;
15025 	struct workhead *wkhd;
15026 
15027 	if (have_addr == 0) {
15028 		db_printf("worklist address required "
15029 		    "(for example value in bp->b_dep)\n");
15030 		return;
15031 	}
15032 	/*
15033 	 * We often do not have the address of the worklist head but
15034 	 * instead a pointer to its first entry (e.g., we have the
15035 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
15036 	 * pointer of bp->b_dep will point at the head of the list, so
15037 	 * we cheat and use that instead. If we are in the middle of
15038 	 * a list we will still get the same result, so nothing
15039 	 * unexpected will result.
15040 	 */
15041 	wk = (struct worklist *)addr;
15042 	if (wk == NULL)
15043 		return;
15044 	wkhd = (struct workhead *)wk->wk_list.le_prev;
15045 	LIST_FOREACH(wk, wkhd, wk_list) {
15046 		switch(wk->wk_type) {
15047 		case D_INODEDEP:
15048 			inodedep_print(WK_INODEDEP(wk), 0);
15049 			continue;
15050 		case D_ALLOCDIRECT:
15051 			allocdirect_print(WK_ALLOCDIRECT(wk));
15052 			continue;
15053 		case D_ALLOCINDIR:
15054 			allocindir_print(WK_ALLOCINDIR(wk));
15055 			continue;
15056 		case D_MKDIR:
15057 			mkdir_print(WK_MKDIR(wk));
15058 			continue;
15059 		default:
15060 			worklist_print(wk, 0);
15061 			continue;
15062 		}
15063 	}
15064 }
15065 
15066 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
15067 {
15068 	if (have_addr == 0) {
15069 		db_printf("mkdir address required\n");
15070 		return;
15071 	}
15072 	mkdir_print((struct mkdir *)addr);
15073 }
15074 
15075 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
15076 {
15077 	struct mkdirlist *mkdirlisthd;
15078 	struct mkdir *mkdir;
15079 
15080 	if (have_addr == 0) {
15081 		db_printf("mkdir listhead address required\n");
15082 		return;
15083 	}
15084 	mkdirlisthd = (struct mkdirlist *)addr;
15085 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
15086 		mkdir_print(mkdir);
15087 		if (mkdir->md_diradd != NULL) {
15088 			db_printf("    ");
15089 			worklist_print(&mkdir->md_diradd->da_list, 0);
15090 		}
15091 		if (mkdir->md_jaddref != NULL) {
15092 			db_printf("    ");
15093 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
15094 		}
15095 	}
15096 }
15097 
15098 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
15099 {
15100 	if (have_addr == 0) {
15101 		db_printf("allocdirect address required\n");
15102 		return;
15103 	}
15104 	allocdirect_print((struct allocdirect *)addr);
15105 }
15106 
15107 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
15108 {
15109 	if (have_addr == 0) {
15110 		db_printf("allocindir address required\n");
15111 		return;
15112 	}
15113 	allocindir_print((struct allocindir *)addr);
15114 }
15115 
15116 #endif /* DDB */
15117 
15118 #endif /* SOFTUPDATES */
15119