xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 5686c6c38a3e1cc78804eaf5f880bda23dcf592f)
1 /*-
2  * Copyright 1998, 2000 Marshall Kirk McKusick.
3  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
4  * All rights reserved.
5  *
6  * The soft updates code is derived from the appendix of a University
7  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
8  * "Soft Updates: A Solution to the Metadata Update Problem in File
9  * Systems", CSE-TR-254-95, August 1995).
10  *
11  * Further information about soft updates can be obtained from:
12  *
13  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
14  *	1614 Oxford Street		mckusick@mckusick.com
15  *	Berkeley, CA 94709-1608		+1-510-843-9542
16  *	USA
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  *
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  *
39  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
40  */
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include "opt_ffs.h"
46 #include "opt_quota.h"
47 #include "opt_ddb.h"
48 
49 /*
50  * For now we want the safety net that the DEBUG flag provides.
51  */
52 #ifndef DEBUG
53 #define DEBUG
54 #endif
55 
56 #include <sys/param.h>
57 #include <sys/kernel.h>
58 #include <sys/systm.h>
59 #include <sys/bio.h>
60 #include <sys/buf.h>
61 #include <sys/kdb.h>
62 #include <sys/kthread.h>
63 #include <sys/ktr.h>
64 #include <sys/limits.h>
65 #include <sys/lock.h>
66 #include <sys/malloc.h>
67 #include <sys/mount.h>
68 #include <sys/mutex.h>
69 #include <sys/namei.h>
70 #include <sys/priv.h>
71 #include <sys/proc.h>
72 #include <sys/stat.h>
73 #include <sys/sysctl.h>
74 #include <sys/syslog.h>
75 #include <sys/vnode.h>
76 #include <sys/conf.h>
77 
78 #include <ufs/ufs/dir.h>
79 #include <ufs/ufs/extattr.h>
80 #include <ufs/ufs/quota.h>
81 #include <ufs/ufs/inode.h>
82 #include <ufs/ufs/ufsmount.h>
83 #include <ufs/ffs/fs.h>
84 #include <ufs/ffs/softdep.h>
85 #include <ufs/ffs/ffs_extern.h>
86 #include <ufs/ufs/ufs_extern.h>
87 
88 #include <vm/vm.h>
89 #include <vm/vm_extern.h>
90 #include <vm/vm_object.h>
91 
92 #include <geom/geom.h>
93 
94 #include <ddb/ddb.h>
95 
96 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
97 
98 #ifndef SOFTUPDATES
99 
100 int
101 softdep_flushfiles(oldmnt, flags, td)
102 	struct mount *oldmnt;
103 	int flags;
104 	struct thread *td;
105 {
106 
107 	panic("softdep_flushfiles called");
108 }
109 
110 int
111 softdep_mount(devvp, mp, fs, cred)
112 	struct vnode *devvp;
113 	struct mount *mp;
114 	struct fs *fs;
115 	struct ucred *cred;
116 {
117 
118 	return (0);
119 }
120 
121 void
122 softdep_initialize()
123 {
124 
125 	return;
126 }
127 
128 void
129 softdep_uninitialize()
130 {
131 
132 	return;
133 }
134 
135 void
136 softdep_unmount(mp)
137 	struct mount *mp;
138 {
139 
140 }
141 
142 void
143 softdep_setup_sbupdate(ump, fs, bp)
144 	struct ufsmount *ump;
145 	struct fs *fs;
146 	struct buf *bp;
147 {
148 }
149 
150 void
151 softdep_setup_inomapdep(bp, ip, newinum, mode)
152 	struct buf *bp;
153 	struct inode *ip;
154 	ino_t newinum;
155 	int mode;
156 {
157 
158 	panic("softdep_setup_inomapdep called");
159 }
160 
161 void
162 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
163 	struct buf *bp;
164 	struct mount *mp;
165 	ufs2_daddr_t newblkno;
166 	int frags;
167 	int oldfrags;
168 {
169 
170 	panic("softdep_setup_blkmapdep called");
171 }
172 
173 void
174 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
175 	struct inode *ip;
176 	ufs_lbn_t lbn;
177 	ufs2_daddr_t newblkno;
178 	ufs2_daddr_t oldblkno;
179 	long newsize;
180 	long oldsize;
181 	struct buf *bp;
182 {
183 
184 	panic("softdep_setup_allocdirect called");
185 }
186 
187 void
188 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
189 	struct inode *ip;
190 	ufs_lbn_t lbn;
191 	ufs2_daddr_t newblkno;
192 	ufs2_daddr_t oldblkno;
193 	long newsize;
194 	long oldsize;
195 	struct buf *bp;
196 {
197 
198 	panic("softdep_setup_allocext called");
199 }
200 
201 void
202 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
203 	struct inode *ip;
204 	ufs_lbn_t lbn;
205 	struct buf *bp;
206 	int ptrno;
207 	ufs2_daddr_t newblkno;
208 	ufs2_daddr_t oldblkno;
209 	struct buf *nbp;
210 {
211 
212 	panic("softdep_setup_allocindir_page called");
213 }
214 
215 void
216 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
217 	struct buf *nbp;
218 	struct inode *ip;
219 	struct buf *bp;
220 	int ptrno;
221 	ufs2_daddr_t newblkno;
222 {
223 
224 	panic("softdep_setup_allocindir_meta called");
225 }
226 
227 void
228 softdep_journal_freeblocks(ip, cred, length, flags)
229 	struct inode *ip;
230 	struct ucred *cred;
231 	off_t length;
232 	int flags;
233 {
234 
235 	panic("softdep_journal_freeblocks called");
236 }
237 
238 void
239 softdep_journal_fsync(ip)
240 	struct inode *ip;
241 {
242 
243 	panic("softdep_journal_fsync called");
244 }
245 
246 void
247 softdep_setup_freeblocks(ip, length, flags)
248 	struct inode *ip;
249 	off_t length;
250 	int flags;
251 {
252 
253 	panic("softdep_setup_freeblocks called");
254 }
255 
256 void
257 softdep_freefile(pvp, ino, mode)
258 		struct vnode *pvp;
259 		ino_t ino;
260 		int mode;
261 {
262 
263 	panic("softdep_freefile called");
264 }
265 
266 int
267 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
268 	struct buf *bp;
269 	struct inode *dp;
270 	off_t diroffset;
271 	ino_t newinum;
272 	struct buf *newdirbp;
273 	int isnewblk;
274 {
275 
276 	panic("softdep_setup_directory_add called");
277 }
278 
279 void
280 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
281 	struct buf *bp;
282 	struct inode *dp;
283 	caddr_t base;
284 	caddr_t oldloc;
285 	caddr_t newloc;
286 	int entrysize;
287 {
288 
289 	panic("softdep_change_directoryentry_offset called");
290 }
291 
292 void
293 softdep_setup_remove(bp, dp, ip, isrmdir)
294 	struct buf *bp;
295 	struct inode *dp;
296 	struct inode *ip;
297 	int isrmdir;
298 {
299 
300 	panic("softdep_setup_remove called");
301 }
302 
303 void
304 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
305 	struct buf *bp;
306 	struct inode *dp;
307 	struct inode *ip;
308 	ino_t newinum;
309 	int isrmdir;
310 {
311 
312 	panic("softdep_setup_directory_change called");
313 }
314 
315 void
316 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
317 	struct mount *mp;
318 	struct buf *bp;
319 	ufs2_daddr_t blkno;
320 	int frags;
321 	struct workhead *wkhd;
322 {
323 
324 	panic("%s called", __FUNCTION__);
325 }
326 
327 void
328 softdep_setup_inofree(mp, bp, ino, wkhd)
329 	struct mount *mp;
330 	struct buf *bp;
331 	ino_t ino;
332 	struct workhead *wkhd;
333 {
334 
335 	panic("%s called", __FUNCTION__);
336 }
337 
338 void
339 softdep_setup_unlink(dp, ip)
340 	struct inode *dp;
341 	struct inode *ip;
342 {
343 
344 	panic("%s called", __FUNCTION__);
345 }
346 
347 void
348 softdep_setup_link(dp, ip)
349 	struct inode *dp;
350 	struct inode *ip;
351 {
352 
353 	panic("%s called", __FUNCTION__);
354 }
355 
356 void
357 softdep_revert_link(dp, ip)
358 	struct inode *dp;
359 	struct inode *ip;
360 {
361 
362 	panic("%s called", __FUNCTION__);
363 }
364 
365 void
366 softdep_setup_rmdir(dp, ip)
367 	struct inode *dp;
368 	struct inode *ip;
369 {
370 
371 	panic("%s called", __FUNCTION__);
372 }
373 
374 void
375 softdep_revert_rmdir(dp, ip)
376 	struct inode *dp;
377 	struct inode *ip;
378 {
379 
380 	panic("%s called", __FUNCTION__);
381 }
382 
383 void
384 softdep_setup_create(dp, ip)
385 	struct inode *dp;
386 	struct inode *ip;
387 {
388 
389 	panic("%s called", __FUNCTION__);
390 }
391 
392 void
393 softdep_revert_create(dp, ip)
394 	struct inode *dp;
395 	struct inode *ip;
396 {
397 
398 	panic("%s called", __FUNCTION__);
399 }
400 
401 void
402 softdep_setup_mkdir(dp, ip)
403 	struct inode *dp;
404 	struct inode *ip;
405 {
406 
407 	panic("%s called", __FUNCTION__);
408 }
409 
410 void
411 softdep_revert_mkdir(dp, ip)
412 	struct inode *dp;
413 	struct inode *ip;
414 {
415 
416 	panic("%s called", __FUNCTION__);
417 }
418 
419 void
420 softdep_setup_dotdot_link(dp, ip)
421 	struct inode *dp;
422 	struct inode *ip;
423 {
424 
425 	panic("%s called", __FUNCTION__);
426 }
427 
428 int
429 softdep_prealloc(vp, waitok)
430 	struct vnode *vp;
431 	int waitok;
432 {
433 
434 	panic("%s called", __FUNCTION__);
435 
436 	return (0);
437 }
438 
439 int
440 softdep_journal_lookup(mp, vpp)
441 	struct mount *mp;
442 	struct vnode **vpp;
443 {
444 
445 	return (ENOENT);
446 }
447 
448 void
449 softdep_change_linkcnt(ip)
450 	struct inode *ip;
451 {
452 
453 	panic("softdep_change_linkcnt called");
454 }
455 
456 void
457 softdep_load_inodeblock(ip)
458 	struct inode *ip;
459 {
460 
461 	panic("softdep_load_inodeblock called");
462 }
463 
464 void
465 softdep_update_inodeblock(ip, bp, waitfor)
466 	struct inode *ip;
467 	struct buf *bp;
468 	int waitfor;
469 {
470 
471 	panic("softdep_update_inodeblock called");
472 }
473 
474 int
475 softdep_fsync(vp)
476 	struct vnode *vp;	/* the "in_core" copy of the inode */
477 {
478 
479 	return (0);
480 }
481 
482 void
483 softdep_fsync_mountdev(vp)
484 	struct vnode *vp;
485 {
486 
487 	return;
488 }
489 
490 int
491 softdep_flushworklist(oldmnt, countp, td)
492 	struct mount *oldmnt;
493 	int *countp;
494 	struct thread *td;
495 {
496 
497 	*countp = 0;
498 	return (0);
499 }
500 
501 int
502 softdep_sync_metadata(struct vnode *vp)
503 {
504 
505 	return (0);
506 }
507 
508 int
509 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
510 {
511 
512 	return (0);
513 }
514 
515 int
516 softdep_slowdown(vp)
517 	struct vnode *vp;
518 {
519 
520 	panic("softdep_slowdown called");
521 }
522 
523 void
524 softdep_releasefile(ip)
525 	struct inode *ip;	/* inode with the zero effective link count */
526 {
527 
528 	panic("softdep_releasefile called");
529 }
530 
531 int
532 softdep_request_cleanup(fs, vp, cred, resource)
533 	struct fs *fs;
534 	struct vnode *vp;
535 	struct ucred *cred;
536 	int resource;
537 {
538 
539 	return (0);
540 }
541 
542 int
543 softdep_check_suspend(struct mount *mp,
544 		      struct vnode *devvp,
545 		      int softdep_deps,
546 		      int softdep_accdeps,
547 		      int secondary_writes,
548 		      int secondary_accwrites)
549 {
550 	struct bufobj *bo;
551 	int error;
552 
553 	(void) softdep_deps,
554 	(void) softdep_accdeps;
555 
556 	bo = &devvp->v_bufobj;
557 	ASSERT_BO_LOCKED(bo);
558 
559 	MNT_ILOCK(mp);
560 	while (mp->mnt_secondary_writes != 0) {
561 		BO_UNLOCK(bo);
562 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
563 		    (PUSER - 1) | PDROP, "secwr", 0);
564 		BO_LOCK(bo);
565 		MNT_ILOCK(mp);
566 	}
567 
568 	/*
569 	 * Reasons for needing more work before suspend:
570 	 * - Dirty buffers on devvp.
571 	 * - Secondary writes occurred after start of vnode sync loop
572 	 */
573 	error = 0;
574 	if (bo->bo_numoutput > 0 ||
575 	    bo->bo_dirty.bv_cnt > 0 ||
576 	    secondary_writes != 0 ||
577 	    mp->mnt_secondary_writes != 0 ||
578 	    secondary_accwrites != mp->mnt_secondary_accwrites)
579 		error = EAGAIN;
580 	BO_UNLOCK(bo);
581 	return (error);
582 }
583 
584 void
585 softdep_get_depcounts(struct mount *mp,
586 		      int *softdepactivep,
587 		      int *softdepactiveaccp)
588 {
589 	(void) mp;
590 	*softdepactivep = 0;
591 	*softdepactiveaccp = 0;
592 }
593 
594 void
595 softdep_buf_append(bp, wkhd)
596 	struct buf *bp;
597 	struct workhead *wkhd;
598 {
599 
600 	panic("softdep_buf_appendwork called");
601 }
602 
603 void
604 softdep_inode_append(ip, cred, wkhd)
605 	struct inode *ip;
606 	struct ucred *cred;
607 	struct workhead *wkhd;
608 {
609 
610 	panic("softdep_inode_appendwork called");
611 }
612 
613 void
614 softdep_freework(wkhd)
615 	struct workhead *wkhd;
616 {
617 
618 	panic("softdep_freework called");
619 }
620 
621 #else
622 
623 FEATURE(softupdates, "FFS soft-updates support");
624 
625 /*
626  * These definitions need to be adapted to the system to which
627  * this file is being ported.
628  */
629 
630 #define M_SOFTDEP_FLAGS	(M_WAITOK)
631 
632 #define	D_PAGEDEP	0
633 #define	D_INODEDEP	1
634 #define	D_BMSAFEMAP	2
635 #define	D_NEWBLK	3
636 #define	D_ALLOCDIRECT	4
637 #define	D_INDIRDEP	5
638 #define	D_ALLOCINDIR	6
639 #define	D_FREEFRAG	7
640 #define	D_FREEBLKS	8
641 #define	D_FREEFILE	9
642 #define	D_DIRADD	10
643 #define	D_MKDIR		11
644 #define	D_DIRREM	12
645 #define	D_NEWDIRBLK	13
646 #define	D_FREEWORK	14
647 #define	D_FREEDEP	15
648 #define	D_JADDREF	16
649 #define	D_JREMREF	17
650 #define	D_JMVREF	18
651 #define	D_JNEWBLK	19
652 #define	D_JFREEBLK	20
653 #define	D_JFREEFRAG	21
654 #define	D_JSEG		22
655 #define	D_JSEGDEP	23
656 #define	D_SBDEP		24
657 #define	D_JTRUNC	25
658 #define	D_JFSYNC	26
659 #define	D_SENTINEL	27
660 #define	D_LAST		D_SENTINEL
661 
662 unsigned long dep_current[D_LAST + 1];
663 unsigned long dep_total[D_LAST + 1];
664 unsigned long dep_write[D_LAST + 1];
665 
666 
667 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
668     "soft updates stats");
669 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
670     "total dependencies allocated");
671 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
672     "current dependencies allocated");
673 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
674     "current dependencies written");
675 
676 #define	SOFTDEP_TYPE(type, str, long)					\
677     static MALLOC_DEFINE(M_ ## type, #str, long);			\
678     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
679 	&dep_total[D_ ## type], 0, "");					\
680     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
681 	&dep_current[D_ ## type], 0, "");				\
682     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
683 	&dep_write[D_ ## type], 0, "");
684 
685 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
686 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
687 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
688     "Block or frag allocated from cyl group map");
689 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
690 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
691 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
692 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
693 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
694 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
695 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
696 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
697 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
698 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
699 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
700 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
701 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
702 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
703 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
704 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
705 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
706 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
707 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
708 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
709 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
710 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
711 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
712 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
713 
714 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
715 
716 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
717 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
718 
719 /*
720  * translate from workitem type to memory type
721  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
722  */
723 static struct malloc_type *memtype[] = {
724 	M_PAGEDEP,
725 	M_INODEDEP,
726 	M_BMSAFEMAP,
727 	M_NEWBLK,
728 	M_ALLOCDIRECT,
729 	M_INDIRDEP,
730 	M_ALLOCINDIR,
731 	M_FREEFRAG,
732 	M_FREEBLKS,
733 	M_FREEFILE,
734 	M_DIRADD,
735 	M_MKDIR,
736 	M_DIRREM,
737 	M_NEWDIRBLK,
738 	M_FREEWORK,
739 	M_FREEDEP,
740 	M_JADDREF,
741 	M_JREMREF,
742 	M_JMVREF,
743 	M_JNEWBLK,
744 	M_JFREEBLK,
745 	M_JFREEFRAG,
746 	M_JSEG,
747 	M_JSEGDEP,
748 	M_SBDEP,
749 	M_JTRUNC,
750 	M_JFSYNC,
751 	M_SENTINEL
752 };
753 
754 static LIST_HEAD(mkdirlist, mkdir) mkdirlisthd;
755 
756 #define DtoM(type) (memtype[type])
757 
758 /*
759  * Names of malloc types.
760  */
761 #define TYPENAME(type)  \
762 	((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
763 /*
764  * End system adaptation definitions.
765  */
766 
767 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
768 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
769 
770 /*
771  * Forward declarations.
772  */
773 struct inodedep_hashhead;
774 struct newblk_hashhead;
775 struct pagedep_hashhead;
776 struct bmsafemap_hashhead;
777 
778 /*
779  * Private journaling structures.
780  */
781 struct jblocks {
782 	struct jseglst	jb_segs;	/* TAILQ of current segments. */
783 	struct jseg	*jb_writeseg;	/* Next write to complete. */
784 	struct jseg	*jb_oldestseg;	/* Oldest segment with valid entries. */
785 	struct jextent	*jb_extent;	/* Extent array. */
786 	uint64_t	jb_nextseq;	/* Next sequence number. */
787 	uint64_t	jb_oldestwrseq;	/* Oldest written sequence number. */
788 	uint8_t		jb_needseg;	/* Need a forced segment. */
789 	uint8_t		jb_suspended;	/* Did journal suspend writes? */
790 	int		jb_avail;	/* Available extents. */
791 	int		jb_used;	/* Last used extent. */
792 	int		jb_head;	/* Allocator head. */
793 	int		jb_off;		/* Allocator extent offset. */
794 	int		jb_blocks;	/* Total disk blocks covered. */
795 	int		jb_free;	/* Total disk blocks free. */
796 	int		jb_min;		/* Minimum free space. */
797 	int		jb_low;		/* Low on space. */
798 	int		jb_age;		/* Insertion time of oldest rec. */
799 };
800 
801 struct jextent {
802 	ufs2_daddr_t	je_daddr;	/* Disk block address. */
803 	int		je_blocks;	/* Disk block count. */
804 };
805 
806 /*
807  * Internal function prototypes.
808  */
809 static	void softdep_error(char *, int);
810 static	void drain_output(struct vnode *);
811 static	struct buf *getdirtybuf(struct buf *, struct mtx *, int);
812 static	void clear_remove(void);
813 static	void clear_inodedeps(void);
814 static	void unlinked_inodedep(struct mount *, struct inodedep *);
815 static	void clear_unlinked_inodedep(struct inodedep *);
816 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
817 static	int flush_pagedep_deps(struct vnode *, struct mount *,
818 	    struct diraddhd *);
819 static	int free_pagedep(struct pagedep *);
820 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
821 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
822 static	int flush_deplist(struct allocdirectlst *, int, int *);
823 static	int sync_cgs(struct mount *, int);
824 static	int handle_written_filepage(struct pagedep *, struct buf *);
825 static	int handle_written_sbdep(struct sbdep *, struct buf *);
826 static	void initiate_write_sbdep(struct sbdep *);
827 static  void diradd_inode_written(struct diradd *, struct inodedep *);
828 static	int handle_written_indirdep(struct indirdep *, struct buf *,
829 	    struct buf**);
830 static	int handle_written_inodeblock(struct inodedep *, struct buf *);
831 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
832 	    uint8_t *);
833 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *);
834 static	void handle_written_jaddref(struct jaddref *);
835 static	void handle_written_jremref(struct jremref *);
836 static	void handle_written_jseg(struct jseg *, struct buf *);
837 static	void handle_written_jnewblk(struct jnewblk *);
838 static	void handle_written_jblkdep(struct jblkdep *);
839 static	void handle_written_jfreefrag(struct jfreefrag *);
840 static	void complete_jseg(struct jseg *);
841 static	void complete_jsegs(struct jseg *);
842 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
843 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
844 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
845 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
846 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
847 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
848 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
849 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
850 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
851 static	inline void inoref_write(struct inoref *, struct jseg *,
852 	    struct jrefrec *);
853 static	void handle_allocdirect_partdone(struct allocdirect *,
854 	    struct workhead *);
855 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
856 	    struct workhead *);
857 static	void indirdep_complete(struct indirdep *);
858 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
859 static	void indirblk_insert(struct freework *);
860 static	void indirblk_remove(struct freework *);
861 static	void handle_allocindir_partdone(struct allocindir *);
862 static	void initiate_write_filepage(struct pagedep *, struct buf *);
863 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
864 static	void handle_written_mkdir(struct mkdir *, int);
865 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
866 	    uint8_t *);
867 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
868 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
869 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
870 static	void handle_workitem_freefile(struct freefile *);
871 static	int handle_workitem_remove(struct dirrem *, int);
872 static	struct dirrem *newdirrem(struct buf *, struct inode *,
873 	    struct inode *, int, struct dirrem **);
874 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
875 	    struct buf *);
876 static	void cancel_indirdep(struct indirdep *, struct buf *,
877 	    struct freeblks *);
878 static	void free_indirdep(struct indirdep *);
879 static	void free_diradd(struct diradd *, struct workhead *);
880 static	void merge_diradd(struct inodedep *, struct diradd *);
881 static	void complete_diradd(struct diradd *);
882 static	struct diradd *diradd_lookup(struct pagedep *, int);
883 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
884 	    struct jremref *);
885 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
886 	    struct jremref *);
887 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
888 	    struct jremref *, struct jremref *);
889 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
890 	    struct jremref *);
891 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
892 	    struct freeblks *, int);
893 static	int setup_trunc_indir(struct freeblks *, struct inode *,
894 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
895 static	void complete_trunc_indir(struct freework *);
896 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
897 	    int);
898 static	void complete_mkdir(struct mkdir *);
899 static	void free_newdirblk(struct newdirblk *);
900 static	void free_jremref(struct jremref *);
901 static	void free_jaddref(struct jaddref *);
902 static	void free_jsegdep(struct jsegdep *);
903 static	void free_jsegs(struct jblocks *);
904 static	void rele_jseg(struct jseg *);
905 static	void free_jseg(struct jseg *, struct jblocks *);
906 static	void free_jnewblk(struct jnewblk *);
907 static	void free_jblkdep(struct jblkdep *);
908 static	void free_jfreefrag(struct jfreefrag *);
909 static	void free_freedep(struct freedep *);
910 static	void journal_jremref(struct dirrem *, struct jremref *,
911 	    struct inodedep *);
912 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
913 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
914 	    struct workhead *);
915 static	void cancel_jfreefrag(struct jfreefrag *);
916 static	inline void setup_freedirect(struct freeblks *, struct inode *,
917 	    int, int);
918 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
919 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
920 	    ufs_lbn_t, int);
921 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
922 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
923 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
924 ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
925 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
926 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
927 	    int, int);
928 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
929 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
930 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
931 static	void newblk_freefrag(struct newblk*);
932 static	void free_newblk(struct newblk *);
933 static	void cancel_allocdirect(struct allocdirectlst *,
934 	    struct allocdirect *, struct freeblks *);
935 static	int check_inode_unwritten(struct inodedep *);
936 static	int free_inodedep(struct inodedep *);
937 static	void freework_freeblock(struct freework *);
938 static	void freework_enqueue(struct freework *);
939 static	int handle_workitem_freeblocks(struct freeblks *, int);
940 static	int handle_complete_freeblocks(struct freeblks *, int);
941 static	void handle_workitem_indirblk(struct freework *);
942 static	void handle_written_freework(struct freework *);
943 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
944 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
945 	    struct workhead *);
946 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
947 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
948 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
949 	    ufs2_daddr_t, ufs_lbn_t);
950 static	void handle_workitem_freefrag(struct freefrag *);
951 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
952 	    ufs_lbn_t);
953 static	void allocdirect_merge(struct allocdirectlst *,
954 	    struct allocdirect *, struct allocdirect *);
955 static	struct freefrag *allocindir_merge(struct allocindir *,
956 	    struct allocindir *);
957 static	int bmsafemap_find(struct bmsafemap_hashhead *, struct mount *, int,
958 	    struct bmsafemap **);
959 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
960 	    int cg, struct bmsafemap *);
961 static	int newblk_find(struct newblk_hashhead *, struct mount *, ufs2_daddr_t,
962 	    int, struct newblk **);
963 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
964 static	int inodedep_find(struct inodedep_hashhead *, struct fs *, ino_t,
965 	    struct inodedep **);
966 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
967 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
968 	    int, struct pagedep **);
969 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
970 	    struct mount *mp, int, struct pagedep **);
971 static	void pause_timer(void *);
972 static	int request_cleanup(struct mount *, int);
973 static	int process_worklist_item(struct mount *, int, int);
974 static	void process_removes(struct vnode *);
975 static	void process_truncates(struct vnode *);
976 static	void jwork_move(struct workhead *, struct workhead *);
977 static	void jwork_insert(struct workhead *, struct jsegdep *);
978 static	void add_to_worklist(struct worklist *, int);
979 static	void wake_worklist(struct worklist *);
980 static	void wait_worklist(struct worklist *, char *);
981 static	void remove_from_worklist(struct worklist *);
982 static	void softdep_flush(void);
983 static	void softdep_flushjournal(struct mount *);
984 static	int softdep_speedup(void);
985 static	void worklist_speedup(void);
986 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
987 static	void journal_unmount(struct mount *);
988 static	int journal_space(struct ufsmount *, int);
989 static	void journal_suspend(struct ufsmount *);
990 static	int journal_unsuspend(struct ufsmount *ump);
991 static	void softdep_prelink(struct vnode *, struct vnode *);
992 static	void add_to_journal(struct worklist *);
993 static	void remove_from_journal(struct worklist *);
994 static	void softdep_process_journal(struct mount *, struct worklist *, int);
995 static	struct jremref *newjremref(struct dirrem *, struct inode *,
996 	    struct inode *ip, off_t, nlink_t);
997 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
998 	    uint16_t);
999 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
1000 	    uint16_t);
1001 static	inline struct jsegdep *inoref_jseg(struct inoref *);
1002 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
1003 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
1004 	    ufs2_daddr_t, int);
1005 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
1006 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
1007 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
1008 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
1009 	    ufs2_daddr_t, long, ufs_lbn_t);
1010 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
1011 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
1012 static	int jwait(struct worklist *, int);
1013 static	struct inodedep *inodedep_lookup_ip(struct inode *);
1014 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
1015 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
1016 static	void handle_jwork(struct workhead *);
1017 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
1018 	    struct mkdir **);
1019 static	struct jblocks *jblocks_create(void);
1020 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
1021 static	void jblocks_free(struct jblocks *, struct mount *, int);
1022 static	void jblocks_destroy(struct jblocks *);
1023 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
1024 
1025 /*
1026  * Exported softdep operations.
1027  */
1028 static	void softdep_disk_io_initiation(struct buf *);
1029 static	void softdep_disk_write_complete(struct buf *);
1030 static	void softdep_deallocate_dependencies(struct buf *);
1031 static	int softdep_count_dependencies(struct buf *bp, int);
1032 
1033 static struct mtx lk;
1034 MTX_SYSINIT(softdep_lock, &lk, "Softdep Lock", MTX_DEF);
1035 
1036 #define TRY_ACQUIRE_LOCK(lk)		mtx_trylock(lk)
1037 #define ACQUIRE_LOCK(lk)		mtx_lock(lk)
1038 #define FREE_LOCK(lk)			mtx_unlock(lk)
1039 
1040 #define	BUF_AREC(bp)			lockallowrecurse(&(bp)->b_lock)
1041 #define	BUF_NOREC(bp)			lockdisablerecurse(&(bp)->b_lock)
1042 
1043 /*
1044  * Worklist queue management.
1045  * These routines require that the lock be held.
1046  */
1047 #ifndef /* NOT */ DEBUG
1048 #define WORKLIST_INSERT(head, item) do {	\
1049 	(item)->wk_state |= ONWORKLIST;		\
1050 	LIST_INSERT_HEAD(head, item, wk_list);	\
1051 } while (0)
1052 #define WORKLIST_REMOVE(item) do {		\
1053 	(item)->wk_state &= ~ONWORKLIST;	\
1054 	LIST_REMOVE(item, wk_list);		\
1055 } while (0)
1056 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1057 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1058 
1059 #else /* DEBUG */
1060 static	void worklist_insert(struct workhead *, struct worklist *, int);
1061 static	void worklist_remove(struct worklist *, int);
1062 
1063 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1064 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1065 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1066 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1067 
1068 static void
1069 worklist_insert(head, item, locked)
1070 	struct workhead *head;
1071 	struct worklist *item;
1072 	int locked;
1073 {
1074 
1075 	if (locked)
1076 		mtx_assert(&lk, MA_OWNED);
1077 	if (item->wk_state & ONWORKLIST)
1078 		panic("worklist_insert: %p %s(0x%X) already on list",
1079 		    item, TYPENAME(item->wk_type), item->wk_state);
1080 	item->wk_state |= ONWORKLIST;
1081 	LIST_INSERT_HEAD(head, item, wk_list);
1082 }
1083 
1084 static void
1085 worklist_remove(item, locked)
1086 	struct worklist *item;
1087 	int locked;
1088 {
1089 
1090 	if (locked)
1091 		mtx_assert(&lk, MA_OWNED);
1092 	if ((item->wk_state & ONWORKLIST) == 0)
1093 		panic("worklist_remove: %p %s(0x%X) not on list",
1094 		    item, TYPENAME(item->wk_type), item->wk_state);
1095 	item->wk_state &= ~ONWORKLIST;
1096 	LIST_REMOVE(item, wk_list);
1097 }
1098 #endif /* DEBUG */
1099 
1100 /*
1101  * Merge two jsegdeps keeping only the oldest one as newer references
1102  * can't be discarded until after older references.
1103  */
1104 static inline struct jsegdep *
1105 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1106 {
1107 	struct jsegdep *swp;
1108 
1109 	if (two == NULL)
1110 		return (one);
1111 
1112 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1113 		swp = one;
1114 		one = two;
1115 		two = swp;
1116 	}
1117 	WORKLIST_REMOVE(&two->jd_list);
1118 	free_jsegdep(two);
1119 
1120 	return (one);
1121 }
1122 
1123 /*
1124  * If two freedeps are compatible free one to reduce list size.
1125  */
1126 static inline struct freedep *
1127 freedep_merge(struct freedep *one, struct freedep *two)
1128 {
1129 	if (two == NULL)
1130 		return (one);
1131 
1132 	if (one->fd_freework == two->fd_freework) {
1133 		WORKLIST_REMOVE(&two->fd_list);
1134 		free_freedep(two);
1135 	}
1136 	return (one);
1137 }
1138 
1139 /*
1140  * Move journal work from one list to another.  Duplicate freedeps and
1141  * jsegdeps are coalesced to keep the lists as small as possible.
1142  */
1143 static void
1144 jwork_move(dst, src)
1145 	struct workhead *dst;
1146 	struct workhead *src;
1147 {
1148 	struct freedep *freedep;
1149 	struct jsegdep *jsegdep;
1150 	struct worklist *wkn;
1151 	struct worklist *wk;
1152 
1153 	KASSERT(dst != src,
1154 	    ("jwork_move: dst == src"));
1155 	freedep = NULL;
1156 	jsegdep = NULL;
1157 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1158 		if (wk->wk_type == D_JSEGDEP)
1159 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1160 		if (wk->wk_type == D_FREEDEP)
1161 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1162 	}
1163 
1164 	mtx_assert(&lk, MA_OWNED);
1165 	while ((wk = LIST_FIRST(src)) != NULL) {
1166 		WORKLIST_REMOVE(wk);
1167 		WORKLIST_INSERT(dst, wk);
1168 		if (wk->wk_type == D_JSEGDEP) {
1169 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1170 			continue;
1171 		}
1172 		if (wk->wk_type == D_FREEDEP)
1173 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1174 	}
1175 }
1176 
1177 static void
1178 jwork_insert(dst, jsegdep)
1179 	struct workhead *dst;
1180 	struct jsegdep *jsegdep;
1181 {
1182 	struct jsegdep *jsegdepn;
1183 	struct worklist *wk;
1184 
1185 	LIST_FOREACH(wk, dst, wk_list)
1186 		if (wk->wk_type == D_JSEGDEP)
1187 			break;
1188 	if (wk == NULL) {
1189 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1190 		return;
1191 	}
1192 	jsegdepn = WK_JSEGDEP(wk);
1193 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1194 		WORKLIST_REMOVE(wk);
1195 		free_jsegdep(jsegdepn);
1196 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1197 	} else
1198 		free_jsegdep(jsegdep);
1199 }
1200 
1201 /*
1202  * Routines for tracking and managing workitems.
1203  */
1204 static	void workitem_free(struct worklist *, int);
1205 static	void workitem_alloc(struct worklist *, int, struct mount *);
1206 
1207 #define	WORKITEM_FREE(item, type) workitem_free((struct worklist *)(item), (type))
1208 
1209 static void
1210 workitem_free(item, type)
1211 	struct worklist *item;
1212 	int type;
1213 {
1214 	struct ufsmount *ump;
1215 	mtx_assert(&lk, MA_OWNED);
1216 
1217 #ifdef DEBUG
1218 	if (item->wk_state & ONWORKLIST)
1219 		panic("workitem_free: %s(0x%X) still on list",
1220 		    TYPENAME(item->wk_type), item->wk_state);
1221 	if (item->wk_type != type)
1222 		panic("workitem_free: type mismatch %s != %s",
1223 		    TYPENAME(item->wk_type), TYPENAME(type));
1224 #endif
1225 	if (item->wk_state & IOWAITING)
1226 		wakeup(item);
1227 	ump = VFSTOUFS(item->wk_mp);
1228 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1229 		wakeup(&ump->softdep_deps);
1230 	dep_current[type]--;
1231 	free(item, DtoM(type));
1232 }
1233 
1234 static void
1235 workitem_alloc(item, type, mp)
1236 	struct worklist *item;
1237 	int type;
1238 	struct mount *mp;
1239 {
1240 	struct ufsmount *ump;
1241 
1242 	item->wk_type = type;
1243 	item->wk_mp = mp;
1244 	item->wk_state = 0;
1245 
1246 	ump = VFSTOUFS(mp);
1247 	ACQUIRE_LOCK(&lk);
1248 	dep_current[type]++;
1249 	dep_total[type]++;
1250 	ump->softdep_deps++;
1251 	ump->softdep_accdeps++;
1252 	FREE_LOCK(&lk);
1253 }
1254 
1255 /*
1256  * Workitem queue management
1257  */
1258 static int max_softdeps;	/* maximum number of structs before slowdown */
1259 static int maxindirdeps = 50;	/* max number of indirdeps before slowdown */
1260 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1261 static int proc_waiting;	/* tracks whether we have a timeout posted */
1262 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1263 static struct callout softdep_callout;
1264 static int req_pending;
1265 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1266 static int req_clear_remove;	/* syncer process flush some freeblks */
1267 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1268 
1269 /*
1270  * runtime statistics
1271  */
1272 static int stat_worklist_push;	/* number of worklist cleanups */
1273 static int stat_blk_limit_push;	/* number of times block limit neared */
1274 static int stat_ino_limit_push;	/* number of times inode limit neared */
1275 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1276 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1277 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1278 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1279 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1280 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1281 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1282 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1283 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1284 static int stat_journal_min;	/* Times hit journal min threshold */
1285 static int stat_journal_low;	/* Times hit journal low threshold */
1286 static int stat_journal_wait;	/* Times blocked in jwait(). */
1287 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1288 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1289 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1290 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1291 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1292 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1293 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1294 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1295 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1296 
1297 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1298     &max_softdeps, 0, "");
1299 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1300     &tickdelay, 0, "");
1301 SYSCTL_INT(_debug_softdep, OID_AUTO, maxindirdeps, CTLFLAG_RW,
1302     &maxindirdeps, 0, "");
1303 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1304     &stat_worklist_push, 0,"");
1305 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1306     &stat_blk_limit_push, 0,"");
1307 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1308     &stat_ino_limit_push, 0,"");
1309 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1310     &stat_blk_limit_hit, 0, "");
1311 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1312     &stat_ino_limit_hit, 0, "");
1313 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1314     &stat_sync_limit_hit, 0, "");
1315 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1316     &stat_indir_blk_ptrs, 0, "");
1317 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1318     &stat_inode_bitmap, 0, "");
1319 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1320     &stat_direct_blk_ptrs, 0, "");
1321 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1322     &stat_dir_entry, 0, "");
1323 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1324     &stat_jaddref, 0, "");
1325 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1326     &stat_jnewblk, 0, "");
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1328     &stat_journal_low, 0, "");
1329 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1330     &stat_journal_min, 0, "");
1331 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1332     &stat_journal_wait, 0, "");
1333 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1334     &stat_jwait_filepage, 0, "");
1335 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1336     &stat_jwait_freeblks, 0, "");
1337 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1338     &stat_jwait_inode, 0, "");
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1340     &stat_jwait_newblk, 0, "");
1341 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1342     &stat_cleanup_blkrequests, 0, "");
1343 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1344     &stat_cleanup_inorequests, 0, "");
1345 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1346     &stat_cleanup_high_delay, 0, "");
1347 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1348     &stat_cleanup_retries, 0, "");
1349 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1350     &stat_cleanup_failures, 0, "");
1351 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1352     &softdep_flushcache, 0, "");
1353 
1354 SYSCTL_DECL(_vfs_ffs);
1355 
1356 LIST_HEAD(bmsafemap_hashhead, bmsafemap) *bmsafemap_hashtbl;
1357 static u_long	bmsafemap_hash;	/* size of hash table - 1 */
1358 
1359 static int compute_summary_at_mount = 0;	/* Whether to recompute the summary at mount time */
1360 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1361 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1362 
1363 static struct proc *softdepproc;
1364 static struct kproc_desc softdep_kp = {
1365 	"softdepflush",
1366 	softdep_flush,
1367 	&softdepproc
1368 };
1369 SYSINIT(sdproc, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start,
1370     &softdep_kp);
1371 
1372 static void
1373 softdep_flush(void)
1374 {
1375 	struct mount *nmp;
1376 	struct mount *mp;
1377 	struct ufsmount *ump;
1378 	struct thread *td;
1379 	int remaining;
1380 	int progress;
1381 
1382 	td = curthread;
1383 	td->td_pflags |= TDP_NORUNNINGBUF;
1384 
1385 	for (;;) {
1386 		kproc_suspend_check(softdepproc);
1387 		ACQUIRE_LOCK(&lk);
1388 		/*
1389 		 * If requested, try removing inode or removal dependencies.
1390 		 */
1391 		if (req_clear_inodedeps) {
1392 			clear_inodedeps();
1393 			req_clear_inodedeps -= 1;
1394 			wakeup_one(&proc_waiting);
1395 		}
1396 		if (req_clear_remove) {
1397 			clear_remove();
1398 			req_clear_remove -= 1;
1399 			wakeup_one(&proc_waiting);
1400 		}
1401 		FREE_LOCK(&lk);
1402 		remaining = progress = 0;
1403 		mtx_lock(&mountlist_mtx);
1404 		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp)  {
1405 			nmp = TAILQ_NEXT(mp, mnt_list);
1406 			if (MOUNTEDSOFTDEP(mp) == 0)
1407 				continue;
1408 			if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
1409 				continue;
1410 			progress += softdep_process_worklist(mp, 0);
1411 			ump = VFSTOUFS(mp);
1412 			remaining += ump->softdep_on_worklist;
1413 			mtx_lock(&mountlist_mtx);
1414 			nmp = TAILQ_NEXT(mp, mnt_list);
1415 			vfs_unbusy(mp);
1416 		}
1417 		mtx_unlock(&mountlist_mtx);
1418 		if (remaining && progress)
1419 			continue;
1420 		ACQUIRE_LOCK(&lk);
1421 		if (!req_pending)
1422 			msleep(&req_pending, &lk, PVM, "sdflush", hz);
1423 		req_pending = 0;
1424 		FREE_LOCK(&lk);
1425 	}
1426 }
1427 
1428 static void
1429 worklist_speedup(void)
1430 {
1431 	mtx_assert(&lk, MA_OWNED);
1432 	if (req_pending == 0) {
1433 		req_pending = 1;
1434 		wakeup(&req_pending);
1435 	}
1436 }
1437 
1438 static int
1439 softdep_speedup(void)
1440 {
1441 
1442 	worklist_speedup();
1443 	bd_speedup();
1444 	return speedup_syncer();
1445 }
1446 
1447 /*
1448  * Add an item to the end of the work queue.
1449  * This routine requires that the lock be held.
1450  * This is the only routine that adds items to the list.
1451  * The following routine is the only one that removes items
1452  * and does so in order from first to last.
1453  */
1454 
1455 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1456 #define	WK_NODELAY	0x0002	/* Process immediately. */
1457 
1458 static void
1459 add_to_worklist(wk, flags)
1460 	struct worklist *wk;
1461 	int flags;
1462 {
1463 	struct ufsmount *ump;
1464 
1465 	mtx_assert(&lk, MA_OWNED);
1466 	ump = VFSTOUFS(wk->wk_mp);
1467 	if (wk->wk_state & ONWORKLIST)
1468 		panic("add_to_worklist: %s(0x%X) already on list",
1469 		    TYPENAME(wk->wk_type), wk->wk_state);
1470 	wk->wk_state |= ONWORKLIST;
1471 	if (ump->softdep_on_worklist == 0) {
1472 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1473 		ump->softdep_worklist_tail = wk;
1474 	} else if (flags & WK_HEAD) {
1475 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1476 	} else {
1477 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1478 		ump->softdep_worklist_tail = wk;
1479 	}
1480 	ump->softdep_on_worklist += 1;
1481 	if (flags & WK_NODELAY)
1482 		worklist_speedup();
1483 }
1484 
1485 /*
1486  * Remove the item to be processed. If we are removing the last
1487  * item on the list, we need to recalculate the tail pointer.
1488  */
1489 static void
1490 remove_from_worklist(wk)
1491 	struct worklist *wk;
1492 {
1493 	struct ufsmount *ump;
1494 
1495 	ump = VFSTOUFS(wk->wk_mp);
1496 	WORKLIST_REMOVE(wk);
1497 	if (ump->softdep_worklist_tail == wk)
1498 		ump->softdep_worklist_tail =
1499 		    (struct worklist *)wk->wk_list.le_prev;
1500 	ump->softdep_on_worklist -= 1;
1501 }
1502 
1503 static void
1504 wake_worklist(wk)
1505 	struct worklist *wk;
1506 {
1507 	if (wk->wk_state & IOWAITING) {
1508 		wk->wk_state &= ~IOWAITING;
1509 		wakeup(wk);
1510 	}
1511 }
1512 
1513 static void
1514 wait_worklist(wk, wmesg)
1515 	struct worklist *wk;
1516 	char *wmesg;
1517 {
1518 
1519 	wk->wk_state |= IOWAITING;
1520 	msleep(wk, &lk, PVM, wmesg, 0);
1521 }
1522 
1523 /*
1524  * Process that runs once per second to handle items in the background queue.
1525  *
1526  * Note that we ensure that everything is done in the order in which they
1527  * appear in the queue. The code below depends on this property to ensure
1528  * that blocks of a file are freed before the inode itself is freed. This
1529  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1530  * until all the old ones have been purged from the dependency lists.
1531  */
1532 int
1533 softdep_process_worklist(mp, full)
1534 	struct mount *mp;
1535 	int full;
1536 {
1537 	int cnt, matchcnt;
1538 	struct ufsmount *ump;
1539 	long starttime;
1540 
1541 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1542 	/*
1543 	 * Record the process identifier of our caller so that we can give
1544 	 * this process preferential treatment in request_cleanup below.
1545 	 */
1546 	matchcnt = 0;
1547 	ump = VFSTOUFS(mp);
1548 	ACQUIRE_LOCK(&lk);
1549 	starttime = time_second;
1550 	softdep_process_journal(mp, NULL, full?MNT_WAIT:0);
1551 	while (ump->softdep_on_worklist > 0) {
1552 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1553 			break;
1554 		else
1555 			matchcnt += cnt;
1556 		/*
1557 		 * If requested, try removing inode or removal dependencies.
1558 		 */
1559 		if (req_clear_inodedeps) {
1560 			clear_inodedeps();
1561 			req_clear_inodedeps -= 1;
1562 			wakeup_one(&proc_waiting);
1563 		}
1564 		if (req_clear_remove) {
1565 			clear_remove();
1566 			req_clear_remove -= 1;
1567 			wakeup_one(&proc_waiting);
1568 		}
1569 		/*
1570 		 * We do not generally want to stop for buffer space, but if
1571 		 * we are really being a buffer hog, we will stop and wait.
1572 		 */
1573 		if (should_yield()) {
1574 			FREE_LOCK(&lk);
1575 			kern_yield(PRI_USER);
1576 			bwillwrite();
1577 			ACQUIRE_LOCK(&lk);
1578 		}
1579 		/*
1580 		 * Never allow processing to run for more than one
1581 		 * second. Otherwise the other mountpoints may get
1582 		 * excessively backlogged.
1583 		 */
1584 		if (!full && starttime != time_second)
1585 			break;
1586 	}
1587 	if (full == 0)
1588 		journal_unsuspend(ump);
1589 	FREE_LOCK(&lk);
1590 	return (matchcnt);
1591 }
1592 
1593 /*
1594  * Process all removes associated with a vnode if we are running out of
1595  * journal space.  Any other process which attempts to flush these will
1596  * be unable as we have the vnodes locked.
1597  */
1598 static void
1599 process_removes(vp)
1600 	struct vnode *vp;
1601 {
1602 	struct inodedep *inodedep;
1603 	struct dirrem *dirrem;
1604 	struct mount *mp;
1605 	ino_t inum;
1606 
1607 	mtx_assert(&lk, MA_OWNED);
1608 
1609 	mp = vp->v_mount;
1610 	inum = VTOI(vp)->i_number;
1611 	for (;;) {
1612 top:
1613 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1614 			return;
1615 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1616 			/*
1617 			 * If another thread is trying to lock this vnode
1618 			 * it will fail but we must wait for it to do so
1619 			 * before we can proceed.
1620 			 */
1621 			if (dirrem->dm_state & INPROGRESS) {
1622 				wait_worklist(&dirrem->dm_list, "pwrwait");
1623 				goto top;
1624 			}
1625 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1626 			    (COMPLETE | ONWORKLIST))
1627 				break;
1628 		}
1629 		if (dirrem == NULL)
1630 			return;
1631 		remove_from_worklist(&dirrem->dm_list);
1632 		FREE_LOCK(&lk);
1633 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1634 			panic("process_removes: suspended filesystem");
1635 		handle_workitem_remove(dirrem, 0);
1636 		vn_finished_secondary_write(mp);
1637 		ACQUIRE_LOCK(&lk);
1638 	}
1639 }
1640 
1641 /*
1642  * Process all truncations associated with a vnode if we are running out
1643  * of journal space.  This is called when the vnode lock is already held
1644  * and no other process can clear the truncation.  This function returns
1645  * a value greater than zero if it did any work.
1646  */
1647 static void
1648 process_truncates(vp)
1649 	struct vnode *vp;
1650 {
1651 	struct inodedep *inodedep;
1652 	struct freeblks *freeblks;
1653 	struct mount *mp;
1654 	ino_t inum;
1655 	int cgwait;
1656 
1657 	mtx_assert(&lk, MA_OWNED);
1658 
1659 	mp = vp->v_mount;
1660 	inum = VTOI(vp)->i_number;
1661 	for (;;) {
1662 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1663 			return;
1664 		cgwait = 0;
1665 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1666 			/* Journal entries not yet written.  */
1667 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1668 				jwait(&LIST_FIRST(
1669 				    &freeblks->fb_jblkdephd)->jb_list,
1670 				    MNT_WAIT);
1671 				break;
1672 			}
1673 			/* Another thread is executing this item. */
1674 			if (freeblks->fb_state & INPROGRESS) {
1675 				wait_worklist(&freeblks->fb_list, "ptrwait");
1676 				break;
1677 			}
1678 			/* Freeblks is waiting on a inode write. */
1679 			if ((freeblks->fb_state & COMPLETE) == 0) {
1680 				FREE_LOCK(&lk);
1681 				ffs_update(vp, 1);
1682 				ACQUIRE_LOCK(&lk);
1683 				break;
1684 			}
1685 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1686 			    (ALLCOMPLETE | ONWORKLIST)) {
1687 				remove_from_worklist(&freeblks->fb_list);
1688 				freeblks->fb_state |= INPROGRESS;
1689 				FREE_LOCK(&lk);
1690 				if (vn_start_secondary_write(NULL, &mp,
1691 				    V_NOWAIT))
1692 					panic("process_truncates: "
1693 					    "suspended filesystem");
1694 				handle_workitem_freeblocks(freeblks, 0);
1695 				vn_finished_secondary_write(mp);
1696 				ACQUIRE_LOCK(&lk);
1697 				break;
1698 			}
1699 			if (freeblks->fb_cgwait)
1700 				cgwait++;
1701 		}
1702 		if (cgwait) {
1703 			FREE_LOCK(&lk);
1704 			sync_cgs(mp, MNT_WAIT);
1705 			ffs_sync_snap(mp, MNT_WAIT);
1706 			ACQUIRE_LOCK(&lk);
1707 			continue;
1708 		}
1709 		if (freeblks == NULL)
1710 			break;
1711 	}
1712 	return;
1713 }
1714 
1715 /*
1716  * Process one item on the worklist.
1717  */
1718 static int
1719 process_worklist_item(mp, target, flags)
1720 	struct mount *mp;
1721 	int target;
1722 	int flags;
1723 {
1724 	struct worklist sentinel;
1725 	struct worklist *wk;
1726 	struct ufsmount *ump;
1727 	int matchcnt;
1728 	int error;
1729 
1730 	mtx_assert(&lk, MA_OWNED);
1731 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1732 	/*
1733 	 * If we are being called because of a process doing a
1734 	 * copy-on-write, then it is not safe to write as we may
1735 	 * recurse into the copy-on-write routine.
1736 	 */
1737 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1738 		return (-1);
1739 	PHOLD(curproc);	/* Don't let the stack go away. */
1740 	ump = VFSTOUFS(mp);
1741 	matchcnt = 0;
1742 	sentinel.wk_mp = NULL;
1743 	sentinel.wk_type = D_SENTINEL;
1744 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1745 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1746 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1747 		if (wk->wk_type == D_SENTINEL) {
1748 			LIST_REMOVE(&sentinel, wk_list);
1749 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1750 			continue;
1751 		}
1752 		if (wk->wk_state & INPROGRESS)
1753 			panic("process_worklist_item: %p already in progress.",
1754 			    wk);
1755 		wk->wk_state |= INPROGRESS;
1756 		remove_from_worklist(wk);
1757 		FREE_LOCK(&lk);
1758 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1759 			panic("process_worklist_item: suspended filesystem");
1760 		switch (wk->wk_type) {
1761 		case D_DIRREM:
1762 			/* removal of a directory entry */
1763 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1764 			break;
1765 
1766 		case D_FREEBLKS:
1767 			/* releasing blocks and/or fragments from a file */
1768 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1769 			    flags);
1770 			break;
1771 
1772 		case D_FREEFRAG:
1773 			/* releasing a fragment when replaced as a file grows */
1774 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1775 			error = 0;
1776 			break;
1777 
1778 		case D_FREEFILE:
1779 			/* releasing an inode when its link count drops to 0 */
1780 			handle_workitem_freefile(WK_FREEFILE(wk));
1781 			error = 0;
1782 			break;
1783 
1784 		default:
1785 			panic("%s_process_worklist: Unknown type %s",
1786 			    "softdep", TYPENAME(wk->wk_type));
1787 			/* NOTREACHED */
1788 		}
1789 		vn_finished_secondary_write(mp);
1790 		ACQUIRE_LOCK(&lk);
1791 		if (error == 0) {
1792 			if (++matchcnt == target)
1793 				break;
1794 			continue;
1795 		}
1796 		/*
1797 		 * We have to retry the worklist item later.  Wake up any
1798 		 * waiters who may be able to complete it immediately and
1799 		 * add the item back to the head so we don't try to execute
1800 		 * it again.
1801 		 */
1802 		wk->wk_state &= ~INPROGRESS;
1803 		wake_worklist(wk);
1804 		add_to_worklist(wk, WK_HEAD);
1805 	}
1806 	LIST_REMOVE(&sentinel, wk_list);
1807 	/* Sentinal could've become the tail from remove_from_worklist. */
1808 	if (ump->softdep_worklist_tail == &sentinel)
1809 		ump->softdep_worklist_tail =
1810 		    (struct worklist *)sentinel.wk_list.le_prev;
1811 	PRELE(curproc);
1812 	return (matchcnt);
1813 }
1814 
1815 /*
1816  * Move dependencies from one buffer to another.
1817  */
1818 int
1819 softdep_move_dependencies(oldbp, newbp)
1820 	struct buf *oldbp;
1821 	struct buf *newbp;
1822 {
1823 	struct worklist *wk, *wktail;
1824 	int dirty;
1825 
1826 	dirty = 0;
1827 	wktail = NULL;
1828 	ACQUIRE_LOCK(&lk);
1829 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1830 		LIST_REMOVE(wk, wk_list);
1831 		if (wk->wk_type == D_BMSAFEMAP &&
1832 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1833 			dirty = 1;
1834 		if (wktail == 0)
1835 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1836 		else
1837 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1838 		wktail = wk;
1839 	}
1840 	FREE_LOCK(&lk);
1841 
1842 	return (dirty);
1843 }
1844 
1845 /*
1846  * Purge the work list of all items associated with a particular mount point.
1847  */
1848 int
1849 softdep_flushworklist(oldmnt, countp, td)
1850 	struct mount *oldmnt;
1851 	int *countp;
1852 	struct thread *td;
1853 {
1854 	struct vnode *devvp;
1855 	int count, error = 0;
1856 	struct ufsmount *ump;
1857 
1858 	/*
1859 	 * Alternately flush the block device associated with the mount
1860 	 * point and process any dependencies that the flushing
1861 	 * creates. We continue until no more worklist dependencies
1862 	 * are found.
1863 	 */
1864 	*countp = 0;
1865 	ump = VFSTOUFS(oldmnt);
1866 	devvp = ump->um_devvp;
1867 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1868 		*countp += count;
1869 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1870 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1871 		VOP_UNLOCK(devvp, 0);
1872 		if (error)
1873 			break;
1874 	}
1875 	return (error);
1876 }
1877 
1878 int
1879 softdep_waitidle(struct mount *mp)
1880 {
1881 	struct ufsmount *ump;
1882 	int error;
1883 	int i;
1884 
1885 	ump = VFSTOUFS(mp);
1886 	ACQUIRE_LOCK(&lk);
1887 	for (i = 0; i < 10 && ump->softdep_deps; i++) {
1888 		ump->softdep_req = 1;
1889 		if (ump->softdep_on_worklist)
1890 			panic("softdep_waitidle: work added after flush.");
1891 		msleep(&ump->softdep_deps, &lk, PVM, "softdeps", 1);
1892 	}
1893 	ump->softdep_req = 0;
1894 	FREE_LOCK(&lk);
1895 	error = 0;
1896 	if (i == 10) {
1897 		error = EBUSY;
1898 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1899 		    mp);
1900 	}
1901 
1902 	return (error);
1903 }
1904 
1905 /*
1906  * Flush all vnodes and worklist items associated with a specified mount point.
1907  */
1908 int
1909 softdep_flushfiles(oldmnt, flags, td)
1910 	struct mount *oldmnt;
1911 	int flags;
1912 	struct thread *td;
1913 {
1914 #ifdef QUOTA
1915 	struct ufsmount *ump;
1916 	int i;
1917 #endif
1918 	int error, early, depcount, loopcnt, retry_flush_count, retry;
1919 	int morework;
1920 
1921 	loopcnt = 10;
1922 	retry_flush_count = 3;
1923 retry_flush:
1924 	error = 0;
1925 
1926 	/*
1927 	 * Alternately flush the vnodes associated with the mount
1928 	 * point and process any dependencies that the flushing
1929 	 * creates. In theory, this loop can happen at most twice,
1930 	 * but we give it a few extra just to be sure.
1931 	 */
1932 	for (; loopcnt > 0; loopcnt--) {
1933 		/*
1934 		 * Do another flush in case any vnodes were brought in
1935 		 * as part of the cleanup operations.
1936 		 */
1937 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
1938 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
1939 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
1940 			break;
1941 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1942 		    depcount == 0)
1943 			break;
1944 	}
1945 	/*
1946 	 * If we are unmounting then it is an error to fail. If we
1947 	 * are simply trying to downgrade to read-only, then filesystem
1948 	 * activity can keep us busy forever, so we just fail with EBUSY.
1949 	 */
1950 	if (loopcnt == 0) {
1951 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
1952 			panic("softdep_flushfiles: looping");
1953 		error = EBUSY;
1954 	}
1955 	if (!error)
1956 		error = softdep_waitidle(oldmnt);
1957 	if (!error) {
1958 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
1959 			retry = 0;
1960 			MNT_ILOCK(oldmnt);
1961 			KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
1962 			    ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
1963 			morework = oldmnt->mnt_nvnodelistsize > 0;
1964 #ifdef QUOTA
1965 			ump = VFSTOUFS(oldmnt);
1966 			UFS_LOCK(ump);
1967 			for (i = 0; i < MAXQUOTAS; i++) {
1968 				if (ump->um_quotas[i] != NULLVP)
1969 					morework = 1;
1970 			}
1971 			UFS_UNLOCK(ump);
1972 #endif
1973 			if (morework) {
1974 				if (--retry_flush_count > 0) {
1975 					retry = 1;
1976 					loopcnt = 3;
1977 				} else
1978 					error = EBUSY;
1979 			}
1980 			MNT_IUNLOCK(oldmnt);
1981 			if (retry)
1982 				goto retry_flush;
1983 		}
1984 	}
1985 	return (error);
1986 }
1987 
1988 /*
1989  * Structure hashing.
1990  *
1991  * There are three types of structures that can be looked up:
1992  *	1) pagedep structures identified by mount point, inode number,
1993  *	   and logical block.
1994  *	2) inodedep structures identified by mount point and inode number.
1995  *	3) newblk structures identified by mount point and
1996  *	   physical block number.
1997  *
1998  * The "pagedep" and "inodedep" dependency structures are hashed
1999  * separately from the file blocks and inodes to which they correspond.
2000  * This separation helps when the in-memory copy of an inode or
2001  * file block must be replaced. It also obviates the need to access
2002  * an inode or file page when simply updating (or de-allocating)
2003  * dependency structures. Lookup of newblk structures is needed to
2004  * find newly allocated blocks when trying to associate them with
2005  * their allocdirect or allocindir structure.
2006  *
2007  * The lookup routines optionally create and hash a new instance when
2008  * an existing entry is not found.
2009  */
2010 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2011 #define NODELAY		0x0002	/* cannot do background work */
2012 
2013 /*
2014  * Structures and routines associated with pagedep caching.
2015  */
2016 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
2017 u_long	pagedep_hash;		/* size of hash table - 1 */
2018 #define	PAGEDEP_HASH(mp, inum, lbn) \
2019 	(&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
2020 	    pagedep_hash])
2021 
2022 static int
2023 pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp)
2024 	struct pagedep_hashhead *pagedephd;
2025 	ino_t ino;
2026 	ufs_lbn_t lbn;
2027 	struct mount *mp;
2028 	int flags;
2029 	struct pagedep **pagedeppp;
2030 {
2031 	struct pagedep *pagedep;
2032 
2033 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2034 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn &&
2035 		    mp == pagedep->pd_list.wk_mp) {
2036 			*pagedeppp = pagedep;
2037 			return (1);
2038 		}
2039 	}
2040 	*pagedeppp = NULL;
2041 	return (0);
2042 }
2043 /*
2044  * Look up a pagedep. Return 1 if found, 0 otherwise.
2045  * If not found, allocate if DEPALLOC flag is passed.
2046  * Found or allocated entry is returned in pagedeppp.
2047  * This routine must be called with splbio interrupts blocked.
2048  */
2049 static int
2050 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2051 	struct mount *mp;
2052 	struct buf *bp;
2053 	ino_t ino;
2054 	ufs_lbn_t lbn;
2055 	int flags;
2056 	struct pagedep **pagedeppp;
2057 {
2058 	struct pagedep *pagedep;
2059 	struct pagedep_hashhead *pagedephd;
2060 	struct worklist *wk;
2061 	int ret;
2062 	int i;
2063 
2064 	mtx_assert(&lk, MA_OWNED);
2065 	if (bp) {
2066 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2067 			if (wk->wk_type == D_PAGEDEP) {
2068 				*pagedeppp = WK_PAGEDEP(wk);
2069 				return (1);
2070 			}
2071 		}
2072 	}
2073 	pagedephd = PAGEDEP_HASH(mp, ino, lbn);
2074 	ret = pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp);
2075 	if (ret) {
2076 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2077 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2078 		return (1);
2079 	}
2080 	if ((flags & DEPALLOC) == 0)
2081 		return (0);
2082 	FREE_LOCK(&lk);
2083 	pagedep = malloc(sizeof(struct pagedep),
2084 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2085 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2086 	ACQUIRE_LOCK(&lk);
2087 	ret = pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp);
2088 	if (*pagedeppp) {
2089 		/*
2090 		 * This should never happen since we only create pagedeps
2091 		 * with the vnode lock held.  Could be an assert.
2092 		 */
2093 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2094 		return (ret);
2095 	}
2096 	pagedep->pd_ino = ino;
2097 	pagedep->pd_lbn = lbn;
2098 	LIST_INIT(&pagedep->pd_dirremhd);
2099 	LIST_INIT(&pagedep->pd_pendinghd);
2100 	for (i = 0; i < DAHASHSZ; i++)
2101 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2102 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2103 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2104 	*pagedeppp = pagedep;
2105 	return (0);
2106 }
2107 
2108 /*
2109  * Structures and routines associated with inodedep caching.
2110  */
2111 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
2112 static u_long	inodedep_hash;	/* size of hash table - 1 */
2113 #define	INODEDEP_HASH(fs, inum) \
2114       (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
2115 
2116 static int
2117 inodedep_find(inodedephd, fs, inum, inodedeppp)
2118 	struct inodedep_hashhead *inodedephd;
2119 	struct fs *fs;
2120 	ino_t inum;
2121 	struct inodedep **inodedeppp;
2122 {
2123 	struct inodedep *inodedep;
2124 
2125 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2126 		if (inum == inodedep->id_ino && fs == inodedep->id_fs)
2127 			break;
2128 	if (inodedep) {
2129 		*inodedeppp = inodedep;
2130 		return (1);
2131 	}
2132 	*inodedeppp = NULL;
2133 
2134 	return (0);
2135 }
2136 /*
2137  * Look up an inodedep. Return 1 if found, 0 if not found.
2138  * If not found, allocate if DEPALLOC flag is passed.
2139  * Found or allocated entry is returned in inodedeppp.
2140  * This routine must be called with splbio interrupts blocked.
2141  */
2142 static int
2143 inodedep_lookup(mp, inum, flags, inodedeppp)
2144 	struct mount *mp;
2145 	ino_t inum;
2146 	int flags;
2147 	struct inodedep **inodedeppp;
2148 {
2149 	struct inodedep *inodedep;
2150 	struct inodedep_hashhead *inodedephd;
2151 	struct fs *fs;
2152 
2153 	mtx_assert(&lk, MA_OWNED);
2154 	fs = VFSTOUFS(mp)->um_fs;
2155 	inodedephd = INODEDEP_HASH(fs, inum);
2156 
2157 	if (inodedep_find(inodedephd, fs, inum, inodedeppp))
2158 		return (1);
2159 	if ((flags & DEPALLOC) == 0)
2160 		return (0);
2161 	/*
2162 	 * If we are over our limit, try to improve the situation.
2163 	 */
2164 	if (dep_current[D_INODEDEP] > max_softdeps && (flags & NODELAY) == 0)
2165 		request_cleanup(mp, FLUSH_INODES);
2166 	FREE_LOCK(&lk);
2167 	inodedep = malloc(sizeof(struct inodedep),
2168 		M_INODEDEP, M_SOFTDEP_FLAGS);
2169 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2170 	ACQUIRE_LOCK(&lk);
2171 	if (inodedep_find(inodedephd, fs, inum, inodedeppp)) {
2172 		WORKITEM_FREE(inodedep, D_INODEDEP);
2173 		return (1);
2174 	}
2175 	inodedep->id_fs = fs;
2176 	inodedep->id_ino = inum;
2177 	inodedep->id_state = ALLCOMPLETE;
2178 	inodedep->id_nlinkdelta = 0;
2179 	inodedep->id_savedino1 = NULL;
2180 	inodedep->id_savedsize = -1;
2181 	inodedep->id_savedextsize = -1;
2182 	inodedep->id_savednlink = -1;
2183 	inodedep->id_bmsafemap = NULL;
2184 	inodedep->id_mkdiradd = NULL;
2185 	LIST_INIT(&inodedep->id_dirremhd);
2186 	LIST_INIT(&inodedep->id_pendinghd);
2187 	LIST_INIT(&inodedep->id_inowait);
2188 	LIST_INIT(&inodedep->id_bufwait);
2189 	TAILQ_INIT(&inodedep->id_inoreflst);
2190 	TAILQ_INIT(&inodedep->id_inoupdt);
2191 	TAILQ_INIT(&inodedep->id_newinoupdt);
2192 	TAILQ_INIT(&inodedep->id_extupdt);
2193 	TAILQ_INIT(&inodedep->id_newextupdt);
2194 	TAILQ_INIT(&inodedep->id_freeblklst);
2195 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2196 	*inodedeppp = inodedep;
2197 	return (0);
2198 }
2199 
2200 /*
2201  * Structures and routines associated with newblk caching.
2202  */
2203 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
2204 u_long	newblk_hash;		/* size of hash table - 1 */
2205 #define	NEWBLK_HASH(fs, inum) \
2206 	(&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
2207 
2208 static int
2209 newblk_find(newblkhd, mp, newblkno, flags, newblkpp)
2210 	struct newblk_hashhead *newblkhd;
2211 	struct mount *mp;
2212 	ufs2_daddr_t newblkno;
2213 	int flags;
2214 	struct newblk **newblkpp;
2215 {
2216 	struct newblk *newblk;
2217 
2218 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2219 		if (newblkno != newblk->nb_newblkno)
2220 			continue;
2221 		if (mp != newblk->nb_list.wk_mp)
2222 			continue;
2223 		/*
2224 		 * If we're creating a new dependency don't match those that
2225 		 * have already been converted to allocdirects.  This is for
2226 		 * a frag extend.
2227 		 */
2228 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2229 			continue;
2230 		break;
2231 	}
2232 	if (newblk) {
2233 		*newblkpp = newblk;
2234 		return (1);
2235 	}
2236 	*newblkpp = NULL;
2237 	return (0);
2238 }
2239 
2240 /*
2241  * Look up a newblk. Return 1 if found, 0 if not found.
2242  * If not found, allocate if DEPALLOC flag is passed.
2243  * Found or allocated entry is returned in newblkpp.
2244  */
2245 static int
2246 newblk_lookup(mp, newblkno, flags, newblkpp)
2247 	struct mount *mp;
2248 	ufs2_daddr_t newblkno;
2249 	int flags;
2250 	struct newblk **newblkpp;
2251 {
2252 	struct newblk *newblk;
2253 	struct newblk_hashhead *newblkhd;
2254 
2255 	newblkhd = NEWBLK_HASH(VFSTOUFS(mp)->um_fs, newblkno);
2256 	if (newblk_find(newblkhd, mp, newblkno, flags, newblkpp))
2257 		return (1);
2258 	if ((flags & DEPALLOC) == 0)
2259 		return (0);
2260 	FREE_LOCK(&lk);
2261 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2262 	    M_SOFTDEP_FLAGS | M_ZERO);
2263 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2264 	ACQUIRE_LOCK(&lk);
2265 	if (newblk_find(newblkhd, mp, newblkno, flags, newblkpp)) {
2266 		WORKITEM_FREE(newblk, D_NEWBLK);
2267 		return (1);
2268 	}
2269 	newblk->nb_freefrag = NULL;
2270 	LIST_INIT(&newblk->nb_indirdeps);
2271 	LIST_INIT(&newblk->nb_newdirblk);
2272 	LIST_INIT(&newblk->nb_jwork);
2273 	newblk->nb_state = ATTACHED;
2274 	newblk->nb_newblkno = newblkno;
2275 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2276 	*newblkpp = newblk;
2277 	return (0);
2278 }
2279 
2280 /*
2281  * Structures and routines associated with freed indirect block caching.
2282  */
2283 struct freeworklst *indir_hashtbl;
2284 u_long	indir_hash;		/* size of hash table - 1 */
2285 #define	INDIR_HASH(mp, blkno) \
2286 	(&indir_hashtbl[((((register_t)(mp)) >> 13) + (blkno)) & indir_hash])
2287 
2288 /*
2289  * Lookup an indirect block in the indir hash table.  The freework is
2290  * removed and potentially freed.  The caller must do a blocking journal
2291  * write before writing to the blkno.
2292  */
2293 static int
2294 indirblk_lookup(mp, blkno)
2295 	struct mount *mp;
2296 	ufs2_daddr_t blkno;
2297 {
2298 	struct freework *freework;
2299 	struct freeworklst *wkhd;
2300 
2301 	wkhd = INDIR_HASH(mp, blkno);
2302 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2303 		if (freework->fw_blkno != blkno)
2304 			continue;
2305 		if (freework->fw_list.wk_mp != mp)
2306 			continue;
2307 		indirblk_remove(freework);
2308 		return (1);
2309 	}
2310 	return (0);
2311 }
2312 
2313 /*
2314  * Insert an indirect block represented by freework into the indirblk
2315  * hash table so that it may prevent the block from being re-used prior
2316  * to the journal being written.
2317  */
2318 static void
2319 indirblk_insert(freework)
2320 	struct freework *freework;
2321 {
2322 	struct jblocks *jblocks;
2323 	struct jseg *jseg;
2324 
2325 	jblocks = VFSTOUFS(freework->fw_list.wk_mp)->softdep_jblocks;
2326 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2327 	if (jseg == NULL)
2328 		return;
2329 
2330 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2331 	TAILQ_INSERT_HEAD(INDIR_HASH(freework->fw_list.wk_mp,
2332 	    freework->fw_blkno), freework, fw_next);
2333 	freework->fw_state &= ~DEPCOMPLETE;
2334 }
2335 
2336 static void
2337 indirblk_remove(freework)
2338 	struct freework *freework;
2339 {
2340 
2341 	LIST_REMOVE(freework, fw_segs);
2342 	TAILQ_REMOVE(INDIR_HASH(freework->fw_list.wk_mp,
2343 	    freework->fw_blkno), freework, fw_next);
2344 	freework->fw_state |= DEPCOMPLETE;
2345 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2346 		WORKITEM_FREE(freework, D_FREEWORK);
2347 }
2348 
2349 /*
2350  * Executed during filesystem system initialization before
2351  * mounting any filesystems.
2352  */
2353 void
2354 softdep_initialize()
2355 {
2356 	int i;
2357 
2358 	LIST_INIT(&mkdirlisthd);
2359 	max_softdeps = desiredvnodes * 4;
2360 	pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP, &pagedep_hash);
2361 	inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
2362 	newblk_hashtbl = hashinit(desiredvnodes / 5,  M_NEWBLK, &newblk_hash);
2363 	bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP, &bmsafemap_hash);
2364 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2365 	indir_hashtbl = malloc(i * sizeof(indir_hashtbl[0]), M_FREEWORK,
2366 	    M_WAITOK);
2367 	indir_hash = i - 1;
2368 	for (i = 0; i <= indir_hash; i++)
2369 		TAILQ_INIT(&indir_hashtbl[i]);
2370 
2371 	/* initialise bioops hack */
2372 	bioops.io_start = softdep_disk_io_initiation;
2373 	bioops.io_complete = softdep_disk_write_complete;
2374 	bioops.io_deallocate = softdep_deallocate_dependencies;
2375 	bioops.io_countdeps = softdep_count_dependencies;
2376 
2377 	/* Initialize the callout with an mtx. */
2378 	callout_init_mtx(&softdep_callout, &lk, 0);
2379 }
2380 
2381 /*
2382  * Executed after all filesystems have been unmounted during
2383  * filesystem module unload.
2384  */
2385 void
2386 softdep_uninitialize()
2387 {
2388 
2389 	callout_drain(&softdep_callout);
2390 	hashdestroy(pagedep_hashtbl, M_PAGEDEP, pagedep_hash);
2391 	hashdestroy(inodedep_hashtbl, M_INODEDEP, inodedep_hash);
2392 	hashdestroy(newblk_hashtbl, M_NEWBLK, newblk_hash);
2393 	hashdestroy(bmsafemap_hashtbl, M_BMSAFEMAP, bmsafemap_hash);
2394 	free(indir_hashtbl, M_FREEWORK);
2395 }
2396 
2397 /*
2398  * Called at mount time to notify the dependency code that a
2399  * filesystem wishes to use it.
2400  */
2401 int
2402 softdep_mount(devvp, mp, fs, cred)
2403 	struct vnode *devvp;
2404 	struct mount *mp;
2405 	struct fs *fs;
2406 	struct ucred *cred;
2407 {
2408 	struct csum_total cstotal;
2409 	struct ufsmount *ump;
2410 	struct cg *cgp;
2411 	struct buf *bp;
2412 	int error, cyl;
2413 
2414 	MNT_ILOCK(mp);
2415 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2416 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2417 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2418 			MNTK_SOFTDEP | MNTK_NOASYNC;
2419 	}
2420 	MNT_IUNLOCK(mp);
2421 	ump = VFSTOUFS(mp);
2422 	LIST_INIT(&ump->softdep_workitem_pending);
2423 	LIST_INIT(&ump->softdep_journal_pending);
2424 	TAILQ_INIT(&ump->softdep_unlinked);
2425 	LIST_INIT(&ump->softdep_dirtycg);
2426 	ump->softdep_worklist_tail = NULL;
2427 	ump->softdep_on_worklist = 0;
2428 	ump->softdep_deps = 0;
2429 	if ((fs->fs_flags & FS_SUJ) &&
2430 	    (error = journal_mount(mp, fs, cred)) != 0) {
2431 		printf("Failed to start journal: %d\n", error);
2432 		return (error);
2433 	}
2434 	/*
2435 	 * When doing soft updates, the counters in the
2436 	 * superblock may have gotten out of sync. Recomputation
2437 	 * can take a long time and can be deferred for background
2438 	 * fsck.  However, the old behavior of scanning the cylinder
2439 	 * groups and recalculating them at mount time is available
2440 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2441 	 */
2442 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2443 		return (0);
2444 	bzero(&cstotal, sizeof cstotal);
2445 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2446 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2447 		    fs->fs_cgsize, cred, &bp)) != 0) {
2448 			brelse(bp);
2449 			return (error);
2450 		}
2451 		cgp = (struct cg *)bp->b_data;
2452 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2453 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2454 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2455 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2456 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2457 		brelse(bp);
2458 	}
2459 #ifdef DEBUG
2460 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2461 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2462 #endif
2463 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2464 	return (0);
2465 }
2466 
2467 void
2468 softdep_unmount(mp)
2469 	struct mount *mp;
2470 {
2471 
2472 	MNT_ILOCK(mp);
2473 	mp->mnt_flag &= ~MNT_SOFTDEP;
2474 	if (MOUNTEDSUJ(mp) == 0) {
2475 		MNT_IUNLOCK(mp);
2476 		return;
2477 	}
2478 	mp->mnt_flag &= ~MNT_SUJ;
2479 	MNT_IUNLOCK(mp);
2480 	journal_unmount(mp);
2481 }
2482 
2483 static struct jblocks *
2484 jblocks_create(void)
2485 {
2486 	struct jblocks *jblocks;
2487 
2488 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2489 	TAILQ_INIT(&jblocks->jb_segs);
2490 	jblocks->jb_avail = 10;
2491 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2492 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2493 
2494 	return (jblocks);
2495 }
2496 
2497 static ufs2_daddr_t
2498 jblocks_alloc(jblocks, bytes, actual)
2499 	struct jblocks *jblocks;
2500 	int bytes;
2501 	int *actual;
2502 {
2503 	ufs2_daddr_t daddr;
2504 	struct jextent *jext;
2505 	int freecnt;
2506 	int blocks;
2507 
2508 	blocks = bytes / DEV_BSIZE;
2509 	jext = &jblocks->jb_extent[jblocks->jb_head];
2510 	freecnt = jext->je_blocks - jblocks->jb_off;
2511 	if (freecnt == 0) {
2512 		jblocks->jb_off = 0;
2513 		if (++jblocks->jb_head > jblocks->jb_used)
2514 			jblocks->jb_head = 0;
2515 		jext = &jblocks->jb_extent[jblocks->jb_head];
2516 		freecnt = jext->je_blocks;
2517 	}
2518 	if (freecnt > blocks)
2519 		freecnt = blocks;
2520 	*actual = freecnt * DEV_BSIZE;
2521 	daddr = jext->je_daddr + jblocks->jb_off;
2522 	jblocks->jb_off += freecnt;
2523 	jblocks->jb_free -= freecnt;
2524 
2525 	return (daddr);
2526 }
2527 
2528 static void
2529 jblocks_free(jblocks, mp, bytes)
2530 	struct jblocks *jblocks;
2531 	struct mount *mp;
2532 	int bytes;
2533 {
2534 
2535 	jblocks->jb_free += bytes / DEV_BSIZE;
2536 	if (jblocks->jb_suspended)
2537 		worklist_speedup();
2538 	wakeup(jblocks);
2539 }
2540 
2541 static void
2542 jblocks_destroy(jblocks)
2543 	struct jblocks *jblocks;
2544 {
2545 
2546 	if (jblocks->jb_extent)
2547 		free(jblocks->jb_extent, M_JBLOCKS);
2548 	free(jblocks, M_JBLOCKS);
2549 }
2550 
2551 static void
2552 jblocks_add(jblocks, daddr, blocks)
2553 	struct jblocks *jblocks;
2554 	ufs2_daddr_t daddr;
2555 	int blocks;
2556 {
2557 	struct jextent *jext;
2558 
2559 	jblocks->jb_blocks += blocks;
2560 	jblocks->jb_free += blocks;
2561 	jext = &jblocks->jb_extent[jblocks->jb_used];
2562 	/* Adding the first block. */
2563 	if (jext->je_daddr == 0) {
2564 		jext->je_daddr = daddr;
2565 		jext->je_blocks = blocks;
2566 		return;
2567 	}
2568 	/* Extending the last extent. */
2569 	if (jext->je_daddr + jext->je_blocks == daddr) {
2570 		jext->je_blocks += blocks;
2571 		return;
2572 	}
2573 	/* Adding a new extent. */
2574 	if (++jblocks->jb_used == jblocks->jb_avail) {
2575 		jblocks->jb_avail *= 2;
2576 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2577 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2578 		memcpy(jext, jblocks->jb_extent,
2579 		    sizeof(struct jextent) * jblocks->jb_used);
2580 		free(jblocks->jb_extent, M_JBLOCKS);
2581 		jblocks->jb_extent = jext;
2582 	}
2583 	jext = &jblocks->jb_extent[jblocks->jb_used];
2584 	jext->je_daddr = daddr;
2585 	jext->je_blocks = blocks;
2586 	return;
2587 }
2588 
2589 int
2590 softdep_journal_lookup(mp, vpp)
2591 	struct mount *mp;
2592 	struct vnode **vpp;
2593 {
2594 	struct componentname cnp;
2595 	struct vnode *dvp;
2596 	ino_t sujournal;
2597 	int error;
2598 
2599 	error = VFS_VGET(mp, ROOTINO, LK_EXCLUSIVE, &dvp);
2600 	if (error)
2601 		return (error);
2602 	bzero(&cnp, sizeof(cnp));
2603 	cnp.cn_nameiop = LOOKUP;
2604 	cnp.cn_flags = ISLASTCN;
2605 	cnp.cn_thread = curthread;
2606 	cnp.cn_cred = curthread->td_ucred;
2607 	cnp.cn_pnbuf = SUJ_FILE;
2608 	cnp.cn_nameptr = SUJ_FILE;
2609 	cnp.cn_namelen = strlen(SUJ_FILE);
2610 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2611 	vput(dvp);
2612 	if (error != 0)
2613 		return (error);
2614 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2615 	return (error);
2616 }
2617 
2618 /*
2619  * Open and verify the journal file.
2620  */
2621 static int
2622 journal_mount(mp, fs, cred)
2623 	struct mount *mp;
2624 	struct fs *fs;
2625 	struct ucred *cred;
2626 {
2627 	struct jblocks *jblocks;
2628 	struct vnode *vp;
2629 	struct inode *ip;
2630 	ufs2_daddr_t blkno;
2631 	int bcount;
2632 	int error;
2633 	int i;
2634 
2635 	error = softdep_journal_lookup(mp, &vp);
2636 	if (error != 0) {
2637 		printf("Failed to find journal.  Use tunefs to create one\n");
2638 		return (error);
2639 	}
2640 	ip = VTOI(vp);
2641 	if (ip->i_size < SUJ_MIN) {
2642 		error = ENOSPC;
2643 		goto out;
2644 	}
2645 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2646 	jblocks = jblocks_create();
2647 	for (i = 0; i < bcount; i++) {
2648 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2649 		if (error)
2650 			break;
2651 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2652 	}
2653 	if (error) {
2654 		jblocks_destroy(jblocks);
2655 		goto out;
2656 	}
2657 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2658 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2659 	VFSTOUFS(mp)->softdep_jblocks = jblocks;
2660 out:
2661 	if (error == 0) {
2662 		MNT_ILOCK(mp);
2663 		mp->mnt_flag |= MNT_SUJ;
2664 		mp->mnt_flag &= ~MNT_SOFTDEP;
2665 		MNT_IUNLOCK(mp);
2666 		/*
2667 		 * Only validate the journal contents if the
2668 		 * filesystem is clean, otherwise we write the logs
2669 		 * but they'll never be used.  If the filesystem was
2670 		 * still dirty when we mounted it the journal is
2671 		 * invalid and a new journal can only be valid if it
2672 		 * starts from a clean mount.
2673 		 */
2674 		if (fs->fs_clean) {
2675 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2676 			ip->i_flags |= IN_MODIFIED;
2677 			ffs_update(vp, 1);
2678 		}
2679 	}
2680 	vput(vp);
2681 	return (error);
2682 }
2683 
2684 static void
2685 journal_unmount(mp)
2686 	struct mount *mp;
2687 {
2688 	struct ufsmount *ump;
2689 
2690 	ump = VFSTOUFS(mp);
2691 	if (ump->softdep_jblocks)
2692 		jblocks_destroy(ump->softdep_jblocks);
2693 	ump->softdep_jblocks = NULL;
2694 }
2695 
2696 /*
2697  * Called when a journal record is ready to be written.  Space is allocated
2698  * and the journal entry is created when the journal is flushed to stable
2699  * store.
2700  */
2701 static void
2702 add_to_journal(wk)
2703 	struct worklist *wk;
2704 {
2705 	struct ufsmount *ump;
2706 
2707 	mtx_assert(&lk, MA_OWNED);
2708 	ump = VFSTOUFS(wk->wk_mp);
2709 	if (wk->wk_state & ONWORKLIST)
2710 		panic("add_to_journal: %s(0x%X) already on list",
2711 		    TYPENAME(wk->wk_type), wk->wk_state);
2712 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2713 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2714 		ump->softdep_jblocks->jb_age = ticks;
2715 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2716 	} else
2717 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2718 	ump->softdep_journal_tail = wk;
2719 	ump->softdep_on_journal += 1;
2720 }
2721 
2722 /*
2723  * Remove an arbitrary item for the journal worklist maintain the tail
2724  * pointer.  This happens when a new operation obviates the need to
2725  * journal an old operation.
2726  */
2727 static void
2728 remove_from_journal(wk)
2729 	struct worklist *wk;
2730 {
2731 	struct ufsmount *ump;
2732 
2733 	mtx_assert(&lk, MA_OWNED);
2734 	ump = VFSTOUFS(wk->wk_mp);
2735 #ifdef SUJ_DEBUG
2736 	{
2737 		struct worklist *wkn;
2738 
2739 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2740 			if (wkn == wk)
2741 				break;
2742 		if (wkn == NULL)
2743 			panic("remove_from_journal: %p is not in journal", wk);
2744 	}
2745 #endif
2746 	/*
2747 	 * We emulate a TAILQ to save space in most structures which do not
2748 	 * require TAILQ semantics.  Here we must update the tail position
2749 	 * when removing the tail which is not the final entry. This works
2750 	 * only if the worklist linkage are at the beginning of the structure.
2751 	 */
2752 	if (ump->softdep_journal_tail == wk)
2753 		ump->softdep_journal_tail =
2754 		    (struct worklist *)wk->wk_list.le_prev;
2755 
2756 	WORKLIST_REMOVE(wk);
2757 	ump->softdep_on_journal -= 1;
2758 }
2759 
2760 /*
2761  * Check for journal space as well as dependency limits so the prelink
2762  * code can throttle both journaled and non-journaled filesystems.
2763  * Threshold is 0 for low and 1 for min.
2764  */
2765 static int
2766 journal_space(ump, thresh)
2767 	struct ufsmount *ump;
2768 	int thresh;
2769 {
2770 	struct jblocks *jblocks;
2771 	int avail;
2772 
2773 	jblocks = ump->softdep_jblocks;
2774 	if (jblocks == NULL)
2775 		return (1);
2776 	/*
2777 	 * We use a tighter restriction here to prevent request_cleanup()
2778 	 * running in threads from running into locks we currently hold.
2779 	 */
2780 	if (dep_current[D_INODEDEP] > (max_softdeps / 10) * 9)
2781 		return (0);
2782 	if (thresh)
2783 		thresh = jblocks->jb_min;
2784 	else
2785 		thresh = jblocks->jb_low;
2786 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2787 	avail = jblocks->jb_free - avail;
2788 
2789 	return (avail > thresh);
2790 }
2791 
2792 static void
2793 journal_suspend(ump)
2794 	struct ufsmount *ump;
2795 {
2796 	struct jblocks *jblocks;
2797 	struct mount *mp;
2798 
2799 	mp = UFSTOVFS(ump);
2800 	jblocks = ump->softdep_jblocks;
2801 	MNT_ILOCK(mp);
2802 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2803 		stat_journal_min++;
2804 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2805 		mp->mnt_susp_owner = FIRST_THREAD_IN_PROC(softdepproc);
2806 	}
2807 	jblocks->jb_suspended = 1;
2808 	MNT_IUNLOCK(mp);
2809 }
2810 
2811 static int
2812 journal_unsuspend(struct ufsmount *ump)
2813 {
2814 	struct jblocks *jblocks;
2815 	struct mount *mp;
2816 
2817 	mp = UFSTOVFS(ump);
2818 	jblocks = ump->softdep_jblocks;
2819 
2820 	if (jblocks != NULL && jblocks->jb_suspended &&
2821 	    journal_space(ump, jblocks->jb_min)) {
2822 		jblocks->jb_suspended = 0;
2823 		FREE_LOCK(&lk);
2824 		mp->mnt_susp_owner = curthread;
2825 		vfs_write_resume(mp, 0);
2826 		ACQUIRE_LOCK(&lk);
2827 		return (1);
2828 	}
2829 	return (0);
2830 }
2831 
2832 /*
2833  * Called before any allocation function to be certain that there is
2834  * sufficient space in the journal prior to creating any new records.
2835  * Since in the case of block allocation we may have multiple locked
2836  * buffers at the time of the actual allocation we can not block
2837  * when the journal records are created.  Doing so would create a deadlock
2838  * if any of these buffers needed to be flushed to reclaim space.  Instead
2839  * we require a sufficiently large amount of available space such that
2840  * each thread in the system could have passed this allocation check and
2841  * still have sufficient free space.  With 20% of a minimum journal size
2842  * of 1MB we have 6553 records available.
2843  */
2844 int
2845 softdep_prealloc(vp, waitok)
2846 	struct vnode *vp;
2847 	int waitok;
2848 {
2849 	struct ufsmount *ump;
2850 
2851 	/*
2852 	 * Nothing to do if we are not running journaled soft updates.
2853 	 * If we currently hold the snapshot lock, we must avoid handling
2854 	 * other resources that could cause deadlock.
2855 	 */
2856 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)))
2857 		return (0);
2858 	ump = VFSTOUFS(vp->v_mount);
2859 	ACQUIRE_LOCK(&lk);
2860 	if (journal_space(ump, 0)) {
2861 		FREE_LOCK(&lk);
2862 		return (0);
2863 	}
2864 	stat_journal_low++;
2865 	FREE_LOCK(&lk);
2866 	if (waitok == MNT_NOWAIT)
2867 		return (ENOSPC);
2868 	/*
2869 	 * Attempt to sync this vnode once to flush any journal
2870 	 * work attached to it.
2871 	 */
2872 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
2873 		ffs_syncvnode(vp, waitok, 0);
2874 	ACQUIRE_LOCK(&lk);
2875 	process_removes(vp);
2876 	process_truncates(vp);
2877 	if (journal_space(ump, 0) == 0) {
2878 		softdep_speedup();
2879 		if (journal_space(ump, 1) == 0)
2880 			journal_suspend(ump);
2881 	}
2882 	FREE_LOCK(&lk);
2883 
2884 	return (0);
2885 }
2886 
2887 /*
2888  * Before adjusting a link count on a vnode verify that we have sufficient
2889  * journal space.  If not, process operations that depend on the currently
2890  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
2891  * and softdep flush threads can not acquire these locks to reclaim space.
2892  */
2893 static void
2894 softdep_prelink(dvp, vp)
2895 	struct vnode *dvp;
2896 	struct vnode *vp;
2897 {
2898 	struct ufsmount *ump;
2899 
2900 	ump = VFSTOUFS(dvp->v_mount);
2901 	mtx_assert(&lk, MA_OWNED);
2902 	/*
2903 	 * Nothing to do if we have sufficient journal space.
2904 	 * If we currently hold the snapshot lock, we must avoid
2905 	 * handling other resources that could cause deadlock.
2906 	 */
2907 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
2908 		return;
2909 	stat_journal_low++;
2910 	FREE_LOCK(&lk);
2911 	if (vp)
2912 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
2913 	ffs_syncvnode(dvp, MNT_WAIT, 0);
2914 	ACQUIRE_LOCK(&lk);
2915 	/* Process vp before dvp as it may create .. removes. */
2916 	if (vp) {
2917 		process_removes(vp);
2918 		process_truncates(vp);
2919 	}
2920 	process_removes(dvp);
2921 	process_truncates(dvp);
2922 	softdep_speedup();
2923 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
2924 	if (journal_space(ump, 0) == 0) {
2925 		softdep_speedup();
2926 		if (journal_space(ump, 1) == 0)
2927 			journal_suspend(ump);
2928 	}
2929 }
2930 
2931 static void
2932 jseg_write(ump, jseg, data)
2933 	struct ufsmount *ump;
2934 	struct jseg *jseg;
2935 	uint8_t *data;
2936 {
2937 	struct jsegrec *rec;
2938 
2939 	rec = (struct jsegrec *)data;
2940 	rec->jsr_seq = jseg->js_seq;
2941 	rec->jsr_oldest = jseg->js_oldseq;
2942 	rec->jsr_cnt = jseg->js_cnt;
2943 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
2944 	rec->jsr_crc = 0;
2945 	rec->jsr_time = ump->um_fs->fs_mtime;
2946 }
2947 
2948 static inline void
2949 inoref_write(inoref, jseg, rec)
2950 	struct inoref *inoref;
2951 	struct jseg *jseg;
2952 	struct jrefrec *rec;
2953 {
2954 
2955 	inoref->if_jsegdep->jd_seg = jseg;
2956 	rec->jr_ino = inoref->if_ino;
2957 	rec->jr_parent = inoref->if_parent;
2958 	rec->jr_nlink = inoref->if_nlink;
2959 	rec->jr_mode = inoref->if_mode;
2960 	rec->jr_diroff = inoref->if_diroff;
2961 }
2962 
2963 static void
2964 jaddref_write(jaddref, jseg, data)
2965 	struct jaddref *jaddref;
2966 	struct jseg *jseg;
2967 	uint8_t *data;
2968 {
2969 	struct jrefrec *rec;
2970 
2971 	rec = (struct jrefrec *)data;
2972 	rec->jr_op = JOP_ADDREF;
2973 	inoref_write(&jaddref->ja_ref, jseg, rec);
2974 }
2975 
2976 static void
2977 jremref_write(jremref, jseg, data)
2978 	struct jremref *jremref;
2979 	struct jseg *jseg;
2980 	uint8_t *data;
2981 {
2982 	struct jrefrec *rec;
2983 
2984 	rec = (struct jrefrec *)data;
2985 	rec->jr_op = JOP_REMREF;
2986 	inoref_write(&jremref->jr_ref, jseg, rec);
2987 }
2988 
2989 static void
2990 jmvref_write(jmvref, jseg, data)
2991 	struct jmvref *jmvref;
2992 	struct jseg *jseg;
2993 	uint8_t *data;
2994 {
2995 	struct jmvrec *rec;
2996 
2997 	rec = (struct jmvrec *)data;
2998 	rec->jm_op = JOP_MVREF;
2999 	rec->jm_ino = jmvref->jm_ino;
3000 	rec->jm_parent = jmvref->jm_parent;
3001 	rec->jm_oldoff = jmvref->jm_oldoff;
3002 	rec->jm_newoff = jmvref->jm_newoff;
3003 }
3004 
3005 static void
3006 jnewblk_write(jnewblk, jseg, data)
3007 	struct jnewblk *jnewblk;
3008 	struct jseg *jseg;
3009 	uint8_t *data;
3010 {
3011 	struct jblkrec *rec;
3012 
3013 	jnewblk->jn_jsegdep->jd_seg = jseg;
3014 	rec = (struct jblkrec *)data;
3015 	rec->jb_op = JOP_NEWBLK;
3016 	rec->jb_ino = jnewblk->jn_ino;
3017 	rec->jb_blkno = jnewblk->jn_blkno;
3018 	rec->jb_lbn = jnewblk->jn_lbn;
3019 	rec->jb_frags = jnewblk->jn_frags;
3020 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3021 }
3022 
3023 static void
3024 jfreeblk_write(jfreeblk, jseg, data)
3025 	struct jfreeblk *jfreeblk;
3026 	struct jseg *jseg;
3027 	uint8_t *data;
3028 {
3029 	struct jblkrec *rec;
3030 
3031 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3032 	rec = (struct jblkrec *)data;
3033 	rec->jb_op = JOP_FREEBLK;
3034 	rec->jb_ino = jfreeblk->jf_ino;
3035 	rec->jb_blkno = jfreeblk->jf_blkno;
3036 	rec->jb_lbn = jfreeblk->jf_lbn;
3037 	rec->jb_frags = jfreeblk->jf_frags;
3038 	rec->jb_oldfrags = 0;
3039 }
3040 
3041 static void
3042 jfreefrag_write(jfreefrag, jseg, data)
3043 	struct jfreefrag *jfreefrag;
3044 	struct jseg *jseg;
3045 	uint8_t *data;
3046 {
3047 	struct jblkrec *rec;
3048 
3049 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3050 	rec = (struct jblkrec *)data;
3051 	rec->jb_op = JOP_FREEBLK;
3052 	rec->jb_ino = jfreefrag->fr_ino;
3053 	rec->jb_blkno = jfreefrag->fr_blkno;
3054 	rec->jb_lbn = jfreefrag->fr_lbn;
3055 	rec->jb_frags = jfreefrag->fr_frags;
3056 	rec->jb_oldfrags = 0;
3057 }
3058 
3059 static void
3060 jtrunc_write(jtrunc, jseg, data)
3061 	struct jtrunc *jtrunc;
3062 	struct jseg *jseg;
3063 	uint8_t *data;
3064 {
3065 	struct jtrncrec *rec;
3066 
3067 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3068 	rec = (struct jtrncrec *)data;
3069 	rec->jt_op = JOP_TRUNC;
3070 	rec->jt_ino = jtrunc->jt_ino;
3071 	rec->jt_size = jtrunc->jt_size;
3072 	rec->jt_extsize = jtrunc->jt_extsize;
3073 }
3074 
3075 static void
3076 jfsync_write(jfsync, jseg, data)
3077 	struct jfsync *jfsync;
3078 	struct jseg *jseg;
3079 	uint8_t *data;
3080 {
3081 	struct jtrncrec *rec;
3082 
3083 	rec = (struct jtrncrec *)data;
3084 	rec->jt_op = JOP_SYNC;
3085 	rec->jt_ino = jfsync->jfs_ino;
3086 	rec->jt_size = jfsync->jfs_size;
3087 	rec->jt_extsize = jfsync->jfs_extsize;
3088 }
3089 
3090 static void
3091 softdep_flushjournal(mp)
3092 	struct mount *mp;
3093 {
3094 	struct jblocks *jblocks;
3095 	struct ufsmount *ump;
3096 
3097 	if (MOUNTEDSUJ(mp) == 0)
3098 		return;
3099 	ump = VFSTOUFS(mp);
3100 	jblocks = ump->softdep_jblocks;
3101 	ACQUIRE_LOCK(&lk);
3102 	while (ump->softdep_on_journal) {
3103 		jblocks->jb_needseg = 1;
3104 		softdep_process_journal(mp, NULL, MNT_WAIT);
3105 	}
3106 	FREE_LOCK(&lk);
3107 }
3108 
3109 static void softdep_synchronize_completed(struct bio *);
3110 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3111 
3112 static void
3113 softdep_synchronize_completed(bp)
3114         struct bio *bp;
3115 {
3116 	struct jseg *oldest;
3117 	struct jseg *jseg;
3118 
3119 	/*
3120 	 * caller1 marks the last segment written before we issued the
3121 	 * synchronize cache.
3122 	 */
3123 	jseg = bp->bio_caller1;
3124 	oldest = NULL;
3125 	ACQUIRE_LOCK(&lk);
3126 	/*
3127 	 * Mark all the journal entries waiting on the synchronize cache
3128 	 * as completed so they may continue on.
3129 	 */
3130 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3131 		jseg->js_state |= COMPLETE;
3132 		oldest = jseg;
3133 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3134 	}
3135 	/*
3136 	 * Restart deferred journal entry processing from the oldest
3137 	 * completed jseg.
3138 	 */
3139 	if (oldest)
3140 		complete_jsegs(oldest);
3141 
3142 	FREE_LOCK(&lk);
3143 	g_destroy_bio(bp);
3144 }
3145 
3146 /*
3147  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3148  * barriers.  The journal must be written prior to any blocks that depend
3149  * on it and the journal can not be released until the blocks have be
3150  * written.  This code handles both barriers simultaneously.
3151  */
3152 static void
3153 softdep_synchronize(bp, ump, caller1)
3154 	struct bio *bp;
3155 	struct ufsmount *ump;
3156 	void *caller1;
3157 {
3158 
3159 	bp->bio_cmd = BIO_FLUSH;
3160 	bp->bio_flags |= BIO_ORDERED;
3161 	bp->bio_data = NULL;
3162 	bp->bio_offset = ump->um_cp->provider->mediasize;
3163 	bp->bio_length = 0;
3164 	bp->bio_done = softdep_synchronize_completed;
3165 	bp->bio_caller1 = caller1;
3166 	g_io_request(bp,
3167 	    (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3168 }
3169 
3170 /*
3171  * Flush some journal records to disk.
3172  */
3173 static void
3174 softdep_process_journal(mp, needwk, flags)
3175 	struct mount *mp;
3176 	struct worklist *needwk;
3177 	int flags;
3178 {
3179 	struct jblocks *jblocks;
3180 	struct ufsmount *ump;
3181 	struct worklist *wk;
3182 	struct jseg *jseg;
3183 	struct buf *bp;
3184 	struct bio *bio;
3185 	uint8_t *data;
3186 	struct fs *fs;
3187 	int shouldflush;
3188 	int segwritten;
3189 	int jrecmin;	/* Minimum records per block. */
3190 	int jrecmax;	/* Maximum records per block. */
3191 	int size;
3192 	int cnt;
3193 	int off;
3194 	int devbsize;
3195 
3196 	if (MOUNTEDSUJ(mp) == 0)
3197 		return;
3198 	shouldflush = softdep_flushcache;
3199 	bio = NULL;
3200 	jseg = NULL;
3201 	ump = VFSTOUFS(mp);
3202 	fs = ump->um_fs;
3203 	jblocks = ump->softdep_jblocks;
3204 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3205 	/*
3206 	 * We write anywhere between a disk block and fs block.  The upper
3207 	 * bound is picked to prevent buffer cache fragmentation and limit
3208 	 * processing time per I/O.
3209 	 */
3210 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3211 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3212 	segwritten = 0;
3213 	for (;;) {
3214 		cnt = ump->softdep_on_journal;
3215 		/*
3216 		 * Criteria for writing a segment:
3217 		 * 1) We have a full block.
3218 		 * 2) We're called from jwait() and haven't found the
3219 		 *    journal item yet.
3220 		 * 3) Always write if needseg is set.
3221 		 * 4) If we are called from process_worklist and have
3222 		 *    not yet written anything we write a partial block
3223 		 *    to enforce a 1 second maximum latency on journal
3224 		 *    entries.
3225 		 */
3226 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3227 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3228 			break;
3229 		cnt++;
3230 		/*
3231 		 * Verify some free journal space.  softdep_prealloc() should
3232 	 	 * guarantee that we don't run out so this is indicative of
3233 		 * a problem with the flow control.  Try to recover
3234 		 * gracefully in any event.
3235 		 */
3236 		while (jblocks->jb_free == 0) {
3237 			if (flags != MNT_WAIT)
3238 				break;
3239 			printf("softdep: Out of journal space!\n");
3240 			softdep_speedup();
3241 			msleep(jblocks, &lk, PRIBIO, "jblocks", hz);
3242 		}
3243 		FREE_LOCK(&lk);
3244 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3245 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3246 		LIST_INIT(&jseg->js_entries);
3247 		LIST_INIT(&jseg->js_indirs);
3248 		jseg->js_state = ATTACHED;
3249 		if (shouldflush == 0)
3250 			jseg->js_state |= COMPLETE;
3251 		else if (bio == NULL)
3252 			bio = g_alloc_bio();
3253 		jseg->js_jblocks = jblocks;
3254 		bp = geteblk(fs->fs_bsize, 0);
3255 		ACQUIRE_LOCK(&lk);
3256 		/*
3257 		 * If there was a race while we were allocating the block
3258 		 * and jseg the entry we care about was likely written.
3259 		 * We bail out in both the WAIT and NOWAIT case and assume
3260 		 * the caller will loop if the entry it cares about is
3261 		 * not written.
3262 		 */
3263 		cnt = ump->softdep_on_journal;
3264 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3265 			bp->b_flags |= B_INVAL | B_NOCACHE;
3266 			WORKITEM_FREE(jseg, D_JSEG);
3267 			FREE_LOCK(&lk);
3268 			brelse(bp);
3269 			ACQUIRE_LOCK(&lk);
3270 			break;
3271 		}
3272 		/*
3273 		 * Calculate the disk block size required for the available
3274 		 * records rounded to the min size.
3275 		 */
3276 		if (cnt == 0)
3277 			size = devbsize;
3278 		else if (cnt < jrecmax)
3279 			size = howmany(cnt, jrecmin) * devbsize;
3280 		else
3281 			size = fs->fs_bsize;
3282 		/*
3283 		 * Allocate a disk block for this journal data and account
3284 		 * for truncation of the requested size if enough contiguous
3285 		 * space was not available.
3286 		 */
3287 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3288 		bp->b_lblkno = bp->b_blkno;
3289 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3290 		bp->b_bcount = size;
3291 		bp->b_flags &= ~B_INVAL;
3292 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3293 		/*
3294 		 * Initialize our jseg with cnt records.  Assign the next
3295 		 * sequence number to it and link it in-order.
3296 		 */
3297 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3298 		jseg->js_buf = bp;
3299 		jseg->js_cnt = cnt;
3300 		jseg->js_refs = cnt + 1;	/* Self ref. */
3301 		jseg->js_size = size;
3302 		jseg->js_seq = jblocks->jb_nextseq++;
3303 		if (jblocks->jb_oldestseg == NULL)
3304 			jblocks->jb_oldestseg = jseg;
3305 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3306 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3307 		if (jblocks->jb_writeseg == NULL)
3308 			jblocks->jb_writeseg = jseg;
3309 		/*
3310 		 * Start filling in records from the pending list.
3311 		 */
3312 		data = bp->b_data;
3313 		off = 0;
3314 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3315 		    != NULL) {
3316 			if (cnt == 0)
3317 				break;
3318 			/* Place a segment header on every device block. */
3319 			if ((off % devbsize) == 0) {
3320 				jseg_write(ump, jseg, data);
3321 				off += JREC_SIZE;
3322 				data = bp->b_data + off;
3323 			}
3324 			if (wk == needwk)
3325 				needwk = NULL;
3326 			remove_from_journal(wk);
3327 			wk->wk_state |= INPROGRESS;
3328 			WORKLIST_INSERT(&jseg->js_entries, wk);
3329 			switch (wk->wk_type) {
3330 			case D_JADDREF:
3331 				jaddref_write(WK_JADDREF(wk), jseg, data);
3332 				break;
3333 			case D_JREMREF:
3334 				jremref_write(WK_JREMREF(wk), jseg, data);
3335 				break;
3336 			case D_JMVREF:
3337 				jmvref_write(WK_JMVREF(wk), jseg, data);
3338 				break;
3339 			case D_JNEWBLK:
3340 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3341 				break;
3342 			case D_JFREEBLK:
3343 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3344 				break;
3345 			case D_JFREEFRAG:
3346 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3347 				break;
3348 			case D_JTRUNC:
3349 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3350 				break;
3351 			case D_JFSYNC:
3352 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3353 				break;
3354 			default:
3355 				panic("process_journal: Unknown type %s",
3356 				    TYPENAME(wk->wk_type));
3357 				/* NOTREACHED */
3358 			}
3359 			off += JREC_SIZE;
3360 			data = bp->b_data + off;
3361 			cnt--;
3362 		}
3363 		/*
3364 		 * Write this one buffer and continue.
3365 		 */
3366 		segwritten = 1;
3367 		jblocks->jb_needseg = 0;
3368 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3369 		FREE_LOCK(&lk);
3370 		pbgetvp(ump->um_devvp, bp);
3371 		/*
3372 		 * We only do the blocking wait once we find the journal
3373 		 * entry we're looking for.
3374 		 */
3375 		if (needwk == NULL && flags == MNT_WAIT)
3376 			bwrite(bp);
3377 		else
3378 			bawrite(bp);
3379 		ACQUIRE_LOCK(&lk);
3380 	}
3381 	/*
3382 	 * If we wrote a segment issue a synchronize cache so the journal
3383 	 * is reflected on disk before the data is written.  Since reclaiming
3384 	 * journal space also requires writing a journal record this
3385 	 * process also enforces a barrier before reclamation.
3386 	 */
3387 	if (segwritten && shouldflush) {
3388 		softdep_synchronize(bio, ump,
3389 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3390 	} else if (bio)
3391 		g_destroy_bio(bio);
3392 	/*
3393 	 * If we've suspended the filesystem because we ran out of journal
3394 	 * space either try to sync it here to make some progress or
3395 	 * unsuspend it if we already have.
3396 	 */
3397 	if (flags == 0 && jblocks->jb_suspended) {
3398 		if (journal_unsuspend(ump))
3399 			return;
3400 		FREE_LOCK(&lk);
3401 		VFS_SYNC(mp, MNT_NOWAIT);
3402 		ffs_sbupdate(ump, MNT_WAIT, 0);
3403 		ACQUIRE_LOCK(&lk);
3404 	}
3405 }
3406 
3407 /*
3408  * Complete a jseg, allowing all dependencies awaiting journal writes
3409  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3410  * structures so that the journal segment can be freed to reclaim space.
3411  */
3412 static void
3413 complete_jseg(jseg)
3414 	struct jseg *jseg;
3415 {
3416 	struct worklist *wk;
3417 	struct jmvref *jmvref;
3418 	int waiting;
3419 #ifdef INVARIANTS
3420 	int i = 0;
3421 #endif
3422 
3423 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3424 		WORKLIST_REMOVE(wk);
3425 		waiting = wk->wk_state & IOWAITING;
3426 		wk->wk_state &= ~(INPROGRESS | IOWAITING);
3427 		wk->wk_state |= COMPLETE;
3428 		KASSERT(i++ < jseg->js_cnt,
3429 		    ("handle_written_jseg: overflow %d >= %d",
3430 		    i - 1, jseg->js_cnt));
3431 		switch (wk->wk_type) {
3432 		case D_JADDREF:
3433 			handle_written_jaddref(WK_JADDREF(wk));
3434 			break;
3435 		case D_JREMREF:
3436 			handle_written_jremref(WK_JREMREF(wk));
3437 			break;
3438 		case D_JMVREF:
3439 			rele_jseg(jseg);	/* No jsegdep. */
3440 			jmvref = WK_JMVREF(wk);
3441 			LIST_REMOVE(jmvref, jm_deps);
3442 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3443 				free_pagedep(jmvref->jm_pagedep);
3444 			WORKITEM_FREE(jmvref, D_JMVREF);
3445 			break;
3446 		case D_JNEWBLK:
3447 			handle_written_jnewblk(WK_JNEWBLK(wk));
3448 			break;
3449 		case D_JFREEBLK:
3450 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3451 			break;
3452 		case D_JTRUNC:
3453 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3454 			break;
3455 		case D_JFSYNC:
3456 			rele_jseg(jseg);	/* No jsegdep. */
3457 			WORKITEM_FREE(wk, D_JFSYNC);
3458 			break;
3459 		case D_JFREEFRAG:
3460 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3461 			break;
3462 		default:
3463 			panic("handle_written_jseg: Unknown type %s",
3464 			    TYPENAME(wk->wk_type));
3465 			/* NOTREACHED */
3466 		}
3467 		if (waiting)
3468 			wakeup(wk);
3469 	}
3470 	/* Release the self reference so the structure may be freed. */
3471 	rele_jseg(jseg);
3472 }
3473 
3474 /*
3475  * Determine which jsegs are ready for completion processing.  Waits for
3476  * synchronize cache to complete as well as forcing in-order completion
3477  * of journal entries.
3478  */
3479 static void
3480 complete_jsegs(jseg)
3481 	struct jseg *jseg;
3482 {
3483 	struct jblocks *jblocks;
3484 	struct jseg *jsegn;
3485 
3486 	jblocks = jseg->js_jblocks;
3487 	/*
3488 	 * Don't allow out of order completions.  If this isn't the first
3489 	 * block wait for it to write before we're done.
3490 	 */
3491 	if (jseg != jblocks->jb_writeseg)
3492 		return;
3493 	/* Iterate through available jsegs processing their entries. */
3494 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3495 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3496 		jsegn = TAILQ_NEXT(jseg, js_next);
3497 		complete_jseg(jseg);
3498 		jseg = jsegn;
3499 	}
3500 	jblocks->jb_writeseg = jseg;
3501 	/*
3502 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3503 	 */
3504 	free_jsegs(jblocks);
3505 }
3506 
3507 /*
3508  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3509  * the final completions.
3510  */
3511 static void
3512 handle_written_jseg(jseg, bp)
3513 	struct jseg *jseg;
3514 	struct buf *bp;
3515 {
3516 
3517 	if (jseg->js_refs == 0)
3518 		panic("handle_written_jseg: No self-reference on %p", jseg);
3519 	jseg->js_state |= DEPCOMPLETE;
3520 	/*
3521 	 * We'll never need this buffer again, set flags so it will be
3522 	 * discarded.
3523 	 */
3524 	bp->b_flags |= B_INVAL | B_NOCACHE;
3525 	pbrelvp(bp);
3526 	complete_jsegs(jseg);
3527 }
3528 
3529 static inline struct jsegdep *
3530 inoref_jseg(inoref)
3531 	struct inoref *inoref;
3532 {
3533 	struct jsegdep *jsegdep;
3534 
3535 	jsegdep = inoref->if_jsegdep;
3536 	inoref->if_jsegdep = NULL;
3537 
3538 	return (jsegdep);
3539 }
3540 
3541 /*
3542  * Called once a jremref has made it to stable store.  The jremref is marked
3543  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3544  * for the jremref to complete will be awoken by free_jremref.
3545  */
3546 static void
3547 handle_written_jremref(jremref)
3548 	struct jremref *jremref;
3549 {
3550 	struct inodedep *inodedep;
3551 	struct jsegdep *jsegdep;
3552 	struct dirrem *dirrem;
3553 
3554 	/* Grab the jsegdep. */
3555 	jsegdep = inoref_jseg(&jremref->jr_ref);
3556 	/*
3557 	 * Remove us from the inoref list.
3558 	 */
3559 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3560 	    0, &inodedep) == 0)
3561 		panic("handle_written_jremref: Lost inodedep");
3562 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3563 	/*
3564 	 * Complete the dirrem.
3565 	 */
3566 	dirrem = jremref->jr_dirrem;
3567 	jremref->jr_dirrem = NULL;
3568 	LIST_REMOVE(jremref, jr_deps);
3569 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3570 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3571 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3572 	    (dirrem->dm_state & COMPLETE) != 0)
3573 		add_to_worklist(&dirrem->dm_list, 0);
3574 	free_jremref(jremref);
3575 }
3576 
3577 /*
3578  * Called once a jaddref has made it to stable store.  The dependency is
3579  * marked complete and any dependent structures are added to the inode
3580  * bufwait list to be completed as soon as it is written.  If a bitmap write
3581  * depends on this entry we move the inode into the inodedephd of the
3582  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3583  */
3584 static void
3585 handle_written_jaddref(jaddref)
3586 	struct jaddref *jaddref;
3587 {
3588 	struct jsegdep *jsegdep;
3589 	struct inodedep *inodedep;
3590 	struct diradd *diradd;
3591 	struct mkdir *mkdir;
3592 
3593 	/* Grab the jsegdep. */
3594 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3595 	mkdir = NULL;
3596 	diradd = NULL;
3597 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3598 	    0, &inodedep) == 0)
3599 		panic("handle_written_jaddref: Lost inodedep.");
3600 	if (jaddref->ja_diradd == NULL)
3601 		panic("handle_written_jaddref: No dependency");
3602 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3603 		diradd = jaddref->ja_diradd;
3604 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3605 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3606 		mkdir = jaddref->ja_mkdir;
3607 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3608 	} else if (jaddref->ja_state & MKDIR_BODY)
3609 		mkdir = jaddref->ja_mkdir;
3610 	else
3611 		panic("handle_written_jaddref: Unknown dependency %p",
3612 		    jaddref->ja_diradd);
3613 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3614 	/*
3615 	 * Remove us from the inode list.
3616 	 */
3617 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3618 	/*
3619 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3620 	 */
3621 	if (mkdir) {
3622 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3623 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3624 		    TYPENAME(mkdir->md_list.wk_type)));
3625 		mkdir->md_jaddref = NULL;
3626 		diradd = mkdir->md_diradd;
3627 		mkdir->md_state |= DEPCOMPLETE;
3628 		complete_mkdir(mkdir);
3629 	}
3630 	jwork_insert(&diradd->da_jwork, jsegdep);
3631 	if (jaddref->ja_state & NEWBLOCK) {
3632 		inodedep->id_state |= ONDEPLIST;
3633 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3634 		    inodedep, id_deps);
3635 	}
3636 	free_jaddref(jaddref);
3637 }
3638 
3639 /*
3640  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3641  * is placed in the bmsafemap to await notification of a written bitmap.  If
3642  * the operation was canceled we add the segdep to the appropriate
3643  * dependency to free the journal space once the canceling operation
3644  * completes.
3645  */
3646 static void
3647 handle_written_jnewblk(jnewblk)
3648 	struct jnewblk *jnewblk;
3649 {
3650 	struct bmsafemap *bmsafemap;
3651 	struct freefrag *freefrag;
3652 	struct freework *freework;
3653 	struct jsegdep *jsegdep;
3654 	struct newblk *newblk;
3655 
3656 	/* Grab the jsegdep. */
3657 	jsegdep = jnewblk->jn_jsegdep;
3658 	jnewblk->jn_jsegdep = NULL;
3659 	if (jnewblk->jn_dep == NULL)
3660 		panic("handle_written_jnewblk: No dependency for the segdep.");
3661 	switch (jnewblk->jn_dep->wk_type) {
3662 	case D_NEWBLK:
3663 	case D_ALLOCDIRECT:
3664 	case D_ALLOCINDIR:
3665 		/*
3666 		 * Add the written block to the bmsafemap so it can
3667 		 * be notified when the bitmap is on disk.
3668 		 */
3669 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3670 		newblk->nb_jnewblk = NULL;
3671 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3672 			bmsafemap = newblk->nb_bmsafemap;
3673 			newblk->nb_state |= ONDEPLIST;
3674 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3675 			    nb_deps);
3676 		}
3677 		jwork_insert(&newblk->nb_jwork, jsegdep);
3678 		break;
3679 	case D_FREEFRAG:
3680 		/*
3681 		 * A newblock being removed by a freefrag when replaced by
3682 		 * frag extension.
3683 		 */
3684 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3685 		freefrag->ff_jdep = NULL;
3686 		jwork_insert(&freefrag->ff_jwork, jsegdep);
3687 		break;
3688 	case D_FREEWORK:
3689 		/*
3690 		 * A direct block was removed by truncate.
3691 		 */
3692 		freework = WK_FREEWORK(jnewblk->jn_dep);
3693 		freework->fw_jnewblk = NULL;
3694 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3695 		break;
3696 	default:
3697 		panic("handle_written_jnewblk: Unknown type %d.",
3698 		    jnewblk->jn_dep->wk_type);
3699 	}
3700 	jnewblk->jn_dep = NULL;
3701 	free_jnewblk(jnewblk);
3702 }
3703 
3704 /*
3705  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3706  * an in-flight allocation that has not yet been committed.  Divorce us
3707  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3708  * to the worklist.
3709  */
3710 static void
3711 cancel_jfreefrag(jfreefrag)
3712 	struct jfreefrag *jfreefrag;
3713 {
3714 	struct freefrag *freefrag;
3715 
3716 	if (jfreefrag->fr_jsegdep) {
3717 		free_jsegdep(jfreefrag->fr_jsegdep);
3718 		jfreefrag->fr_jsegdep = NULL;
3719 	}
3720 	freefrag = jfreefrag->fr_freefrag;
3721 	jfreefrag->fr_freefrag = NULL;
3722 	free_jfreefrag(jfreefrag);
3723 	freefrag->ff_state |= DEPCOMPLETE;
3724 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3725 }
3726 
3727 /*
3728  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3729  */
3730 static void
3731 free_jfreefrag(jfreefrag)
3732 	struct jfreefrag *jfreefrag;
3733 {
3734 
3735 	if (jfreefrag->fr_state & INPROGRESS)
3736 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3737 	else if (jfreefrag->fr_state & ONWORKLIST)
3738 		remove_from_journal(&jfreefrag->fr_list);
3739 	if (jfreefrag->fr_freefrag != NULL)
3740 		panic("free_jfreefrag:  Still attached to a freefrag.");
3741 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3742 }
3743 
3744 /*
3745  * Called when the journal write for a jfreefrag completes.  The parent
3746  * freefrag is added to the worklist if this completes its dependencies.
3747  */
3748 static void
3749 handle_written_jfreefrag(jfreefrag)
3750 	struct jfreefrag *jfreefrag;
3751 {
3752 	struct jsegdep *jsegdep;
3753 	struct freefrag *freefrag;
3754 
3755 	/* Grab the jsegdep. */
3756 	jsegdep = jfreefrag->fr_jsegdep;
3757 	jfreefrag->fr_jsegdep = NULL;
3758 	freefrag = jfreefrag->fr_freefrag;
3759 	if (freefrag == NULL)
3760 		panic("handle_written_jfreefrag: No freefrag.");
3761 	freefrag->ff_state |= DEPCOMPLETE;
3762 	freefrag->ff_jdep = NULL;
3763 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3764 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3765 		add_to_worklist(&freefrag->ff_list, 0);
3766 	jfreefrag->fr_freefrag = NULL;
3767 	free_jfreefrag(jfreefrag);
3768 }
3769 
3770 /*
3771  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3772  * is removed from the freeblks list of pending journal writes and the
3773  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3774  * have been reclaimed.
3775  */
3776 static void
3777 handle_written_jblkdep(jblkdep)
3778 	struct jblkdep *jblkdep;
3779 {
3780 	struct freeblks *freeblks;
3781 	struct jsegdep *jsegdep;
3782 
3783 	/* Grab the jsegdep. */
3784 	jsegdep = jblkdep->jb_jsegdep;
3785 	jblkdep->jb_jsegdep = NULL;
3786 	freeblks = jblkdep->jb_freeblks;
3787 	LIST_REMOVE(jblkdep, jb_deps);
3788 	jwork_insert(&freeblks->fb_jwork, jsegdep);
3789 	/*
3790 	 * If the freeblks is all journaled, we can add it to the worklist.
3791 	 */
3792 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3793 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3794 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3795 
3796 	free_jblkdep(jblkdep);
3797 }
3798 
3799 static struct jsegdep *
3800 newjsegdep(struct worklist *wk)
3801 {
3802 	struct jsegdep *jsegdep;
3803 
3804 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3805 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3806 	jsegdep->jd_seg = NULL;
3807 
3808 	return (jsegdep);
3809 }
3810 
3811 static struct jmvref *
3812 newjmvref(dp, ino, oldoff, newoff)
3813 	struct inode *dp;
3814 	ino_t ino;
3815 	off_t oldoff;
3816 	off_t newoff;
3817 {
3818 	struct jmvref *jmvref;
3819 
3820 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
3821 	workitem_alloc(&jmvref->jm_list, D_JMVREF, UFSTOVFS(dp->i_ump));
3822 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
3823 	jmvref->jm_parent = dp->i_number;
3824 	jmvref->jm_ino = ino;
3825 	jmvref->jm_oldoff = oldoff;
3826 	jmvref->jm_newoff = newoff;
3827 
3828 	return (jmvref);
3829 }
3830 
3831 /*
3832  * Allocate a new jremref that tracks the removal of ip from dp with the
3833  * directory entry offset of diroff.  Mark the entry as ATTACHED and
3834  * DEPCOMPLETE as we have all the information required for the journal write
3835  * and the directory has already been removed from the buffer.  The caller
3836  * is responsible for linking the jremref into the pagedep and adding it
3837  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
3838  * a DOTDOT addition so handle_workitem_remove() can properly assign
3839  * the jsegdep when we're done.
3840  */
3841 static struct jremref *
3842 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
3843     off_t diroff, nlink_t nlink)
3844 {
3845 	struct jremref *jremref;
3846 
3847 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
3848 	workitem_alloc(&jremref->jr_list, D_JREMREF, UFSTOVFS(dp->i_ump));
3849 	jremref->jr_state = ATTACHED;
3850 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
3851 	   nlink, ip->i_mode);
3852 	jremref->jr_dirrem = dirrem;
3853 
3854 	return (jremref);
3855 }
3856 
3857 static inline void
3858 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
3859     nlink_t nlink, uint16_t mode)
3860 {
3861 
3862 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
3863 	inoref->if_diroff = diroff;
3864 	inoref->if_ino = ino;
3865 	inoref->if_parent = parent;
3866 	inoref->if_nlink = nlink;
3867 	inoref->if_mode = mode;
3868 }
3869 
3870 /*
3871  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
3872  * directory offset may not be known until later.  The caller is responsible
3873  * adding the entry to the journal when this information is available.  nlink
3874  * should be the link count prior to the addition and mode is only required
3875  * to have the correct FMT.
3876  */
3877 static struct jaddref *
3878 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
3879     uint16_t mode)
3880 {
3881 	struct jaddref *jaddref;
3882 
3883 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
3884 	workitem_alloc(&jaddref->ja_list, D_JADDREF, UFSTOVFS(dp->i_ump));
3885 	jaddref->ja_state = ATTACHED;
3886 	jaddref->ja_mkdir = NULL;
3887 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
3888 
3889 	return (jaddref);
3890 }
3891 
3892 /*
3893  * Create a new free dependency for a freework.  The caller is responsible
3894  * for adjusting the reference count when it has the lock held.  The freedep
3895  * will track an outstanding bitmap write that will ultimately clear the
3896  * freework to continue.
3897  */
3898 static struct freedep *
3899 newfreedep(struct freework *freework)
3900 {
3901 	struct freedep *freedep;
3902 
3903 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
3904 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
3905 	freedep->fd_freework = freework;
3906 
3907 	return (freedep);
3908 }
3909 
3910 /*
3911  * Free a freedep structure once the buffer it is linked to is written.  If
3912  * this is the last reference to the freework schedule it for completion.
3913  */
3914 static void
3915 free_freedep(freedep)
3916 	struct freedep *freedep;
3917 {
3918 	struct freework *freework;
3919 
3920 	freework = freedep->fd_freework;
3921 	freework->fw_freeblks->fb_cgwait--;
3922 	if (--freework->fw_ref == 0)
3923 		freework_enqueue(freework);
3924 	WORKITEM_FREE(freedep, D_FREEDEP);
3925 }
3926 
3927 /*
3928  * Allocate a new freework structure that may be a level in an indirect
3929  * when parent is not NULL or a top level block when it is.  The top level
3930  * freework structures are allocated without lk held and before the freeblks
3931  * is visible outside of softdep_setup_freeblocks().
3932  */
3933 static struct freework *
3934 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
3935 	struct ufsmount *ump;
3936 	struct freeblks *freeblks;
3937 	struct freework *parent;
3938 	ufs_lbn_t lbn;
3939 	ufs2_daddr_t nb;
3940 	int frags;
3941 	int off;
3942 	int journal;
3943 {
3944 	struct freework *freework;
3945 
3946 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
3947 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
3948 	freework->fw_state = ATTACHED;
3949 	freework->fw_jnewblk = NULL;
3950 	freework->fw_freeblks = freeblks;
3951 	freework->fw_parent = parent;
3952 	freework->fw_lbn = lbn;
3953 	freework->fw_blkno = nb;
3954 	freework->fw_frags = frags;
3955 	freework->fw_indir = NULL;
3956 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 || lbn >= -NXADDR)
3957 		? 0 : NINDIR(ump->um_fs) + 1;
3958 	freework->fw_start = freework->fw_off = off;
3959 	if (journal)
3960 		newjfreeblk(freeblks, lbn, nb, frags);
3961 	if (parent == NULL) {
3962 		ACQUIRE_LOCK(&lk);
3963 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
3964 		freeblks->fb_ref++;
3965 		FREE_LOCK(&lk);
3966 	}
3967 
3968 	return (freework);
3969 }
3970 
3971 /*
3972  * Eliminate a jfreeblk for a block that does not need journaling.
3973  */
3974 static void
3975 cancel_jfreeblk(freeblks, blkno)
3976 	struct freeblks *freeblks;
3977 	ufs2_daddr_t blkno;
3978 {
3979 	struct jfreeblk *jfreeblk;
3980 	struct jblkdep *jblkdep;
3981 
3982 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
3983 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
3984 			continue;
3985 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
3986 		if (jfreeblk->jf_blkno == blkno)
3987 			break;
3988 	}
3989 	if (jblkdep == NULL)
3990 		return;
3991 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
3992 	free_jsegdep(jblkdep->jb_jsegdep);
3993 	LIST_REMOVE(jblkdep, jb_deps);
3994 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
3995 }
3996 
3997 /*
3998  * Allocate a new jfreeblk to journal top level block pointer when truncating
3999  * a file.  The caller must add this to the worklist when lk is held.
4000  */
4001 static struct jfreeblk *
4002 newjfreeblk(freeblks, lbn, blkno, frags)
4003 	struct freeblks *freeblks;
4004 	ufs_lbn_t lbn;
4005 	ufs2_daddr_t blkno;
4006 	int frags;
4007 {
4008 	struct jfreeblk *jfreeblk;
4009 
4010 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4011 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4012 	    freeblks->fb_list.wk_mp);
4013 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4014 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4015 	jfreeblk->jf_ino = freeblks->fb_inum;
4016 	jfreeblk->jf_lbn = lbn;
4017 	jfreeblk->jf_blkno = blkno;
4018 	jfreeblk->jf_frags = frags;
4019 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4020 
4021 	return (jfreeblk);
4022 }
4023 
4024 /*
4025  * Allocate a new jtrunc to track a partial truncation.
4026  */
4027 static struct jtrunc *
4028 newjtrunc(freeblks, size, extsize)
4029 	struct freeblks *freeblks;
4030 	off_t size;
4031 	int extsize;
4032 {
4033 	struct jtrunc *jtrunc;
4034 
4035 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4036 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4037 	    freeblks->fb_list.wk_mp);
4038 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4039 	jtrunc->jt_dep.jb_freeblks = freeblks;
4040 	jtrunc->jt_ino = freeblks->fb_inum;
4041 	jtrunc->jt_size = size;
4042 	jtrunc->jt_extsize = extsize;
4043 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4044 
4045 	return (jtrunc);
4046 }
4047 
4048 /*
4049  * If we're canceling a new bitmap we have to search for another ref
4050  * to move into the bmsafemap dep.  This might be better expressed
4051  * with another structure.
4052  */
4053 static void
4054 move_newblock_dep(jaddref, inodedep)
4055 	struct jaddref *jaddref;
4056 	struct inodedep *inodedep;
4057 {
4058 	struct inoref *inoref;
4059 	struct jaddref *jaddrefn;
4060 
4061 	jaddrefn = NULL;
4062 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4063 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4064 		if ((jaddref->ja_state & NEWBLOCK) &&
4065 		    inoref->if_list.wk_type == D_JADDREF) {
4066 			jaddrefn = (struct jaddref *)inoref;
4067 			break;
4068 		}
4069 	}
4070 	if (jaddrefn == NULL)
4071 		return;
4072 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4073 	jaddrefn->ja_state |= jaddref->ja_state &
4074 	    (ATTACHED | UNDONE | NEWBLOCK);
4075 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4076 	jaddref->ja_state |= ATTACHED;
4077 	LIST_REMOVE(jaddref, ja_bmdeps);
4078 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4079 	    ja_bmdeps);
4080 }
4081 
4082 /*
4083  * Cancel a jaddref either before it has been written or while it is being
4084  * written.  This happens when a link is removed before the add reaches
4085  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4086  * and inode to prevent the link count or bitmap from reaching the disk
4087  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4088  * required.
4089  *
4090  * Returns 1 if the canceled addref requires journaling of the remove and
4091  * 0 otherwise.
4092  */
4093 static int
4094 cancel_jaddref(jaddref, inodedep, wkhd)
4095 	struct jaddref *jaddref;
4096 	struct inodedep *inodedep;
4097 	struct workhead *wkhd;
4098 {
4099 	struct inoref *inoref;
4100 	struct jsegdep *jsegdep;
4101 	int needsj;
4102 
4103 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4104 	    ("cancel_jaddref: Canceling complete jaddref"));
4105 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4106 		needsj = 1;
4107 	else
4108 		needsj = 0;
4109 	if (inodedep == NULL)
4110 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4111 		    0, &inodedep) == 0)
4112 			panic("cancel_jaddref: Lost inodedep");
4113 	/*
4114 	 * We must adjust the nlink of any reference operation that follows
4115 	 * us so that it is consistent with the in-memory reference.  This
4116 	 * ensures that inode nlink rollbacks always have the correct link.
4117 	 */
4118 	if (needsj == 0) {
4119 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4120 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4121 			if (inoref->if_state & GOINGAWAY)
4122 				break;
4123 			inoref->if_nlink--;
4124 		}
4125 	}
4126 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4127 	if (jaddref->ja_state & NEWBLOCK)
4128 		move_newblock_dep(jaddref, inodedep);
4129 	wake_worklist(&jaddref->ja_list);
4130 	jaddref->ja_mkdir = NULL;
4131 	if (jaddref->ja_state & INPROGRESS) {
4132 		jaddref->ja_state &= ~INPROGRESS;
4133 		WORKLIST_REMOVE(&jaddref->ja_list);
4134 		jwork_insert(wkhd, jsegdep);
4135 	} else {
4136 		free_jsegdep(jsegdep);
4137 		if (jaddref->ja_state & DEPCOMPLETE)
4138 			remove_from_journal(&jaddref->ja_list);
4139 	}
4140 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4141 	/*
4142 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4143 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4144 	 * no longer need this addref attached to the inoreflst and it
4145 	 * will incorrectly adjust nlink if we leave it.
4146 	 */
4147 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4148 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4149 		    if_deps);
4150 		jaddref->ja_state |= COMPLETE;
4151 		free_jaddref(jaddref);
4152 		return (needsj);
4153 	}
4154 	/*
4155 	 * Leave the head of the list for jsegdeps for fast merging.
4156 	 */
4157 	if (LIST_FIRST(wkhd) != NULL) {
4158 		jaddref->ja_state |= ONWORKLIST;
4159 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4160 	} else
4161 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4162 
4163 	return (needsj);
4164 }
4165 
4166 /*
4167  * Attempt to free a jaddref structure when some work completes.  This
4168  * should only succeed once the entry is written and all dependencies have
4169  * been notified.
4170  */
4171 static void
4172 free_jaddref(jaddref)
4173 	struct jaddref *jaddref;
4174 {
4175 
4176 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4177 		return;
4178 	if (jaddref->ja_ref.if_jsegdep)
4179 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4180 		    jaddref, jaddref->ja_state);
4181 	if (jaddref->ja_state & NEWBLOCK)
4182 		LIST_REMOVE(jaddref, ja_bmdeps);
4183 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4184 		panic("free_jaddref: Bad state %p(0x%X)",
4185 		    jaddref, jaddref->ja_state);
4186 	if (jaddref->ja_mkdir != NULL)
4187 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4188 	WORKITEM_FREE(jaddref, D_JADDREF);
4189 }
4190 
4191 /*
4192  * Free a jremref structure once it has been written or discarded.
4193  */
4194 static void
4195 free_jremref(jremref)
4196 	struct jremref *jremref;
4197 {
4198 
4199 	if (jremref->jr_ref.if_jsegdep)
4200 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4201 	if (jremref->jr_state & INPROGRESS)
4202 		panic("free_jremref: IO still pending");
4203 	WORKITEM_FREE(jremref, D_JREMREF);
4204 }
4205 
4206 /*
4207  * Free a jnewblk structure.
4208  */
4209 static void
4210 free_jnewblk(jnewblk)
4211 	struct jnewblk *jnewblk;
4212 {
4213 
4214 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4215 		return;
4216 	LIST_REMOVE(jnewblk, jn_deps);
4217 	if (jnewblk->jn_dep != NULL)
4218 		panic("free_jnewblk: Dependency still attached.");
4219 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4220 }
4221 
4222 /*
4223  * Cancel a jnewblk which has been been made redundant by frag extension.
4224  */
4225 static void
4226 cancel_jnewblk(jnewblk, wkhd)
4227 	struct jnewblk *jnewblk;
4228 	struct workhead *wkhd;
4229 {
4230 	struct jsegdep *jsegdep;
4231 
4232 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4233 	jsegdep = jnewblk->jn_jsegdep;
4234 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4235 		panic("cancel_jnewblk: Invalid state");
4236 	jnewblk->jn_jsegdep  = NULL;
4237 	jnewblk->jn_dep = NULL;
4238 	jnewblk->jn_state |= GOINGAWAY;
4239 	if (jnewblk->jn_state & INPROGRESS) {
4240 		jnewblk->jn_state &= ~INPROGRESS;
4241 		WORKLIST_REMOVE(&jnewblk->jn_list);
4242 		jwork_insert(wkhd, jsegdep);
4243 	} else {
4244 		free_jsegdep(jsegdep);
4245 		remove_from_journal(&jnewblk->jn_list);
4246 	}
4247 	wake_worklist(&jnewblk->jn_list);
4248 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4249 }
4250 
4251 static void
4252 free_jblkdep(jblkdep)
4253 	struct jblkdep *jblkdep;
4254 {
4255 
4256 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4257 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4258 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4259 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4260 	else
4261 		panic("free_jblkdep: Unexpected type %s",
4262 		    TYPENAME(jblkdep->jb_list.wk_type));
4263 }
4264 
4265 /*
4266  * Free a single jseg once it is no longer referenced in memory or on
4267  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4268  * to disappear.
4269  */
4270 static void
4271 free_jseg(jseg, jblocks)
4272 	struct jseg *jseg;
4273 	struct jblocks *jblocks;
4274 {
4275 	struct freework *freework;
4276 
4277 	/*
4278 	 * Free freework structures that were lingering to indicate freed
4279 	 * indirect blocks that forced journal write ordering on reallocate.
4280 	 */
4281 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4282 		indirblk_remove(freework);
4283 	if (jblocks->jb_oldestseg == jseg)
4284 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4285 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4286 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4287 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4288 	    ("free_jseg: Freed jseg has valid entries."));
4289 	WORKITEM_FREE(jseg, D_JSEG);
4290 }
4291 
4292 /*
4293  * Free all jsegs that meet the criteria for being reclaimed and update
4294  * oldestseg.
4295  */
4296 static void
4297 free_jsegs(jblocks)
4298 	struct jblocks *jblocks;
4299 {
4300 	struct jseg *jseg;
4301 
4302 	/*
4303 	 * Free only those jsegs which have none allocated before them to
4304 	 * preserve the journal space ordering.
4305 	 */
4306 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4307 		/*
4308 		 * Only reclaim space when nothing depends on this journal
4309 		 * set and another set has written that it is no longer
4310 		 * valid.
4311 		 */
4312 		if (jseg->js_refs != 0) {
4313 			jblocks->jb_oldestseg = jseg;
4314 			return;
4315 		}
4316 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4317 			break;
4318 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4319 			break;
4320 		/*
4321 		 * We can free jsegs that didn't write entries when
4322 		 * oldestwrseq == js_seq.
4323 		 */
4324 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4325 		    jseg->js_cnt != 0)
4326 			break;
4327 		free_jseg(jseg, jblocks);
4328 	}
4329 	/*
4330 	 * If we exited the loop above we still must discover the
4331 	 * oldest valid segment.
4332 	 */
4333 	if (jseg)
4334 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4335 		     jseg = TAILQ_NEXT(jseg, js_next))
4336 			if (jseg->js_refs != 0)
4337 				break;
4338 	jblocks->jb_oldestseg = jseg;
4339 	/*
4340 	 * The journal has no valid records but some jsegs may still be
4341 	 * waiting on oldestwrseq to advance.  We force a small record
4342 	 * out to permit these lingering records to be reclaimed.
4343 	 */
4344 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4345 		jblocks->jb_needseg = 1;
4346 }
4347 
4348 /*
4349  * Release one reference to a jseg and free it if the count reaches 0.  This
4350  * should eventually reclaim journal space as well.
4351  */
4352 static void
4353 rele_jseg(jseg)
4354 	struct jseg *jseg;
4355 {
4356 
4357 	KASSERT(jseg->js_refs > 0,
4358 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4359 	if (--jseg->js_refs != 0)
4360 		return;
4361 	free_jsegs(jseg->js_jblocks);
4362 }
4363 
4364 /*
4365  * Release a jsegdep and decrement the jseg count.
4366  */
4367 static void
4368 free_jsegdep(jsegdep)
4369 	struct jsegdep *jsegdep;
4370 {
4371 
4372 	if (jsegdep->jd_seg)
4373 		rele_jseg(jsegdep->jd_seg);
4374 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4375 }
4376 
4377 /*
4378  * Wait for a journal item to make it to disk.  Initiate journal processing
4379  * if required.
4380  */
4381 static int
4382 jwait(wk, waitfor)
4383 	struct worklist *wk;
4384 	int waitfor;
4385 {
4386 
4387 	/*
4388 	 * Blocking journal waits cause slow synchronous behavior.  Record
4389 	 * stats on the frequency of these blocking operations.
4390 	 */
4391 	if (waitfor == MNT_WAIT) {
4392 		stat_journal_wait++;
4393 		switch (wk->wk_type) {
4394 		case D_JREMREF:
4395 		case D_JMVREF:
4396 			stat_jwait_filepage++;
4397 			break;
4398 		case D_JTRUNC:
4399 		case D_JFREEBLK:
4400 			stat_jwait_freeblks++;
4401 			break;
4402 		case D_JNEWBLK:
4403 			stat_jwait_newblk++;
4404 			break;
4405 		case D_JADDREF:
4406 			stat_jwait_inode++;
4407 			break;
4408 		default:
4409 			break;
4410 		}
4411 	}
4412 	/*
4413 	 * If IO has not started we process the journal.  We can't mark the
4414 	 * worklist item as IOWAITING because we drop the lock while
4415 	 * processing the journal and the worklist entry may be freed after
4416 	 * this point.  The caller may call back in and re-issue the request.
4417 	 */
4418 	if ((wk->wk_state & INPROGRESS) == 0) {
4419 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4420 		if (waitfor != MNT_WAIT)
4421 			return (EBUSY);
4422 		return (0);
4423 	}
4424 	if (waitfor != MNT_WAIT)
4425 		return (EBUSY);
4426 	wait_worklist(wk, "jwait");
4427 	return (0);
4428 }
4429 
4430 /*
4431  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4432  * appropriate.  This is a convenience function to reduce duplicate code
4433  * for the setup and revert functions below.
4434  */
4435 static struct inodedep *
4436 inodedep_lookup_ip(ip)
4437 	struct inode *ip;
4438 {
4439 	struct inodedep *inodedep;
4440 	int dflags;
4441 
4442 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4443 	    ("inodedep_lookup_ip: bad delta"));
4444 	dflags = DEPALLOC;
4445 	if (IS_SNAPSHOT(ip))
4446 		dflags |= NODELAY;
4447 	(void) inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags,
4448 	    &inodedep);
4449 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4450 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4451 
4452 	return (inodedep);
4453 }
4454 
4455 /*
4456  * Called prior to creating a new inode and linking it to a directory.  The
4457  * jaddref structure must already be allocated by softdep_setup_inomapdep
4458  * and it is discovered here so we can initialize the mode and update
4459  * nlinkdelta.
4460  */
4461 void
4462 softdep_setup_create(dp, ip)
4463 	struct inode *dp;
4464 	struct inode *ip;
4465 {
4466 	struct inodedep *inodedep;
4467 	struct jaddref *jaddref;
4468 	struct vnode *dvp;
4469 
4470 	KASSERT(ip->i_nlink == 1,
4471 	    ("softdep_setup_create: Invalid link count."));
4472 	dvp = ITOV(dp);
4473 	ACQUIRE_LOCK(&lk);
4474 	inodedep = inodedep_lookup_ip(ip);
4475 	if (DOINGSUJ(dvp)) {
4476 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4477 		    inoreflst);
4478 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4479 		    ("softdep_setup_create: No addref structure present."));
4480 	}
4481 	softdep_prelink(dvp, NULL);
4482 	FREE_LOCK(&lk);
4483 }
4484 
4485 /*
4486  * Create a jaddref structure to track the addition of a DOTDOT link when
4487  * we are reparenting an inode as part of a rename.  This jaddref will be
4488  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4489  * non-journaling softdep.
4490  */
4491 void
4492 softdep_setup_dotdot_link(dp, ip)
4493 	struct inode *dp;
4494 	struct inode *ip;
4495 {
4496 	struct inodedep *inodedep;
4497 	struct jaddref *jaddref;
4498 	struct vnode *dvp;
4499 	struct vnode *vp;
4500 
4501 	dvp = ITOV(dp);
4502 	vp = ITOV(ip);
4503 	jaddref = NULL;
4504 	/*
4505 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4506 	 * is used as a normal link would be.
4507 	 */
4508 	if (DOINGSUJ(dvp))
4509 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4510 		    dp->i_effnlink - 1, dp->i_mode);
4511 	ACQUIRE_LOCK(&lk);
4512 	inodedep = inodedep_lookup_ip(dp);
4513 	if (jaddref)
4514 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4515 		    if_deps);
4516 	softdep_prelink(dvp, ITOV(ip));
4517 	FREE_LOCK(&lk);
4518 }
4519 
4520 /*
4521  * Create a jaddref structure to track a new link to an inode.  The directory
4522  * offset is not known until softdep_setup_directory_add or
4523  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4524  * softdep.
4525  */
4526 void
4527 softdep_setup_link(dp, ip)
4528 	struct inode *dp;
4529 	struct inode *ip;
4530 {
4531 	struct inodedep *inodedep;
4532 	struct jaddref *jaddref;
4533 	struct vnode *dvp;
4534 
4535 	dvp = ITOV(dp);
4536 	jaddref = NULL;
4537 	if (DOINGSUJ(dvp))
4538 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4539 		    ip->i_mode);
4540 	ACQUIRE_LOCK(&lk);
4541 	inodedep = inodedep_lookup_ip(ip);
4542 	if (jaddref)
4543 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4544 		    if_deps);
4545 	softdep_prelink(dvp, ITOV(ip));
4546 	FREE_LOCK(&lk);
4547 }
4548 
4549 /*
4550  * Called to create the jaddref structures to track . and .. references as
4551  * well as lookup and further initialize the incomplete jaddref created
4552  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4553  * nlinkdelta for non-journaling softdep.
4554  */
4555 void
4556 softdep_setup_mkdir(dp, ip)
4557 	struct inode *dp;
4558 	struct inode *ip;
4559 {
4560 	struct inodedep *inodedep;
4561 	struct jaddref *dotdotaddref;
4562 	struct jaddref *dotaddref;
4563 	struct jaddref *jaddref;
4564 	struct vnode *dvp;
4565 
4566 	dvp = ITOV(dp);
4567 	dotaddref = dotdotaddref = NULL;
4568 	if (DOINGSUJ(dvp)) {
4569 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4570 		    ip->i_mode);
4571 		dotaddref->ja_state |= MKDIR_BODY;
4572 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4573 		    dp->i_effnlink - 1, dp->i_mode);
4574 		dotdotaddref->ja_state |= MKDIR_PARENT;
4575 	}
4576 	ACQUIRE_LOCK(&lk);
4577 	inodedep = inodedep_lookup_ip(ip);
4578 	if (DOINGSUJ(dvp)) {
4579 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4580 		    inoreflst);
4581 		KASSERT(jaddref != NULL,
4582 		    ("softdep_setup_mkdir: No addref structure present."));
4583 		KASSERT(jaddref->ja_parent == dp->i_number,
4584 		    ("softdep_setup_mkdir: bad parent %ju",
4585 		    (uintmax_t)jaddref->ja_parent));
4586 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4587 		    if_deps);
4588 	}
4589 	inodedep = inodedep_lookup_ip(dp);
4590 	if (DOINGSUJ(dvp))
4591 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4592 		    &dotdotaddref->ja_ref, if_deps);
4593 	softdep_prelink(ITOV(dp), NULL);
4594 	FREE_LOCK(&lk);
4595 }
4596 
4597 /*
4598  * Called to track nlinkdelta of the inode and parent directories prior to
4599  * unlinking a directory.
4600  */
4601 void
4602 softdep_setup_rmdir(dp, ip)
4603 	struct inode *dp;
4604 	struct inode *ip;
4605 {
4606 	struct vnode *dvp;
4607 
4608 	dvp = ITOV(dp);
4609 	ACQUIRE_LOCK(&lk);
4610 	(void) inodedep_lookup_ip(ip);
4611 	(void) inodedep_lookup_ip(dp);
4612 	softdep_prelink(dvp, ITOV(ip));
4613 	FREE_LOCK(&lk);
4614 }
4615 
4616 /*
4617  * Called to track nlinkdelta of the inode and parent directories prior to
4618  * unlink.
4619  */
4620 void
4621 softdep_setup_unlink(dp, ip)
4622 	struct inode *dp;
4623 	struct inode *ip;
4624 {
4625 	struct vnode *dvp;
4626 
4627 	dvp = ITOV(dp);
4628 	ACQUIRE_LOCK(&lk);
4629 	(void) inodedep_lookup_ip(ip);
4630 	(void) inodedep_lookup_ip(dp);
4631 	softdep_prelink(dvp, ITOV(ip));
4632 	FREE_LOCK(&lk);
4633 }
4634 
4635 /*
4636  * Called to release the journal structures created by a failed non-directory
4637  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4638  */
4639 void
4640 softdep_revert_create(dp, ip)
4641 	struct inode *dp;
4642 	struct inode *ip;
4643 {
4644 	struct inodedep *inodedep;
4645 	struct jaddref *jaddref;
4646 	struct vnode *dvp;
4647 
4648 	dvp = ITOV(dp);
4649 	ACQUIRE_LOCK(&lk);
4650 	inodedep = inodedep_lookup_ip(ip);
4651 	if (DOINGSUJ(dvp)) {
4652 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4653 		    inoreflst);
4654 		KASSERT(jaddref->ja_parent == dp->i_number,
4655 		    ("softdep_revert_create: addref parent mismatch"));
4656 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4657 	}
4658 	FREE_LOCK(&lk);
4659 }
4660 
4661 /*
4662  * Called to release the journal structures created by a failed dotdot link
4663  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4664  */
4665 void
4666 softdep_revert_dotdot_link(dp, ip)
4667 	struct inode *dp;
4668 	struct inode *ip;
4669 {
4670 	struct inodedep *inodedep;
4671 	struct jaddref *jaddref;
4672 	struct vnode *dvp;
4673 
4674 	dvp = ITOV(dp);
4675 	ACQUIRE_LOCK(&lk);
4676 	inodedep = inodedep_lookup_ip(dp);
4677 	if (DOINGSUJ(dvp)) {
4678 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4679 		    inoreflst);
4680 		KASSERT(jaddref->ja_parent == ip->i_number,
4681 		    ("softdep_revert_dotdot_link: addref parent mismatch"));
4682 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4683 	}
4684 	FREE_LOCK(&lk);
4685 }
4686 
4687 /*
4688  * Called to release the journal structures created by a failed link
4689  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4690  */
4691 void
4692 softdep_revert_link(dp, ip)
4693 	struct inode *dp;
4694 	struct inode *ip;
4695 {
4696 	struct inodedep *inodedep;
4697 	struct jaddref *jaddref;
4698 	struct vnode *dvp;
4699 
4700 	dvp = ITOV(dp);
4701 	ACQUIRE_LOCK(&lk);
4702 	inodedep = inodedep_lookup_ip(ip);
4703 	if (DOINGSUJ(dvp)) {
4704 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4705 		    inoreflst);
4706 		KASSERT(jaddref->ja_parent == dp->i_number,
4707 		    ("softdep_revert_link: addref parent mismatch"));
4708 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4709 	}
4710 	FREE_LOCK(&lk);
4711 }
4712 
4713 /*
4714  * Called to release the journal structures created by a failed mkdir
4715  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4716  */
4717 void
4718 softdep_revert_mkdir(dp, ip)
4719 	struct inode *dp;
4720 	struct inode *ip;
4721 {
4722 	struct inodedep *inodedep;
4723 	struct jaddref *jaddref;
4724 	struct jaddref *dotaddref;
4725 	struct vnode *dvp;
4726 
4727 	dvp = ITOV(dp);
4728 
4729 	ACQUIRE_LOCK(&lk);
4730 	inodedep = inodedep_lookup_ip(dp);
4731 	if (DOINGSUJ(dvp)) {
4732 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4733 		    inoreflst);
4734 		KASSERT(jaddref->ja_parent == ip->i_number,
4735 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4736 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4737 	}
4738 	inodedep = inodedep_lookup_ip(ip);
4739 	if (DOINGSUJ(dvp)) {
4740 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4741 		    inoreflst);
4742 		KASSERT(jaddref->ja_parent == dp->i_number,
4743 		    ("softdep_revert_mkdir: addref parent mismatch"));
4744 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4745 		    inoreflst, if_deps);
4746 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4747 		KASSERT(dotaddref->ja_parent == ip->i_number,
4748 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4749 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4750 	}
4751 	FREE_LOCK(&lk);
4752 }
4753 
4754 /*
4755  * Called to correct nlinkdelta after a failed rmdir.
4756  */
4757 void
4758 softdep_revert_rmdir(dp, ip)
4759 	struct inode *dp;
4760 	struct inode *ip;
4761 {
4762 
4763 	ACQUIRE_LOCK(&lk);
4764 	(void) inodedep_lookup_ip(ip);
4765 	(void) inodedep_lookup_ip(dp);
4766 	FREE_LOCK(&lk);
4767 }
4768 
4769 /*
4770  * Protecting the freemaps (or bitmaps).
4771  *
4772  * To eliminate the need to execute fsck before mounting a filesystem
4773  * after a power failure, one must (conservatively) guarantee that the
4774  * on-disk copy of the bitmaps never indicate that a live inode or block is
4775  * free.  So, when a block or inode is allocated, the bitmap should be
4776  * updated (on disk) before any new pointers.  When a block or inode is
4777  * freed, the bitmap should not be updated until all pointers have been
4778  * reset.  The latter dependency is handled by the delayed de-allocation
4779  * approach described below for block and inode de-allocation.  The former
4780  * dependency is handled by calling the following procedure when a block or
4781  * inode is allocated. When an inode is allocated an "inodedep" is created
4782  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4783  * Each "inodedep" is also inserted into the hash indexing structure so
4784  * that any additional link additions can be made dependent on the inode
4785  * allocation.
4786  *
4787  * The ufs filesystem maintains a number of free block counts (e.g., per
4788  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4789  * in addition to the bitmaps.  These counts are used to improve efficiency
4790  * during allocation and therefore must be consistent with the bitmaps.
4791  * There is no convenient way to guarantee post-crash consistency of these
4792  * counts with simple update ordering, for two main reasons: (1) The counts
4793  * and bitmaps for a single cylinder group block are not in the same disk
4794  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4795  * be written and the other not.  (2) Some of the counts are located in the
4796  * superblock rather than the cylinder group block. So, we focus our soft
4797  * updates implementation on protecting the bitmaps. When mounting a
4798  * filesystem, we recompute the auxiliary counts from the bitmaps.
4799  */
4800 
4801 /*
4802  * Called just after updating the cylinder group block to allocate an inode.
4803  */
4804 void
4805 softdep_setup_inomapdep(bp, ip, newinum, mode)
4806 	struct buf *bp;		/* buffer for cylgroup block with inode map */
4807 	struct inode *ip;	/* inode related to allocation */
4808 	ino_t newinum;		/* new inode number being allocated */
4809 	int mode;
4810 {
4811 	struct inodedep *inodedep;
4812 	struct bmsafemap *bmsafemap;
4813 	struct jaddref *jaddref;
4814 	struct mount *mp;
4815 	struct fs *fs;
4816 
4817 	mp = UFSTOVFS(ip->i_ump);
4818 	fs = ip->i_ump->um_fs;
4819 	jaddref = NULL;
4820 
4821 	/*
4822 	 * Allocate the journal reference add structure so that the bitmap
4823 	 * can be dependent on it.
4824 	 */
4825 	if (MOUNTEDSUJ(mp)) {
4826 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
4827 		jaddref->ja_state |= NEWBLOCK;
4828 	}
4829 
4830 	/*
4831 	 * Create a dependency for the newly allocated inode.
4832 	 * Panic if it already exists as something is seriously wrong.
4833 	 * Otherwise add it to the dependency list for the buffer holding
4834 	 * the cylinder group map from which it was allocated.
4835 	 *
4836 	 * We have to preallocate a bmsafemap entry in case it is needed
4837 	 * in bmsafemap_lookup since once we allocate the inodedep, we
4838 	 * have to finish initializing it before we can FREE_LOCK().
4839 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
4840 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
4841 	 * creating the inodedep as it can be freed during the time
4842 	 * that we FREE_LOCK() while allocating the inodedep. We must
4843 	 * call workitem_alloc() before entering the locked section as
4844 	 * it also acquires the lock and we must avoid trying doing so
4845 	 * recursively.
4846 	 */
4847 	bmsafemap = malloc(sizeof(struct bmsafemap),
4848 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
4849 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
4850 	ACQUIRE_LOCK(&lk);
4851 	if ((inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep)))
4852 		panic("softdep_setup_inomapdep: dependency %p for new"
4853 		    "inode already exists", inodedep);
4854 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
4855 	if (jaddref) {
4856 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
4857 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4858 		    if_deps);
4859 	} else {
4860 		inodedep->id_state |= ONDEPLIST;
4861 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
4862 	}
4863 	inodedep->id_bmsafemap = bmsafemap;
4864 	inodedep->id_state &= ~DEPCOMPLETE;
4865 	FREE_LOCK(&lk);
4866 }
4867 
4868 /*
4869  * Called just after updating the cylinder group block to
4870  * allocate block or fragment.
4871  */
4872 void
4873 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
4874 	struct buf *bp;		/* buffer for cylgroup block with block map */
4875 	struct mount *mp;	/* filesystem doing allocation */
4876 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
4877 	int frags;		/* Number of fragments. */
4878 	int oldfrags;		/* Previous number of fragments for extend. */
4879 {
4880 	struct newblk *newblk;
4881 	struct bmsafemap *bmsafemap;
4882 	struct jnewblk *jnewblk;
4883 	struct fs *fs;
4884 
4885 	fs = VFSTOUFS(mp)->um_fs;
4886 	jnewblk = NULL;
4887 	/*
4888 	 * Create a dependency for the newly allocated block.
4889 	 * Add it to the dependency list for the buffer holding
4890 	 * the cylinder group map from which it was allocated.
4891 	 */
4892 	if (MOUNTEDSUJ(mp)) {
4893 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
4894 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
4895 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
4896 		jnewblk->jn_state = ATTACHED;
4897 		jnewblk->jn_blkno = newblkno;
4898 		jnewblk->jn_frags = frags;
4899 		jnewblk->jn_oldfrags = oldfrags;
4900 #ifdef SUJ_DEBUG
4901 		{
4902 			struct cg *cgp;
4903 			uint8_t *blksfree;
4904 			long bno;
4905 			int i;
4906 
4907 			cgp = (struct cg *)bp->b_data;
4908 			blksfree = cg_blksfree(cgp);
4909 			bno = dtogd(fs, jnewblk->jn_blkno);
4910 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
4911 			    i++) {
4912 				if (isset(blksfree, bno + i))
4913 					panic("softdep_setup_blkmapdep: "
4914 					    "free fragment %d from %d-%d "
4915 					    "state 0x%X dep %p", i,
4916 					    jnewblk->jn_oldfrags,
4917 					    jnewblk->jn_frags,
4918 					    jnewblk->jn_state,
4919 					    jnewblk->jn_dep);
4920 			}
4921 		}
4922 #endif
4923 	}
4924 
4925 	CTR3(KTR_SUJ,
4926 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
4927 	    newblkno, frags, oldfrags);
4928 	ACQUIRE_LOCK(&lk);
4929 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
4930 		panic("softdep_setup_blkmapdep: found block");
4931 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
4932 	    dtog(fs, newblkno), NULL);
4933 	if (jnewblk) {
4934 		jnewblk->jn_dep = (struct worklist *)newblk;
4935 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
4936 	} else {
4937 		newblk->nb_state |= ONDEPLIST;
4938 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
4939 	}
4940 	newblk->nb_bmsafemap = bmsafemap;
4941 	newblk->nb_jnewblk = jnewblk;
4942 	FREE_LOCK(&lk);
4943 }
4944 
4945 #define	BMSAFEMAP_HASH(fs, cg) \
4946       (&bmsafemap_hashtbl[((((register_t)(fs)) >> 13) + (cg)) & bmsafemap_hash])
4947 
4948 static int
4949 bmsafemap_find(bmsafemaphd, mp, cg, bmsafemapp)
4950 	struct bmsafemap_hashhead *bmsafemaphd;
4951 	struct mount *mp;
4952 	int cg;
4953 	struct bmsafemap **bmsafemapp;
4954 {
4955 	struct bmsafemap *bmsafemap;
4956 
4957 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
4958 		if (bmsafemap->sm_list.wk_mp == mp && bmsafemap->sm_cg == cg)
4959 			break;
4960 	if (bmsafemap) {
4961 		*bmsafemapp = bmsafemap;
4962 		return (1);
4963 	}
4964 	*bmsafemapp = NULL;
4965 
4966 	return (0);
4967 }
4968 
4969 /*
4970  * Find the bmsafemap associated with a cylinder group buffer.
4971  * If none exists, create one. The buffer must be locked when
4972  * this routine is called and this routine must be called with
4973  * the softdep lock held. To avoid giving up the lock while
4974  * allocating a new bmsafemap, a preallocated bmsafemap may be
4975  * provided. If it is provided but not needed, it is freed.
4976  */
4977 static struct bmsafemap *
4978 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
4979 	struct mount *mp;
4980 	struct buf *bp;
4981 	int cg;
4982 	struct bmsafemap *newbmsafemap;
4983 {
4984 	struct bmsafemap_hashhead *bmsafemaphd;
4985 	struct bmsafemap *bmsafemap, *collision;
4986 	struct worklist *wk;
4987 	struct fs *fs;
4988 
4989 	mtx_assert(&lk, MA_OWNED);
4990 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
4991 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4992 		if (wk->wk_type == D_BMSAFEMAP) {
4993 			if (newbmsafemap)
4994 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
4995 			return (WK_BMSAFEMAP(wk));
4996 		}
4997 	}
4998 	fs = VFSTOUFS(mp)->um_fs;
4999 	bmsafemaphd = BMSAFEMAP_HASH(fs, cg);
5000 	if (bmsafemap_find(bmsafemaphd, mp, cg, &bmsafemap) == 1) {
5001 		if (newbmsafemap)
5002 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5003 		return (bmsafemap);
5004 	}
5005 	if (newbmsafemap) {
5006 		bmsafemap = newbmsafemap;
5007 	} else {
5008 		FREE_LOCK(&lk);
5009 		bmsafemap = malloc(sizeof(struct bmsafemap),
5010 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5011 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5012 		ACQUIRE_LOCK(&lk);
5013 	}
5014 	bmsafemap->sm_buf = bp;
5015 	LIST_INIT(&bmsafemap->sm_inodedephd);
5016 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5017 	LIST_INIT(&bmsafemap->sm_newblkhd);
5018 	LIST_INIT(&bmsafemap->sm_newblkwr);
5019 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5020 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5021 	LIST_INIT(&bmsafemap->sm_freehd);
5022 	LIST_INIT(&bmsafemap->sm_freewr);
5023 	if (bmsafemap_find(bmsafemaphd, mp, cg, &collision) == 1) {
5024 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5025 		return (collision);
5026 	}
5027 	bmsafemap->sm_cg = cg;
5028 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5029 	LIST_INSERT_HEAD(&VFSTOUFS(mp)->softdep_dirtycg, bmsafemap, sm_next);
5030 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5031 	return (bmsafemap);
5032 }
5033 
5034 /*
5035  * Direct block allocation dependencies.
5036  *
5037  * When a new block is allocated, the corresponding disk locations must be
5038  * initialized (with zeros or new data) before the on-disk inode points to
5039  * them.  Also, the freemap from which the block was allocated must be
5040  * updated (on disk) before the inode's pointer. These two dependencies are
5041  * independent of each other and are needed for all file blocks and indirect
5042  * blocks that are pointed to directly by the inode.  Just before the
5043  * "in-core" version of the inode is updated with a newly allocated block
5044  * number, a procedure (below) is called to setup allocation dependency
5045  * structures.  These structures are removed when the corresponding
5046  * dependencies are satisfied or when the block allocation becomes obsolete
5047  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5048  * fragment that gets upgraded).  All of these cases are handled in
5049  * procedures described later.
5050  *
5051  * When a file extension causes a fragment to be upgraded, either to a larger
5052  * fragment or to a full block, the on-disk location may change (if the
5053  * previous fragment could not simply be extended). In this case, the old
5054  * fragment must be de-allocated, but not until after the inode's pointer has
5055  * been updated. In most cases, this is handled by later procedures, which
5056  * will construct a "freefrag" structure to be added to the workitem queue
5057  * when the inode update is complete (or obsolete).  The main exception to
5058  * this is when an allocation occurs while a pending allocation dependency
5059  * (for the same block pointer) remains.  This case is handled in the main
5060  * allocation dependency setup procedure by immediately freeing the
5061  * unreferenced fragments.
5062  */
5063 void
5064 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5065 	struct inode *ip;	/* inode to which block is being added */
5066 	ufs_lbn_t off;		/* block pointer within inode */
5067 	ufs2_daddr_t newblkno;	/* disk block number being added */
5068 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5069 	long newsize;		/* size of new block */
5070 	long oldsize;		/* size of new block */
5071 	struct buf *bp;		/* bp for allocated block */
5072 {
5073 	struct allocdirect *adp, *oldadp;
5074 	struct allocdirectlst *adphead;
5075 	struct freefrag *freefrag;
5076 	struct inodedep *inodedep;
5077 	struct pagedep *pagedep;
5078 	struct jnewblk *jnewblk;
5079 	struct newblk *newblk;
5080 	struct mount *mp;
5081 	ufs_lbn_t lbn;
5082 
5083 	lbn = bp->b_lblkno;
5084 	mp = UFSTOVFS(ip->i_ump);
5085 	if (oldblkno && oldblkno != newblkno)
5086 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5087 	else
5088 		freefrag = NULL;
5089 
5090 	CTR6(KTR_SUJ,
5091 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5092 	    "off %jd newsize %ld oldsize %d",
5093 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5094 	ACQUIRE_LOCK(&lk);
5095 	if (off >= NDADDR) {
5096 		if (lbn > 0)
5097 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5098 			    lbn, off);
5099 		/* allocating an indirect block */
5100 		if (oldblkno != 0)
5101 			panic("softdep_setup_allocdirect: non-zero indir");
5102 	} else {
5103 		if (off != lbn)
5104 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5105 			    lbn, off);
5106 		/*
5107 		 * Allocating a direct block.
5108 		 *
5109 		 * If we are allocating a directory block, then we must
5110 		 * allocate an associated pagedep to track additions and
5111 		 * deletions.
5112 		 */
5113 		if ((ip->i_mode & IFMT) == IFDIR)
5114 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5115 			    &pagedep);
5116 	}
5117 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5118 		panic("softdep_setup_allocdirect: lost block");
5119 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5120 	    ("softdep_setup_allocdirect: newblk already initialized"));
5121 	/*
5122 	 * Convert the newblk to an allocdirect.
5123 	 */
5124 	newblk->nb_list.wk_type = D_ALLOCDIRECT;
5125 	adp = (struct allocdirect *)newblk;
5126 	newblk->nb_freefrag = freefrag;
5127 	adp->ad_offset = off;
5128 	adp->ad_oldblkno = oldblkno;
5129 	adp->ad_newsize = newsize;
5130 	adp->ad_oldsize = oldsize;
5131 
5132 	/*
5133 	 * Finish initializing the journal.
5134 	 */
5135 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5136 		jnewblk->jn_ino = ip->i_number;
5137 		jnewblk->jn_lbn = lbn;
5138 		add_to_journal(&jnewblk->jn_list);
5139 	}
5140 	if (freefrag && freefrag->ff_jdep != NULL &&
5141 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5142 		add_to_journal(freefrag->ff_jdep);
5143 	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
5144 	adp->ad_inodedep = inodedep;
5145 
5146 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5147 	/*
5148 	 * The list of allocdirects must be kept in sorted and ascending
5149 	 * order so that the rollback routines can quickly determine the
5150 	 * first uncommitted block (the size of the file stored on disk
5151 	 * ends at the end of the lowest committed fragment, or if there
5152 	 * are no fragments, at the end of the highest committed block).
5153 	 * Since files generally grow, the typical case is that the new
5154 	 * block is to be added at the end of the list. We speed this
5155 	 * special case by checking against the last allocdirect in the
5156 	 * list before laboriously traversing the list looking for the
5157 	 * insertion point.
5158 	 */
5159 	adphead = &inodedep->id_newinoupdt;
5160 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5161 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5162 		/* insert at end of list */
5163 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5164 		if (oldadp != NULL && oldadp->ad_offset == off)
5165 			allocdirect_merge(adphead, adp, oldadp);
5166 		FREE_LOCK(&lk);
5167 		return;
5168 	}
5169 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5170 		if (oldadp->ad_offset >= off)
5171 			break;
5172 	}
5173 	if (oldadp == NULL)
5174 		panic("softdep_setup_allocdirect: lost entry");
5175 	/* insert in middle of list */
5176 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5177 	if (oldadp->ad_offset == off)
5178 		allocdirect_merge(adphead, adp, oldadp);
5179 
5180 	FREE_LOCK(&lk);
5181 }
5182 
5183 /*
5184  * Merge a newer and older journal record to be stored either in a
5185  * newblock or freefrag.  This handles aggregating journal records for
5186  * fragment allocation into a second record as well as replacing a
5187  * journal free with an aborted journal allocation.  A segment for the
5188  * oldest record will be placed on wkhd if it has been written.  If not
5189  * the segment for the newer record will suffice.
5190  */
5191 static struct worklist *
5192 jnewblk_merge(new, old, wkhd)
5193 	struct worklist *new;
5194 	struct worklist *old;
5195 	struct workhead *wkhd;
5196 {
5197 	struct jnewblk *njnewblk;
5198 	struct jnewblk *jnewblk;
5199 
5200 	/* Handle NULLs to simplify callers. */
5201 	if (new == NULL)
5202 		return (old);
5203 	if (old == NULL)
5204 		return (new);
5205 	/* Replace a jfreefrag with a jnewblk. */
5206 	if (new->wk_type == D_JFREEFRAG) {
5207 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5208 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5209 			    old, new);
5210 		cancel_jfreefrag(WK_JFREEFRAG(new));
5211 		return (old);
5212 	}
5213 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5214 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5215 		    old->wk_type, new->wk_type);
5216 	/*
5217 	 * Handle merging of two jnewblk records that describe
5218 	 * different sets of fragments in the same block.
5219 	 */
5220 	jnewblk = WK_JNEWBLK(old);
5221 	njnewblk = WK_JNEWBLK(new);
5222 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5223 		panic("jnewblk_merge: Merging disparate blocks.");
5224 	/*
5225 	 * The record may be rolled back in the cg.
5226 	 */
5227 	if (jnewblk->jn_state & UNDONE) {
5228 		jnewblk->jn_state &= ~UNDONE;
5229 		njnewblk->jn_state |= UNDONE;
5230 		njnewblk->jn_state &= ~ATTACHED;
5231 	}
5232 	/*
5233 	 * We modify the newer addref and free the older so that if neither
5234 	 * has been written the most up-to-date copy will be on disk.  If
5235 	 * both have been written but rolled back we only temporarily need
5236 	 * one of them to fix the bits when the cg write completes.
5237 	 */
5238 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5239 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5240 	cancel_jnewblk(jnewblk, wkhd);
5241 	WORKLIST_REMOVE(&jnewblk->jn_list);
5242 	free_jnewblk(jnewblk);
5243 	return (new);
5244 }
5245 
5246 /*
5247  * Replace an old allocdirect dependency with a newer one.
5248  * This routine must be called with splbio interrupts blocked.
5249  */
5250 static void
5251 allocdirect_merge(adphead, newadp, oldadp)
5252 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5253 	struct allocdirect *newadp;	/* allocdirect being added */
5254 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5255 {
5256 	struct worklist *wk;
5257 	struct freefrag *freefrag;
5258 
5259 	freefrag = NULL;
5260 	mtx_assert(&lk, MA_OWNED);
5261 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5262 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5263 	    newadp->ad_offset >= NDADDR)
5264 		panic("%s %jd != new %jd || old size %ld != new %ld",
5265 		    "allocdirect_merge: old blkno",
5266 		    (intmax_t)newadp->ad_oldblkno,
5267 		    (intmax_t)oldadp->ad_newblkno,
5268 		    newadp->ad_oldsize, oldadp->ad_newsize);
5269 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5270 	newadp->ad_oldsize = oldadp->ad_oldsize;
5271 	/*
5272 	 * If the old dependency had a fragment to free or had never
5273 	 * previously had a block allocated, then the new dependency
5274 	 * can immediately post its freefrag and adopt the old freefrag.
5275 	 * This action is done by swapping the freefrag dependencies.
5276 	 * The new dependency gains the old one's freefrag, and the
5277 	 * old one gets the new one and then immediately puts it on
5278 	 * the worklist when it is freed by free_newblk. It is
5279 	 * not possible to do this swap when the old dependency had a
5280 	 * non-zero size but no previous fragment to free. This condition
5281 	 * arises when the new block is an extension of the old block.
5282 	 * Here, the first part of the fragment allocated to the new
5283 	 * dependency is part of the block currently claimed on disk by
5284 	 * the old dependency, so cannot legitimately be freed until the
5285 	 * conditions for the new dependency are fulfilled.
5286 	 */
5287 	freefrag = newadp->ad_freefrag;
5288 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5289 		newadp->ad_freefrag = oldadp->ad_freefrag;
5290 		oldadp->ad_freefrag = freefrag;
5291 	}
5292 	/*
5293 	 * If we are tracking a new directory-block allocation,
5294 	 * move it from the old allocdirect to the new allocdirect.
5295 	 */
5296 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5297 		WORKLIST_REMOVE(wk);
5298 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5299 			panic("allocdirect_merge: extra newdirblk");
5300 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5301 	}
5302 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5303 	/*
5304 	 * We need to move any journal dependencies over to the freefrag
5305 	 * that releases this block if it exists.  Otherwise we are
5306 	 * extending an existing block and we'll wait until that is
5307 	 * complete to release the journal space and extend the
5308 	 * new journal to cover this old space as well.
5309 	 */
5310 	if (freefrag == NULL) {
5311 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5312 			panic("allocdirect_merge: %jd != %jd",
5313 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5314 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5315 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5316 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5317 		    &newadp->ad_block.nb_jwork);
5318 		oldadp->ad_block.nb_jnewblk = NULL;
5319 		cancel_newblk(&oldadp->ad_block, NULL,
5320 		    &newadp->ad_block.nb_jwork);
5321 	} else {
5322 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5323 		    &freefrag->ff_list, &freefrag->ff_jwork);
5324 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5325 		    &freefrag->ff_jwork);
5326 	}
5327 	free_newblk(&oldadp->ad_block);
5328 }
5329 
5330 /*
5331  * Allocate a jfreefrag structure to journal a single block free.
5332  */
5333 static struct jfreefrag *
5334 newjfreefrag(freefrag, ip, blkno, size, lbn)
5335 	struct freefrag *freefrag;
5336 	struct inode *ip;
5337 	ufs2_daddr_t blkno;
5338 	long size;
5339 	ufs_lbn_t lbn;
5340 {
5341 	struct jfreefrag *jfreefrag;
5342 	struct fs *fs;
5343 
5344 	fs = ip->i_fs;
5345 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5346 	    M_SOFTDEP_FLAGS);
5347 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, UFSTOVFS(ip->i_ump));
5348 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5349 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5350 	jfreefrag->fr_ino = ip->i_number;
5351 	jfreefrag->fr_lbn = lbn;
5352 	jfreefrag->fr_blkno = blkno;
5353 	jfreefrag->fr_frags = numfrags(fs, size);
5354 	jfreefrag->fr_freefrag = freefrag;
5355 
5356 	return (jfreefrag);
5357 }
5358 
5359 /*
5360  * Allocate a new freefrag structure.
5361  */
5362 static struct freefrag *
5363 newfreefrag(ip, blkno, size, lbn)
5364 	struct inode *ip;
5365 	ufs2_daddr_t blkno;
5366 	long size;
5367 	ufs_lbn_t lbn;
5368 {
5369 	struct freefrag *freefrag;
5370 	struct fs *fs;
5371 
5372 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5373 	    ip->i_number, blkno, size, lbn);
5374 	fs = ip->i_fs;
5375 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5376 		panic("newfreefrag: frag size");
5377 	freefrag = malloc(sizeof(struct freefrag),
5378 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5379 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ip->i_ump));
5380 	freefrag->ff_state = ATTACHED;
5381 	LIST_INIT(&freefrag->ff_jwork);
5382 	freefrag->ff_inum = ip->i_number;
5383 	freefrag->ff_vtype = ITOV(ip)->v_type;
5384 	freefrag->ff_blkno = blkno;
5385 	freefrag->ff_fragsize = size;
5386 
5387 	if (MOUNTEDSUJ(UFSTOVFS(ip->i_ump))) {
5388 		freefrag->ff_jdep = (struct worklist *)
5389 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5390 	} else {
5391 		freefrag->ff_state |= DEPCOMPLETE;
5392 		freefrag->ff_jdep = NULL;
5393 	}
5394 
5395 	return (freefrag);
5396 }
5397 
5398 /*
5399  * This workitem de-allocates fragments that were replaced during
5400  * file block allocation.
5401  */
5402 static void
5403 handle_workitem_freefrag(freefrag)
5404 	struct freefrag *freefrag;
5405 {
5406 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5407 	struct workhead wkhd;
5408 
5409 	CTR3(KTR_SUJ,
5410 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5411 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5412 	/*
5413 	 * It would be illegal to add new completion items to the
5414 	 * freefrag after it was schedule to be done so it must be
5415 	 * safe to modify the list head here.
5416 	 */
5417 	LIST_INIT(&wkhd);
5418 	ACQUIRE_LOCK(&lk);
5419 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5420 	/*
5421 	 * If the journal has not been written we must cancel it here.
5422 	 */
5423 	if (freefrag->ff_jdep) {
5424 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5425 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5426 			    freefrag->ff_jdep->wk_type);
5427 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5428 	}
5429 	FREE_LOCK(&lk);
5430 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5431 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5432 	ACQUIRE_LOCK(&lk);
5433 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5434 	FREE_LOCK(&lk);
5435 }
5436 
5437 /*
5438  * Set up a dependency structure for an external attributes data block.
5439  * This routine follows much of the structure of softdep_setup_allocdirect.
5440  * See the description of softdep_setup_allocdirect above for details.
5441  */
5442 void
5443 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5444 	struct inode *ip;
5445 	ufs_lbn_t off;
5446 	ufs2_daddr_t newblkno;
5447 	ufs2_daddr_t oldblkno;
5448 	long newsize;
5449 	long oldsize;
5450 	struct buf *bp;
5451 {
5452 	struct allocdirect *adp, *oldadp;
5453 	struct allocdirectlst *adphead;
5454 	struct freefrag *freefrag;
5455 	struct inodedep *inodedep;
5456 	struct jnewblk *jnewblk;
5457 	struct newblk *newblk;
5458 	struct mount *mp;
5459 	ufs_lbn_t lbn;
5460 
5461 	if (off >= NXADDR)
5462 		panic("softdep_setup_allocext: lbn %lld > NXADDR",
5463 		    (long long)off);
5464 
5465 	lbn = bp->b_lblkno;
5466 	mp = UFSTOVFS(ip->i_ump);
5467 	if (oldblkno && oldblkno != newblkno)
5468 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5469 	else
5470 		freefrag = NULL;
5471 
5472 	ACQUIRE_LOCK(&lk);
5473 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5474 		panic("softdep_setup_allocext: lost block");
5475 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5476 	    ("softdep_setup_allocext: newblk already initialized"));
5477 	/*
5478 	 * Convert the newblk to an allocdirect.
5479 	 */
5480 	newblk->nb_list.wk_type = D_ALLOCDIRECT;
5481 	adp = (struct allocdirect *)newblk;
5482 	newblk->nb_freefrag = freefrag;
5483 	adp->ad_offset = off;
5484 	adp->ad_oldblkno = oldblkno;
5485 	adp->ad_newsize = newsize;
5486 	adp->ad_oldsize = oldsize;
5487 	adp->ad_state |=  EXTDATA;
5488 
5489 	/*
5490 	 * Finish initializing the journal.
5491 	 */
5492 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5493 		jnewblk->jn_ino = ip->i_number;
5494 		jnewblk->jn_lbn = lbn;
5495 		add_to_journal(&jnewblk->jn_list);
5496 	}
5497 	if (freefrag && freefrag->ff_jdep != NULL &&
5498 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5499 		add_to_journal(freefrag->ff_jdep);
5500 	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
5501 	adp->ad_inodedep = inodedep;
5502 
5503 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5504 	/*
5505 	 * The list of allocdirects must be kept in sorted and ascending
5506 	 * order so that the rollback routines can quickly determine the
5507 	 * first uncommitted block (the size of the file stored on disk
5508 	 * ends at the end of the lowest committed fragment, or if there
5509 	 * are no fragments, at the end of the highest committed block).
5510 	 * Since files generally grow, the typical case is that the new
5511 	 * block is to be added at the end of the list. We speed this
5512 	 * special case by checking against the last allocdirect in the
5513 	 * list before laboriously traversing the list looking for the
5514 	 * insertion point.
5515 	 */
5516 	adphead = &inodedep->id_newextupdt;
5517 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5518 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5519 		/* insert at end of list */
5520 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5521 		if (oldadp != NULL && oldadp->ad_offset == off)
5522 			allocdirect_merge(adphead, adp, oldadp);
5523 		FREE_LOCK(&lk);
5524 		return;
5525 	}
5526 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5527 		if (oldadp->ad_offset >= off)
5528 			break;
5529 	}
5530 	if (oldadp == NULL)
5531 		panic("softdep_setup_allocext: lost entry");
5532 	/* insert in middle of list */
5533 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5534 	if (oldadp->ad_offset == off)
5535 		allocdirect_merge(adphead, adp, oldadp);
5536 	FREE_LOCK(&lk);
5537 }
5538 
5539 /*
5540  * Indirect block allocation dependencies.
5541  *
5542  * The same dependencies that exist for a direct block also exist when
5543  * a new block is allocated and pointed to by an entry in a block of
5544  * indirect pointers. The undo/redo states described above are also
5545  * used here. Because an indirect block contains many pointers that
5546  * may have dependencies, a second copy of the entire in-memory indirect
5547  * block is kept. The buffer cache copy is always completely up-to-date.
5548  * The second copy, which is used only as a source for disk writes,
5549  * contains only the safe pointers (i.e., those that have no remaining
5550  * update dependencies). The second copy is freed when all pointers
5551  * are safe. The cache is not allowed to replace indirect blocks with
5552  * pending update dependencies. If a buffer containing an indirect
5553  * block with dependencies is written, these routines will mark it
5554  * dirty again. It can only be successfully written once all the
5555  * dependencies are removed. The ffs_fsync routine in conjunction with
5556  * softdep_sync_metadata work together to get all the dependencies
5557  * removed so that a file can be successfully written to disk. Three
5558  * procedures are used when setting up indirect block pointer
5559  * dependencies. The division is necessary because of the organization
5560  * of the "balloc" routine and because of the distinction between file
5561  * pages and file metadata blocks.
5562  */
5563 
5564 /*
5565  * Allocate a new allocindir structure.
5566  */
5567 static struct allocindir *
5568 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5569 	struct inode *ip;	/* inode for file being extended */
5570 	int ptrno;		/* offset of pointer in indirect block */
5571 	ufs2_daddr_t newblkno;	/* disk block number being added */
5572 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5573 	ufs_lbn_t lbn;
5574 {
5575 	struct newblk *newblk;
5576 	struct allocindir *aip;
5577 	struct freefrag *freefrag;
5578 	struct jnewblk *jnewblk;
5579 
5580 	if (oldblkno)
5581 		freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize, lbn);
5582 	else
5583 		freefrag = NULL;
5584 	ACQUIRE_LOCK(&lk);
5585 	if (newblk_lookup(UFSTOVFS(ip->i_ump), newblkno, 0, &newblk) == 0)
5586 		panic("new_allocindir: lost block");
5587 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5588 	    ("newallocindir: newblk already initialized"));
5589 	newblk->nb_list.wk_type = D_ALLOCINDIR;
5590 	newblk->nb_freefrag = freefrag;
5591 	aip = (struct allocindir *)newblk;
5592 	aip->ai_offset = ptrno;
5593 	aip->ai_oldblkno = oldblkno;
5594 	aip->ai_lbn = lbn;
5595 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5596 		jnewblk->jn_ino = ip->i_number;
5597 		jnewblk->jn_lbn = lbn;
5598 		add_to_journal(&jnewblk->jn_list);
5599 	}
5600 	if (freefrag && freefrag->ff_jdep != NULL &&
5601 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5602 		add_to_journal(freefrag->ff_jdep);
5603 	return (aip);
5604 }
5605 
5606 /*
5607  * Called just before setting an indirect block pointer
5608  * to a newly allocated file page.
5609  */
5610 void
5611 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5612 	struct inode *ip;	/* inode for file being extended */
5613 	ufs_lbn_t lbn;		/* allocated block number within file */
5614 	struct buf *bp;		/* buffer with indirect blk referencing page */
5615 	int ptrno;		/* offset of pointer in indirect block */
5616 	ufs2_daddr_t newblkno;	/* disk block number being added */
5617 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5618 	struct buf *nbp;	/* buffer holding allocated page */
5619 {
5620 	struct inodedep *inodedep;
5621 	struct freefrag *freefrag;
5622 	struct allocindir *aip;
5623 	struct pagedep *pagedep;
5624 	struct mount *mp;
5625 	int dflags;
5626 
5627 	if (lbn != nbp->b_lblkno)
5628 		panic("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5629 		    lbn, bp->b_lblkno);
5630 	CTR4(KTR_SUJ,
5631 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5632 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5633 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5634 	mp = UFSTOVFS(ip->i_ump);
5635 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5636 	dflags = DEPALLOC;
5637 	if (IS_SNAPSHOT(ip))
5638 		dflags |= NODELAY;
5639 	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
5640 	/*
5641 	 * If we are allocating a directory page, then we must
5642 	 * allocate an associated pagedep to track additions and
5643 	 * deletions.
5644 	 */
5645 	if ((ip->i_mode & IFMT) == IFDIR)
5646 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5647 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5648 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5649 	FREE_LOCK(&lk);
5650 	if (freefrag)
5651 		handle_workitem_freefrag(freefrag);
5652 }
5653 
5654 /*
5655  * Called just before setting an indirect block pointer to a
5656  * newly allocated indirect block.
5657  */
5658 void
5659 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5660 	struct buf *nbp;	/* newly allocated indirect block */
5661 	struct inode *ip;	/* inode for file being extended */
5662 	struct buf *bp;		/* indirect block referencing allocated block */
5663 	int ptrno;		/* offset of pointer in indirect block */
5664 	ufs2_daddr_t newblkno;	/* disk block number being added */
5665 {
5666 	struct inodedep *inodedep;
5667 	struct allocindir *aip;
5668 	ufs_lbn_t lbn;
5669 	int dflags;
5670 
5671 	CTR3(KTR_SUJ,
5672 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5673 	    ip->i_number, newblkno, ptrno);
5674 	lbn = nbp->b_lblkno;
5675 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5676 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5677 	dflags = DEPALLOC;
5678 	if (IS_SNAPSHOT(ip))
5679 		dflags |= NODELAY;
5680 	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags, &inodedep);
5681 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5682 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5683 		panic("softdep_setup_allocindir_meta: Block already existed");
5684 	FREE_LOCK(&lk);
5685 }
5686 
5687 static void
5688 indirdep_complete(indirdep)
5689 	struct indirdep *indirdep;
5690 {
5691 	struct allocindir *aip;
5692 
5693 	LIST_REMOVE(indirdep, ir_next);
5694 	indirdep->ir_state |= DEPCOMPLETE;
5695 
5696 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5697 		LIST_REMOVE(aip, ai_next);
5698 		free_newblk(&aip->ai_block);
5699 	}
5700 	/*
5701 	 * If this indirdep is not attached to a buf it was simply waiting
5702 	 * on completion to clear completehd.  free_indirdep() asserts
5703 	 * that nothing is dangling.
5704 	 */
5705 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5706 		free_indirdep(indirdep);
5707 }
5708 
5709 static struct indirdep *
5710 indirdep_lookup(mp, ip, bp)
5711 	struct mount *mp;
5712 	struct inode *ip;
5713 	struct buf *bp;
5714 {
5715 	struct indirdep *indirdep, *newindirdep;
5716 	struct newblk *newblk;
5717 	struct worklist *wk;
5718 	struct fs *fs;
5719 	ufs2_daddr_t blkno;
5720 
5721 	mtx_assert(&lk, MA_OWNED);
5722 	indirdep = NULL;
5723 	newindirdep = NULL;
5724 	fs = ip->i_fs;
5725 	for (;;) {
5726 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5727 			if (wk->wk_type != D_INDIRDEP)
5728 				continue;
5729 			indirdep = WK_INDIRDEP(wk);
5730 			break;
5731 		}
5732 		/* Found on the buffer worklist, no new structure to free. */
5733 		if (indirdep != NULL && newindirdep == NULL)
5734 			return (indirdep);
5735 		if (indirdep != NULL && newindirdep != NULL)
5736 			panic("indirdep_lookup: simultaneous create");
5737 		/* None found on the buffer and a new structure is ready. */
5738 		if (indirdep == NULL && newindirdep != NULL)
5739 			break;
5740 		/* None found and no new structure available. */
5741 		FREE_LOCK(&lk);
5742 		newindirdep = malloc(sizeof(struct indirdep),
5743 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
5744 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5745 		newindirdep->ir_state = ATTACHED;
5746 		if (ip->i_ump->um_fstype == UFS1)
5747 			newindirdep->ir_state |= UFS1FMT;
5748 		TAILQ_INIT(&newindirdep->ir_trunc);
5749 		newindirdep->ir_saveddata = NULL;
5750 		LIST_INIT(&newindirdep->ir_deplisthd);
5751 		LIST_INIT(&newindirdep->ir_donehd);
5752 		LIST_INIT(&newindirdep->ir_writehd);
5753 		LIST_INIT(&newindirdep->ir_completehd);
5754 		if (bp->b_blkno == bp->b_lblkno) {
5755 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5756 			    NULL, NULL);
5757 			bp->b_blkno = blkno;
5758 		}
5759 		newindirdep->ir_freeblks = NULL;
5760 		newindirdep->ir_savebp =
5761 		    getblk(ip->i_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5762 		newindirdep->ir_bp = bp;
5763 		BUF_KERNPROC(newindirdep->ir_savebp);
5764 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5765 		ACQUIRE_LOCK(&lk);
5766 	}
5767 	indirdep = newindirdep;
5768 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5769 	/*
5770 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
5771 	 * that we don't free dependencies until the pointers are valid.
5772 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5773 	 * than using the hash.
5774 	 */
5775 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5776 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5777 	else
5778 		indirdep->ir_state |= DEPCOMPLETE;
5779 	return (indirdep);
5780 }
5781 
5782 /*
5783  * Called to finish the allocation of the "aip" allocated
5784  * by one of the two routines above.
5785  */
5786 static struct freefrag *
5787 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
5788 	struct buf *bp;		/* in-memory copy of the indirect block */
5789 	struct inode *ip;	/* inode for file being extended */
5790 	struct inodedep *inodedep; /* Inodedep for ip */
5791 	struct allocindir *aip;	/* allocindir allocated by the above routines */
5792 	ufs_lbn_t lbn;		/* Logical block number for this block. */
5793 {
5794 	struct fs *fs;
5795 	struct indirdep *indirdep;
5796 	struct allocindir *oldaip;
5797 	struct freefrag *freefrag;
5798 	struct mount *mp;
5799 
5800 	mtx_assert(&lk, MA_OWNED);
5801 	mp = UFSTOVFS(ip->i_ump);
5802 	fs = ip->i_fs;
5803 	if (bp->b_lblkno >= 0)
5804 		panic("setup_allocindir_phase2: not indir blk");
5805 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
5806 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
5807 	indirdep = indirdep_lookup(mp, ip, bp);
5808 	KASSERT(indirdep->ir_savebp != NULL,
5809 	    ("setup_allocindir_phase2 NULL ir_savebp"));
5810 	aip->ai_indirdep = indirdep;
5811 	/*
5812 	 * Check for an unwritten dependency for this indirect offset.  If
5813 	 * there is, merge the old dependency into the new one.  This happens
5814 	 * as a result of reallocblk only.
5815 	 */
5816 	freefrag = NULL;
5817 	if (aip->ai_oldblkno != 0) {
5818 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
5819 			if (oldaip->ai_offset == aip->ai_offset) {
5820 				freefrag = allocindir_merge(aip, oldaip);
5821 				goto done;
5822 			}
5823 		}
5824 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
5825 			if (oldaip->ai_offset == aip->ai_offset) {
5826 				freefrag = allocindir_merge(aip, oldaip);
5827 				goto done;
5828 			}
5829 		}
5830 	}
5831 done:
5832 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
5833 	return (freefrag);
5834 }
5835 
5836 /*
5837  * Merge two allocindirs which refer to the same block.  Move newblock
5838  * dependencies and setup the freefrags appropriately.
5839  */
5840 static struct freefrag *
5841 allocindir_merge(aip, oldaip)
5842 	struct allocindir *aip;
5843 	struct allocindir *oldaip;
5844 {
5845 	struct freefrag *freefrag;
5846 	struct worklist *wk;
5847 
5848 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
5849 		panic("allocindir_merge: blkno");
5850 	aip->ai_oldblkno = oldaip->ai_oldblkno;
5851 	freefrag = aip->ai_freefrag;
5852 	aip->ai_freefrag = oldaip->ai_freefrag;
5853 	oldaip->ai_freefrag = NULL;
5854 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
5855 	/*
5856 	 * If we are tracking a new directory-block allocation,
5857 	 * move it from the old allocindir to the new allocindir.
5858 	 */
5859 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
5860 		WORKLIST_REMOVE(wk);
5861 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
5862 			panic("allocindir_merge: extra newdirblk");
5863 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
5864 	}
5865 	/*
5866 	 * We can skip journaling for this freefrag and just complete
5867 	 * any pending journal work for the allocindir that is being
5868 	 * removed after the freefrag completes.
5869 	 */
5870 	if (freefrag->ff_jdep)
5871 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
5872 	LIST_REMOVE(oldaip, ai_next);
5873 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
5874 	    &freefrag->ff_list, &freefrag->ff_jwork);
5875 	free_newblk(&oldaip->ai_block);
5876 
5877 	return (freefrag);
5878 }
5879 
5880 static inline void
5881 setup_freedirect(freeblks, ip, i, needj)
5882 	struct freeblks *freeblks;
5883 	struct inode *ip;
5884 	int i;
5885 	int needj;
5886 {
5887 	ufs2_daddr_t blkno;
5888 	int frags;
5889 
5890 	blkno = DIP(ip, i_db[i]);
5891 	if (blkno == 0)
5892 		return;
5893 	DIP_SET(ip, i_db[i], 0);
5894 	frags = sblksize(ip->i_fs, ip->i_size, i);
5895 	frags = numfrags(ip->i_fs, frags);
5896 	newfreework(ip->i_ump, freeblks, NULL, i, blkno, frags, 0, needj);
5897 }
5898 
5899 static inline void
5900 setup_freeext(freeblks, ip, i, needj)
5901 	struct freeblks *freeblks;
5902 	struct inode *ip;
5903 	int i;
5904 	int needj;
5905 {
5906 	ufs2_daddr_t blkno;
5907 	int frags;
5908 
5909 	blkno = ip->i_din2->di_extb[i];
5910 	if (blkno == 0)
5911 		return;
5912 	ip->i_din2->di_extb[i] = 0;
5913 	frags = sblksize(ip->i_fs, ip->i_din2->di_extsize, i);
5914 	frags = numfrags(ip->i_fs, frags);
5915 	newfreework(ip->i_ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
5916 }
5917 
5918 static inline void
5919 setup_freeindir(freeblks, ip, i, lbn, needj)
5920 	struct freeblks *freeblks;
5921 	struct inode *ip;
5922 	int i;
5923 	ufs_lbn_t lbn;
5924 	int needj;
5925 {
5926 	ufs2_daddr_t blkno;
5927 
5928 	blkno = DIP(ip, i_ib[i]);
5929 	if (blkno == 0)
5930 		return;
5931 	DIP_SET(ip, i_ib[i], 0);
5932 	newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, ip->i_fs->fs_frag,
5933 	    0, needj);
5934 }
5935 
5936 static inline struct freeblks *
5937 newfreeblks(mp, ip)
5938 	struct mount *mp;
5939 	struct inode *ip;
5940 {
5941 	struct freeblks *freeblks;
5942 
5943 	freeblks = malloc(sizeof(struct freeblks),
5944 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
5945 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
5946 	LIST_INIT(&freeblks->fb_jblkdephd);
5947 	LIST_INIT(&freeblks->fb_jwork);
5948 	freeblks->fb_ref = 0;
5949 	freeblks->fb_cgwait = 0;
5950 	freeblks->fb_state = ATTACHED;
5951 	freeblks->fb_uid = ip->i_uid;
5952 	freeblks->fb_inum = ip->i_number;
5953 	freeblks->fb_vtype = ITOV(ip)->v_type;
5954 	freeblks->fb_modrev = DIP(ip, i_modrev);
5955 	freeblks->fb_devvp = ip->i_devvp;
5956 	freeblks->fb_chkcnt = 0;
5957 	freeblks->fb_len = 0;
5958 
5959 	return (freeblks);
5960 }
5961 
5962 static void
5963 trunc_indirdep(indirdep, freeblks, bp, off)
5964 	struct indirdep *indirdep;
5965 	struct freeblks *freeblks;
5966 	struct buf *bp;
5967 	int off;
5968 {
5969 	struct allocindir *aip, *aipn;
5970 
5971 	/*
5972 	 * The first set of allocindirs won't be in savedbp.
5973 	 */
5974 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
5975 		if (aip->ai_offset > off)
5976 			cancel_allocindir(aip, bp, freeblks, 1);
5977 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
5978 		if (aip->ai_offset > off)
5979 			cancel_allocindir(aip, bp, freeblks, 1);
5980 	/*
5981 	 * These will exist in savedbp.
5982 	 */
5983 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
5984 		if (aip->ai_offset > off)
5985 			cancel_allocindir(aip, NULL, freeblks, 0);
5986 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
5987 		if (aip->ai_offset > off)
5988 			cancel_allocindir(aip, NULL, freeblks, 0);
5989 }
5990 
5991 /*
5992  * Follow the chain of indirects down to lastlbn creating a freework
5993  * structure for each.  This will be used to start indir_trunc() at
5994  * the right offset and create the journal records for the parrtial
5995  * truncation.  A second step will handle the truncated dependencies.
5996  */
5997 static int
5998 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
5999 	struct freeblks *freeblks;
6000 	struct inode *ip;
6001 	ufs_lbn_t lbn;
6002 	ufs_lbn_t lastlbn;
6003 	ufs2_daddr_t blkno;
6004 {
6005 	struct indirdep *indirdep;
6006 	struct indirdep *indirn;
6007 	struct freework *freework;
6008 	struct newblk *newblk;
6009 	struct mount *mp;
6010 	struct buf *bp;
6011 	uint8_t *start;
6012 	uint8_t *end;
6013 	ufs_lbn_t lbnadd;
6014 	int level;
6015 	int error;
6016 	int off;
6017 
6018 
6019 	freework = NULL;
6020 	if (blkno == 0)
6021 		return (0);
6022 	mp = freeblks->fb_list.wk_mp;
6023 	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6024 	if ((bp->b_flags & B_CACHE) == 0) {
6025 		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6026 		bp->b_iocmd = BIO_READ;
6027 		bp->b_flags &= ~B_INVAL;
6028 		bp->b_ioflags &= ~BIO_ERROR;
6029 		vfs_busy_pages(bp, 0);
6030 		bp->b_iooffset = dbtob(bp->b_blkno);
6031 		bstrategy(bp);
6032 		curthread->td_ru.ru_inblock++;
6033 		error = bufwait(bp);
6034 		if (error) {
6035 			brelse(bp);
6036 			return (error);
6037 		}
6038 	}
6039 	level = lbn_level(lbn);
6040 	lbnadd = lbn_offset(ip->i_fs, level);
6041 	/*
6042 	 * Compute the offset of the last block we want to keep.  Store
6043 	 * in the freework the first block we want to completely free.
6044 	 */
6045 	off = (lastlbn - -(lbn + level)) / lbnadd;
6046 	if (off + 1 == NINDIR(ip->i_fs))
6047 		goto nowork;
6048 	freework = newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, 0, off+1,
6049 	    0);
6050 	/*
6051 	 * Link the freework into the indirdep.  This will prevent any new
6052 	 * allocations from proceeding until we are finished with the
6053 	 * truncate and the block is written.
6054 	 */
6055 	ACQUIRE_LOCK(&lk);
6056 	indirdep = indirdep_lookup(mp, ip, bp);
6057 	if (indirdep->ir_freeblks)
6058 		panic("setup_trunc_indir: indirdep already truncated.");
6059 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6060 	freework->fw_indir = indirdep;
6061 	/*
6062 	 * Cancel any allocindirs that will not make it to disk.
6063 	 * We have to do this for all copies of the indirdep that
6064 	 * live on this newblk.
6065 	 */
6066 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6067 		newblk_lookup(mp, dbtofsb(ip->i_fs, bp->b_blkno), 0, &newblk);
6068 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6069 			trunc_indirdep(indirn, freeblks, bp, off);
6070 	} else
6071 		trunc_indirdep(indirdep, freeblks, bp, off);
6072 	FREE_LOCK(&lk);
6073 	/*
6074 	 * Creation is protected by the buf lock. The saveddata is only
6075 	 * needed if a full truncation follows a partial truncation but it
6076 	 * is difficult to allocate in that case so we fetch it anyway.
6077 	 */
6078 	if (indirdep->ir_saveddata == NULL)
6079 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6080 		    M_SOFTDEP_FLAGS);
6081 nowork:
6082 	/* Fetch the blkno of the child and the zero start offset. */
6083 	if (ip->i_ump->um_fstype == UFS1) {
6084 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6085 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6086 	} else {
6087 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6088 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6089 	}
6090 	if (freework) {
6091 		/* Zero the truncated pointers. */
6092 		end = bp->b_data + bp->b_bcount;
6093 		bzero(start, end - start);
6094 		bdwrite(bp);
6095 	} else
6096 		bqrelse(bp);
6097 	if (level == 0)
6098 		return (0);
6099 	lbn++; /* adjust level */
6100 	lbn -= (off * lbnadd);
6101 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6102 }
6103 
6104 /*
6105  * Complete the partial truncation of an indirect block setup by
6106  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6107  * copy and writes them to disk before the freeblks is allowed to complete.
6108  */
6109 static void
6110 complete_trunc_indir(freework)
6111 	struct freework *freework;
6112 {
6113 	struct freework *fwn;
6114 	struct indirdep *indirdep;
6115 	struct buf *bp;
6116 	uintptr_t start;
6117 	int count;
6118 
6119 	indirdep = freework->fw_indir;
6120 	for (;;) {
6121 		bp = indirdep->ir_bp;
6122 		/* See if the block was discarded. */
6123 		if (bp == NULL)
6124 			break;
6125 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6126 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6127 			break;
6128 		if (BUF_LOCK(bp,
6129 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, &lk) == 0)
6130 			BUF_UNLOCK(bp);
6131 		ACQUIRE_LOCK(&lk);
6132 	}
6133 	mtx_assert(&lk, MA_OWNED);
6134 	freework->fw_state |= DEPCOMPLETE;
6135 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6136 	/*
6137 	 * Zero the pointers in the saved copy.
6138 	 */
6139 	if (indirdep->ir_state & UFS1FMT)
6140 		start = sizeof(ufs1_daddr_t);
6141 	else
6142 		start = sizeof(ufs2_daddr_t);
6143 	start *= freework->fw_start;
6144 	count = indirdep->ir_savebp->b_bcount - start;
6145 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6146 	bzero((char *)start, count);
6147 	/*
6148 	 * We need to start the next truncation in the list if it has not
6149 	 * been started yet.
6150 	 */
6151 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6152 	if (fwn != NULL) {
6153 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6154 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6155 		if ((fwn->fw_state & ONWORKLIST) == 0)
6156 			freework_enqueue(fwn);
6157 	}
6158 	/*
6159 	 * If bp is NULL the block was fully truncated, restore
6160 	 * the saved block list otherwise free it if it is no
6161 	 * longer needed.
6162 	 */
6163 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6164 		if (bp == NULL)
6165 			bcopy(indirdep->ir_saveddata,
6166 			    indirdep->ir_savebp->b_data,
6167 			    indirdep->ir_savebp->b_bcount);
6168 		free(indirdep->ir_saveddata, M_INDIRDEP);
6169 		indirdep->ir_saveddata = NULL;
6170 	}
6171 	/*
6172 	 * When bp is NULL there is a full truncation pending.  We
6173 	 * must wait for this full truncation to be journaled before
6174 	 * we can release this freework because the disk pointers will
6175 	 * never be written as zero.
6176 	 */
6177 	if (bp == NULL)  {
6178 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6179 			handle_written_freework(freework);
6180 		else
6181 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6182 			   &freework->fw_list);
6183 	} else {
6184 		/* Complete when the real copy is written. */
6185 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6186 		BUF_UNLOCK(bp);
6187 	}
6188 }
6189 
6190 /*
6191  * Calculate the number of blocks we are going to release where datablocks
6192  * is the current total and length is the new file size.
6193  */
6194 ufs2_daddr_t
6195 blkcount(fs, datablocks, length)
6196 	struct fs *fs;
6197 	ufs2_daddr_t datablocks;
6198 	off_t length;
6199 {
6200 	off_t totblks, numblks;
6201 
6202 	totblks = 0;
6203 	numblks = howmany(length, fs->fs_bsize);
6204 	if (numblks <= NDADDR) {
6205 		totblks = howmany(length, fs->fs_fsize);
6206 		goto out;
6207 	}
6208         totblks = blkstofrags(fs, numblks);
6209 	numblks -= NDADDR;
6210 	/*
6211 	 * Count all single, then double, then triple indirects required.
6212 	 * Subtracting one indirects worth of blocks for each pass
6213 	 * acknowledges one of each pointed to by the inode.
6214 	 */
6215 	for (;;) {
6216 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6217 		numblks -= NINDIR(fs);
6218 		if (numblks <= 0)
6219 			break;
6220 		numblks = howmany(numblks, NINDIR(fs));
6221 	}
6222 out:
6223 	totblks = fsbtodb(fs, totblks);
6224 	/*
6225 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6226 	 * references.  We will correct it later in handle_complete_freeblks()
6227 	 * when we know the real count.
6228 	 */
6229 	if (totblks > datablocks)
6230 		return (0);
6231 	return (datablocks - totblks);
6232 }
6233 
6234 /*
6235  * Handle freeblocks for journaled softupdate filesystems.
6236  *
6237  * Contrary to normal softupdates, we must preserve the block pointers in
6238  * indirects until their subordinates are free.  This is to avoid journaling
6239  * every block that is freed which may consume more space than the journal
6240  * itself.  The recovery program will see the free block journals at the
6241  * base of the truncated area and traverse them to reclaim space.  The
6242  * pointers in the inode may be cleared immediately after the journal
6243  * records are written because each direct and indirect pointer in the
6244  * inode is recorded in a journal.  This permits full truncation to proceed
6245  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6246  *
6247  * The algorithm is as follows:
6248  * 1) Traverse the in-memory state and create journal entries to release
6249  *    the relevant blocks and full indirect trees.
6250  * 2) Traverse the indirect block chain adding partial truncation freework
6251  *    records to indirects in the path to lastlbn.  The freework will
6252  *    prevent new allocation dependencies from being satisfied in this
6253  *    indirect until the truncation completes.
6254  * 3) Read and lock the inode block, performing an update with the new size
6255  *    and pointers.  This prevents truncated data from becoming valid on
6256  *    disk through step 4.
6257  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6258  *    eliminate journal work for those records that do not require it.
6259  * 5) Schedule the journal records to be written followed by the inode block.
6260  * 6) Allocate any necessary frags for the end of file.
6261  * 7) Zero any partially truncated blocks.
6262  *
6263  * From this truncation proceeds asynchronously using the freework and
6264  * indir_trunc machinery.  The file will not be extended again into a
6265  * partially truncated indirect block until all work is completed but
6266  * the normal dependency mechanism ensures that it is rolled back/forward
6267  * as appropriate.  Further truncation may occur without delay and is
6268  * serialized in indir_trunc().
6269  */
6270 void
6271 softdep_journal_freeblocks(ip, cred, length, flags)
6272 	struct inode *ip;	/* The inode whose length is to be reduced */
6273 	struct ucred *cred;
6274 	off_t length;		/* The new length for the file */
6275 	int flags;		/* IO_EXT and/or IO_NORMAL */
6276 {
6277 	struct freeblks *freeblks, *fbn;
6278 	struct worklist *wk, *wkn;
6279 	struct inodedep *inodedep;
6280 	struct jblkdep *jblkdep;
6281 	struct allocdirect *adp, *adpn;
6282 	struct fs *fs;
6283 	struct buf *bp;
6284 	struct vnode *vp;
6285 	struct mount *mp;
6286 	ufs2_daddr_t extblocks, datablocks;
6287 	ufs_lbn_t tmpval, lbn, lastlbn;
6288 	int frags, lastoff, iboff, allocblock, needj, dflags, error, i;
6289 
6290 	fs = ip->i_fs;
6291 	mp = UFSTOVFS(ip->i_ump);
6292 	vp = ITOV(ip);
6293 	needj = 1;
6294 	iboff = -1;
6295 	allocblock = 0;
6296 	extblocks = 0;
6297 	datablocks = 0;
6298 	frags = 0;
6299 	freeblks = newfreeblks(mp, ip);
6300 	ACQUIRE_LOCK(&lk);
6301 	/*
6302 	 * If we're truncating a removed file that will never be written
6303 	 * we don't need to journal the block frees.  The canceled journals
6304 	 * for the allocations will suffice.
6305 	 */
6306 	dflags = DEPALLOC;
6307 	if (IS_SNAPSHOT(ip))
6308 		dflags |= NODELAY;
6309 	inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6310 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6311 	    length == 0)
6312 		needj = 0;
6313 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6314 	    ip->i_number, length, needj);
6315 	FREE_LOCK(&lk);
6316 	/*
6317 	 * Calculate the lbn that we are truncating to.  This results in -1
6318 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6319 	 * to keep, not the first lbn we want to truncate.
6320 	 */
6321 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6322 	lastoff = blkoff(fs, length);
6323 	/*
6324 	 * Compute frags we are keeping in lastlbn.  0 means all.
6325 	 */
6326 	if (lastlbn >= 0 && lastlbn < NDADDR) {
6327 		frags = fragroundup(fs, lastoff);
6328 		/* adp offset of last valid allocdirect. */
6329 		iboff = lastlbn;
6330 	} else if (lastlbn > 0)
6331 		iboff = NDADDR;
6332 	if (fs->fs_magic == FS_UFS2_MAGIC)
6333 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6334 	/*
6335 	 * Handle normal data blocks and indirects.  This section saves
6336 	 * values used after the inode update to complete frag and indirect
6337 	 * truncation.
6338 	 */
6339 	if ((flags & IO_NORMAL) != 0) {
6340 		/*
6341 		 * Handle truncation of whole direct and indirect blocks.
6342 		 */
6343 		for (i = iboff + 1; i < NDADDR; i++)
6344 			setup_freedirect(freeblks, ip, i, needj);
6345 		for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6346 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6347 			/* Release a whole indirect tree. */
6348 			if (lbn > lastlbn) {
6349 				setup_freeindir(freeblks, ip, i, -lbn -i,
6350 				    needj);
6351 				continue;
6352 			}
6353 			iboff = i + NDADDR;
6354 			/*
6355 			 * Traverse partially truncated indirect tree.
6356 			 */
6357 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6358 				setup_trunc_indir(freeblks, ip, -lbn - i,
6359 				    lastlbn, DIP(ip, i_ib[i]));
6360 		}
6361 		/*
6362 		 * Handle partial truncation to a frag boundary.
6363 		 */
6364 		if (frags) {
6365 			ufs2_daddr_t blkno;
6366 			long oldfrags;
6367 
6368 			oldfrags = blksize(fs, ip, lastlbn);
6369 			blkno = DIP(ip, i_db[lastlbn]);
6370 			if (blkno && oldfrags != frags) {
6371 				oldfrags -= frags;
6372 				oldfrags = numfrags(ip->i_fs, oldfrags);
6373 				blkno += numfrags(ip->i_fs, frags);
6374 				newfreework(ip->i_ump, freeblks, NULL, lastlbn,
6375 				    blkno, oldfrags, 0, needj);
6376 			} else if (blkno == 0)
6377 				allocblock = 1;
6378 		}
6379 		/*
6380 		 * Add a journal record for partial truncate if we are
6381 		 * handling indirect blocks.  Non-indirects need no extra
6382 		 * journaling.
6383 		 */
6384 		if (length != 0 && lastlbn >= NDADDR) {
6385 			ip->i_flag |= IN_TRUNCATED;
6386 			newjtrunc(freeblks, length, 0);
6387 		}
6388 		ip->i_size = length;
6389 		DIP_SET(ip, i_size, ip->i_size);
6390 		datablocks = DIP(ip, i_blocks) - extblocks;
6391 		if (length != 0)
6392 			datablocks = blkcount(ip->i_fs, datablocks, length);
6393 		freeblks->fb_len = length;
6394 	}
6395 	if ((flags & IO_EXT) != 0) {
6396 		for (i = 0; i < NXADDR; i++)
6397 			setup_freeext(freeblks, ip, i, needj);
6398 		ip->i_din2->di_extsize = 0;
6399 		datablocks += extblocks;
6400 	}
6401 #ifdef QUOTA
6402 	/* Reference the quotas in case the block count is wrong in the end. */
6403 	quotaref(vp, freeblks->fb_quota);
6404 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6405 #endif
6406 	freeblks->fb_chkcnt = -datablocks;
6407 	UFS_LOCK(ip->i_ump);
6408 	fs->fs_pendingblocks += datablocks;
6409 	UFS_UNLOCK(ip->i_ump);
6410 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6411 	/*
6412 	 * Handle truncation of incomplete alloc direct dependencies.  We
6413 	 * hold the inode block locked to prevent incomplete dependencies
6414 	 * from reaching the disk while we are eliminating those that
6415 	 * have been truncated.  This is a partially inlined ffs_update().
6416 	 */
6417 	ufs_itimes(vp);
6418 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6419 	error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6420 	    (int)fs->fs_bsize, cred, &bp);
6421 	if (error) {
6422 		brelse(bp);
6423 		softdep_error("softdep_journal_freeblocks", error);
6424 		return;
6425 	}
6426 	if (bp->b_bufsize == fs->fs_bsize)
6427 		bp->b_flags |= B_CLUSTEROK;
6428 	softdep_update_inodeblock(ip, bp, 0);
6429 	if (ip->i_ump->um_fstype == UFS1)
6430 		*((struct ufs1_dinode *)bp->b_data +
6431 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6432 	else
6433 		*((struct ufs2_dinode *)bp->b_data +
6434 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6435 	ACQUIRE_LOCK(&lk);
6436 	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6437 	if ((inodedep->id_state & IOSTARTED) != 0)
6438 		panic("softdep_setup_freeblocks: inode busy");
6439 	/*
6440 	 * Add the freeblks structure to the list of operations that
6441 	 * must await the zero'ed inode being written to disk. If we
6442 	 * still have a bitmap dependency (needj), then the inode
6443 	 * has never been written to disk, so we can process the
6444 	 * freeblks below once we have deleted the dependencies.
6445 	 */
6446 	if (needj)
6447 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6448 	else
6449 		freeblks->fb_state |= COMPLETE;
6450 	if ((flags & IO_NORMAL) != 0) {
6451 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6452 			if (adp->ad_offset > iboff)
6453 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6454 				    freeblks);
6455 			/*
6456 			 * Truncate the allocdirect.  We could eliminate
6457 			 * or modify journal records as well.
6458 			 */
6459 			else if (adp->ad_offset == iboff && frags)
6460 				adp->ad_newsize = frags;
6461 		}
6462 	}
6463 	if ((flags & IO_EXT) != 0)
6464 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6465 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6466 			    freeblks);
6467 	/*
6468 	 * Scan the bufwait list for newblock dependencies that will never
6469 	 * make it to disk.
6470 	 */
6471 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6472 		if (wk->wk_type != D_ALLOCDIRECT)
6473 			continue;
6474 		adp = WK_ALLOCDIRECT(wk);
6475 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6476 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6477 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6478 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6479 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6480 		}
6481 	}
6482 	/*
6483 	 * Add journal work.
6484 	 */
6485 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6486 		add_to_journal(&jblkdep->jb_list);
6487 	FREE_LOCK(&lk);
6488 	bdwrite(bp);
6489 	/*
6490 	 * Truncate dependency structures beyond length.
6491 	 */
6492 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6493 	/*
6494 	 * This is only set when we need to allocate a fragment because
6495 	 * none existed at the end of a frag-sized file.  It handles only
6496 	 * allocating a new, zero filled block.
6497 	 */
6498 	if (allocblock) {
6499 		ip->i_size = length - lastoff;
6500 		DIP_SET(ip, i_size, ip->i_size);
6501 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6502 		if (error != 0) {
6503 			softdep_error("softdep_journal_freeblks", error);
6504 			return;
6505 		}
6506 		ip->i_size = length;
6507 		DIP_SET(ip, i_size, length);
6508 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6509 		allocbuf(bp, frags);
6510 		ffs_update(vp, 0);
6511 		bawrite(bp);
6512 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6513 		int size;
6514 
6515 		/*
6516 		 * Zero the end of a truncated frag or block.
6517 		 */
6518 		size = sblksize(fs, length, lastlbn);
6519 		error = bread(vp, lastlbn, size, cred, &bp);
6520 		if (error) {
6521 			softdep_error("softdep_journal_freeblks", error);
6522 			return;
6523 		}
6524 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6525 		bawrite(bp);
6526 
6527 	}
6528 	ACQUIRE_LOCK(&lk);
6529 	inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6530 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6531 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6532 	/*
6533 	 * We zero earlier truncations so they don't erroneously
6534 	 * update i_blocks.
6535 	 */
6536 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6537 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6538 			fbn->fb_len = 0;
6539 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6540 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6541 		freeblks->fb_state |= INPROGRESS;
6542 	else
6543 		freeblks = NULL;
6544 	FREE_LOCK(&lk);
6545 	if (freeblks)
6546 		handle_workitem_freeblocks(freeblks, 0);
6547 	trunc_pages(ip, length, extblocks, flags);
6548 
6549 }
6550 
6551 /*
6552  * Flush a JOP_SYNC to the journal.
6553  */
6554 void
6555 softdep_journal_fsync(ip)
6556 	struct inode *ip;
6557 {
6558 	struct jfsync *jfsync;
6559 
6560 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6561 		return;
6562 	ip->i_flag &= ~IN_TRUNCATED;
6563 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6564 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ip->i_ump));
6565 	jfsync->jfs_size = ip->i_size;
6566 	jfsync->jfs_ino = ip->i_number;
6567 	ACQUIRE_LOCK(&lk);
6568 	add_to_journal(&jfsync->jfs_list);
6569 	jwait(&jfsync->jfs_list, MNT_WAIT);
6570 	FREE_LOCK(&lk);
6571 }
6572 
6573 /*
6574  * Block de-allocation dependencies.
6575  *
6576  * When blocks are de-allocated, the on-disk pointers must be nullified before
6577  * the blocks are made available for use by other files.  (The true
6578  * requirement is that old pointers must be nullified before new on-disk
6579  * pointers are set.  We chose this slightly more stringent requirement to
6580  * reduce complexity.) Our implementation handles this dependency by updating
6581  * the inode (or indirect block) appropriately but delaying the actual block
6582  * de-allocation (i.e., freemap and free space count manipulation) until
6583  * after the updated versions reach stable storage.  After the disk is
6584  * updated, the blocks can be safely de-allocated whenever it is convenient.
6585  * This implementation handles only the common case of reducing a file's
6586  * length to zero. Other cases are handled by the conventional synchronous
6587  * write approach.
6588  *
6589  * The ffs implementation with which we worked double-checks
6590  * the state of the block pointers and file size as it reduces
6591  * a file's length.  Some of this code is replicated here in our
6592  * soft updates implementation.  The freeblks->fb_chkcnt field is
6593  * used to transfer a part of this information to the procedure
6594  * that eventually de-allocates the blocks.
6595  *
6596  * This routine should be called from the routine that shortens
6597  * a file's length, before the inode's size or block pointers
6598  * are modified. It will save the block pointer information for
6599  * later release and zero the inode so that the calling routine
6600  * can release it.
6601  */
6602 void
6603 softdep_setup_freeblocks(ip, length, flags)
6604 	struct inode *ip;	/* The inode whose length is to be reduced */
6605 	off_t length;		/* The new length for the file */
6606 	int flags;		/* IO_EXT and/or IO_NORMAL */
6607 {
6608 	struct ufs1_dinode *dp1;
6609 	struct ufs2_dinode *dp2;
6610 	struct freeblks *freeblks;
6611 	struct inodedep *inodedep;
6612 	struct allocdirect *adp;
6613 	struct buf *bp;
6614 	struct fs *fs;
6615 	ufs2_daddr_t extblocks, datablocks;
6616 	struct mount *mp;
6617 	int i, delay, error, dflags;
6618 	ufs_lbn_t tmpval;
6619 	ufs_lbn_t lbn;
6620 
6621 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6622 	    ip->i_number, length);
6623 	fs = ip->i_fs;
6624 	mp = UFSTOVFS(ip->i_ump);
6625 	if (length != 0)
6626 		panic("softdep_setup_freeblocks: non-zero length");
6627 	freeblks = newfreeblks(mp, ip);
6628 	extblocks = 0;
6629 	datablocks = 0;
6630 	if (fs->fs_magic == FS_UFS2_MAGIC)
6631 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6632 	if ((flags & IO_NORMAL) != 0) {
6633 		for (i = 0; i < NDADDR; i++)
6634 			setup_freedirect(freeblks, ip, i, 0);
6635 		for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6636 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6637 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6638 		ip->i_size = 0;
6639 		DIP_SET(ip, i_size, 0);
6640 		datablocks = DIP(ip, i_blocks) - extblocks;
6641 	}
6642 	if ((flags & IO_EXT) != 0) {
6643 		for (i = 0; i < NXADDR; i++)
6644 			setup_freeext(freeblks, ip, i, 0);
6645 		ip->i_din2->di_extsize = 0;
6646 		datablocks += extblocks;
6647 	}
6648 #ifdef QUOTA
6649 	/* Reference the quotas in case the block count is wrong in the end. */
6650 	quotaref(ITOV(ip), freeblks->fb_quota);
6651 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6652 #endif
6653 	freeblks->fb_chkcnt = -datablocks;
6654 	UFS_LOCK(ip->i_ump);
6655 	fs->fs_pendingblocks += datablocks;
6656 	UFS_UNLOCK(ip->i_ump);
6657 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6658 	/*
6659 	 * Push the zero'ed inode to to its disk buffer so that we are free
6660 	 * to delete its dependencies below. Once the dependencies are gone
6661 	 * the buffer can be safely released.
6662 	 */
6663 	if ((error = bread(ip->i_devvp,
6664 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6665 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6666 		brelse(bp);
6667 		softdep_error("softdep_setup_freeblocks", error);
6668 	}
6669 	if (ip->i_ump->um_fstype == UFS1) {
6670 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6671 		    ino_to_fsbo(fs, ip->i_number));
6672 		ip->i_din1->di_freelink = dp1->di_freelink;
6673 		*dp1 = *ip->i_din1;
6674 	} else {
6675 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6676 		    ino_to_fsbo(fs, ip->i_number));
6677 		ip->i_din2->di_freelink = dp2->di_freelink;
6678 		*dp2 = *ip->i_din2;
6679 	}
6680 	/*
6681 	 * Find and eliminate any inode dependencies.
6682 	 */
6683 	ACQUIRE_LOCK(&lk);
6684 	dflags = DEPALLOC;
6685 	if (IS_SNAPSHOT(ip))
6686 		dflags |= NODELAY;
6687 	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6688 	if ((inodedep->id_state & IOSTARTED) != 0)
6689 		panic("softdep_setup_freeblocks: inode busy");
6690 	/*
6691 	 * Add the freeblks structure to the list of operations that
6692 	 * must await the zero'ed inode being written to disk. If we
6693 	 * still have a bitmap dependency (delay == 0), then the inode
6694 	 * has never been written to disk, so we can process the
6695 	 * freeblks below once we have deleted the dependencies.
6696 	 */
6697 	delay = (inodedep->id_state & DEPCOMPLETE);
6698 	if (delay)
6699 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6700 	else
6701 		freeblks->fb_state |= COMPLETE;
6702 	/*
6703 	 * Because the file length has been truncated to zero, any
6704 	 * pending block allocation dependency structures associated
6705 	 * with this inode are obsolete and can simply be de-allocated.
6706 	 * We must first merge the two dependency lists to get rid of
6707 	 * any duplicate freefrag structures, then purge the merged list.
6708 	 * If we still have a bitmap dependency, then the inode has never
6709 	 * been written to disk, so we can free any fragments without delay.
6710 	 */
6711 	if (flags & IO_NORMAL) {
6712 		merge_inode_lists(&inodedep->id_newinoupdt,
6713 		    &inodedep->id_inoupdt);
6714 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
6715 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
6716 			    freeblks);
6717 	}
6718 	if (flags & IO_EXT) {
6719 		merge_inode_lists(&inodedep->id_newextupdt,
6720 		    &inodedep->id_extupdt);
6721 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6722 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6723 			    freeblks);
6724 	}
6725 	FREE_LOCK(&lk);
6726 	bdwrite(bp);
6727 	trunc_dependencies(ip, freeblks, -1, 0, flags);
6728 	ACQUIRE_LOCK(&lk);
6729 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6730 		(void) free_inodedep(inodedep);
6731 	freeblks->fb_state |= DEPCOMPLETE;
6732 	/*
6733 	 * If the inode with zeroed block pointers is now on disk
6734 	 * we can start freeing blocks.
6735 	 */
6736 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6737 		freeblks->fb_state |= INPROGRESS;
6738 	else
6739 		freeblks = NULL;
6740 	FREE_LOCK(&lk);
6741 	if (freeblks)
6742 		handle_workitem_freeblocks(freeblks, 0);
6743 	trunc_pages(ip, length, extblocks, flags);
6744 }
6745 
6746 /*
6747  * Eliminate pages from the page cache that back parts of this inode and
6748  * adjust the vnode pager's idea of our size.  This prevents stale data
6749  * from hanging around in the page cache.
6750  */
6751 static void
6752 trunc_pages(ip, length, extblocks, flags)
6753 	struct inode *ip;
6754 	off_t length;
6755 	ufs2_daddr_t extblocks;
6756 	int flags;
6757 {
6758 	struct vnode *vp;
6759 	struct fs *fs;
6760 	ufs_lbn_t lbn;
6761 	off_t end, extend;
6762 
6763 	vp = ITOV(ip);
6764 	fs = ip->i_fs;
6765 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
6766 	if ((flags & IO_EXT) != 0)
6767 		vn_pages_remove(vp, extend, 0);
6768 	if ((flags & IO_NORMAL) == 0)
6769 		return;
6770 	BO_LOCK(&vp->v_bufobj);
6771 	drain_output(vp);
6772 	BO_UNLOCK(&vp->v_bufobj);
6773 	/*
6774 	 * The vnode pager eliminates file pages we eliminate indirects
6775 	 * below.
6776 	 */
6777 	vnode_pager_setsize(vp, length);
6778 	/*
6779 	 * Calculate the end based on the last indirect we want to keep.  If
6780 	 * the block extends into indirects we can just use the negative of
6781 	 * its lbn.  Doubles and triples exist at lower numbers so we must
6782 	 * be careful not to remove those, if they exist.  double and triple
6783 	 * indirect lbns do not overlap with others so it is not important
6784 	 * to verify how many levels are required.
6785 	 */
6786 	lbn = lblkno(fs, length);
6787 	if (lbn >= NDADDR) {
6788 		/* Calculate the virtual lbn of the triple indirect. */
6789 		lbn = -lbn - (NIADDR - 1);
6790 		end = OFF_TO_IDX(lblktosize(fs, lbn));
6791 	} else
6792 		end = extend;
6793 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
6794 }
6795 
6796 /*
6797  * See if the buf bp is in the range eliminated by truncation.
6798  */
6799 static int
6800 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
6801 	struct buf *bp;
6802 	int *blkoffp;
6803 	ufs_lbn_t lastlbn;
6804 	int lastoff;
6805 	int flags;
6806 {
6807 	ufs_lbn_t lbn;
6808 
6809 	*blkoffp = 0;
6810 	/* Only match ext/normal blocks as appropriate. */
6811 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
6812 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
6813 		return (0);
6814 	/* ALTDATA is always a full truncation. */
6815 	if ((bp->b_xflags & BX_ALTDATA) != 0)
6816 		return (1);
6817 	/* -1 is full truncation. */
6818 	if (lastlbn == -1)
6819 		return (1);
6820 	/*
6821 	 * If this is a partial truncate we only want those
6822 	 * blocks and indirect blocks that cover the range
6823 	 * we're after.
6824 	 */
6825 	lbn = bp->b_lblkno;
6826 	if (lbn < 0)
6827 		lbn = -(lbn + lbn_level(lbn));
6828 	if (lbn < lastlbn)
6829 		return (0);
6830 	/* Here we only truncate lblkno if it's partial. */
6831 	if (lbn == lastlbn) {
6832 		if (lastoff == 0)
6833 			return (0);
6834 		*blkoffp = lastoff;
6835 	}
6836 	return (1);
6837 }
6838 
6839 /*
6840  * Eliminate any dependencies that exist in memory beyond lblkno:off
6841  */
6842 static void
6843 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
6844 	struct inode *ip;
6845 	struct freeblks *freeblks;
6846 	ufs_lbn_t lastlbn;
6847 	int lastoff;
6848 	int flags;
6849 {
6850 	struct bufobj *bo;
6851 	struct vnode *vp;
6852 	struct buf *bp;
6853 	struct fs *fs;
6854 	int blkoff;
6855 
6856 	/*
6857 	 * We must wait for any I/O in progress to finish so that
6858 	 * all potential buffers on the dirty list will be visible.
6859 	 * Once they are all there, walk the list and get rid of
6860 	 * any dependencies.
6861 	 */
6862 	fs = ip->i_fs;
6863 	vp = ITOV(ip);
6864 	bo = &vp->v_bufobj;
6865 	BO_LOCK(bo);
6866 	drain_output(vp);
6867 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
6868 		bp->b_vflags &= ~BV_SCANNED;
6869 restart:
6870 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
6871 		if (bp->b_vflags & BV_SCANNED)
6872 			continue;
6873 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
6874 			bp->b_vflags |= BV_SCANNED;
6875 			continue;
6876 		}
6877 		if ((bp = getdirtybuf(bp, BO_MTX(bo), MNT_WAIT)) == NULL)
6878 			goto restart;
6879 		BO_UNLOCK(bo);
6880 		if (deallocate_dependencies(bp, freeblks, blkoff))
6881 			bqrelse(bp);
6882 		else
6883 			brelse(bp);
6884 		BO_LOCK(bo);
6885 		goto restart;
6886 	}
6887 	/*
6888 	 * Now do the work of vtruncbuf while also matching indirect blocks.
6889 	 */
6890 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
6891 		bp->b_vflags &= ~BV_SCANNED;
6892 cleanrestart:
6893 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
6894 		if (bp->b_vflags & BV_SCANNED)
6895 			continue;
6896 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
6897 			bp->b_vflags |= BV_SCANNED;
6898 			continue;
6899 		}
6900 		if (BUF_LOCK(bp,
6901 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6902 		    BO_MTX(bo)) == ENOLCK) {
6903 			BO_LOCK(bo);
6904 			goto cleanrestart;
6905 		}
6906 		bp->b_vflags |= BV_SCANNED;
6907 		BO_LOCK(bo);
6908 		bremfree(bp);
6909 		BO_UNLOCK(bo);
6910 		if (blkoff != 0) {
6911 			allocbuf(bp, blkoff);
6912 			bqrelse(bp);
6913 		} else {
6914 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
6915 			brelse(bp);
6916 		}
6917 		BO_LOCK(bo);
6918 		goto cleanrestart;
6919 	}
6920 	drain_output(vp);
6921 	BO_UNLOCK(bo);
6922 }
6923 
6924 static int
6925 cancel_pagedep(pagedep, freeblks, blkoff)
6926 	struct pagedep *pagedep;
6927 	struct freeblks *freeblks;
6928 	int blkoff;
6929 {
6930 	struct jremref *jremref;
6931 	struct jmvref *jmvref;
6932 	struct dirrem *dirrem, *tmp;
6933 	int i;
6934 
6935 	/*
6936 	 * Copy any directory remove dependencies to the list
6937 	 * to be processed after the freeblks proceeds.  If
6938 	 * directory entry never made it to disk they
6939 	 * can be dumped directly onto the work list.
6940 	 */
6941 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
6942 		/* Skip this directory removal if it is intended to remain. */
6943 		if (dirrem->dm_offset < blkoff)
6944 			continue;
6945 		/*
6946 		 * If there are any dirrems we wait for the journal write
6947 		 * to complete and then restart the buf scan as the lock
6948 		 * has been dropped.
6949 		 */
6950 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
6951 			jwait(&jremref->jr_list, MNT_WAIT);
6952 			return (ERESTART);
6953 		}
6954 		LIST_REMOVE(dirrem, dm_next);
6955 		dirrem->dm_dirinum = pagedep->pd_ino;
6956 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
6957 	}
6958 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
6959 		jwait(&jmvref->jm_list, MNT_WAIT);
6960 		return (ERESTART);
6961 	}
6962 	/*
6963 	 * When we're partially truncating a pagedep we just want to flush
6964 	 * journal entries and return.  There can not be any adds in the
6965 	 * truncated portion of the directory and newblk must remain if
6966 	 * part of the block remains.
6967 	 */
6968 	if (blkoff != 0) {
6969 		struct diradd *dap;
6970 
6971 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
6972 			if (dap->da_offset > blkoff)
6973 				panic("cancel_pagedep: diradd %p off %d > %d",
6974 				    dap, dap->da_offset, blkoff);
6975 		for (i = 0; i < DAHASHSZ; i++)
6976 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
6977 				if (dap->da_offset > blkoff)
6978 					panic("cancel_pagedep: diradd %p off %d > %d",
6979 					    dap, dap->da_offset, blkoff);
6980 		return (0);
6981 	}
6982 	/*
6983 	 * There should be no directory add dependencies present
6984 	 * as the directory could not be truncated until all
6985 	 * children were removed.
6986 	 */
6987 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
6988 	    ("deallocate_dependencies: pendinghd != NULL"));
6989 	for (i = 0; i < DAHASHSZ; i++)
6990 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
6991 		    ("deallocate_dependencies: diraddhd != NULL"));
6992 	if ((pagedep->pd_state & NEWBLOCK) != 0)
6993 		free_newdirblk(pagedep->pd_newdirblk);
6994 	if (free_pagedep(pagedep) == 0)
6995 		panic("Failed to free pagedep %p", pagedep);
6996 	return (0);
6997 }
6998 
6999 /*
7000  * Reclaim any dependency structures from a buffer that is about to
7001  * be reallocated to a new vnode. The buffer must be locked, thus,
7002  * no I/O completion operations can occur while we are manipulating
7003  * its associated dependencies. The mutex is held so that other I/O's
7004  * associated with related dependencies do not occur.
7005  */
7006 static int
7007 deallocate_dependencies(bp, freeblks, off)
7008 	struct buf *bp;
7009 	struct freeblks *freeblks;
7010 	int off;
7011 {
7012 	struct indirdep *indirdep;
7013 	struct pagedep *pagedep;
7014 	struct allocdirect *adp;
7015 	struct worklist *wk, *wkn;
7016 
7017 	ACQUIRE_LOCK(&lk);
7018 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7019 		switch (wk->wk_type) {
7020 		case D_INDIRDEP:
7021 			indirdep = WK_INDIRDEP(wk);
7022 			if (bp->b_lblkno >= 0 ||
7023 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7024 				panic("deallocate_dependencies: not indir");
7025 			cancel_indirdep(indirdep, bp, freeblks);
7026 			continue;
7027 
7028 		case D_PAGEDEP:
7029 			pagedep = WK_PAGEDEP(wk);
7030 			if (cancel_pagedep(pagedep, freeblks, off)) {
7031 				FREE_LOCK(&lk);
7032 				return (ERESTART);
7033 			}
7034 			continue;
7035 
7036 		case D_ALLOCINDIR:
7037 			/*
7038 			 * Simply remove the allocindir, we'll find it via
7039 			 * the indirdep where we can clear pointers if
7040 			 * needed.
7041 			 */
7042 			WORKLIST_REMOVE(wk);
7043 			continue;
7044 
7045 		case D_FREEWORK:
7046 			/*
7047 			 * A truncation is waiting for the zero'd pointers
7048 			 * to be written.  It can be freed when the freeblks
7049 			 * is journaled.
7050 			 */
7051 			WORKLIST_REMOVE(wk);
7052 			wk->wk_state |= ONDEPLIST;
7053 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7054 			break;
7055 
7056 		case D_ALLOCDIRECT:
7057 			adp = WK_ALLOCDIRECT(wk);
7058 			if (off != 0)
7059 				continue;
7060 			/* FALLTHROUGH */
7061 		default:
7062 			panic("deallocate_dependencies: Unexpected type %s",
7063 			    TYPENAME(wk->wk_type));
7064 			/* NOTREACHED */
7065 		}
7066 	}
7067 	FREE_LOCK(&lk);
7068 	/*
7069 	 * Don't throw away this buf, we were partially truncating and
7070 	 * some deps may always remain.
7071 	 */
7072 	if (off) {
7073 		allocbuf(bp, off);
7074 		bp->b_vflags |= BV_SCANNED;
7075 		return (EBUSY);
7076 	}
7077 	bp->b_flags |= B_INVAL | B_NOCACHE;
7078 
7079 	return (0);
7080 }
7081 
7082 /*
7083  * An allocdirect is being canceled due to a truncate.  We must make sure
7084  * the journal entry is released in concert with the blkfree that releases
7085  * the storage.  Completed journal entries must not be released until the
7086  * space is no longer pointed to by the inode or in the bitmap.
7087  */
7088 static void
7089 cancel_allocdirect(adphead, adp, freeblks)
7090 	struct allocdirectlst *adphead;
7091 	struct allocdirect *adp;
7092 	struct freeblks *freeblks;
7093 {
7094 	struct freework *freework;
7095 	struct newblk *newblk;
7096 	struct worklist *wk;
7097 
7098 	TAILQ_REMOVE(adphead, adp, ad_next);
7099 	newblk = (struct newblk *)adp;
7100 	freework = NULL;
7101 	/*
7102 	 * Find the correct freework structure.
7103 	 */
7104 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7105 		if (wk->wk_type != D_FREEWORK)
7106 			continue;
7107 		freework = WK_FREEWORK(wk);
7108 		if (freework->fw_blkno == newblk->nb_newblkno)
7109 			break;
7110 	}
7111 	if (freework == NULL)
7112 		panic("cancel_allocdirect: Freework not found");
7113 	/*
7114 	 * If a newblk exists at all we still have the journal entry that
7115 	 * initiated the allocation so we do not need to journal the free.
7116 	 */
7117 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7118 	/*
7119 	 * If the journal hasn't been written the jnewblk must be passed
7120 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7121 	 * this by linking the journal dependency into the freework to be
7122 	 * freed when freework_freeblock() is called.  If the journal has
7123 	 * been written we can simply reclaim the journal space when the
7124 	 * freeblks work is complete.
7125 	 */
7126 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7127 	    &freeblks->fb_jwork);
7128 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7129 }
7130 
7131 
7132 /*
7133  * Cancel a new block allocation.  May be an indirect or direct block.  We
7134  * remove it from various lists and return any journal record that needs to
7135  * be resolved by the caller.
7136  *
7137  * A special consideration is made for indirects which were never pointed
7138  * at on disk and will never be found once this block is released.
7139  */
7140 static struct jnewblk *
7141 cancel_newblk(newblk, wk, wkhd)
7142 	struct newblk *newblk;
7143 	struct worklist *wk;
7144 	struct workhead *wkhd;
7145 {
7146 	struct jnewblk *jnewblk;
7147 
7148 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7149 
7150 	newblk->nb_state |= GOINGAWAY;
7151 	/*
7152 	 * Previously we traversed the completedhd on each indirdep
7153 	 * attached to this newblk to cancel them and gather journal
7154 	 * work.  Since we need only the oldest journal segment and
7155 	 * the lowest point on the tree will always have the oldest
7156 	 * journal segment we are free to release the segments
7157 	 * of any subordinates and may leave the indirdep list to
7158 	 * indirdep_complete() when this newblk is freed.
7159 	 */
7160 	if (newblk->nb_state & ONDEPLIST) {
7161 		newblk->nb_state &= ~ONDEPLIST;
7162 		LIST_REMOVE(newblk, nb_deps);
7163 	}
7164 	if (newblk->nb_state & ONWORKLIST)
7165 		WORKLIST_REMOVE(&newblk->nb_list);
7166 	/*
7167 	 * If the journal entry hasn't been written we save a pointer to
7168 	 * the dependency that frees it until it is written or the
7169 	 * superseding operation completes.
7170 	 */
7171 	jnewblk = newblk->nb_jnewblk;
7172 	if (jnewblk != NULL && wk != NULL) {
7173 		newblk->nb_jnewblk = NULL;
7174 		jnewblk->jn_dep = wk;
7175 	}
7176 	if (!LIST_EMPTY(&newblk->nb_jwork))
7177 		jwork_move(wkhd, &newblk->nb_jwork);
7178 	/*
7179 	 * When truncating we must free the newdirblk early to remove
7180 	 * the pagedep from the hash before returning.
7181 	 */
7182 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7183 		free_newdirblk(WK_NEWDIRBLK(wk));
7184 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7185 		panic("cancel_newblk: extra newdirblk");
7186 
7187 	return (jnewblk);
7188 }
7189 
7190 /*
7191  * Schedule the freefrag associated with a newblk to be released once
7192  * the pointers are written and the previous block is no longer needed.
7193  */
7194 static void
7195 newblk_freefrag(newblk)
7196 	struct newblk *newblk;
7197 {
7198 	struct freefrag *freefrag;
7199 
7200 	if (newblk->nb_freefrag == NULL)
7201 		return;
7202 	freefrag = newblk->nb_freefrag;
7203 	newblk->nb_freefrag = NULL;
7204 	freefrag->ff_state |= COMPLETE;
7205 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7206 		add_to_worklist(&freefrag->ff_list, 0);
7207 }
7208 
7209 /*
7210  * Free a newblk. Generate a new freefrag work request if appropriate.
7211  * This must be called after the inode pointer and any direct block pointers
7212  * are valid or fully removed via truncate or frag extension.
7213  */
7214 static void
7215 free_newblk(newblk)
7216 	struct newblk *newblk;
7217 {
7218 	struct indirdep *indirdep;
7219 	struct worklist *wk;
7220 
7221 	KASSERT(newblk->nb_jnewblk == NULL,
7222 	    ("free_newblk; jnewblk %p still attached", newblk->nb_jnewblk));
7223 	mtx_assert(&lk, MA_OWNED);
7224 	newblk_freefrag(newblk);
7225 	if (newblk->nb_state & ONDEPLIST)
7226 		LIST_REMOVE(newblk, nb_deps);
7227 	if (newblk->nb_state & ONWORKLIST)
7228 		WORKLIST_REMOVE(&newblk->nb_list);
7229 	LIST_REMOVE(newblk, nb_hash);
7230 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7231 		free_newdirblk(WK_NEWDIRBLK(wk));
7232 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7233 		panic("free_newblk: extra newdirblk");
7234 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7235 		indirdep_complete(indirdep);
7236 	handle_jwork(&newblk->nb_jwork);
7237 	newblk->nb_list.wk_type = D_NEWBLK;
7238 	WORKITEM_FREE(newblk, D_NEWBLK);
7239 }
7240 
7241 /*
7242  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7243  * This routine must be called with splbio interrupts blocked.
7244  */
7245 static void
7246 free_newdirblk(newdirblk)
7247 	struct newdirblk *newdirblk;
7248 {
7249 	struct pagedep *pagedep;
7250 	struct diradd *dap;
7251 	struct worklist *wk;
7252 
7253 	mtx_assert(&lk, MA_OWNED);
7254 	WORKLIST_REMOVE(&newdirblk->db_list);
7255 	/*
7256 	 * If the pagedep is still linked onto the directory buffer
7257 	 * dependency chain, then some of the entries on the
7258 	 * pd_pendinghd list may not be committed to disk yet. In
7259 	 * this case, we will simply clear the NEWBLOCK flag and
7260 	 * let the pd_pendinghd list be processed when the pagedep
7261 	 * is next written. If the pagedep is no longer on the buffer
7262 	 * dependency chain, then all the entries on the pd_pending
7263 	 * list are committed to disk and we can free them here.
7264 	 */
7265 	pagedep = newdirblk->db_pagedep;
7266 	pagedep->pd_state &= ~NEWBLOCK;
7267 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7268 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7269 			free_diradd(dap, NULL);
7270 		/*
7271 		 * If no dependencies remain, the pagedep will be freed.
7272 		 */
7273 		free_pagedep(pagedep);
7274 	}
7275 	/* Should only ever be one item in the list. */
7276 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7277 		WORKLIST_REMOVE(wk);
7278 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7279 	}
7280 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7281 }
7282 
7283 /*
7284  * Prepare an inode to be freed. The actual free operation is not
7285  * done until the zero'ed inode has been written to disk.
7286  */
7287 void
7288 softdep_freefile(pvp, ino, mode)
7289 	struct vnode *pvp;
7290 	ino_t ino;
7291 	int mode;
7292 {
7293 	struct inode *ip = VTOI(pvp);
7294 	struct inodedep *inodedep;
7295 	struct freefile *freefile;
7296 	struct freeblks *freeblks;
7297 
7298 	/*
7299 	 * This sets up the inode de-allocation dependency.
7300 	 */
7301 	freefile = malloc(sizeof(struct freefile),
7302 		M_FREEFILE, M_SOFTDEP_FLAGS);
7303 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7304 	freefile->fx_mode = mode;
7305 	freefile->fx_oldinum = ino;
7306 	freefile->fx_devvp = ip->i_devvp;
7307 	LIST_INIT(&freefile->fx_jwork);
7308 	UFS_LOCK(ip->i_ump);
7309 	ip->i_fs->fs_pendinginodes += 1;
7310 	UFS_UNLOCK(ip->i_ump);
7311 
7312 	/*
7313 	 * If the inodedep does not exist, then the zero'ed inode has
7314 	 * been written to disk. If the allocated inode has never been
7315 	 * written to disk, then the on-disk inode is zero'ed. In either
7316 	 * case we can free the file immediately.  If the journal was
7317 	 * canceled before being written the inode will never make it to
7318 	 * disk and we must send the canceled journal entrys to
7319 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7320 	 * Any blocks waiting on the inode to write can be safely freed
7321 	 * here as it will never been written.
7322 	 */
7323 	ACQUIRE_LOCK(&lk);
7324 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7325 	if (inodedep) {
7326 		/*
7327 		 * Clear out freeblks that no longer need to reference
7328 		 * this inode.
7329 		 */
7330 		while ((freeblks =
7331 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7332 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7333 			    fb_next);
7334 			freeblks->fb_state &= ~ONDEPLIST;
7335 		}
7336 		/*
7337 		 * Remove this inode from the unlinked list.
7338 		 */
7339 		if (inodedep->id_state & UNLINKED) {
7340 			/*
7341 			 * Save the journal work to be freed with the bitmap
7342 			 * before we clear UNLINKED.  Otherwise it can be lost
7343 			 * if the inode block is written.
7344 			 */
7345 			handle_bufwait(inodedep, &freefile->fx_jwork);
7346 			clear_unlinked_inodedep(inodedep);
7347 			/* Re-acquire inodedep as we've dropped lk. */
7348 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7349 		}
7350 	}
7351 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7352 		FREE_LOCK(&lk);
7353 		handle_workitem_freefile(freefile);
7354 		return;
7355 	}
7356 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7357 		inodedep->id_state |= GOINGAWAY;
7358 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7359 	FREE_LOCK(&lk);
7360 	if (ip->i_number == ino)
7361 		ip->i_flag |= IN_MODIFIED;
7362 }
7363 
7364 /*
7365  * Check to see if an inode has never been written to disk. If
7366  * so free the inodedep and return success, otherwise return failure.
7367  * This routine must be called with splbio interrupts blocked.
7368  *
7369  * If we still have a bitmap dependency, then the inode has never
7370  * been written to disk. Drop the dependency as it is no longer
7371  * necessary since the inode is being deallocated. We set the
7372  * ALLCOMPLETE flags since the bitmap now properly shows that the
7373  * inode is not allocated. Even if the inode is actively being
7374  * written, it has been rolled back to its zero'ed state, so we
7375  * are ensured that a zero inode is what is on the disk. For short
7376  * lived files, this change will usually result in removing all the
7377  * dependencies from the inode so that it can be freed immediately.
7378  */
7379 static int
7380 check_inode_unwritten(inodedep)
7381 	struct inodedep *inodedep;
7382 {
7383 
7384 	mtx_assert(&lk, MA_OWNED);
7385 
7386 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7387 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7388 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7389 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7390 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7391 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7392 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7393 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7394 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7395 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7396 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7397 	    inodedep->id_mkdiradd != NULL ||
7398 	    inodedep->id_nlinkdelta != 0)
7399 		return (0);
7400 	/*
7401 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7402 	 * trying to allocate memory without holding "Softdep Lock".
7403 	 */
7404 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7405 	    inodedep->id_savedino1 == NULL)
7406 		return (0);
7407 
7408 	if (inodedep->id_state & ONDEPLIST)
7409 		LIST_REMOVE(inodedep, id_deps);
7410 	inodedep->id_state &= ~ONDEPLIST;
7411 	inodedep->id_state |= ALLCOMPLETE;
7412 	inodedep->id_bmsafemap = NULL;
7413 	if (inodedep->id_state & ONWORKLIST)
7414 		WORKLIST_REMOVE(&inodedep->id_list);
7415 	if (inodedep->id_savedino1 != NULL) {
7416 		free(inodedep->id_savedino1, M_SAVEDINO);
7417 		inodedep->id_savedino1 = NULL;
7418 	}
7419 	if (free_inodedep(inodedep) == 0)
7420 		panic("check_inode_unwritten: busy inode");
7421 	return (1);
7422 }
7423 
7424 /*
7425  * Try to free an inodedep structure. Return 1 if it could be freed.
7426  */
7427 static int
7428 free_inodedep(inodedep)
7429 	struct inodedep *inodedep;
7430 {
7431 
7432 	mtx_assert(&lk, MA_OWNED);
7433 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7434 	    (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7435 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7436 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7437 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7438 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7439 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7440 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7441 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7442 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7443 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7444 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7445 	    inodedep->id_mkdiradd != NULL ||
7446 	    inodedep->id_nlinkdelta != 0 ||
7447 	    inodedep->id_savedino1 != NULL)
7448 		return (0);
7449 	if (inodedep->id_state & ONDEPLIST)
7450 		LIST_REMOVE(inodedep, id_deps);
7451 	LIST_REMOVE(inodedep, id_hash);
7452 	WORKITEM_FREE(inodedep, D_INODEDEP);
7453 	return (1);
7454 }
7455 
7456 /*
7457  * Free the block referenced by a freework structure.  The parent freeblks
7458  * structure is released and completed when the final cg bitmap reaches
7459  * the disk.  This routine may be freeing a jnewblk which never made it to
7460  * disk in which case we do not have to wait as the operation is undone
7461  * in memory immediately.
7462  */
7463 static void
7464 freework_freeblock(freework)
7465 	struct freework *freework;
7466 {
7467 	struct freeblks *freeblks;
7468 	struct jnewblk *jnewblk;
7469 	struct ufsmount *ump;
7470 	struct workhead wkhd;
7471 	struct fs *fs;
7472 	int bsize;
7473 	int needj;
7474 
7475 	mtx_assert(&lk, MA_OWNED);
7476 	/*
7477 	 * Handle partial truncate separately.
7478 	 */
7479 	if (freework->fw_indir) {
7480 		complete_trunc_indir(freework);
7481 		return;
7482 	}
7483 	freeblks = freework->fw_freeblks;
7484 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7485 	fs = ump->um_fs;
7486 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7487 	bsize = lfragtosize(fs, freework->fw_frags);
7488 	LIST_INIT(&wkhd);
7489 	/*
7490 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7491 	 * on the indirblk hashtable and prevents premature freeing.
7492 	 */
7493 	freework->fw_state |= DEPCOMPLETE;
7494 	/*
7495 	 * SUJ needs to wait for the segment referencing freed indirect
7496 	 * blocks to expire so that we know the checker will not confuse
7497 	 * a re-allocated indirect block with its old contents.
7498 	 */
7499 	if (needj && freework->fw_lbn <= -NDADDR)
7500 		indirblk_insert(freework);
7501 	/*
7502 	 * If we are canceling an existing jnewblk pass it to the free
7503 	 * routine, otherwise pass the freeblk which will ultimately
7504 	 * release the freeblks.  If we're not journaling, we can just
7505 	 * free the freeblks immediately.
7506 	 */
7507 	jnewblk = freework->fw_jnewblk;
7508 	if (jnewblk != NULL) {
7509 		cancel_jnewblk(jnewblk, &wkhd);
7510 		needj = 0;
7511 	} else if (needj) {
7512 		freework->fw_state |= DELAYEDFREE;
7513 		freeblks->fb_cgwait++;
7514 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7515 	}
7516 	FREE_LOCK(&lk);
7517 	freeblks_free(ump, freeblks, btodb(bsize));
7518 	CTR4(KTR_SUJ,
7519 	    "freework_freeblock: ino %d blkno %jd lbn %jd size %ld",
7520 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7521 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7522 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7523 	ACQUIRE_LOCK(&lk);
7524 	/*
7525 	 * The jnewblk will be discarded and the bits in the map never
7526 	 * made it to disk.  We can immediately free the freeblk.
7527 	 */
7528 	if (needj == 0)
7529 		handle_written_freework(freework);
7530 }
7531 
7532 /*
7533  * We enqueue freework items that need processing back on the freeblks and
7534  * add the freeblks to the worklist.  This makes it easier to find all work
7535  * required to flush a truncation in process_truncates().
7536  */
7537 static void
7538 freework_enqueue(freework)
7539 	struct freework *freework;
7540 {
7541 	struct freeblks *freeblks;
7542 
7543 	freeblks = freework->fw_freeblks;
7544 	if ((freework->fw_state & INPROGRESS) == 0)
7545 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7546 	if ((freeblks->fb_state &
7547 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7548 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7549 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7550 }
7551 
7552 /*
7553  * Start, continue, or finish the process of freeing an indirect block tree.
7554  * The free operation may be paused at any point with fw_off containing the
7555  * offset to restart from.  This enables us to implement some flow control
7556  * for large truncates which may fan out and generate a huge number of
7557  * dependencies.
7558  */
7559 static void
7560 handle_workitem_indirblk(freework)
7561 	struct freework *freework;
7562 {
7563 	struct freeblks *freeblks;
7564 	struct ufsmount *ump;
7565 	struct fs *fs;
7566 
7567 	freeblks = freework->fw_freeblks;
7568 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7569 	fs = ump->um_fs;
7570 	if (freework->fw_state & DEPCOMPLETE) {
7571 		handle_written_freework(freework);
7572 		return;
7573 	}
7574 	if (freework->fw_off == NINDIR(fs)) {
7575 		freework_freeblock(freework);
7576 		return;
7577 	}
7578 	freework->fw_state |= INPROGRESS;
7579 	FREE_LOCK(&lk);
7580 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7581 	    freework->fw_lbn);
7582 	ACQUIRE_LOCK(&lk);
7583 }
7584 
7585 /*
7586  * Called when a freework structure attached to a cg buf is written.  The
7587  * ref on either the parent or the freeblks structure is released and
7588  * the freeblks is added back to the worklist if there is more work to do.
7589  */
7590 static void
7591 handle_written_freework(freework)
7592 	struct freework *freework;
7593 {
7594 	struct freeblks *freeblks;
7595 	struct freework *parent;
7596 
7597 	freeblks = freework->fw_freeblks;
7598 	parent = freework->fw_parent;
7599 	if (freework->fw_state & DELAYEDFREE)
7600 		freeblks->fb_cgwait--;
7601 	freework->fw_state |= COMPLETE;
7602 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7603 		WORKITEM_FREE(freework, D_FREEWORK);
7604 	if (parent) {
7605 		if (--parent->fw_ref == 0)
7606 			freework_enqueue(parent);
7607 		return;
7608 	}
7609 	if (--freeblks->fb_ref != 0)
7610 		return;
7611 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7612 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7613 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7614 }
7615 
7616 /*
7617  * This workitem routine performs the block de-allocation.
7618  * The workitem is added to the pending list after the updated
7619  * inode block has been written to disk.  As mentioned above,
7620  * checks regarding the number of blocks de-allocated (compared
7621  * to the number of blocks allocated for the file) are also
7622  * performed in this function.
7623  */
7624 static int
7625 handle_workitem_freeblocks(freeblks, flags)
7626 	struct freeblks *freeblks;
7627 	int flags;
7628 {
7629 	struct freework *freework;
7630 	struct newblk *newblk;
7631 	struct allocindir *aip;
7632 	struct ufsmount *ump;
7633 	struct worklist *wk;
7634 
7635 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7636 	    ("handle_workitem_freeblocks: Journal entries not written."));
7637 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7638 	ACQUIRE_LOCK(&lk);
7639 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7640 		WORKLIST_REMOVE(wk);
7641 		switch (wk->wk_type) {
7642 		case D_DIRREM:
7643 			wk->wk_state |= COMPLETE;
7644 			add_to_worklist(wk, 0);
7645 			continue;
7646 
7647 		case D_ALLOCDIRECT:
7648 			free_newblk(WK_NEWBLK(wk));
7649 			continue;
7650 
7651 		case D_ALLOCINDIR:
7652 			aip = WK_ALLOCINDIR(wk);
7653 			freework = NULL;
7654 			if (aip->ai_state & DELAYEDFREE) {
7655 				FREE_LOCK(&lk);
7656 				freework = newfreework(ump, freeblks, NULL,
7657 				    aip->ai_lbn, aip->ai_newblkno,
7658 				    ump->um_fs->fs_frag, 0, 0);
7659 				ACQUIRE_LOCK(&lk);
7660 			}
7661 			newblk = WK_NEWBLK(wk);
7662 			if (newblk->nb_jnewblk) {
7663 				freework->fw_jnewblk = newblk->nb_jnewblk;
7664 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7665 				newblk->nb_jnewblk = NULL;
7666 			}
7667 			free_newblk(newblk);
7668 			continue;
7669 
7670 		case D_FREEWORK:
7671 			freework = WK_FREEWORK(wk);
7672 			if (freework->fw_lbn <= -NDADDR)
7673 				handle_workitem_indirblk(freework);
7674 			else
7675 				freework_freeblock(freework);
7676 			continue;
7677 		default:
7678 			panic("handle_workitem_freeblocks: Unknown type %s",
7679 			    TYPENAME(wk->wk_type));
7680 		}
7681 	}
7682 	if (freeblks->fb_ref != 0) {
7683 		freeblks->fb_state &= ~INPROGRESS;
7684 		wake_worklist(&freeblks->fb_list);
7685 		freeblks = NULL;
7686 	}
7687 	FREE_LOCK(&lk);
7688 	if (freeblks)
7689 		return handle_complete_freeblocks(freeblks, flags);
7690 	return (0);
7691 }
7692 
7693 /*
7694  * Handle completion of block free via truncate.  This allows fs_pending
7695  * to track the actual free block count more closely than if we only updated
7696  * it at the end.  We must be careful to handle cases where the block count
7697  * on free was incorrect.
7698  */
7699 static void
7700 freeblks_free(ump, freeblks, blocks)
7701 	struct ufsmount *ump;
7702 	struct freeblks *freeblks;
7703 	int blocks;
7704 {
7705 	struct fs *fs;
7706 	ufs2_daddr_t remain;
7707 
7708 	UFS_LOCK(ump);
7709 	remain = -freeblks->fb_chkcnt;
7710 	freeblks->fb_chkcnt += blocks;
7711 	if (remain > 0) {
7712 		if (remain < blocks)
7713 			blocks = remain;
7714 		fs = ump->um_fs;
7715 		fs->fs_pendingblocks -= blocks;
7716 	}
7717 	UFS_UNLOCK(ump);
7718 }
7719 
7720 /*
7721  * Once all of the freework workitems are complete we can retire the
7722  * freeblocks dependency and any journal work awaiting completion.  This
7723  * can not be called until all other dependencies are stable on disk.
7724  */
7725 static int
7726 handle_complete_freeblocks(freeblks, flags)
7727 	struct freeblks *freeblks;
7728 	int flags;
7729 {
7730 	struct inodedep *inodedep;
7731 	struct inode *ip;
7732 	struct vnode *vp;
7733 	struct fs *fs;
7734 	struct ufsmount *ump;
7735 	ufs2_daddr_t spare;
7736 
7737 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7738 	fs = ump->um_fs;
7739 	flags = LK_EXCLUSIVE | flags;
7740 	spare = freeblks->fb_chkcnt;
7741 
7742 	/*
7743 	 * If we did not release the expected number of blocks we may have
7744 	 * to adjust the inode block count here.  Only do so if it wasn't
7745 	 * a truncation to zero and the modrev still matches.
7746 	 */
7747 	if (spare && freeblks->fb_len != 0) {
7748 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7749 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
7750 			return (EBUSY);
7751 		ip = VTOI(vp);
7752 		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
7753 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
7754 			ip->i_flag |= IN_CHANGE;
7755 			/*
7756 			 * We must wait so this happens before the
7757 			 * journal is reclaimed.
7758 			 */
7759 			ffs_update(vp, 1);
7760 		}
7761 		vput(vp);
7762 	}
7763 	if (spare < 0) {
7764 		UFS_LOCK(ump);
7765 		fs->fs_pendingblocks += spare;
7766 		UFS_UNLOCK(ump);
7767 	}
7768 #ifdef QUOTA
7769 	/* Handle spare. */
7770 	if (spare)
7771 		quotaadj(freeblks->fb_quota, ump, -spare);
7772 	quotarele(freeblks->fb_quota);
7773 #endif
7774 	ACQUIRE_LOCK(&lk);
7775 	if (freeblks->fb_state & ONDEPLIST) {
7776 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7777 		    0, &inodedep);
7778 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
7779 		freeblks->fb_state &= ~ONDEPLIST;
7780 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
7781 			free_inodedep(inodedep);
7782 	}
7783 	/*
7784 	 * All of the freeblock deps must be complete prior to this call
7785 	 * so it's now safe to complete earlier outstanding journal entries.
7786 	 */
7787 	handle_jwork(&freeblks->fb_jwork);
7788 	WORKITEM_FREE(freeblks, D_FREEBLKS);
7789 	FREE_LOCK(&lk);
7790 	return (0);
7791 }
7792 
7793 /*
7794  * Release blocks associated with the freeblks and stored in the indirect
7795  * block dbn. If level is greater than SINGLE, the block is an indirect block
7796  * and recursive calls to indirtrunc must be used to cleanse other indirect
7797  * blocks.
7798  *
7799  * This handles partial and complete truncation of blocks.  Partial is noted
7800  * with goingaway == 0.  In this case the freework is completed after the
7801  * zero'd indirects are written to disk.  For full truncation the freework
7802  * is completed after the block is freed.
7803  */
7804 static void
7805 indir_trunc(freework, dbn, lbn)
7806 	struct freework *freework;
7807 	ufs2_daddr_t dbn;
7808 	ufs_lbn_t lbn;
7809 {
7810 	struct freework *nfreework;
7811 	struct workhead wkhd;
7812 	struct freeblks *freeblks;
7813 	struct buf *bp;
7814 	struct fs *fs;
7815 	struct indirdep *indirdep;
7816 	struct ufsmount *ump;
7817 	ufs1_daddr_t *bap1 = 0;
7818 	ufs2_daddr_t nb, nnb, *bap2 = 0;
7819 	ufs_lbn_t lbnadd, nlbn;
7820 	int i, nblocks, ufs1fmt;
7821 	int freedblocks;
7822 	int goingaway;
7823 	int freedeps;
7824 	int needj;
7825 	int level;
7826 	int cnt;
7827 
7828 	freeblks = freework->fw_freeblks;
7829 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7830 	fs = ump->um_fs;
7831 	/*
7832 	 * Get buffer of block pointers to be freed.  There are three cases:
7833 	 *
7834 	 * 1) Partial truncate caches the indirdep pointer in the freework
7835 	 *    which provides us a back copy to the save bp which holds the
7836 	 *    pointers we want to clear.  When this completes the zero
7837 	 *    pointers are written to the real copy.
7838 	 * 2) The indirect is being completely truncated, cancel_indirdep()
7839 	 *    eliminated the real copy and placed the indirdep on the saved
7840 	 *    copy.  The indirdep and buf are discarded when this completes.
7841 	 * 3) The indirect was not in memory, we read a copy off of the disk
7842 	 *    using the devvp and drop and invalidate the buffer when we're
7843 	 *    done.
7844 	 */
7845 	goingaway = 1;
7846 	indirdep = NULL;
7847 	if (freework->fw_indir != NULL) {
7848 		goingaway = 0;
7849 		indirdep = freework->fw_indir;
7850 		bp = indirdep->ir_savebp;
7851 		if (bp == NULL || bp->b_blkno != dbn)
7852 			panic("indir_trunc: Bad saved buf %p blkno %jd",
7853 			    bp, (intmax_t)dbn);
7854 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
7855 		/*
7856 		 * The lock prevents the buf dep list from changing and
7857 	 	 * indirects on devvp should only ever have one dependency.
7858 		 */
7859 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
7860 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
7861 			panic("indir_trunc: Bad indirdep %p from buf %p",
7862 			    indirdep, bp);
7863 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
7864 	    NOCRED, &bp) != 0) {
7865 		brelse(bp);
7866 		return;
7867 	}
7868 	ACQUIRE_LOCK(&lk);
7869 	/* Protects against a race with complete_trunc_indir(). */
7870 	freework->fw_state &= ~INPROGRESS;
7871 	/*
7872 	 * If we have an indirdep we need to enforce the truncation order
7873 	 * and discard it when it is complete.
7874 	 */
7875 	if (indirdep) {
7876 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
7877 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
7878 			/*
7879 			 * Add the complete truncate to the list on the
7880 			 * indirdep to enforce in-order processing.
7881 			 */
7882 			if (freework->fw_indir == NULL)
7883 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
7884 				    freework, fw_next);
7885 			FREE_LOCK(&lk);
7886 			return;
7887 		}
7888 		/*
7889 		 * If we're goingaway, free the indirdep.  Otherwise it will
7890 		 * linger until the write completes.
7891 		 */
7892 		if (goingaway) {
7893 			free_indirdep(indirdep);
7894 			ump->um_numindirdeps -= 1;
7895 		}
7896 	}
7897 	FREE_LOCK(&lk);
7898 	/* Initialize pointers depending on block size. */
7899 	if (ump->um_fstype == UFS1) {
7900 		bap1 = (ufs1_daddr_t *)bp->b_data;
7901 		nb = bap1[freework->fw_off];
7902 		ufs1fmt = 1;
7903 	} else {
7904 		bap2 = (ufs2_daddr_t *)bp->b_data;
7905 		nb = bap2[freework->fw_off];
7906 		ufs1fmt = 0;
7907 	}
7908 	level = lbn_level(lbn);
7909 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
7910 	lbnadd = lbn_offset(fs, level);
7911 	nblocks = btodb(fs->fs_bsize);
7912 	nfreework = freework;
7913 	freedeps = 0;
7914 	cnt = 0;
7915 	/*
7916 	 * Reclaim blocks.  Traverses into nested indirect levels and
7917 	 * arranges for the current level to be freed when subordinates
7918 	 * are free when journaling.
7919 	 */
7920 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
7921 		if (i != NINDIR(fs) - 1) {
7922 			if (ufs1fmt)
7923 				nnb = bap1[i+1];
7924 			else
7925 				nnb = bap2[i+1];
7926 		} else
7927 			nnb = 0;
7928 		if (nb == 0)
7929 			continue;
7930 		cnt++;
7931 		if (level != 0) {
7932 			nlbn = (lbn + 1) - (i * lbnadd);
7933 			if (needj != 0) {
7934 				nfreework = newfreework(ump, freeblks, freework,
7935 				    nlbn, nb, fs->fs_frag, 0, 0);
7936 				freedeps++;
7937 			}
7938 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
7939 		} else {
7940 			struct freedep *freedep;
7941 
7942 			/*
7943 			 * Attempt to aggregate freedep dependencies for
7944 			 * all blocks being released to the same CG.
7945 			 */
7946 			LIST_INIT(&wkhd);
7947 			if (needj != 0 &&
7948 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
7949 				freedep = newfreedep(freework);
7950 				WORKLIST_INSERT_UNLOCKED(&wkhd,
7951 				    &freedep->fd_list);
7952 				freedeps++;
7953 			}
7954 			CTR3(KTR_SUJ,
7955 			    "indir_trunc: ino %d blkno %jd size %ld",
7956 			    freeblks->fb_inum, nb, fs->fs_bsize);
7957 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
7958 			    fs->fs_bsize, freeblks->fb_inum,
7959 			    freeblks->fb_vtype, &wkhd);
7960 		}
7961 	}
7962 	if (goingaway) {
7963 		bp->b_flags |= B_INVAL | B_NOCACHE;
7964 		brelse(bp);
7965 	}
7966 	freedblocks = 0;
7967 	if (level == 0)
7968 		freedblocks = (nblocks * cnt);
7969 	if (needj == 0)
7970 		freedblocks += nblocks;
7971 	freeblks_free(ump, freeblks, freedblocks);
7972 	/*
7973 	 * If we are journaling set up the ref counts and offset so this
7974 	 * indirect can be completed when its children are free.
7975 	 */
7976 	if (needj) {
7977 		ACQUIRE_LOCK(&lk);
7978 		freework->fw_off = i;
7979 		freework->fw_ref += freedeps;
7980 		freework->fw_ref -= NINDIR(fs) + 1;
7981 		if (level == 0)
7982 			freeblks->fb_cgwait += freedeps;
7983 		if (freework->fw_ref == 0)
7984 			freework_freeblock(freework);
7985 		FREE_LOCK(&lk);
7986 		return;
7987 	}
7988 	/*
7989 	 * If we're not journaling we can free the indirect now.
7990 	 */
7991 	dbn = dbtofsb(fs, dbn);
7992 	CTR3(KTR_SUJ,
7993 	    "indir_trunc 2: ino %d blkno %jd size %ld",
7994 	    freeblks->fb_inum, dbn, fs->fs_bsize);
7995 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
7996 	    freeblks->fb_inum, freeblks->fb_vtype, NULL);
7997 	/* Non SUJ softdep does single-threaded truncations. */
7998 	if (freework->fw_blkno == dbn) {
7999 		freework->fw_state |= ALLCOMPLETE;
8000 		ACQUIRE_LOCK(&lk);
8001 		handle_written_freework(freework);
8002 		FREE_LOCK(&lk);
8003 	}
8004 	return;
8005 }
8006 
8007 /*
8008  * Cancel an allocindir when it is removed via truncation.  When bp is not
8009  * NULL the indirect never appeared on disk and is scheduled to be freed
8010  * independently of the indir so we can more easily track journal work.
8011  */
8012 static void
8013 cancel_allocindir(aip, bp, freeblks, trunc)
8014 	struct allocindir *aip;
8015 	struct buf *bp;
8016 	struct freeblks *freeblks;
8017 	int trunc;
8018 {
8019 	struct indirdep *indirdep;
8020 	struct freefrag *freefrag;
8021 	struct newblk *newblk;
8022 
8023 	newblk = (struct newblk *)aip;
8024 	LIST_REMOVE(aip, ai_next);
8025 	/*
8026 	 * We must eliminate the pointer in bp if it must be freed on its
8027 	 * own due to partial truncate or pending journal work.
8028 	 */
8029 	if (bp && (trunc || newblk->nb_jnewblk)) {
8030 		/*
8031 		 * Clear the pointer and mark the aip to be freed
8032 		 * directly if it never existed on disk.
8033 		 */
8034 		aip->ai_state |= DELAYEDFREE;
8035 		indirdep = aip->ai_indirdep;
8036 		if (indirdep->ir_state & UFS1FMT)
8037 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8038 		else
8039 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8040 	}
8041 	/*
8042 	 * When truncating the previous pointer will be freed via
8043 	 * savedbp.  Eliminate the freefrag which would dup free.
8044 	 */
8045 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8046 		newblk->nb_freefrag = NULL;
8047 		if (freefrag->ff_jdep)
8048 			cancel_jfreefrag(
8049 			    WK_JFREEFRAG(freefrag->ff_jdep));
8050 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8051 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8052 	}
8053 	/*
8054 	 * If the journal hasn't been written the jnewblk must be passed
8055 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8056 	 * this by leaving the journal dependency on the newblk to be freed
8057 	 * when a freework is created in handle_workitem_freeblocks().
8058 	 */
8059 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8060 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8061 }
8062 
8063 /*
8064  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8065  * in to a newdirblk so any subsequent additions are tracked properly.  The
8066  * caller is responsible for adding the mkdir1 dependency to the journal
8067  * and updating id_mkdiradd.  This function returns with lk held.
8068  */
8069 static struct mkdir *
8070 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8071 	struct diradd *dap;
8072 	ino_t newinum;
8073 	ino_t dinum;
8074 	struct buf *newdirbp;
8075 	struct mkdir **mkdirp;
8076 {
8077 	struct newblk *newblk;
8078 	struct pagedep *pagedep;
8079 	struct inodedep *inodedep;
8080 	struct newdirblk *newdirblk = 0;
8081 	struct mkdir *mkdir1, *mkdir2;
8082 	struct worklist *wk;
8083 	struct jaddref *jaddref;
8084 	struct mount *mp;
8085 
8086 	mp = dap->da_list.wk_mp;
8087 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8088 	    M_SOFTDEP_FLAGS);
8089 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8090 	LIST_INIT(&newdirblk->db_mkdir);
8091 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8092 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8093 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8094 	mkdir1->md_diradd = dap;
8095 	mkdir1->md_jaddref = NULL;
8096 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8097 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8098 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8099 	mkdir2->md_diradd = dap;
8100 	mkdir2->md_jaddref = NULL;
8101 	if (MOUNTEDSUJ(mp) == 0) {
8102 		mkdir1->md_state |= DEPCOMPLETE;
8103 		mkdir2->md_state |= DEPCOMPLETE;
8104 	}
8105 	/*
8106 	 * Dependency on "." and ".." being written to disk.
8107 	 */
8108 	mkdir1->md_buf = newdirbp;
8109 	ACQUIRE_LOCK(&lk);
8110 	LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
8111 	/*
8112 	 * We must link the pagedep, allocdirect, and newdirblk for
8113 	 * the initial file page so the pointer to the new directory
8114 	 * is not written until the directory contents are live and
8115 	 * any subsequent additions are not marked live until the
8116 	 * block is reachable via the inode.
8117 	 */
8118 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8119 		panic("setup_newdir: lost pagedep");
8120 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8121 		if (wk->wk_type == D_ALLOCDIRECT)
8122 			break;
8123 	if (wk == NULL)
8124 		panic("setup_newdir: lost allocdirect");
8125 	if (pagedep->pd_state & NEWBLOCK)
8126 		panic("setup_newdir: NEWBLOCK already set");
8127 	newblk = WK_NEWBLK(wk);
8128 	pagedep->pd_state |= NEWBLOCK;
8129 	pagedep->pd_newdirblk = newdirblk;
8130 	newdirblk->db_pagedep = pagedep;
8131 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8132 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8133 	/*
8134 	 * Look up the inodedep for the parent directory so that we
8135 	 * can link mkdir2 into the pending dotdot jaddref or
8136 	 * the inode write if there is none.  If the inode is
8137 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8138 	 * been satisfied and mkdir2 can be freed.
8139 	 */
8140 	inodedep_lookup(mp, dinum, 0, &inodedep);
8141 	if (MOUNTEDSUJ(mp)) {
8142 		if (inodedep == NULL)
8143 			panic("setup_newdir: Lost parent.");
8144 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8145 		    inoreflst);
8146 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8147 		    (jaddref->ja_state & MKDIR_PARENT),
8148 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8149 		LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
8150 		mkdir2->md_jaddref = jaddref;
8151 		jaddref->ja_mkdir = mkdir2;
8152 	} else if (inodedep == NULL ||
8153 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8154 		dap->da_state &= ~MKDIR_PARENT;
8155 		WORKITEM_FREE(mkdir2, D_MKDIR);
8156 		mkdir2 = NULL;
8157 	} else {
8158 		LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
8159 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8160 	}
8161 	*mkdirp = mkdir2;
8162 
8163 	return (mkdir1);
8164 }
8165 
8166 /*
8167  * Directory entry addition dependencies.
8168  *
8169  * When adding a new directory entry, the inode (with its incremented link
8170  * count) must be written to disk before the directory entry's pointer to it.
8171  * Also, if the inode is newly allocated, the corresponding freemap must be
8172  * updated (on disk) before the directory entry's pointer. These requirements
8173  * are met via undo/redo on the directory entry's pointer, which consists
8174  * simply of the inode number.
8175  *
8176  * As directory entries are added and deleted, the free space within a
8177  * directory block can become fragmented.  The ufs filesystem will compact
8178  * a fragmented directory block to make space for a new entry. When this
8179  * occurs, the offsets of previously added entries change. Any "diradd"
8180  * dependency structures corresponding to these entries must be updated with
8181  * the new offsets.
8182  */
8183 
8184 /*
8185  * This routine is called after the in-memory inode's link
8186  * count has been incremented, but before the directory entry's
8187  * pointer to the inode has been set.
8188  */
8189 int
8190 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8191 	struct buf *bp;		/* buffer containing directory block */
8192 	struct inode *dp;	/* inode for directory */
8193 	off_t diroffset;	/* offset of new entry in directory */
8194 	ino_t newinum;		/* inode referenced by new directory entry */
8195 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8196 	int isnewblk;		/* entry is in a newly allocated block */
8197 {
8198 	int offset;		/* offset of new entry within directory block */
8199 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8200 	struct fs *fs;
8201 	struct diradd *dap;
8202 	struct newblk *newblk;
8203 	struct pagedep *pagedep;
8204 	struct inodedep *inodedep;
8205 	struct newdirblk *newdirblk = 0;
8206 	struct mkdir *mkdir1, *mkdir2;
8207 	struct jaddref *jaddref;
8208 	struct mount *mp;
8209 	int isindir;
8210 
8211 	/*
8212 	 * Whiteouts have no dependencies.
8213 	 */
8214 	if (newinum == WINO) {
8215 		if (newdirbp != NULL)
8216 			bdwrite(newdirbp);
8217 		return (0);
8218 	}
8219 	jaddref = NULL;
8220 	mkdir1 = mkdir2 = NULL;
8221 	mp = UFSTOVFS(dp->i_ump);
8222 	fs = dp->i_fs;
8223 	lbn = lblkno(fs, diroffset);
8224 	offset = blkoff(fs, diroffset);
8225 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8226 		M_SOFTDEP_FLAGS|M_ZERO);
8227 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8228 	dap->da_offset = offset;
8229 	dap->da_newinum = newinum;
8230 	dap->da_state = ATTACHED;
8231 	LIST_INIT(&dap->da_jwork);
8232 	isindir = bp->b_lblkno >= NDADDR;
8233 	if (isnewblk &&
8234 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8235 		newdirblk = malloc(sizeof(struct newdirblk),
8236 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8237 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8238 		LIST_INIT(&newdirblk->db_mkdir);
8239 	}
8240 	/*
8241 	 * If we're creating a new directory setup the dependencies and set
8242 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8243 	 * we can move on.
8244 	 */
8245 	if (newdirbp == NULL) {
8246 		dap->da_state |= DEPCOMPLETE;
8247 		ACQUIRE_LOCK(&lk);
8248 	} else {
8249 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8250 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8251 		    &mkdir2);
8252 	}
8253 	/*
8254 	 * Link into parent directory pagedep to await its being written.
8255 	 */
8256 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8257 #ifdef DEBUG
8258 	if (diradd_lookup(pagedep, offset) != NULL)
8259 		panic("softdep_setup_directory_add: %p already at off %d\n",
8260 		    diradd_lookup(pagedep, offset), offset);
8261 #endif
8262 	dap->da_pagedep = pagedep;
8263 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8264 	    da_pdlist);
8265 	inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep);
8266 	/*
8267 	 * If we're journaling, link the diradd into the jaddref so it
8268 	 * may be completed after the journal entry is written.  Otherwise,
8269 	 * link the diradd into its inodedep.  If the inode is not yet
8270 	 * written place it on the bufwait list, otherwise do the post-inode
8271 	 * write processing to put it on the id_pendinghd list.
8272 	 */
8273 	if (MOUNTEDSUJ(mp)) {
8274 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8275 		    inoreflst);
8276 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8277 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8278 		jaddref->ja_diroff = diroffset;
8279 		jaddref->ja_diradd = dap;
8280 		add_to_journal(&jaddref->ja_list);
8281 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8282 		diradd_inode_written(dap, inodedep);
8283 	else
8284 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8285 	/*
8286 	 * Add the journal entries for . and .. links now that the primary
8287 	 * link is written.
8288 	 */
8289 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8290 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8291 		    inoreflst, if_deps);
8292 		KASSERT(jaddref != NULL &&
8293 		    jaddref->ja_ino == jaddref->ja_parent &&
8294 		    (jaddref->ja_state & MKDIR_BODY),
8295 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8296 		    jaddref));
8297 		mkdir1->md_jaddref = jaddref;
8298 		jaddref->ja_mkdir = mkdir1;
8299 		/*
8300 		 * It is important that the dotdot journal entry
8301 		 * is added prior to the dot entry since dot writes
8302 		 * both the dot and dotdot links.  These both must
8303 		 * be added after the primary link for the journal
8304 		 * to remain consistent.
8305 		 */
8306 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8307 		add_to_journal(&jaddref->ja_list);
8308 	}
8309 	/*
8310 	 * If we are adding a new directory remember this diradd so that if
8311 	 * we rename it we can keep the dot and dotdot dependencies.  If
8312 	 * we are adding a new name for an inode that has a mkdiradd we
8313 	 * must be in rename and we have to move the dot and dotdot
8314 	 * dependencies to this new name.  The old name is being orphaned
8315 	 * soon.
8316 	 */
8317 	if (mkdir1 != NULL) {
8318 		if (inodedep->id_mkdiradd != NULL)
8319 			panic("softdep_setup_directory_add: Existing mkdir");
8320 		inodedep->id_mkdiradd = dap;
8321 	} else if (inodedep->id_mkdiradd)
8322 		merge_diradd(inodedep, dap);
8323 	if (newdirblk) {
8324 		/*
8325 		 * There is nothing to do if we are already tracking
8326 		 * this block.
8327 		 */
8328 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8329 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8330 			FREE_LOCK(&lk);
8331 			return (0);
8332 		}
8333 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8334 		    == 0)
8335 			panic("softdep_setup_directory_add: lost entry");
8336 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8337 		pagedep->pd_state |= NEWBLOCK;
8338 		pagedep->pd_newdirblk = newdirblk;
8339 		newdirblk->db_pagedep = pagedep;
8340 		FREE_LOCK(&lk);
8341 		/*
8342 		 * If we extended into an indirect signal direnter to sync.
8343 		 */
8344 		if (isindir)
8345 			return (1);
8346 		return (0);
8347 	}
8348 	FREE_LOCK(&lk);
8349 	return (0);
8350 }
8351 
8352 /*
8353  * This procedure is called to change the offset of a directory
8354  * entry when compacting a directory block which must be owned
8355  * exclusively by the caller. Note that the actual entry movement
8356  * must be done in this procedure to ensure that no I/O completions
8357  * occur while the move is in progress.
8358  */
8359 void
8360 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8361 	struct buf *bp;		/* Buffer holding directory block. */
8362 	struct inode *dp;	/* inode for directory */
8363 	caddr_t base;		/* address of dp->i_offset */
8364 	caddr_t oldloc;		/* address of old directory location */
8365 	caddr_t newloc;		/* address of new directory location */
8366 	int entrysize;		/* size of directory entry */
8367 {
8368 	int offset, oldoffset, newoffset;
8369 	struct pagedep *pagedep;
8370 	struct jmvref *jmvref;
8371 	struct diradd *dap;
8372 	struct direct *de;
8373 	struct mount *mp;
8374 	ufs_lbn_t lbn;
8375 	int flags;
8376 
8377 	mp = UFSTOVFS(dp->i_ump);
8378 	de = (struct direct *)oldloc;
8379 	jmvref = NULL;
8380 	flags = 0;
8381 	/*
8382 	 * Moves are always journaled as it would be too complex to
8383 	 * determine if any affected adds or removes are present in the
8384 	 * journal.
8385 	 */
8386 	if (MOUNTEDSUJ(mp)) {
8387 		flags = DEPALLOC;
8388 		jmvref = newjmvref(dp, de->d_ino,
8389 		    dp->i_offset + (oldloc - base),
8390 		    dp->i_offset + (newloc - base));
8391 	}
8392 	lbn = lblkno(dp->i_fs, dp->i_offset);
8393 	offset = blkoff(dp->i_fs, dp->i_offset);
8394 	oldoffset = offset + (oldloc - base);
8395 	newoffset = offset + (newloc - base);
8396 	ACQUIRE_LOCK(&lk);
8397 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8398 		goto done;
8399 	dap = diradd_lookup(pagedep, oldoffset);
8400 	if (dap) {
8401 		dap->da_offset = newoffset;
8402 		newoffset = DIRADDHASH(newoffset);
8403 		oldoffset = DIRADDHASH(oldoffset);
8404 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8405 		    newoffset != oldoffset) {
8406 			LIST_REMOVE(dap, da_pdlist);
8407 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8408 			    dap, da_pdlist);
8409 		}
8410 	}
8411 done:
8412 	if (jmvref) {
8413 		jmvref->jm_pagedep = pagedep;
8414 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8415 		add_to_journal(&jmvref->jm_list);
8416 	}
8417 	bcopy(oldloc, newloc, entrysize);
8418 	FREE_LOCK(&lk);
8419 }
8420 
8421 /*
8422  * Move the mkdir dependencies and journal work from one diradd to another
8423  * when renaming a directory.  The new name must depend on the mkdir deps
8424  * completing as the old name did.  Directories can only have one valid link
8425  * at a time so one must be canonical.
8426  */
8427 static void
8428 merge_diradd(inodedep, newdap)
8429 	struct inodedep *inodedep;
8430 	struct diradd *newdap;
8431 {
8432 	struct diradd *olddap;
8433 	struct mkdir *mkdir, *nextmd;
8434 	short state;
8435 
8436 	olddap = inodedep->id_mkdiradd;
8437 	inodedep->id_mkdiradd = newdap;
8438 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8439 		newdap->da_state &= ~DEPCOMPLETE;
8440 		for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
8441 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8442 			if (mkdir->md_diradd != olddap)
8443 				continue;
8444 			mkdir->md_diradd = newdap;
8445 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8446 			newdap->da_state |= state;
8447 			olddap->da_state &= ~state;
8448 			if ((olddap->da_state &
8449 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8450 				break;
8451 		}
8452 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8453 			panic("merge_diradd: unfound ref");
8454 	}
8455 	/*
8456 	 * Any mkdir related journal items are not safe to be freed until
8457 	 * the new name is stable.
8458 	 */
8459 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8460 	olddap->da_state |= DEPCOMPLETE;
8461 	complete_diradd(olddap);
8462 }
8463 
8464 /*
8465  * Move the diradd to the pending list when all diradd dependencies are
8466  * complete.
8467  */
8468 static void
8469 complete_diradd(dap)
8470 	struct diradd *dap;
8471 {
8472 	struct pagedep *pagedep;
8473 
8474 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8475 		if (dap->da_state & DIRCHG)
8476 			pagedep = dap->da_previous->dm_pagedep;
8477 		else
8478 			pagedep = dap->da_pagedep;
8479 		LIST_REMOVE(dap, da_pdlist);
8480 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8481 	}
8482 }
8483 
8484 /*
8485  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8486  * add entries and conditonally journal the remove.
8487  */
8488 static void
8489 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8490 	struct diradd *dap;
8491 	struct dirrem *dirrem;
8492 	struct jremref *jremref;
8493 	struct jremref *dotremref;
8494 	struct jremref *dotdotremref;
8495 {
8496 	struct inodedep *inodedep;
8497 	struct jaddref *jaddref;
8498 	struct inoref *inoref;
8499 	struct mkdir *mkdir;
8500 
8501 	/*
8502 	 * If no remove references were allocated we're on a non-journaled
8503 	 * filesystem and can skip the cancel step.
8504 	 */
8505 	if (jremref == NULL) {
8506 		free_diradd(dap, NULL);
8507 		return;
8508 	}
8509 	/*
8510 	 * Cancel the primary name an free it if it does not require
8511 	 * journaling.
8512 	 */
8513 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8514 	    0, &inodedep) != 0) {
8515 		/* Abort the addref that reference this diradd.  */
8516 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8517 			if (inoref->if_list.wk_type != D_JADDREF)
8518 				continue;
8519 			jaddref = (struct jaddref *)inoref;
8520 			if (jaddref->ja_diradd != dap)
8521 				continue;
8522 			if (cancel_jaddref(jaddref, inodedep,
8523 			    &dirrem->dm_jwork) == 0) {
8524 				free_jremref(jremref);
8525 				jremref = NULL;
8526 			}
8527 			break;
8528 		}
8529 	}
8530 	/*
8531 	 * Cancel subordinate names and free them if they do not require
8532 	 * journaling.
8533 	 */
8534 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8535 		LIST_FOREACH(mkdir, &mkdirlisthd, md_mkdirs) {
8536 			if (mkdir->md_diradd != dap)
8537 				continue;
8538 			if ((jaddref = mkdir->md_jaddref) == NULL)
8539 				continue;
8540 			mkdir->md_jaddref = NULL;
8541 			if (mkdir->md_state & MKDIR_PARENT) {
8542 				if (cancel_jaddref(jaddref, NULL,
8543 				    &dirrem->dm_jwork) == 0) {
8544 					free_jremref(dotdotremref);
8545 					dotdotremref = NULL;
8546 				}
8547 			} else {
8548 				if (cancel_jaddref(jaddref, inodedep,
8549 				    &dirrem->dm_jwork) == 0) {
8550 					free_jremref(dotremref);
8551 					dotremref = NULL;
8552 				}
8553 			}
8554 		}
8555 	}
8556 
8557 	if (jremref)
8558 		journal_jremref(dirrem, jremref, inodedep);
8559 	if (dotremref)
8560 		journal_jremref(dirrem, dotremref, inodedep);
8561 	if (dotdotremref)
8562 		journal_jremref(dirrem, dotdotremref, NULL);
8563 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8564 	free_diradd(dap, &dirrem->dm_jwork);
8565 }
8566 
8567 /*
8568  * Free a diradd dependency structure. This routine must be called
8569  * with splbio interrupts blocked.
8570  */
8571 static void
8572 free_diradd(dap, wkhd)
8573 	struct diradd *dap;
8574 	struct workhead *wkhd;
8575 {
8576 	struct dirrem *dirrem;
8577 	struct pagedep *pagedep;
8578 	struct inodedep *inodedep;
8579 	struct mkdir *mkdir, *nextmd;
8580 
8581 	mtx_assert(&lk, MA_OWNED);
8582 	LIST_REMOVE(dap, da_pdlist);
8583 	if (dap->da_state & ONWORKLIST)
8584 		WORKLIST_REMOVE(&dap->da_list);
8585 	if ((dap->da_state & DIRCHG) == 0) {
8586 		pagedep = dap->da_pagedep;
8587 	} else {
8588 		dirrem = dap->da_previous;
8589 		pagedep = dirrem->dm_pagedep;
8590 		dirrem->dm_dirinum = pagedep->pd_ino;
8591 		dirrem->dm_state |= COMPLETE;
8592 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8593 			add_to_worklist(&dirrem->dm_list, 0);
8594 	}
8595 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8596 	    0, &inodedep) != 0)
8597 		if (inodedep->id_mkdiradd == dap)
8598 			inodedep->id_mkdiradd = NULL;
8599 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8600 		for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
8601 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8602 			if (mkdir->md_diradd != dap)
8603 				continue;
8604 			dap->da_state &=
8605 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8606 			LIST_REMOVE(mkdir, md_mkdirs);
8607 			if (mkdir->md_state & ONWORKLIST)
8608 				WORKLIST_REMOVE(&mkdir->md_list);
8609 			if (mkdir->md_jaddref != NULL)
8610 				panic("free_diradd: Unexpected jaddref");
8611 			WORKITEM_FREE(mkdir, D_MKDIR);
8612 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8613 				break;
8614 		}
8615 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8616 			panic("free_diradd: unfound ref");
8617 	}
8618 	if (inodedep)
8619 		free_inodedep(inodedep);
8620 	/*
8621 	 * Free any journal segments waiting for the directory write.
8622 	 */
8623 	handle_jwork(&dap->da_jwork);
8624 	WORKITEM_FREE(dap, D_DIRADD);
8625 }
8626 
8627 /*
8628  * Directory entry removal dependencies.
8629  *
8630  * When removing a directory entry, the entry's inode pointer must be
8631  * zero'ed on disk before the corresponding inode's link count is decremented
8632  * (possibly freeing the inode for re-use). This dependency is handled by
8633  * updating the directory entry but delaying the inode count reduction until
8634  * after the directory block has been written to disk. After this point, the
8635  * inode count can be decremented whenever it is convenient.
8636  */
8637 
8638 /*
8639  * This routine should be called immediately after removing
8640  * a directory entry.  The inode's link count should not be
8641  * decremented by the calling procedure -- the soft updates
8642  * code will do this task when it is safe.
8643  */
8644 void
8645 softdep_setup_remove(bp, dp, ip, isrmdir)
8646 	struct buf *bp;		/* buffer containing directory block */
8647 	struct inode *dp;	/* inode for the directory being modified */
8648 	struct inode *ip;	/* inode for directory entry being removed */
8649 	int isrmdir;		/* indicates if doing RMDIR */
8650 {
8651 	struct dirrem *dirrem, *prevdirrem;
8652 	struct inodedep *inodedep;
8653 	int direct;
8654 
8655 	/*
8656 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8657 	 * newdirrem() to setup the full directory remove which requires
8658 	 * isrmdir > 1.
8659 	 */
8660 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8661 	/*
8662 	 * Add the dirrem to the inodedep's pending remove list for quick
8663 	 * discovery later.
8664 	 */
8665 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8666 	    &inodedep) == 0)
8667 		panic("softdep_setup_remove: Lost inodedep.");
8668 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8669 	dirrem->dm_state |= ONDEPLIST;
8670 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8671 
8672 	/*
8673 	 * If the COMPLETE flag is clear, then there were no active
8674 	 * entries and we want to roll back to a zeroed entry until
8675 	 * the new inode is committed to disk. If the COMPLETE flag is
8676 	 * set then we have deleted an entry that never made it to
8677 	 * disk. If the entry we deleted resulted from a name change,
8678 	 * then the old name still resides on disk. We cannot delete
8679 	 * its inode (returned to us in prevdirrem) until the zeroed
8680 	 * directory entry gets to disk. The new inode has never been
8681 	 * referenced on the disk, so can be deleted immediately.
8682 	 */
8683 	if ((dirrem->dm_state & COMPLETE) == 0) {
8684 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8685 		    dm_next);
8686 		FREE_LOCK(&lk);
8687 	} else {
8688 		if (prevdirrem != NULL)
8689 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8690 			    prevdirrem, dm_next);
8691 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8692 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8693 		FREE_LOCK(&lk);
8694 		if (direct)
8695 			handle_workitem_remove(dirrem, 0);
8696 	}
8697 }
8698 
8699 /*
8700  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8701  * pd_pendinghd list of a pagedep.
8702  */
8703 static struct diradd *
8704 diradd_lookup(pagedep, offset)
8705 	struct pagedep *pagedep;
8706 	int offset;
8707 {
8708 	struct diradd *dap;
8709 
8710 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8711 		if (dap->da_offset == offset)
8712 			return (dap);
8713 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8714 		if (dap->da_offset == offset)
8715 			return (dap);
8716 	return (NULL);
8717 }
8718 
8719 /*
8720  * Search for a .. diradd dependency in a directory that is being removed.
8721  * If the directory was renamed to a new parent we have a diradd rather
8722  * than a mkdir for the .. entry.  We need to cancel it now before
8723  * it is found in truncate().
8724  */
8725 static struct jremref *
8726 cancel_diradd_dotdot(ip, dirrem, jremref)
8727 	struct inode *ip;
8728 	struct dirrem *dirrem;
8729 	struct jremref *jremref;
8730 {
8731 	struct pagedep *pagedep;
8732 	struct diradd *dap;
8733 	struct worklist *wk;
8734 
8735 	if (pagedep_lookup(UFSTOVFS(ip->i_ump), NULL, ip->i_number, 0, 0,
8736 	    &pagedep) == 0)
8737 		return (jremref);
8738 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
8739 	if (dap == NULL)
8740 		return (jremref);
8741 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
8742 	/*
8743 	 * Mark any journal work as belonging to the parent so it is freed
8744 	 * with the .. reference.
8745 	 */
8746 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
8747 		wk->wk_state |= MKDIR_PARENT;
8748 	return (NULL);
8749 }
8750 
8751 /*
8752  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
8753  * replace it with a dirrem/diradd pair as a result of re-parenting a
8754  * directory.  This ensures that we don't simultaneously have a mkdir and
8755  * a diradd for the same .. entry.
8756  */
8757 static struct jremref *
8758 cancel_mkdir_dotdot(ip, dirrem, jremref)
8759 	struct inode *ip;
8760 	struct dirrem *dirrem;
8761 	struct jremref *jremref;
8762 {
8763 	struct inodedep *inodedep;
8764 	struct jaddref *jaddref;
8765 	struct mkdir *mkdir;
8766 	struct diradd *dap;
8767 
8768 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8769 	    &inodedep) == 0)
8770 		return (jremref);
8771 	dap = inodedep->id_mkdiradd;
8772 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
8773 		return (jremref);
8774 	for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir;
8775 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
8776 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
8777 			break;
8778 	if (mkdir == NULL)
8779 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
8780 	if ((jaddref = mkdir->md_jaddref) != NULL) {
8781 		mkdir->md_jaddref = NULL;
8782 		jaddref->ja_state &= ~MKDIR_PARENT;
8783 		if (inodedep_lookup(UFSTOVFS(ip->i_ump), jaddref->ja_ino, 0,
8784 		    &inodedep) == 0)
8785 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
8786 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
8787 			journal_jremref(dirrem, jremref, inodedep);
8788 			jremref = NULL;
8789 		}
8790 	}
8791 	if (mkdir->md_state & ONWORKLIST)
8792 		WORKLIST_REMOVE(&mkdir->md_list);
8793 	mkdir->md_state |= ALLCOMPLETE;
8794 	complete_mkdir(mkdir);
8795 	return (jremref);
8796 }
8797 
8798 static void
8799 journal_jremref(dirrem, jremref, inodedep)
8800 	struct dirrem *dirrem;
8801 	struct jremref *jremref;
8802 	struct inodedep *inodedep;
8803 {
8804 
8805 	if (inodedep == NULL)
8806 		if (inodedep_lookup(jremref->jr_list.wk_mp,
8807 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
8808 			panic("journal_jremref: Lost inodedep");
8809 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
8810 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
8811 	add_to_journal(&jremref->jr_list);
8812 }
8813 
8814 static void
8815 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
8816 	struct dirrem *dirrem;
8817 	struct jremref *jremref;
8818 	struct jremref *dotremref;
8819 	struct jremref *dotdotremref;
8820 {
8821 	struct inodedep *inodedep;
8822 
8823 
8824 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
8825 	    &inodedep) == 0)
8826 		panic("dirrem_journal: Lost inodedep");
8827 	journal_jremref(dirrem, jremref, inodedep);
8828 	if (dotremref)
8829 		journal_jremref(dirrem, dotremref, inodedep);
8830 	if (dotdotremref)
8831 		journal_jremref(dirrem, dotdotremref, NULL);
8832 }
8833 
8834 /*
8835  * Allocate a new dirrem if appropriate and return it along with
8836  * its associated pagedep. Called without a lock, returns with lock.
8837  */
8838 static struct dirrem *
8839 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
8840 	struct buf *bp;		/* buffer containing directory block */
8841 	struct inode *dp;	/* inode for the directory being modified */
8842 	struct inode *ip;	/* inode for directory entry being removed */
8843 	int isrmdir;		/* indicates if doing RMDIR */
8844 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
8845 {
8846 	int offset;
8847 	ufs_lbn_t lbn;
8848 	struct diradd *dap;
8849 	struct dirrem *dirrem;
8850 	struct pagedep *pagedep;
8851 	struct jremref *jremref;
8852 	struct jremref *dotremref;
8853 	struct jremref *dotdotremref;
8854 	struct vnode *dvp;
8855 
8856 	/*
8857 	 * Whiteouts have no deletion dependencies.
8858 	 */
8859 	if (ip == NULL)
8860 		panic("newdirrem: whiteout");
8861 	dvp = ITOV(dp);
8862 	/*
8863 	 * If we are over our limit, try to improve the situation.
8864 	 * Limiting the number of dirrem structures will also limit
8865 	 * the number of freefile and freeblks structures.
8866 	 */
8867 	ACQUIRE_LOCK(&lk);
8868 	if (!IS_SNAPSHOT(ip) && dep_current[D_DIRREM] > max_softdeps / 2)
8869 		(void) request_cleanup(ITOV(dp)->v_mount, FLUSH_BLOCKS);
8870 	FREE_LOCK(&lk);
8871 	dirrem = malloc(sizeof(struct dirrem),
8872 		M_DIRREM, M_SOFTDEP_FLAGS|M_ZERO);
8873 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
8874 	LIST_INIT(&dirrem->dm_jremrefhd);
8875 	LIST_INIT(&dirrem->dm_jwork);
8876 	dirrem->dm_state = isrmdir ? RMDIR : 0;
8877 	dirrem->dm_oldinum = ip->i_number;
8878 	*prevdirremp = NULL;
8879 	/*
8880 	 * Allocate remove reference structures to track journal write
8881 	 * dependencies.  We will always have one for the link and
8882 	 * when doing directories we will always have one more for dot.
8883 	 * When renaming a directory we skip the dotdot link change so
8884 	 * this is not needed.
8885 	 */
8886 	jremref = dotremref = dotdotremref = NULL;
8887 	if (DOINGSUJ(dvp)) {
8888 		if (isrmdir) {
8889 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
8890 			    ip->i_effnlink + 2);
8891 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
8892 			    ip->i_effnlink + 1);
8893 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
8894 			    dp->i_effnlink + 1);
8895 			dotdotremref->jr_state |= MKDIR_PARENT;
8896 		} else
8897 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
8898 			    ip->i_effnlink + 1);
8899 	}
8900 	ACQUIRE_LOCK(&lk);
8901 	lbn = lblkno(dp->i_fs, dp->i_offset);
8902 	offset = blkoff(dp->i_fs, dp->i_offset);
8903 	pagedep_lookup(UFSTOVFS(dp->i_ump), bp, dp->i_number, lbn, DEPALLOC,
8904 	    &pagedep);
8905 	dirrem->dm_pagedep = pagedep;
8906 	dirrem->dm_offset = offset;
8907 	/*
8908 	 * If we're renaming a .. link to a new directory, cancel any
8909 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
8910 	 * the jremref is preserved for any potential diradd in this
8911 	 * location.  This can not coincide with a rmdir.
8912 	 */
8913 	if (dp->i_offset == DOTDOT_OFFSET) {
8914 		if (isrmdir)
8915 			panic("newdirrem: .. directory change during remove?");
8916 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
8917 	}
8918 	/*
8919 	 * If we're removing a directory search for the .. dependency now and
8920 	 * cancel it.  Any pending journal work will be added to the dirrem
8921 	 * to be completed when the workitem remove completes.
8922 	 */
8923 	if (isrmdir)
8924 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
8925 	/*
8926 	 * Check for a diradd dependency for the same directory entry.
8927 	 * If present, then both dependencies become obsolete and can
8928 	 * be de-allocated.
8929 	 */
8930 	dap = diradd_lookup(pagedep, offset);
8931 	if (dap == NULL) {
8932 		/*
8933 		 * Link the jremref structures into the dirrem so they are
8934 		 * written prior to the pagedep.
8935 		 */
8936 		if (jremref)
8937 			dirrem_journal(dirrem, jremref, dotremref,
8938 			    dotdotremref);
8939 		return (dirrem);
8940 	}
8941 	/*
8942 	 * Must be ATTACHED at this point.
8943 	 */
8944 	if ((dap->da_state & ATTACHED) == 0)
8945 		panic("newdirrem: not ATTACHED");
8946 	if (dap->da_newinum != ip->i_number)
8947 		panic("newdirrem: inum %ju should be %ju",
8948 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
8949 	/*
8950 	 * If we are deleting a changed name that never made it to disk,
8951 	 * then return the dirrem describing the previous inode (which
8952 	 * represents the inode currently referenced from this entry on disk).
8953 	 */
8954 	if ((dap->da_state & DIRCHG) != 0) {
8955 		*prevdirremp = dap->da_previous;
8956 		dap->da_state &= ~DIRCHG;
8957 		dap->da_pagedep = pagedep;
8958 	}
8959 	/*
8960 	 * We are deleting an entry that never made it to disk.
8961 	 * Mark it COMPLETE so we can delete its inode immediately.
8962 	 */
8963 	dirrem->dm_state |= COMPLETE;
8964 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
8965 #ifdef SUJ_DEBUG
8966 	if (isrmdir == 0) {
8967 		struct worklist *wk;
8968 
8969 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
8970 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
8971 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
8972 	}
8973 #endif
8974 
8975 	return (dirrem);
8976 }
8977 
8978 /*
8979  * Directory entry change dependencies.
8980  *
8981  * Changing an existing directory entry requires that an add operation
8982  * be completed first followed by a deletion. The semantics for the addition
8983  * are identical to the description of adding a new entry above except
8984  * that the rollback is to the old inode number rather than zero. Once
8985  * the addition dependency is completed, the removal is done as described
8986  * in the removal routine above.
8987  */
8988 
8989 /*
8990  * This routine should be called immediately after changing
8991  * a directory entry.  The inode's link count should not be
8992  * decremented by the calling procedure -- the soft updates
8993  * code will perform this task when it is safe.
8994  */
8995 void
8996 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
8997 	struct buf *bp;		/* buffer containing directory block */
8998 	struct inode *dp;	/* inode for the directory being modified */
8999 	struct inode *ip;	/* inode for directory entry being removed */
9000 	ino_t newinum;		/* new inode number for changed entry */
9001 	int isrmdir;		/* indicates if doing RMDIR */
9002 {
9003 	int offset;
9004 	struct diradd *dap = NULL;
9005 	struct dirrem *dirrem, *prevdirrem;
9006 	struct pagedep *pagedep;
9007 	struct inodedep *inodedep;
9008 	struct jaddref *jaddref;
9009 	struct mount *mp;
9010 
9011 	offset = blkoff(dp->i_fs, dp->i_offset);
9012 	mp = UFSTOVFS(dp->i_ump);
9013 
9014 	/*
9015 	 * Whiteouts do not need diradd dependencies.
9016 	 */
9017 	if (newinum != WINO) {
9018 		dap = malloc(sizeof(struct diradd),
9019 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9020 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9021 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9022 		dap->da_offset = offset;
9023 		dap->da_newinum = newinum;
9024 		LIST_INIT(&dap->da_jwork);
9025 	}
9026 
9027 	/*
9028 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9029 	 */
9030 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9031 	pagedep = dirrem->dm_pagedep;
9032 	/*
9033 	 * The possible values for isrmdir:
9034 	 *	0 - non-directory file rename
9035 	 *	1 - directory rename within same directory
9036 	 *   inum - directory rename to new directory of given inode number
9037 	 * When renaming to a new directory, we are both deleting and
9038 	 * creating a new directory entry, so the link count on the new
9039 	 * directory should not change. Thus we do not need the followup
9040 	 * dirrem which is usually done in handle_workitem_remove. We set
9041 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9042 	 * followup dirrem.
9043 	 */
9044 	if (isrmdir > 1)
9045 		dirrem->dm_state |= DIRCHG;
9046 
9047 	/*
9048 	 * Whiteouts have no additional dependencies,
9049 	 * so just put the dirrem on the correct list.
9050 	 */
9051 	if (newinum == WINO) {
9052 		if ((dirrem->dm_state & COMPLETE) == 0) {
9053 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9054 			    dm_next);
9055 		} else {
9056 			dirrem->dm_dirinum = pagedep->pd_ino;
9057 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9058 				add_to_worklist(&dirrem->dm_list, 0);
9059 		}
9060 		FREE_LOCK(&lk);
9061 		return;
9062 	}
9063 	/*
9064 	 * Add the dirrem to the inodedep's pending remove list for quick
9065 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9066 	 * will not fail.
9067 	 */
9068 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9069 		panic("softdep_setup_directory_change: Lost inodedep.");
9070 	dirrem->dm_state |= ONDEPLIST;
9071 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9072 
9073 	/*
9074 	 * If the COMPLETE flag is clear, then there were no active
9075 	 * entries and we want to roll back to the previous inode until
9076 	 * the new inode is committed to disk. If the COMPLETE flag is
9077 	 * set, then we have deleted an entry that never made it to disk.
9078 	 * If the entry we deleted resulted from a name change, then the old
9079 	 * inode reference still resides on disk. Any rollback that we do
9080 	 * needs to be to that old inode (returned to us in prevdirrem). If
9081 	 * the entry we deleted resulted from a create, then there is
9082 	 * no entry on the disk, so we want to roll back to zero rather
9083 	 * than the uncommitted inode. In either of the COMPLETE cases we
9084 	 * want to immediately free the unwritten and unreferenced inode.
9085 	 */
9086 	if ((dirrem->dm_state & COMPLETE) == 0) {
9087 		dap->da_previous = dirrem;
9088 	} else {
9089 		if (prevdirrem != NULL) {
9090 			dap->da_previous = prevdirrem;
9091 		} else {
9092 			dap->da_state &= ~DIRCHG;
9093 			dap->da_pagedep = pagedep;
9094 		}
9095 		dirrem->dm_dirinum = pagedep->pd_ino;
9096 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9097 			add_to_worklist(&dirrem->dm_list, 0);
9098 	}
9099 	/*
9100 	 * Lookup the jaddref for this journal entry.  We must finish
9101 	 * initializing it and make the diradd write dependent on it.
9102 	 * If we're not journaling, put it on the id_bufwait list if the
9103 	 * inode is not yet written. If it is written, do the post-inode
9104 	 * write processing to put it on the id_pendinghd list.
9105 	 */
9106 	inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep);
9107 	if (MOUNTEDSUJ(mp)) {
9108 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9109 		    inoreflst);
9110 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9111 		    ("softdep_setup_directory_change: bad jaddref %p",
9112 		    jaddref));
9113 		jaddref->ja_diroff = dp->i_offset;
9114 		jaddref->ja_diradd = dap;
9115 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9116 		    dap, da_pdlist);
9117 		add_to_journal(&jaddref->ja_list);
9118 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9119 		dap->da_state |= COMPLETE;
9120 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9121 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9122 	} else {
9123 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9124 		    dap, da_pdlist);
9125 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9126 	}
9127 	/*
9128 	 * If we're making a new name for a directory that has not been
9129 	 * committed when need to move the dot and dotdot references to
9130 	 * this new name.
9131 	 */
9132 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9133 		merge_diradd(inodedep, dap);
9134 	FREE_LOCK(&lk);
9135 }
9136 
9137 /*
9138  * Called whenever the link count on an inode is changed.
9139  * It creates an inode dependency so that the new reference(s)
9140  * to the inode cannot be committed to disk until the updated
9141  * inode has been written.
9142  */
9143 void
9144 softdep_change_linkcnt(ip)
9145 	struct inode *ip;	/* the inode with the increased link count */
9146 {
9147 	struct inodedep *inodedep;
9148 	int dflags;
9149 
9150 	ACQUIRE_LOCK(&lk);
9151 	dflags = DEPALLOC;
9152 	if (IS_SNAPSHOT(ip))
9153 		dflags |= NODELAY;
9154 	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags, &inodedep);
9155 	if (ip->i_nlink < ip->i_effnlink)
9156 		panic("softdep_change_linkcnt: bad delta");
9157 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9158 	FREE_LOCK(&lk);
9159 }
9160 
9161 /*
9162  * Attach a sbdep dependency to the superblock buf so that we can keep
9163  * track of the head of the linked list of referenced but unlinked inodes.
9164  */
9165 void
9166 softdep_setup_sbupdate(ump, fs, bp)
9167 	struct ufsmount *ump;
9168 	struct fs *fs;
9169 	struct buf *bp;
9170 {
9171 	struct sbdep *sbdep;
9172 	struct worklist *wk;
9173 
9174 	if (MOUNTEDSUJ(UFSTOVFS(ump)) == 0)
9175 		return;
9176 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9177 		if (wk->wk_type == D_SBDEP)
9178 			break;
9179 	if (wk != NULL)
9180 		return;
9181 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9182 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9183 	sbdep->sb_fs = fs;
9184 	sbdep->sb_ump = ump;
9185 	ACQUIRE_LOCK(&lk);
9186 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9187 	FREE_LOCK(&lk);
9188 }
9189 
9190 /*
9191  * Return the first unlinked inodedep which is ready to be the head of the
9192  * list.  The inodedep and all those after it must have valid next pointers.
9193  */
9194 static struct inodedep *
9195 first_unlinked_inodedep(ump)
9196 	struct ufsmount *ump;
9197 {
9198 	struct inodedep *inodedep;
9199 	struct inodedep *idp;
9200 
9201 	mtx_assert(&lk, MA_OWNED);
9202 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9203 	    inodedep; inodedep = idp) {
9204 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9205 			return (NULL);
9206 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9207 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9208 			break;
9209 		if ((inodedep->id_state & UNLINKPREV) == 0)
9210 			break;
9211 	}
9212 	return (inodedep);
9213 }
9214 
9215 /*
9216  * Set the sujfree unlinked head pointer prior to writing a superblock.
9217  */
9218 static void
9219 initiate_write_sbdep(sbdep)
9220 	struct sbdep *sbdep;
9221 {
9222 	struct inodedep *inodedep;
9223 	struct fs *bpfs;
9224 	struct fs *fs;
9225 
9226 	bpfs = sbdep->sb_fs;
9227 	fs = sbdep->sb_ump->um_fs;
9228 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9229 	if (inodedep) {
9230 		fs->fs_sujfree = inodedep->id_ino;
9231 		inodedep->id_state |= UNLINKPREV;
9232 	} else
9233 		fs->fs_sujfree = 0;
9234 	bpfs->fs_sujfree = fs->fs_sujfree;
9235 }
9236 
9237 /*
9238  * After a superblock is written determine whether it must be written again
9239  * due to a changing unlinked list head.
9240  */
9241 static int
9242 handle_written_sbdep(sbdep, bp)
9243 	struct sbdep *sbdep;
9244 	struct buf *bp;
9245 {
9246 	struct inodedep *inodedep;
9247 	struct mount *mp;
9248 	struct fs *fs;
9249 
9250 	mtx_assert(&lk, MA_OWNED);
9251 	fs = sbdep->sb_fs;
9252 	mp = UFSTOVFS(sbdep->sb_ump);
9253 	/*
9254 	 * If the superblock doesn't match the in-memory list start over.
9255 	 */
9256 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9257 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9258 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9259 		bdirty(bp);
9260 		return (1);
9261 	}
9262 	WORKITEM_FREE(sbdep, D_SBDEP);
9263 	if (fs->fs_sujfree == 0)
9264 		return (0);
9265 	/*
9266 	 * Now that we have a record of this inode in stable store allow it
9267 	 * to be written to free up pending work.  Inodes may see a lot of
9268 	 * write activity after they are unlinked which we must not hold up.
9269 	 */
9270 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9271 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9272 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9273 			    inodedep, inodedep->id_state);
9274 		if (inodedep->id_state & UNLINKONLIST)
9275 			break;
9276 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9277 	}
9278 
9279 	return (0);
9280 }
9281 
9282 /*
9283  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9284  */
9285 static void
9286 unlinked_inodedep(mp, inodedep)
9287 	struct mount *mp;
9288 	struct inodedep *inodedep;
9289 {
9290 	struct ufsmount *ump;
9291 
9292 	mtx_assert(&lk, MA_OWNED);
9293 	if (MOUNTEDSUJ(mp) == 0)
9294 		return;
9295 	ump = VFSTOUFS(mp);
9296 	ump->um_fs->fs_fmod = 1;
9297 	if (inodedep->id_state & UNLINKED)
9298 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9299 	inodedep->id_state |= UNLINKED;
9300 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9301 }
9302 
9303 /*
9304  * Remove an inodedep from the unlinked inodedep list.  This may require
9305  * disk writes if the inode has made it that far.
9306  */
9307 static void
9308 clear_unlinked_inodedep(inodedep)
9309 	struct inodedep *inodedep;
9310 {
9311 	struct ufsmount *ump;
9312 	struct inodedep *idp;
9313 	struct inodedep *idn;
9314 	struct fs *fs;
9315 	struct buf *bp;
9316 	ino_t ino;
9317 	ino_t nino;
9318 	ino_t pino;
9319 	int error;
9320 
9321 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9322 	fs = ump->um_fs;
9323 	ino = inodedep->id_ino;
9324 	error = 0;
9325 	for (;;) {
9326 		mtx_assert(&lk, MA_OWNED);
9327 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9328 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9329 		    inodedep));
9330 		/*
9331 		 * If nothing has yet been written simply remove us from
9332 		 * the in memory list and return.  This is the most common
9333 		 * case where handle_workitem_remove() loses the final
9334 		 * reference.
9335 		 */
9336 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9337 			break;
9338 		/*
9339 		 * If we have a NEXT pointer and no PREV pointer we can simply
9340 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9341 		 * careful not to clear PREV if the superblock points at
9342 		 * next as well.
9343 		 */
9344 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9345 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9346 			if (idn && fs->fs_sujfree != idn->id_ino)
9347 				idn->id_state &= ~UNLINKPREV;
9348 			break;
9349 		}
9350 		/*
9351 		 * Here we have an inodedep which is actually linked into
9352 		 * the list.  We must remove it by forcing a write to the
9353 		 * link before us, whether it be the superblock or an inode.
9354 		 * Unfortunately the list may change while we're waiting
9355 		 * on the buf lock for either resource so we must loop until
9356 		 * we lock the right one.  If both the superblock and an
9357 		 * inode point to this inode we must clear the inode first
9358 		 * followed by the superblock.
9359 		 */
9360 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9361 		pino = 0;
9362 		if (idp && (idp->id_state & UNLINKNEXT))
9363 			pino = idp->id_ino;
9364 		FREE_LOCK(&lk);
9365 		if (pino == 0) {
9366 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9367 			    (int)fs->fs_sbsize, 0, 0, 0);
9368 		} else {
9369 			error = bread(ump->um_devvp,
9370 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9371 			    (int)fs->fs_bsize, NOCRED, &bp);
9372 			if (error)
9373 				brelse(bp);
9374 		}
9375 		ACQUIRE_LOCK(&lk);
9376 		if (error)
9377 			break;
9378 		/* If the list has changed restart the loop. */
9379 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9380 		nino = 0;
9381 		if (idp && (idp->id_state & UNLINKNEXT))
9382 			nino = idp->id_ino;
9383 		if (nino != pino ||
9384 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9385 			FREE_LOCK(&lk);
9386 			brelse(bp);
9387 			ACQUIRE_LOCK(&lk);
9388 			continue;
9389 		}
9390 		nino = 0;
9391 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9392 		if (idn)
9393 			nino = idn->id_ino;
9394 		/*
9395 		 * Remove us from the in memory list.  After this we cannot
9396 		 * access the inodedep.
9397 		 */
9398 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9399 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9400 		    inodedep));
9401 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9402 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9403 		FREE_LOCK(&lk);
9404 		/*
9405 		 * The predecessor's next pointer is manually updated here
9406 		 * so that the NEXT flag is never cleared for an element
9407 		 * that is in the list.
9408 		 */
9409 		if (pino == 0) {
9410 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9411 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9412 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9413 			    bp);
9414 		} else if (fs->fs_magic == FS_UFS1_MAGIC)
9415 			((struct ufs1_dinode *)bp->b_data +
9416 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9417 		else
9418 			((struct ufs2_dinode *)bp->b_data +
9419 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9420 		/*
9421 		 * If the bwrite fails we have no recourse to recover.  The
9422 		 * filesystem is corrupted already.
9423 		 */
9424 		bwrite(bp);
9425 		ACQUIRE_LOCK(&lk);
9426 		/*
9427 		 * If the superblock pointer still needs to be cleared force
9428 		 * a write here.
9429 		 */
9430 		if (fs->fs_sujfree == ino) {
9431 			FREE_LOCK(&lk);
9432 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9433 			    (int)fs->fs_sbsize, 0, 0, 0);
9434 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9435 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9436 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9437 			    bp);
9438 			bwrite(bp);
9439 			ACQUIRE_LOCK(&lk);
9440 		}
9441 
9442 		if (fs->fs_sujfree != ino)
9443 			return;
9444 		panic("clear_unlinked_inodedep: Failed to clear free head");
9445 	}
9446 	if (inodedep->id_ino == fs->fs_sujfree)
9447 		panic("clear_unlinked_inodedep: Freeing head of free list");
9448 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9449 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9450 	return;
9451 }
9452 
9453 /*
9454  * This workitem decrements the inode's link count.
9455  * If the link count reaches zero, the file is removed.
9456  */
9457 static int
9458 handle_workitem_remove(dirrem, flags)
9459 	struct dirrem *dirrem;
9460 	int flags;
9461 {
9462 	struct inodedep *inodedep;
9463 	struct workhead dotdotwk;
9464 	struct worklist *wk;
9465 	struct ufsmount *ump;
9466 	struct mount *mp;
9467 	struct vnode *vp;
9468 	struct inode *ip;
9469 	ino_t oldinum;
9470 
9471 	if (dirrem->dm_state & ONWORKLIST)
9472 		panic("handle_workitem_remove: dirrem %p still on worklist",
9473 		    dirrem);
9474 	oldinum = dirrem->dm_oldinum;
9475 	mp = dirrem->dm_list.wk_mp;
9476 	ump = VFSTOUFS(mp);
9477 	flags |= LK_EXCLUSIVE;
9478 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9479 		return (EBUSY);
9480 	ip = VTOI(vp);
9481 	ACQUIRE_LOCK(&lk);
9482 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9483 		panic("handle_workitem_remove: lost inodedep");
9484 	if (dirrem->dm_state & ONDEPLIST)
9485 		LIST_REMOVE(dirrem, dm_inonext);
9486 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9487 	    ("handle_workitem_remove:  Journal entries not written."));
9488 
9489 	/*
9490 	 * Move all dependencies waiting on the remove to complete
9491 	 * from the dirrem to the inode inowait list to be completed
9492 	 * after the inode has been updated and written to disk.  Any
9493 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9494 	 * is removed.
9495 	 */
9496 	LIST_INIT(&dotdotwk);
9497 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9498 		WORKLIST_REMOVE(wk);
9499 		if (wk->wk_state & MKDIR_PARENT) {
9500 			wk->wk_state &= ~MKDIR_PARENT;
9501 			WORKLIST_INSERT(&dotdotwk, wk);
9502 			continue;
9503 		}
9504 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9505 	}
9506 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9507 	/*
9508 	 * Normal file deletion.
9509 	 */
9510 	if ((dirrem->dm_state & RMDIR) == 0) {
9511 		ip->i_nlink--;
9512 		DIP_SET(ip, i_nlink, ip->i_nlink);
9513 		ip->i_flag |= IN_CHANGE;
9514 		if (ip->i_nlink < ip->i_effnlink)
9515 			panic("handle_workitem_remove: bad file delta");
9516 		if (ip->i_nlink == 0)
9517 			unlinked_inodedep(mp, inodedep);
9518 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9519 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9520 		    ("handle_workitem_remove: worklist not empty. %s",
9521 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9522 		WORKITEM_FREE(dirrem, D_DIRREM);
9523 		FREE_LOCK(&lk);
9524 		goto out;
9525 	}
9526 	/*
9527 	 * Directory deletion. Decrement reference count for both the
9528 	 * just deleted parent directory entry and the reference for ".".
9529 	 * Arrange to have the reference count on the parent decremented
9530 	 * to account for the loss of "..".
9531 	 */
9532 	ip->i_nlink -= 2;
9533 	DIP_SET(ip, i_nlink, ip->i_nlink);
9534 	ip->i_flag |= IN_CHANGE;
9535 	if (ip->i_nlink < ip->i_effnlink)
9536 		panic("handle_workitem_remove: bad dir delta");
9537 	if (ip->i_nlink == 0)
9538 		unlinked_inodedep(mp, inodedep);
9539 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9540 	/*
9541 	 * Rename a directory to a new parent. Since, we are both deleting
9542 	 * and creating a new directory entry, the link count on the new
9543 	 * directory should not change. Thus we skip the followup dirrem.
9544 	 */
9545 	if (dirrem->dm_state & DIRCHG) {
9546 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9547 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9548 		WORKITEM_FREE(dirrem, D_DIRREM);
9549 		FREE_LOCK(&lk);
9550 		goto out;
9551 	}
9552 	dirrem->dm_state = ONDEPLIST;
9553 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9554 	/*
9555 	 * Place the dirrem on the parent's diremhd list.
9556 	 */
9557 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9558 		panic("handle_workitem_remove: lost dir inodedep");
9559 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9560 	/*
9561 	 * If the allocated inode has never been written to disk, then
9562 	 * the on-disk inode is zero'ed and we can remove the file
9563 	 * immediately.  When journaling if the inode has been marked
9564 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9565 	 */
9566 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9567 	if (inodedep == NULL ||
9568 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9569 	    check_inode_unwritten(inodedep)) {
9570 		FREE_LOCK(&lk);
9571 		vput(vp);
9572 		return handle_workitem_remove(dirrem, flags);
9573 	}
9574 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9575 	FREE_LOCK(&lk);
9576 	ip->i_flag |= IN_CHANGE;
9577 out:
9578 	ffs_update(vp, 0);
9579 	vput(vp);
9580 	return (0);
9581 }
9582 
9583 /*
9584  * Inode de-allocation dependencies.
9585  *
9586  * When an inode's link count is reduced to zero, it can be de-allocated. We
9587  * found it convenient to postpone de-allocation until after the inode is
9588  * written to disk with its new link count (zero).  At this point, all of the
9589  * on-disk inode's block pointers are nullified and, with careful dependency
9590  * list ordering, all dependencies related to the inode will be satisfied and
9591  * the corresponding dependency structures de-allocated.  So, if/when the
9592  * inode is reused, there will be no mixing of old dependencies with new
9593  * ones.  This artificial dependency is set up by the block de-allocation
9594  * procedure above (softdep_setup_freeblocks) and completed by the
9595  * following procedure.
9596  */
9597 static void
9598 handle_workitem_freefile(freefile)
9599 	struct freefile *freefile;
9600 {
9601 	struct workhead wkhd;
9602 	struct fs *fs;
9603 	struct inodedep *idp;
9604 	struct ufsmount *ump;
9605 	int error;
9606 
9607 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9608 	fs = ump->um_fs;
9609 #ifdef DEBUG
9610 	ACQUIRE_LOCK(&lk);
9611 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9612 	FREE_LOCK(&lk);
9613 	if (error)
9614 		panic("handle_workitem_freefile: inodedep %p survived", idp);
9615 #endif
9616 	UFS_LOCK(ump);
9617 	fs->fs_pendinginodes -= 1;
9618 	UFS_UNLOCK(ump);
9619 	LIST_INIT(&wkhd);
9620 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9621 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9622 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9623 		softdep_error("handle_workitem_freefile", error);
9624 	ACQUIRE_LOCK(&lk);
9625 	WORKITEM_FREE(freefile, D_FREEFILE);
9626 	FREE_LOCK(&lk);
9627 }
9628 
9629 
9630 /*
9631  * Helper function which unlinks marker element from work list and returns
9632  * the next element on the list.
9633  */
9634 static __inline struct worklist *
9635 markernext(struct worklist *marker)
9636 {
9637 	struct worklist *next;
9638 
9639 	next = LIST_NEXT(marker, wk_list);
9640 	LIST_REMOVE(marker, wk_list);
9641 	return next;
9642 }
9643 
9644 /*
9645  * Disk writes.
9646  *
9647  * The dependency structures constructed above are most actively used when file
9648  * system blocks are written to disk.  No constraints are placed on when a
9649  * block can be written, but unsatisfied update dependencies are made safe by
9650  * modifying (or replacing) the source memory for the duration of the disk
9651  * write.  When the disk write completes, the memory block is again brought
9652  * up-to-date.
9653  *
9654  * In-core inode structure reclamation.
9655  *
9656  * Because there are a finite number of "in-core" inode structures, they are
9657  * reused regularly.  By transferring all inode-related dependencies to the
9658  * in-memory inode block and indexing them separately (via "inodedep"s), we
9659  * can allow "in-core" inode structures to be reused at any time and avoid
9660  * any increase in contention.
9661  *
9662  * Called just before entering the device driver to initiate a new disk I/O.
9663  * The buffer must be locked, thus, no I/O completion operations can occur
9664  * while we are manipulating its associated dependencies.
9665  */
9666 static void
9667 softdep_disk_io_initiation(bp)
9668 	struct buf *bp;		/* structure describing disk write to occur */
9669 {
9670 	struct worklist *wk;
9671 	struct worklist marker;
9672 	struct inodedep *inodedep;
9673 	struct freeblks *freeblks;
9674 	struct jblkdep *jblkdep;
9675 	struct newblk *newblk;
9676 
9677 	/*
9678 	 * We only care about write operations. There should never
9679 	 * be dependencies for reads.
9680 	 */
9681 	if (bp->b_iocmd != BIO_WRITE)
9682 		panic("softdep_disk_io_initiation: not write");
9683 
9684 	if (bp->b_vflags & BV_BKGRDINPROG)
9685 		panic("softdep_disk_io_initiation: Writing buffer with "
9686 		    "background write in progress: %p", bp);
9687 
9688 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
9689 	PHOLD(curproc);			/* Don't swap out kernel stack */
9690 
9691 	ACQUIRE_LOCK(&lk);
9692 	/*
9693 	 * Do any necessary pre-I/O processing.
9694 	 */
9695 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9696 	     wk = markernext(&marker)) {
9697 		LIST_INSERT_AFTER(wk, &marker, wk_list);
9698 		switch (wk->wk_type) {
9699 
9700 		case D_PAGEDEP:
9701 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
9702 			continue;
9703 
9704 		case D_INODEDEP:
9705 			inodedep = WK_INODEDEP(wk);
9706 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
9707 				initiate_write_inodeblock_ufs1(inodedep, bp);
9708 			else
9709 				initiate_write_inodeblock_ufs2(inodedep, bp);
9710 			continue;
9711 
9712 		case D_INDIRDEP:
9713 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
9714 			continue;
9715 
9716 		case D_BMSAFEMAP:
9717 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
9718 			continue;
9719 
9720 		case D_JSEG:
9721 			WK_JSEG(wk)->js_buf = NULL;
9722 			continue;
9723 
9724 		case D_FREEBLKS:
9725 			freeblks = WK_FREEBLKS(wk);
9726 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
9727 			/*
9728 			 * We have to wait for the freeblks to be journaled
9729 			 * before we can write an inodeblock with updated
9730 			 * pointers.  Be careful to arrange the marker so
9731 			 * we revisit the freeblks if it's not removed by
9732 			 * the first jwait().
9733 			 */
9734 			if (jblkdep != NULL) {
9735 				LIST_REMOVE(&marker, wk_list);
9736 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
9737 				jwait(&jblkdep->jb_list, MNT_WAIT);
9738 			}
9739 			continue;
9740 		case D_ALLOCDIRECT:
9741 		case D_ALLOCINDIR:
9742 			/*
9743 			 * We have to wait for the jnewblk to be journaled
9744 			 * before we can write to a block if the contents
9745 			 * may be confused with an earlier file's indirect
9746 			 * at recovery time.  Handle the marker as described
9747 			 * above.
9748 			 */
9749 			newblk = WK_NEWBLK(wk);
9750 			if (newblk->nb_jnewblk != NULL &&
9751 			    indirblk_lookup(newblk->nb_list.wk_mp,
9752 			    newblk->nb_newblkno)) {
9753 				LIST_REMOVE(&marker, wk_list);
9754 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
9755 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
9756 			}
9757 			continue;
9758 
9759 		case D_SBDEP:
9760 			initiate_write_sbdep(WK_SBDEP(wk));
9761 			continue;
9762 
9763 		case D_MKDIR:
9764 		case D_FREEWORK:
9765 		case D_FREEDEP:
9766 		case D_JSEGDEP:
9767 			continue;
9768 
9769 		default:
9770 			panic("handle_disk_io_initiation: Unexpected type %s",
9771 			    TYPENAME(wk->wk_type));
9772 			/* NOTREACHED */
9773 		}
9774 	}
9775 	FREE_LOCK(&lk);
9776 	PRELE(curproc);			/* Allow swapout of kernel stack */
9777 }
9778 
9779 /*
9780  * Called from within the procedure above to deal with unsatisfied
9781  * allocation dependencies in a directory. The buffer must be locked,
9782  * thus, no I/O completion operations can occur while we are
9783  * manipulating its associated dependencies.
9784  */
9785 static void
9786 initiate_write_filepage(pagedep, bp)
9787 	struct pagedep *pagedep;
9788 	struct buf *bp;
9789 {
9790 	struct jremref *jremref;
9791 	struct jmvref *jmvref;
9792 	struct dirrem *dirrem;
9793 	struct diradd *dap;
9794 	struct direct *ep;
9795 	int i;
9796 
9797 	if (pagedep->pd_state & IOSTARTED) {
9798 		/*
9799 		 * This can only happen if there is a driver that does not
9800 		 * understand chaining. Here biodone will reissue the call
9801 		 * to strategy for the incomplete buffers.
9802 		 */
9803 		printf("initiate_write_filepage: already started\n");
9804 		return;
9805 	}
9806 	pagedep->pd_state |= IOSTARTED;
9807 	/*
9808 	 * Wait for all journal remove dependencies to hit the disk.
9809 	 * We can not allow any potentially conflicting directory adds
9810 	 * to be visible before removes and rollback is too difficult.
9811 	 * lk may be dropped and re-acquired, however we hold the buf
9812 	 * locked so the dependency can not go away.
9813 	 */
9814 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
9815 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
9816 			jwait(&jremref->jr_list, MNT_WAIT);
9817 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
9818 		jwait(&jmvref->jm_list, MNT_WAIT);
9819 	for (i = 0; i < DAHASHSZ; i++) {
9820 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
9821 			ep = (struct direct *)
9822 			    ((char *)bp->b_data + dap->da_offset);
9823 			if (ep->d_ino != dap->da_newinum)
9824 				panic("%s: dir inum %ju != new %ju",
9825 				    "initiate_write_filepage",
9826 				    (uintmax_t)ep->d_ino,
9827 				    (uintmax_t)dap->da_newinum);
9828 			if (dap->da_state & DIRCHG)
9829 				ep->d_ino = dap->da_previous->dm_oldinum;
9830 			else
9831 				ep->d_ino = 0;
9832 			dap->da_state &= ~ATTACHED;
9833 			dap->da_state |= UNDONE;
9834 		}
9835 	}
9836 }
9837 
9838 /*
9839  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
9840  * Note that any bug fixes made to this routine must be done in the
9841  * version found below.
9842  *
9843  * Called from within the procedure above to deal with unsatisfied
9844  * allocation dependencies in an inodeblock. The buffer must be
9845  * locked, thus, no I/O completion operations can occur while we
9846  * are manipulating its associated dependencies.
9847  */
9848 static void
9849 initiate_write_inodeblock_ufs1(inodedep, bp)
9850 	struct inodedep *inodedep;
9851 	struct buf *bp;			/* The inode block */
9852 {
9853 	struct allocdirect *adp, *lastadp;
9854 	struct ufs1_dinode *dp;
9855 	struct ufs1_dinode *sip;
9856 	struct inoref *inoref;
9857 	struct fs *fs;
9858 	ufs_lbn_t i;
9859 #ifdef INVARIANTS
9860 	ufs_lbn_t prevlbn = 0;
9861 #endif
9862 	int deplist;
9863 
9864 	if (inodedep->id_state & IOSTARTED)
9865 		panic("initiate_write_inodeblock_ufs1: already started");
9866 	inodedep->id_state |= IOSTARTED;
9867 	fs = inodedep->id_fs;
9868 	dp = (struct ufs1_dinode *)bp->b_data +
9869 	    ino_to_fsbo(fs, inodedep->id_ino);
9870 
9871 	/*
9872 	 * If we're on the unlinked list but have not yet written our
9873 	 * next pointer initialize it here.
9874 	 */
9875 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
9876 		struct inodedep *inon;
9877 
9878 		inon = TAILQ_NEXT(inodedep, id_unlinked);
9879 		dp->di_freelink = inon ? inon->id_ino : 0;
9880 	}
9881 	/*
9882 	 * If the bitmap is not yet written, then the allocated
9883 	 * inode cannot be written to disk.
9884 	 */
9885 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
9886 		if (inodedep->id_savedino1 != NULL)
9887 			panic("initiate_write_inodeblock_ufs1: I/O underway");
9888 		FREE_LOCK(&lk);
9889 		sip = malloc(sizeof(struct ufs1_dinode),
9890 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
9891 		ACQUIRE_LOCK(&lk);
9892 		inodedep->id_savedino1 = sip;
9893 		*inodedep->id_savedino1 = *dp;
9894 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
9895 		dp->di_gen = inodedep->id_savedino1->di_gen;
9896 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
9897 		return;
9898 	}
9899 	/*
9900 	 * If no dependencies, then there is nothing to roll back.
9901 	 */
9902 	inodedep->id_savedsize = dp->di_size;
9903 	inodedep->id_savedextsize = 0;
9904 	inodedep->id_savednlink = dp->di_nlink;
9905 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
9906 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
9907 		return;
9908 	/*
9909 	 * Revert the link count to that of the first unwritten journal entry.
9910 	 */
9911 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
9912 	if (inoref)
9913 		dp->di_nlink = inoref->if_nlink;
9914 	/*
9915 	 * Set the dependencies to busy.
9916 	 */
9917 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9918 	     adp = TAILQ_NEXT(adp, ad_next)) {
9919 #ifdef INVARIANTS
9920 		if (deplist != 0 && prevlbn >= adp->ad_offset)
9921 			panic("softdep_write_inodeblock: lbn order");
9922 		prevlbn = adp->ad_offset;
9923 		if (adp->ad_offset < NDADDR &&
9924 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
9925 			panic("%s: direct pointer #%jd mismatch %d != %jd",
9926 			    "softdep_write_inodeblock",
9927 			    (intmax_t)adp->ad_offset,
9928 			    dp->di_db[adp->ad_offset],
9929 			    (intmax_t)adp->ad_newblkno);
9930 		if (adp->ad_offset >= NDADDR &&
9931 		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
9932 			panic("%s: indirect pointer #%jd mismatch %d != %jd",
9933 			    "softdep_write_inodeblock",
9934 			    (intmax_t)adp->ad_offset - NDADDR,
9935 			    dp->di_ib[adp->ad_offset - NDADDR],
9936 			    (intmax_t)adp->ad_newblkno);
9937 		deplist |= 1 << adp->ad_offset;
9938 		if ((adp->ad_state & ATTACHED) == 0)
9939 			panic("softdep_write_inodeblock: Unknown state 0x%x",
9940 			    adp->ad_state);
9941 #endif /* INVARIANTS */
9942 		adp->ad_state &= ~ATTACHED;
9943 		adp->ad_state |= UNDONE;
9944 	}
9945 	/*
9946 	 * The on-disk inode cannot claim to be any larger than the last
9947 	 * fragment that has been written. Otherwise, the on-disk inode
9948 	 * might have fragments that were not the last block in the file
9949 	 * which would corrupt the filesystem.
9950 	 */
9951 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9952 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
9953 		if (adp->ad_offset >= NDADDR)
9954 			break;
9955 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
9956 		/* keep going until hitting a rollback to a frag */
9957 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
9958 			continue;
9959 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
9960 		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
9961 #ifdef INVARIANTS
9962 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
9963 				panic("softdep_write_inodeblock: lost dep1");
9964 #endif /* INVARIANTS */
9965 			dp->di_db[i] = 0;
9966 		}
9967 		for (i = 0; i < NIADDR; i++) {
9968 #ifdef INVARIANTS
9969 			if (dp->di_ib[i] != 0 &&
9970 			    (deplist & ((1 << NDADDR) << i)) == 0)
9971 				panic("softdep_write_inodeblock: lost dep2");
9972 #endif /* INVARIANTS */
9973 			dp->di_ib[i] = 0;
9974 		}
9975 		return;
9976 	}
9977 	/*
9978 	 * If we have zero'ed out the last allocated block of the file,
9979 	 * roll back the size to the last currently allocated block.
9980 	 * We know that this last allocated block is a full-sized as
9981 	 * we already checked for fragments in the loop above.
9982 	 */
9983 	if (lastadp != NULL &&
9984 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
9985 		for (i = lastadp->ad_offset; i >= 0; i--)
9986 			if (dp->di_db[i] != 0)
9987 				break;
9988 		dp->di_size = (i + 1) * fs->fs_bsize;
9989 	}
9990 	/*
9991 	 * The only dependencies are for indirect blocks.
9992 	 *
9993 	 * The file size for indirect block additions is not guaranteed.
9994 	 * Such a guarantee would be non-trivial to achieve. The conventional
9995 	 * synchronous write implementation also does not make this guarantee.
9996 	 * Fsck should catch and fix discrepancies. Arguably, the file size
9997 	 * can be over-estimated without destroying integrity when the file
9998 	 * moves into the indirect blocks (i.e., is large). If we want to
9999 	 * postpone fsck, we are stuck with this argument.
10000 	 */
10001 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10002 		dp->di_ib[adp->ad_offset - NDADDR] = 0;
10003 }
10004 
10005 /*
10006  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10007  * Note that any bug fixes made to this routine must be done in the
10008  * version found above.
10009  *
10010  * Called from within the procedure above to deal with unsatisfied
10011  * allocation dependencies in an inodeblock. The buffer must be
10012  * locked, thus, no I/O completion operations can occur while we
10013  * are manipulating its associated dependencies.
10014  */
10015 static void
10016 initiate_write_inodeblock_ufs2(inodedep, bp)
10017 	struct inodedep *inodedep;
10018 	struct buf *bp;			/* The inode block */
10019 {
10020 	struct allocdirect *adp, *lastadp;
10021 	struct ufs2_dinode *dp;
10022 	struct ufs2_dinode *sip;
10023 	struct inoref *inoref;
10024 	struct fs *fs;
10025 	ufs_lbn_t i;
10026 #ifdef INVARIANTS
10027 	ufs_lbn_t prevlbn = 0;
10028 #endif
10029 	int deplist;
10030 
10031 	if (inodedep->id_state & IOSTARTED)
10032 		panic("initiate_write_inodeblock_ufs2: already started");
10033 	inodedep->id_state |= IOSTARTED;
10034 	fs = inodedep->id_fs;
10035 	dp = (struct ufs2_dinode *)bp->b_data +
10036 	    ino_to_fsbo(fs, inodedep->id_ino);
10037 
10038 	/*
10039 	 * If we're on the unlinked list but have not yet written our
10040 	 * next pointer initialize it here.
10041 	 */
10042 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10043 		struct inodedep *inon;
10044 
10045 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10046 		dp->di_freelink = inon ? inon->id_ino : 0;
10047 	}
10048 	/*
10049 	 * If the bitmap is not yet written, then the allocated
10050 	 * inode cannot be written to disk.
10051 	 */
10052 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10053 		if (inodedep->id_savedino2 != NULL)
10054 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10055 		FREE_LOCK(&lk);
10056 		sip = malloc(sizeof(struct ufs2_dinode),
10057 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10058 		ACQUIRE_LOCK(&lk);
10059 		inodedep->id_savedino2 = sip;
10060 		*inodedep->id_savedino2 = *dp;
10061 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10062 		dp->di_gen = inodedep->id_savedino2->di_gen;
10063 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10064 		return;
10065 	}
10066 	/*
10067 	 * If no dependencies, then there is nothing to roll back.
10068 	 */
10069 	inodedep->id_savedsize = dp->di_size;
10070 	inodedep->id_savedextsize = dp->di_extsize;
10071 	inodedep->id_savednlink = dp->di_nlink;
10072 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10073 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10074 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10075 		return;
10076 	/*
10077 	 * Revert the link count to that of the first unwritten journal entry.
10078 	 */
10079 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10080 	if (inoref)
10081 		dp->di_nlink = inoref->if_nlink;
10082 
10083 	/*
10084 	 * Set the ext data dependencies to busy.
10085 	 */
10086 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10087 	     adp = TAILQ_NEXT(adp, ad_next)) {
10088 #ifdef INVARIANTS
10089 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10090 			panic("softdep_write_inodeblock: lbn order");
10091 		prevlbn = adp->ad_offset;
10092 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10093 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10094 			    "softdep_write_inodeblock",
10095 			    (intmax_t)adp->ad_offset,
10096 			    (intmax_t)dp->di_extb[adp->ad_offset],
10097 			    (intmax_t)adp->ad_newblkno);
10098 		deplist |= 1 << adp->ad_offset;
10099 		if ((adp->ad_state & ATTACHED) == 0)
10100 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10101 			    adp->ad_state);
10102 #endif /* INVARIANTS */
10103 		adp->ad_state &= ~ATTACHED;
10104 		adp->ad_state |= UNDONE;
10105 	}
10106 	/*
10107 	 * The on-disk inode cannot claim to be any larger than the last
10108 	 * fragment that has been written. Otherwise, the on-disk inode
10109 	 * might have fragments that were not the last block in the ext
10110 	 * data which would corrupt the filesystem.
10111 	 */
10112 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10113 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10114 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10115 		/* keep going until hitting a rollback to a frag */
10116 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10117 			continue;
10118 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10119 		for (i = adp->ad_offset + 1; i < NXADDR; i++) {
10120 #ifdef INVARIANTS
10121 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10122 				panic("softdep_write_inodeblock: lost dep1");
10123 #endif /* INVARIANTS */
10124 			dp->di_extb[i] = 0;
10125 		}
10126 		lastadp = NULL;
10127 		break;
10128 	}
10129 	/*
10130 	 * If we have zero'ed out the last allocated block of the ext
10131 	 * data, roll back the size to the last currently allocated block.
10132 	 * We know that this last allocated block is a full-sized as
10133 	 * we already checked for fragments in the loop above.
10134 	 */
10135 	if (lastadp != NULL &&
10136 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10137 		for (i = lastadp->ad_offset; i >= 0; i--)
10138 			if (dp->di_extb[i] != 0)
10139 				break;
10140 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10141 	}
10142 	/*
10143 	 * Set the file data dependencies to busy.
10144 	 */
10145 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10146 	     adp = TAILQ_NEXT(adp, ad_next)) {
10147 #ifdef INVARIANTS
10148 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10149 			panic("softdep_write_inodeblock: lbn order");
10150 		if ((adp->ad_state & ATTACHED) == 0)
10151 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10152 		prevlbn = adp->ad_offset;
10153 		if (adp->ad_offset < NDADDR &&
10154 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10155 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10156 			    "softdep_write_inodeblock",
10157 			    (intmax_t)adp->ad_offset,
10158 			    (intmax_t)dp->di_db[adp->ad_offset],
10159 			    (intmax_t)adp->ad_newblkno);
10160 		if (adp->ad_offset >= NDADDR &&
10161 		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
10162 			panic("%s indirect pointer #%jd mismatch %jd != %jd",
10163 			    "softdep_write_inodeblock:",
10164 			    (intmax_t)adp->ad_offset - NDADDR,
10165 			    (intmax_t)dp->di_ib[adp->ad_offset - NDADDR],
10166 			    (intmax_t)adp->ad_newblkno);
10167 		deplist |= 1 << adp->ad_offset;
10168 		if ((adp->ad_state & ATTACHED) == 0)
10169 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10170 			    adp->ad_state);
10171 #endif /* INVARIANTS */
10172 		adp->ad_state &= ~ATTACHED;
10173 		adp->ad_state |= UNDONE;
10174 	}
10175 	/*
10176 	 * The on-disk inode cannot claim to be any larger than the last
10177 	 * fragment that has been written. Otherwise, the on-disk inode
10178 	 * might have fragments that were not the last block in the file
10179 	 * which would corrupt the filesystem.
10180 	 */
10181 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10182 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10183 		if (adp->ad_offset >= NDADDR)
10184 			break;
10185 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10186 		/* keep going until hitting a rollback to a frag */
10187 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10188 			continue;
10189 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10190 		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
10191 #ifdef INVARIANTS
10192 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10193 				panic("softdep_write_inodeblock: lost dep2");
10194 #endif /* INVARIANTS */
10195 			dp->di_db[i] = 0;
10196 		}
10197 		for (i = 0; i < NIADDR; i++) {
10198 #ifdef INVARIANTS
10199 			if (dp->di_ib[i] != 0 &&
10200 			    (deplist & ((1 << NDADDR) << i)) == 0)
10201 				panic("softdep_write_inodeblock: lost dep3");
10202 #endif /* INVARIANTS */
10203 			dp->di_ib[i] = 0;
10204 		}
10205 		return;
10206 	}
10207 	/*
10208 	 * If we have zero'ed out the last allocated block of the file,
10209 	 * roll back the size to the last currently allocated block.
10210 	 * We know that this last allocated block is a full-sized as
10211 	 * we already checked for fragments in the loop above.
10212 	 */
10213 	if (lastadp != NULL &&
10214 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10215 		for (i = lastadp->ad_offset; i >= 0; i--)
10216 			if (dp->di_db[i] != 0)
10217 				break;
10218 		dp->di_size = (i + 1) * fs->fs_bsize;
10219 	}
10220 	/*
10221 	 * The only dependencies are for indirect blocks.
10222 	 *
10223 	 * The file size for indirect block additions is not guaranteed.
10224 	 * Such a guarantee would be non-trivial to achieve. The conventional
10225 	 * synchronous write implementation also does not make this guarantee.
10226 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10227 	 * can be over-estimated without destroying integrity when the file
10228 	 * moves into the indirect blocks (i.e., is large). If we want to
10229 	 * postpone fsck, we are stuck with this argument.
10230 	 */
10231 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10232 		dp->di_ib[adp->ad_offset - NDADDR] = 0;
10233 }
10234 
10235 /*
10236  * Cancel an indirdep as a result of truncation.  Release all of the
10237  * children allocindirs and place their journal work on the appropriate
10238  * list.
10239  */
10240 static void
10241 cancel_indirdep(indirdep, bp, freeblks)
10242 	struct indirdep *indirdep;
10243 	struct buf *bp;
10244 	struct freeblks *freeblks;
10245 {
10246 	struct allocindir *aip;
10247 
10248 	/*
10249 	 * None of the indirect pointers will ever be visible,
10250 	 * so they can simply be tossed. GOINGAWAY ensures
10251 	 * that allocated pointers will be saved in the buffer
10252 	 * cache until they are freed. Note that they will
10253 	 * only be able to be found by their physical address
10254 	 * since the inode mapping the logical address will
10255 	 * be gone. The save buffer used for the safe copy
10256 	 * was allocated in setup_allocindir_phase2 using
10257 	 * the physical address so it could be used for this
10258 	 * purpose. Hence we swap the safe copy with the real
10259 	 * copy, allowing the safe copy to be freed and holding
10260 	 * on to the real copy for later use in indir_trunc.
10261 	 */
10262 	if (indirdep->ir_state & GOINGAWAY)
10263 		panic("cancel_indirdep: already gone");
10264 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10265 		indirdep->ir_state |= DEPCOMPLETE;
10266 		LIST_REMOVE(indirdep, ir_next);
10267 	}
10268 	indirdep->ir_state |= GOINGAWAY;
10269 	VFSTOUFS(indirdep->ir_list.wk_mp)->um_numindirdeps += 1;
10270 	/*
10271 	 * Pass in bp for blocks still have journal writes
10272 	 * pending so we can cancel them on their own.
10273 	 */
10274 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
10275 		cancel_allocindir(aip, bp, freeblks, 0);
10276 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0)
10277 		cancel_allocindir(aip, NULL, freeblks, 0);
10278 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0)
10279 		cancel_allocindir(aip, NULL, freeblks, 0);
10280 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != 0)
10281 		cancel_allocindir(aip, NULL, freeblks, 0);
10282 	/*
10283 	 * If there are pending partial truncations we need to keep the
10284 	 * old block copy around until they complete.  This is because
10285 	 * the current b_data is not a perfect superset of the available
10286 	 * blocks.
10287 	 */
10288 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10289 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10290 	else
10291 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10292 	WORKLIST_REMOVE(&indirdep->ir_list);
10293 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10294 	indirdep->ir_bp = NULL;
10295 	indirdep->ir_freeblks = freeblks;
10296 }
10297 
10298 /*
10299  * Free an indirdep once it no longer has new pointers to track.
10300  */
10301 static void
10302 free_indirdep(indirdep)
10303 	struct indirdep *indirdep;
10304 {
10305 
10306 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10307 	    ("free_indirdep: Indir trunc list not empty."));
10308 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10309 	    ("free_indirdep: Complete head not empty."));
10310 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10311 	    ("free_indirdep: write head not empty."));
10312 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10313 	    ("free_indirdep: done head not empty."));
10314 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10315 	    ("free_indirdep: deplist head not empty."));
10316 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10317 	    ("free_indirdep: %p still on newblk list.", indirdep));
10318 	KASSERT(indirdep->ir_saveddata == NULL,
10319 	    ("free_indirdep: %p still has saved data.", indirdep));
10320 	if (indirdep->ir_state & ONWORKLIST)
10321 		WORKLIST_REMOVE(&indirdep->ir_list);
10322 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10323 }
10324 
10325 /*
10326  * Called before a write to an indirdep.  This routine is responsible for
10327  * rolling back pointers to a safe state which includes only those
10328  * allocindirs which have been completed.
10329  */
10330 static void
10331 initiate_write_indirdep(indirdep, bp)
10332 	struct indirdep *indirdep;
10333 	struct buf *bp;
10334 {
10335 
10336 	indirdep->ir_state |= IOSTARTED;
10337 	if (indirdep->ir_state & GOINGAWAY)
10338 		panic("disk_io_initiation: indirdep gone");
10339 	/*
10340 	 * If there are no remaining dependencies, this will be writing
10341 	 * the real pointers.
10342 	 */
10343 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10344 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10345 		return;
10346 	/*
10347 	 * Replace up-to-date version with safe version.
10348 	 */
10349 	if (indirdep->ir_saveddata == NULL) {
10350 		FREE_LOCK(&lk);
10351 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10352 		    M_SOFTDEP_FLAGS);
10353 		ACQUIRE_LOCK(&lk);
10354 	}
10355 	indirdep->ir_state &= ~ATTACHED;
10356 	indirdep->ir_state |= UNDONE;
10357 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10358 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10359 	    bp->b_bcount);
10360 }
10361 
10362 /*
10363  * Called when an inode has been cleared in a cg bitmap.  This finally
10364  * eliminates any canceled jaddrefs
10365  */
10366 void
10367 softdep_setup_inofree(mp, bp, ino, wkhd)
10368 	struct mount *mp;
10369 	struct buf *bp;
10370 	ino_t ino;
10371 	struct workhead *wkhd;
10372 {
10373 	struct worklist *wk, *wkn;
10374 	struct inodedep *inodedep;
10375 	uint8_t *inosused;
10376 	struct cg *cgp;
10377 	struct fs *fs;
10378 
10379 	ACQUIRE_LOCK(&lk);
10380 	fs = VFSTOUFS(mp)->um_fs;
10381 	cgp = (struct cg *)bp->b_data;
10382 	inosused = cg_inosused(cgp);
10383 	if (isset(inosused, ino % fs->fs_ipg))
10384 		panic("softdep_setup_inofree: inode %ju not freed.",
10385 		    (uintmax_t)ino);
10386 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10387 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10388 		    (uintmax_t)ino, inodedep);
10389 	if (wkhd) {
10390 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10391 			if (wk->wk_type != D_JADDREF)
10392 				continue;
10393 			WORKLIST_REMOVE(wk);
10394 			/*
10395 			 * We can free immediately even if the jaddref
10396 			 * isn't attached in a background write as now
10397 			 * the bitmaps are reconciled.
10398 		 	 */
10399 			wk->wk_state |= COMPLETE | ATTACHED;
10400 			free_jaddref(WK_JADDREF(wk));
10401 		}
10402 		jwork_move(&bp->b_dep, wkhd);
10403 	}
10404 	FREE_LOCK(&lk);
10405 }
10406 
10407 
10408 /*
10409  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10410  * map.  Any dependencies waiting for the write to clear are added to the
10411  * buf's list and any jnewblks that are being canceled are discarded
10412  * immediately.
10413  */
10414 void
10415 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10416 	struct mount *mp;
10417 	struct buf *bp;
10418 	ufs2_daddr_t blkno;
10419 	int frags;
10420 	struct workhead *wkhd;
10421 {
10422 	struct bmsafemap *bmsafemap;
10423 	struct jnewblk *jnewblk;
10424 	struct worklist *wk;
10425 	struct fs *fs;
10426 #ifdef SUJ_DEBUG
10427 	uint8_t *blksfree;
10428 	struct cg *cgp;
10429 	ufs2_daddr_t jstart;
10430 	ufs2_daddr_t jend;
10431 	ufs2_daddr_t end;
10432 	long bno;
10433 	int i;
10434 #endif
10435 
10436 	CTR3(KTR_SUJ,
10437 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10438 	    blkno, frags, wkhd);
10439 
10440 	ACQUIRE_LOCK(&lk);
10441 	/* Lookup the bmsafemap so we track when it is dirty. */
10442 	fs = VFSTOUFS(mp)->um_fs;
10443 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10444 	/*
10445 	 * Detach any jnewblks which have been canceled.  They must linger
10446 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10447 	 * an unjournaled allocation from hitting the disk.
10448 	 */
10449 	if (wkhd) {
10450 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10451 			CTR2(KTR_SUJ,
10452 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10453 			    blkno, wk->wk_type);
10454 			WORKLIST_REMOVE(wk);
10455 			if (wk->wk_type != D_JNEWBLK) {
10456 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10457 				continue;
10458 			}
10459 			jnewblk = WK_JNEWBLK(wk);
10460 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10461 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10462 #ifdef SUJ_DEBUG
10463 			/*
10464 			 * Assert that this block is free in the bitmap
10465 			 * before we discard the jnewblk.
10466 			 */
10467 			cgp = (struct cg *)bp->b_data;
10468 			blksfree = cg_blksfree(cgp);
10469 			bno = dtogd(fs, jnewblk->jn_blkno);
10470 			for (i = jnewblk->jn_oldfrags;
10471 			    i < jnewblk->jn_frags; i++) {
10472 				if (isset(blksfree, bno + i))
10473 					continue;
10474 				panic("softdep_setup_blkfree: not free");
10475 			}
10476 #endif
10477 			/*
10478 			 * Even if it's not attached we can free immediately
10479 			 * as the new bitmap is correct.
10480 			 */
10481 			wk->wk_state |= COMPLETE | ATTACHED;
10482 			free_jnewblk(jnewblk);
10483 		}
10484 	}
10485 
10486 #ifdef SUJ_DEBUG
10487 	/*
10488 	 * Assert that we are not freeing a block which has an outstanding
10489 	 * allocation dependency.
10490 	 */
10491 	fs = VFSTOUFS(mp)->um_fs;
10492 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10493 	end = blkno + frags;
10494 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10495 		/*
10496 		 * Don't match against blocks that will be freed when the
10497 		 * background write is done.
10498 		 */
10499 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10500 		    (COMPLETE | DEPCOMPLETE))
10501 			continue;
10502 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10503 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10504 		if ((blkno >= jstart && blkno < jend) ||
10505 		    (end > jstart && end <= jend)) {
10506 			printf("state 0x%X %jd - %d %d dep %p\n",
10507 			    jnewblk->jn_state, jnewblk->jn_blkno,
10508 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10509 			    jnewblk->jn_dep);
10510 			panic("softdep_setup_blkfree: "
10511 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10512 			    blkno, end, frags, jstart, jend);
10513 		}
10514 	}
10515 #endif
10516 	FREE_LOCK(&lk);
10517 }
10518 
10519 /*
10520  * Revert a block allocation when the journal record that describes it
10521  * is not yet written.
10522  */
10523 int
10524 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10525 	struct jnewblk *jnewblk;
10526 	struct fs *fs;
10527 	struct cg *cgp;
10528 	uint8_t *blksfree;
10529 {
10530 	ufs1_daddr_t fragno;
10531 	long cgbno, bbase;
10532 	int frags, blk;
10533 	int i;
10534 
10535 	frags = 0;
10536 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10537 	/*
10538 	 * We have to test which frags need to be rolled back.  We may
10539 	 * be operating on a stale copy when doing background writes.
10540 	 */
10541 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10542 		if (isclr(blksfree, cgbno + i))
10543 			frags++;
10544 	if (frags == 0)
10545 		return (0);
10546 	/*
10547 	 * This is mostly ffs_blkfree() sans some validation and
10548 	 * superblock updates.
10549 	 */
10550 	if (frags == fs->fs_frag) {
10551 		fragno = fragstoblks(fs, cgbno);
10552 		ffs_setblock(fs, blksfree, fragno);
10553 		ffs_clusteracct(fs, cgp, fragno, 1);
10554 		cgp->cg_cs.cs_nbfree++;
10555 	} else {
10556 		cgbno += jnewblk->jn_oldfrags;
10557 		bbase = cgbno - fragnum(fs, cgbno);
10558 		/* Decrement the old frags.  */
10559 		blk = blkmap(fs, blksfree, bbase);
10560 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10561 		/* Deallocate the fragment */
10562 		for (i = 0; i < frags; i++)
10563 			setbit(blksfree, cgbno + i);
10564 		cgp->cg_cs.cs_nffree += frags;
10565 		/* Add back in counts associated with the new frags */
10566 		blk = blkmap(fs, blksfree, bbase);
10567 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10568                 /* If a complete block has been reassembled, account for it. */
10569 		fragno = fragstoblks(fs, bbase);
10570 		if (ffs_isblock(fs, blksfree, fragno)) {
10571 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10572 			ffs_clusteracct(fs, cgp, fragno, 1);
10573 			cgp->cg_cs.cs_nbfree++;
10574 		}
10575 	}
10576 	stat_jnewblk++;
10577 	jnewblk->jn_state &= ~ATTACHED;
10578 	jnewblk->jn_state |= UNDONE;
10579 
10580 	return (frags);
10581 }
10582 
10583 static void
10584 initiate_write_bmsafemap(bmsafemap, bp)
10585 	struct bmsafemap *bmsafemap;
10586 	struct buf *bp;			/* The cg block. */
10587 {
10588 	struct jaddref *jaddref;
10589 	struct jnewblk *jnewblk;
10590 	uint8_t *inosused;
10591 	uint8_t *blksfree;
10592 	struct cg *cgp;
10593 	struct fs *fs;
10594 	ino_t ino;
10595 
10596 	if (bmsafemap->sm_state & IOSTARTED)
10597 		return;
10598 	bmsafemap->sm_state |= IOSTARTED;
10599 	/*
10600 	 * Clear any inode allocations which are pending journal writes.
10601 	 */
10602 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10603 		cgp = (struct cg *)bp->b_data;
10604 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10605 		inosused = cg_inosused(cgp);
10606 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10607 			ino = jaddref->ja_ino % fs->fs_ipg;
10608 			if (isset(inosused, ino)) {
10609 				if ((jaddref->ja_mode & IFMT) == IFDIR)
10610 					cgp->cg_cs.cs_ndir--;
10611 				cgp->cg_cs.cs_nifree++;
10612 				clrbit(inosused, ino);
10613 				jaddref->ja_state &= ~ATTACHED;
10614 				jaddref->ja_state |= UNDONE;
10615 				stat_jaddref++;
10616 			} else
10617 				panic("initiate_write_bmsafemap: inode %ju "
10618 				    "marked free", (uintmax_t)jaddref->ja_ino);
10619 		}
10620 	}
10621 	/*
10622 	 * Clear any block allocations which are pending journal writes.
10623 	 */
10624 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10625 		cgp = (struct cg *)bp->b_data;
10626 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10627 		blksfree = cg_blksfree(cgp);
10628 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10629 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10630 				continue;
10631 			panic("initiate_write_bmsafemap: block %jd "
10632 			    "marked free", jnewblk->jn_blkno);
10633 		}
10634 	}
10635 	/*
10636 	 * Move allocation lists to the written lists so they can be
10637 	 * cleared once the block write is complete.
10638 	 */
10639 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10640 	    inodedep, id_deps);
10641 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10642 	    newblk, nb_deps);
10643 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10644 	    wk_list);
10645 }
10646 
10647 /*
10648  * This routine is called during the completion interrupt
10649  * service routine for a disk write (from the procedure called
10650  * by the device driver to inform the filesystem caches of
10651  * a request completion).  It should be called early in this
10652  * procedure, before the block is made available to other
10653  * processes or other routines are called.
10654  *
10655  */
10656 static void
10657 softdep_disk_write_complete(bp)
10658 	struct buf *bp;		/* describes the completed disk write */
10659 {
10660 	struct worklist *wk;
10661 	struct worklist *owk;
10662 	struct workhead reattach;
10663 	struct freeblks *freeblks;
10664 	struct buf *sbp;
10665 
10666 	/*
10667 	 * If an error occurred while doing the write, then the data
10668 	 * has not hit the disk and the dependencies cannot be unrolled.
10669 	 */
10670 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0)
10671 		return;
10672 	LIST_INIT(&reattach);
10673 	/*
10674 	 * This lock must not be released anywhere in this code segment.
10675 	 */
10676 	sbp = NULL;
10677 	owk = NULL;
10678 	ACQUIRE_LOCK(&lk);
10679 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
10680 		WORKLIST_REMOVE(wk);
10681 		dep_write[wk->wk_type]++;
10682 		if (wk == owk)
10683 			panic("duplicate worklist: %p\n", wk);
10684 		owk = wk;
10685 		switch (wk->wk_type) {
10686 
10687 		case D_PAGEDEP:
10688 			if (handle_written_filepage(WK_PAGEDEP(wk), bp))
10689 				WORKLIST_INSERT(&reattach, wk);
10690 			continue;
10691 
10692 		case D_INODEDEP:
10693 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
10694 				WORKLIST_INSERT(&reattach, wk);
10695 			continue;
10696 
10697 		case D_BMSAFEMAP:
10698 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp))
10699 				WORKLIST_INSERT(&reattach, wk);
10700 			continue;
10701 
10702 		case D_MKDIR:
10703 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
10704 			continue;
10705 
10706 		case D_ALLOCDIRECT:
10707 			wk->wk_state |= COMPLETE;
10708 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
10709 			continue;
10710 
10711 		case D_ALLOCINDIR:
10712 			wk->wk_state |= COMPLETE;
10713 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
10714 			continue;
10715 
10716 		case D_INDIRDEP:
10717 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp))
10718 				WORKLIST_INSERT(&reattach, wk);
10719 			continue;
10720 
10721 		case D_FREEBLKS:
10722 			wk->wk_state |= COMPLETE;
10723 			freeblks = WK_FREEBLKS(wk);
10724 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
10725 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
10726 				add_to_worklist(wk, WK_NODELAY);
10727 			continue;
10728 
10729 		case D_FREEWORK:
10730 			handle_written_freework(WK_FREEWORK(wk));
10731 			break;
10732 
10733 		case D_JSEGDEP:
10734 			free_jsegdep(WK_JSEGDEP(wk));
10735 			continue;
10736 
10737 		case D_JSEG:
10738 			handle_written_jseg(WK_JSEG(wk), bp);
10739 			continue;
10740 
10741 		case D_SBDEP:
10742 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
10743 				WORKLIST_INSERT(&reattach, wk);
10744 			continue;
10745 
10746 		case D_FREEDEP:
10747 			free_freedep(WK_FREEDEP(wk));
10748 			continue;
10749 
10750 		default:
10751 			panic("handle_disk_write_complete: Unknown type %s",
10752 			    TYPENAME(wk->wk_type));
10753 			/* NOTREACHED */
10754 		}
10755 	}
10756 	/*
10757 	 * Reattach any requests that must be redone.
10758 	 */
10759 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
10760 		WORKLIST_REMOVE(wk);
10761 		WORKLIST_INSERT(&bp->b_dep, wk);
10762 	}
10763 	FREE_LOCK(&lk);
10764 	if (sbp)
10765 		brelse(sbp);
10766 }
10767 
10768 /*
10769  * Called from within softdep_disk_write_complete above. Note that
10770  * this routine is always called from interrupt level with further
10771  * splbio interrupts blocked.
10772  */
10773 static void
10774 handle_allocdirect_partdone(adp, wkhd)
10775 	struct allocdirect *adp;	/* the completed allocdirect */
10776 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
10777 {
10778 	struct allocdirectlst *listhead;
10779 	struct allocdirect *listadp;
10780 	struct inodedep *inodedep;
10781 	long bsize;
10782 
10783 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
10784 		return;
10785 	/*
10786 	 * The on-disk inode cannot claim to be any larger than the last
10787 	 * fragment that has been written. Otherwise, the on-disk inode
10788 	 * might have fragments that were not the last block in the file
10789 	 * which would corrupt the filesystem. Thus, we cannot free any
10790 	 * allocdirects after one whose ad_oldblkno claims a fragment as
10791 	 * these blocks must be rolled back to zero before writing the inode.
10792 	 * We check the currently active set of allocdirects in id_inoupdt
10793 	 * or id_extupdt as appropriate.
10794 	 */
10795 	inodedep = adp->ad_inodedep;
10796 	bsize = inodedep->id_fs->fs_bsize;
10797 	if (adp->ad_state & EXTDATA)
10798 		listhead = &inodedep->id_extupdt;
10799 	else
10800 		listhead = &inodedep->id_inoupdt;
10801 	TAILQ_FOREACH(listadp, listhead, ad_next) {
10802 		/* found our block */
10803 		if (listadp == adp)
10804 			break;
10805 		/* continue if ad_oldlbn is not a fragment */
10806 		if (listadp->ad_oldsize == 0 ||
10807 		    listadp->ad_oldsize == bsize)
10808 			continue;
10809 		/* hit a fragment */
10810 		return;
10811 	}
10812 	/*
10813 	 * If we have reached the end of the current list without
10814 	 * finding the just finished dependency, then it must be
10815 	 * on the future dependency list. Future dependencies cannot
10816 	 * be freed until they are moved to the current list.
10817 	 */
10818 	if (listadp == NULL) {
10819 #ifdef DEBUG
10820 		if (adp->ad_state & EXTDATA)
10821 			listhead = &inodedep->id_newextupdt;
10822 		else
10823 			listhead = &inodedep->id_newinoupdt;
10824 		TAILQ_FOREACH(listadp, listhead, ad_next)
10825 			/* found our block */
10826 			if (listadp == adp)
10827 				break;
10828 		if (listadp == NULL)
10829 			panic("handle_allocdirect_partdone: lost dep");
10830 #endif /* DEBUG */
10831 		return;
10832 	}
10833 	/*
10834 	 * If we have found the just finished dependency, then queue
10835 	 * it along with anything that follows it that is complete.
10836 	 * Since the pointer has not yet been written in the inode
10837 	 * as the dependency prevents it, place the allocdirect on the
10838 	 * bufwait list where it will be freed once the pointer is
10839 	 * valid.
10840 	 */
10841 	if (wkhd == NULL)
10842 		wkhd = &inodedep->id_bufwait;
10843 	for (; adp; adp = listadp) {
10844 		listadp = TAILQ_NEXT(adp, ad_next);
10845 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
10846 			return;
10847 		TAILQ_REMOVE(listhead, adp, ad_next);
10848 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
10849 	}
10850 }
10851 
10852 /*
10853  * Called from within softdep_disk_write_complete above.  This routine
10854  * completes successfully written allocindirs.
10855  */
10856 static void
10857 handle_allocindir_partdone(aip)
10858 	struct allocindir *aip;		/* the completed allocindir */
10859 {
10860 	struct indirdep *indirdep;
10861 
10862 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
10863 		return;
10864 	indirdep = aip->ai_indirdep;
10865 	LIST_REMOVE(aip, ai_next);
10866 	/*
10867 	 * Don't set a pointer while the buffer is undergoing IO or while
10868 	 * we have active truncations.
10869 	 */
10870 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
10871 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
10872 		return;
10873 	}
10874 	if (indirdep->ir_state & UFS1FMT)
10875 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
10876 		    aip->ai_newblkno;
10877 	else
10878 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
10879 		    aip->ai_newblkno;
10880 	/*
10881 	 * Await the pointer write before freeing the allocindir.
10882 	 */
10883 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
10884 }
10885 
10886 /*
10887  * Release segments held on a jwork list.
10888  */
10889 static void
10890 handle_jwork(wkhd)
10891 	struct workhead *wkhd;
10892 {
10893 	struct worklist *wk;
10894 
10895 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
10896 		WORKLIST_REMOVE(wk);
10897 		switch (wk->wk_type) {
10898 		case D_JSEGDEP:
10899 			free_jsegdep(WK_JSEGDEP(wk));
10900 			continue;
10901 		case D_FREEDEP:
10902 			free_freedep(WK_FREEDEP(wk));
10903 			continue;
10904 		case D_FREEFRAG:
10905 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
10906 			WORKITEM_FREE(wk, D_FREEFRAG);
10907 			continue;
10908 		case D_FREEWORK:
10909 			handle_written_freework(WK_FREEWORK(wk));
10910 			continue;
10911 		default:
10912 			panic("handle_jwork: Unknown type %s\n",
10913 			    TYPENAME(wk->wk_type));
10914 		}
10915 	}
10916 }
10917 
10918 /*
10919  * Handle the bufwait list on an inode when it is safe to release items
10920  * held there.  This normally happens after an inode block is written but
10921  * may be delayed and handled later if there are pending journal items that
10922  * are not yet safe to be released.
10923  */
10924 static struct freefile *
10925 handle_bufwait(inodedep, refhd)
10926 	struct inodedep *inodedep;
10927 	struct workhead *refhd;
10928 {
10929 	struct jaddref *jaddref;
10930 	struct freefile *freefile;
10931 	struct worklist *wk;
10932 
10933 	freefile = NULL;
10934 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
10935 		WORKLIST_REMOVE(wk);
10936 		switch (wk->wk_type) {
10937 		case D_FREEFILE:
10938 			/*
10939 			 * We defer adding freefile to the worklist
10940 			 * until all other additions have been made to
10941 			 * ensure that it will be done after all the
10942 			 * old blocks have been freed.
10943 			 */
10944 			if (freefile != NULL)
10945 				panic("handle_bufwait: freefile");
10946 			freefile = WK_FREEFILE(wk);
10947 			continue;
10948 
10949 		case D_MKDIR:
10950 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
10951 			continue;
10952 
10953 		case D_DIRADD:
10954 			diradd_inode_written(WK_DIRADD(wk), inodedep);
10955 			continue;
10956 
10957 		case D_FREEFRAG:
10958 			wk->wk_state |= COMPLETE;
10959 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
10960 				add_to_worklist(wk, 0);
10961 			continue;
10962 
10963 		case D_DIRREM:
10964 			wk->wk_state |= COMPLETE;
10965 			add_to_worklist(wk, 0);
10966 			continue;
10967 
10968 		case D_ALLOCDIRECT:
10969 		case D_ALLOCINDIR:
10970 			free_newblk(WK_NEWBLK(wk));
10971 			continue;
10972 
10973 		case D_JNEWBLK:
10974 			wk->wk_state |= COMPLETE;
10975 			free_jnewblk(WK_JNEWBLK(wk));
10976 			continue;
10977 
10978 		/*
10979 		 * Save freed journal segments and add references on
10980 		 * the supplied list which will delay their release
10981 		 * until the cg bitmap is cleared on disk.
10982 		 */
10983 		case D_JSEGDEP:
10984 			if (refhd == NULL)
10985 				free_jsegdep(WK_JSEGDEP(wk));
10986 			else
10987 				WORKLIST_INSERT(refhd, wk);
10988 			continue;
10989 
10990 		case D_JADDREF:
10991 			jaddref = WK_JADDREF(wk);
10992 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
10993 			    if_deps);
10994 			/*
10995 			 * Transfer any jaddrefs to the list to be freed with
10996 			 * the bitmap if we're handling a removed file.
10997 			 */
10998 			if (refhd == NULL) {
10999 				wk->wk_state |= COMPLETE;
11000 				free_jaddref(jaddref);
11001 			} else
11002 				WORKLIST_INSERT(refhd, wk);
11003 			continue;
11004 
11005 		default:
11006 			panic("handle_bufwait: Unknown type %p(%s)",
11007 			    wk, TYPENAME(wk->wk_type));
11008 			/* NOTREACHED */
11009 		}
11010 	}
11011 	return (freefile);
11012 }
11013 /*
11014  * Called from within softdep_disk_write_complete above to restore
11015  * in-memory inode block contents to their most up-to-date state. Note
11016  * that this routine is always called from interrupt level with further
11017  * splbio interrupts blocked.
11018  */
11019 static int
11020 handle_written_inodeblock(inodedep, bp)
11021 	struct inodedep *inodedep;
11022 	struct buf *bp;		/* buffer containing the inode block */
11023 {
11024 	struct freefile *freefile;
11025 	struct allocdirect *adp, *nextadp;
11026 	struct ufs1_dinode *dp1 = NULL;
11027 	struct ufs2_dinode *dp2 = NULL;
11028 	struct workhead wkhd;
11029 	int hadchanges, fstype;
11030 	ino_t freelink;
11031 
11032 	LIST_INIT(&wkhd);
11033 	hadchanges = 0;
11034 	freefile = NULL;
11035 	if ((inodedep->id_state & IOSTARTED) == 0)
11036 		panic("handle_written_inodeblock: not started");
11037 	inodedep->id_state &= ~IOSTARTED;
11038 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11039 		fstype = UFS1;
11040 		dp1 = (struct ufs1_dinode *)bp->b_data +
11041 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11042 		freelink = dp1->di_freelink;
11043 	} else {
11044 		fstype = UFS2;
11045 		dp2 = (struct ufs2_dinode *)bp->b_data +
11046 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11047 		freelink = dp2->di_freelink;
11048 	}
11049 	/*
11050 	 * Leave this inodeblock dirty until it's in the list.
11051 	 */
11052 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED) {
11053 		struct inodedep *inon;
11054 
11055 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11056 		if ((inon == NULL && freelink == 0) ||
11057 		    (inon && inon->id_ino == freelink)) {
11058 			if (inon)
11059 				inon->id_state |= UNLINKPREV;
11060 			inodedep->id_state |= UNLINKNEXT;
11061 		}
11062 		hadchanges = 1;
11063 	}
11064 	/*
11065 	 * If we had to rollback the inode allocation because of
11066 	 * bitmaps being incomplete, then simply restore it.
11067 	 * Keep the block dirty so that it will not be reclaimed until
11068 	 * all associated dependencies have been cleared and the
11069 	 * corresponding updates written to disk.
11070 	 */
11071 	if (inodedep->id_savedino1 != NULL) {
11072 		hadchanges = 1;
11073 		if (fstype == UFS1)
11074 			*dp1 = *inodedep->id_savedino1;
11075 		else
11076 			*dp2 = *inodedep->id_savedino2;
11077 		free(inodedep->id_savedino1, M_SAVEDINO);
11078 		inodedep->id_savedino1 = NULL;
11079 		if ((bp->b_flags & B_DELWRI) == 0)
11080 			stat_inode_bitmap++;
11081 		bdirty(bp);
11082 		/*
11083 		 * If the inode is clear here and GOINGAWAY it will never
11084 		 * be written.  Process the bufwait and clear any pending
11085 		 * work which may include the freefile.
11086 		 */
11087 		if (inodedep->id_state & GOINGAWAY)
11088 			goto bufwait;
11089 		return (1);
11090 	}
11091 	inodedep->id_state |= COMPLETE;
11092 	/*
11093 	 * Roll forward anything that had to be rolled back before
11094 	 * the inode could be updated.
11095 	 */
11096 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11097 		nextadp = TAILQ_NEXT(adp, ad_next);
11098 		if (adp->ad_state & ATTACHED)
11099 			panic("handle_written_inodeblock: new entry");
11100 		if (fstype == UFS1) {
11101 			if (adp->ad_offset < NDADDR) {
11102 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11103 					panic("%s %s #%jd mismatch %d != %jd",
11104 					    "handle_written_inodeblock:",
11105 					    "direct pointer",
11106 					    (intmax_t)adp->ad_offset,
11107 					    dp1->di_db[adp->ad_offset],
11108 					    (intmax_t)adp->ad_oldblkno);
11109 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11110 			} else {
11111 				if (dp1->di_ib[adp->ad_offset - NDADDR] != 0)
11112 					panic("%s: %s #%jd allocated as %d",
11113 					    "handle_written_inodeblock",
11114 					    "indirect pointer",
11115 					    (intmax_t)adp->ad_offset - NDADDR,
11116 					    dp1->di_ib[adp->ad_offset - NDADDR]);
11117 				dp1->di_ib[adp->ad_offset - NDADDR] =
11118 				    adp->ad_newblkno;
11119 			}
11120 		} else {
11121 			if (adp->ad_offset < NDADDR) {
11122 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11123 					panic("%s: %s #%jd %s %jd != %jd",
11124 					    "handle_written_inodeblock",
11125 					    "direct pointer",
11126 					    (intmax_t)adp->ad_offset, "mismatch",
11127 					    (intmax_t)dp2->di_db[adp->ad_offset],
11128 					    (intmax_t)adp->ad_oldblkno);
11129 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11130 			} else {
11131 				if (dp2->di_ib[adp->ad_offset - NDADDR] != 0)
11132 					panic("%s: %s #%jd allocated as %jd",
11133 					    "handle_written_inodeblock",
11134 					    "indirect pointer",
11135 					    (intmax_t)adp->ad_offset - NDADDR,
11136 					    (intmax_t)
11137 					    dp2->di_ib[adp->ad_offset - NDADDR]);
11138 				dp2->di_ib[adp->ad_offset - NDADDR] =
11139 				    adp->ad_newblkno;
11140 			}
11141 		}
11142 		adp->ad_state &= ~UNDONE;
11143 		adp->ad_state |= ATTACHED;
11144 		hadchanges = 1;
11145 	}
11146 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11147 		nextadp = TAILQ_NEXT(adp, ad_next);
11148 		if (adp->ad_state & ATTACHED)
11149 			panic("handle_written_inodeblock: new entry");
11150 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11151 			panic("%s: direct pointers #%jd %s %jd != %jd",
11152 			    "handle_written_inodeblock",
11153 			    (intmax_t)adp->ad_offset, "mismatch",
11154 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11155 			    (intmax_t)adp->ad_oldblkno);
11156 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11157 		adp->ad_state &= ~UNDONE;
11158 		adp->ad_state |= ATTACHED;
11159 		hadchanges = 1;
11160 	}
11161 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11162 		stat_direct_blk_ptrs++;
11163 	/*
11164 	 * Reset the file size to its most up-to-date value.
11165 	 */
11166 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11167 		panic("handle_written_inodeblock: bad size");
11168 	if (inodedep->id_savednlink > LINK_MAX)
11169 		panic("handle_written_inodeblock: Invalid link count "
11170 		    "%d for inodedep %p", inodedep->id_savednlink, inodedep);
11171 	if (fstype == UFS1) {
11172 		if (dp1->di_nlink != inodedep->id_savednlink) {
11173 			dp1->di_nlink = inodedep->id_savednlink;
11174 			hadchanges = 1;
11175 		}
11176 		if (dp1->di_size != inodedep->id_savedsize) {
11177 			dp1->di_size = inodedep->id_savedsize;
11178 			hadchanges = 1;
11179 		}
11180 	} else {
11181 		if (dp2->di_nlink != inodedep->id_savednlink) {
11182 			dp2->di_nlink = inodedep->id_savednlink;
11183 			hadchanges = 1;
11184 		}
11185 		if (dp2->di_size != inodedep->id_savedsize) {
11186 			dp2->di_size = inodedep->id_savedsize;
11187 			hadchanges = 1;
11188 		}
11189 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11190 			dp2->di_extsize = inodedep->id_savedextsize;
11191 			hadchanges = 1;
11192 		}
11193 	}
11194 	inodedep->id_savedsize = -1;
11195 	inodedep->id_savedextsize = -1;
11196 	inodedep->id_savednlink = -1;
11197 	/*
11198 	 * If there were any rollbacks in the inode block, then it must be
11199 	 * marked dirty so that its will eventually get written back in
11200 	 * its correct form.
11201 	 */
11202 	if (hadchanges)
11203 		bdirty(bp);
11204 bufwait:
11205 	/*
11206 	 * Process any allocdirects that completed during the update.
11207 	 */
11208 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11209 		handle_allocdirect_partdone(adp, &wkhd);
11210 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11211 		handle_allocdirect_partdone(adp, &wkhd);
11212 	/*
11213 	 * Process deallocations that were held pending until the
11214 	 * inode had been written to disk. Freeing of the inode
11215 	 * is delayed until after all blocks have been freed to
11216 	 * avoid creation of new <vfsid, inum, lbn> triples
11217 	 * before the old ones have been deleted.  Completely
11218 	 * unlinked inodes are not processed until the unlinked
11219 	 * inode list is written or the last reference is removed.
11220 	 */
11221 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11222 		freefile = handle_bufwait(inodedep, NULL);
11223 		if (freefile && !LIST_EMPTY(&wkhd)) {
11224 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11225 			freefile = NULL;
11226 		}
11227 	}
11228 	/*
11229 	 * Move rolled forward dependency completions to the bufwait list
11230 	 * now that those that were already written have been processed.
11231 	 */
11232 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11233 		panic("handle_written_inodeblock: bufwait but no changes");
11234 	jwork_move(&inodedep->id_bufwait, &wkhd);
11235 
11236 	if (freefile != NULL) {
11237 		/*
11238 		 * If the inode is goingaway it was never written.  Fake up
11239 		 * the state here so free_inodedep() can succeed.
11240 		 */
11241 		if (inodedep->id_state & GOINGAWAY)
11242 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11243 		if (free_inodedep(inodedep) == 0)
11244 			panic("handle_written_inodeblock: live inodedep %p",
11245 			    inodedep);
11246 		add_to_worklist(&freefile->fx_list, 0);
11247 		return (0);
11248 	}
11249 
11250 	/*
11251 	 * If no outstanding dependencies, free it.
11252 	 */
11253 	if (free_inodedep(inodedep) ||
11254 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11255 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11256 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11257 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11258 		return (0);
11259 	return (hadchanges);
11260 }
11261 
11262 static int
11263 handle_written_indirdep(indirdep, bp, bpp)
11264 	struct indirdep *indirdep;
11265 	struct buf *bp;
11266 	struct buf **bpp;
11267 {
11268 	struct allocindir *aip;
11269 	struct buf *sbp;
11270 	int chgs;
11271 
11272 	if (indirdep->ir_state & GOINGAWAY)
11273 		panic("handle_written_indirdep: indirdep gone");
11274 	if ((indirdep->ir_state & IOSTARTED) == 0)
11275 		panic("handle_written_indirdep: IO not started");
11276 	chgs = 0;
11277 	/*
11278 	 * If there were rollbacks revert them here.
11279 	 */
11280 	if (indirdep->ir_saveddata) {
11281 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11282 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11283 			free(indirdep->ir_saveddata, M_INDIRDEP);
11284 			indirdep->ir_saveddata = NULL;
11285 		}
11286 		chgs = 1;
11287 	}
11288 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11289 	indirdep->ir_state |= ATTACHED;
11290 	/*
11291 	 * Move allocindirs with written pointers to the completehd if
11292 	 * the indirdep's pointer is not yet written.  Otherwise
11293 	 * free them here.
11294 	 */
11295 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0) {
11296 		LIST_REMOVE(aip, ai_next);
11297 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11298 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11299 			    ai_next);
11300 			newblk_freefrag(&aip->ai_block);
11301 			continue;
11302 		}
11303 		free_newblk(&aip->ai_block);
11304 	}
11305 	/*
11306 	 * Move allocindirs that have finished dependency processing from
11307 	 * the done list to the write list after updating the pointers.
11308 	 */
11309 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11310 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
11311 			handle_allocindir_partdone(aip);
11312 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11313 				panic("disk_write_complete: not gone");
11314 			chgs = 1;
11315 		}
11316 	}
11317 	/*
11318 	 * Preserve the indirdep if there were any changes or if it is not
11319 	 * yet valid on disk.
11320 	 */
11321 	if (chgs) {
11322 		stat_indir_blk_ptrs++;
11323 		bdirty(bp);
11324 		return (1);
11325 	}
11326 	/*
11327 	 * If there were no changes we can discard the savedbp and detach
11328 	 * ourselves from the buf.  We are only carrying completed pointers
11329 	 * in this case.
11330 	 */
11331 	sbp = indirdep->ir_savebp;
11332 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11333 	indirdep->ir_savebp = NULL;
11334 	indirdep->ir_bp = NULL;
11335 	if (*bpp != NULL)
11336 		panic("handle_written_indirdep: bp already exists.");
11337 	*bpp = sbp;
11338 	/*
11339 	 * The indirdep may not be freed until its parent points at it.
11340 	 */
11341 	if (indirdep->ir_state & DEPCOMPLETE)
11342 		free_indirdep(indirdep);
11343 
11344 	return (0);
11345 }
11346 
11347 /*
11348  * Process a diradd entry after its dependent inode has been written.
11349  * This routine must be called with splbio interrupts blocked.
11350  */
11351 static void
11352 diradd_inode_written(dap, inodedep)
11353 	struct diradd *dap;
11354 	struct inodedep *inodedep;
11355 {
11356 
11357 	dap->da_state |= COMPLETE;
11358 	complete_diradd(dap);
11359 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11360 }
11361 
11362 /*
11363  * Returns true if the bmsafemap will have rollbacks when written.  Must
11364  * only be called with lk and the buf lock on the cg held.
11365  */
11366 static int
11367 bmsafemap_backgroundwrite(bmsafemap, bp)
11368 	struct bmsafemap *bmsafemap;
11369 	struct buf *bp;
11370 {
11371 	int dirty;
11372 
11373 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11374 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11375 	/*
11376 	 * If we're initiating a background write we need to process the
11377 	 * rollbacks as they exist now, not as they exist when IO starts.
11378 	 * No other consumers will look at the contents of the shadowed
11379 	 * buf so this is safe to do here.
11380 	 */
11381 	if (bp->b_xflags & BX_BKGRDMARKER)
11382 		initiate_write_bmsafemap(bmsafemap, bp);
11383 
11384 	return (dirty);
11385 }
11386 
11387 /*
11388  * Re-apply an allocation when a cg write is complete.
11389  */
11390 static int
11391 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11392 	struct jnewblk *jnewblk;
11393 	struct fs *fs;
11394 	struct cg *cgp;
11395 	uint8_t *blksfree;
11396 {
11397 	ufs1_daddr_t fragno;
11398 	ufs2_daddr_t blkno;
11399 	long cgbno, bbase;
11400 	int frags, blk;
11401 	int i;
11402 
11403 	frags = 0;
11404 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11405 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11406 		if (isclr(blksfree, cgbno + i))
11407 			panic("jnewblk_rollforward: re-allocated fragment");
11408 		frags++;
11409 	}
11410 	if (frags == fs->fs_frag) {
11411 		blkno = fragstoblks(fs, cgbno);
11412 		ffs_clrblock(fs, blksfree, (long)blkno);
11413 		ffs_clusteracct(fs, cgp, blkno, -1);
11414 		cgp->cg_cs.cs_nbfree--;
11415 	} else {
11416 		bbase = cgbno - fragnum(fs, cgbno);
11417 		cgbno += jnewblk->jn_oldfrags;
11418                 /* If a complete block had been reassembled, account for it. */
11419 		fragno = fragstoblks(fs, bbase);
11420 		if (ffs_isblock(fs, blksfree, fragno)) {
11421 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11422 			ffs_clusteracct(fs, cgp, fragno, -1);
11423 			cgp->cg_cs.cs_nbfree--;
11424 		}
11425 		/* Decrement the old frags.  */
11426 		blk = blkmap(fs, blksfree, bbase);
11427 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11428 		/* Allocate the fragment */
11429 		for (i = 0; i < frags; i++)
11430 			clrbit(blksfree, cgbno + i);
11431 		cgp->cg_cs.cs_nffree -= frags;
11432 		/* Add back in counts associated with the new frags */
11433 		blk = blkmap(fs, blksfree, bbase);
11434 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11435 	}
11436 	return (frags);
11437 }
11438 
11439 /*
11440  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11441  * changes if it's not a background write.  Set all written dependencies
11442  * to DEPCOMPLETE and free the structure if possible.
11443  */
11444 static int
11445 handle_written_bmsafemap(bmsafemap, bp)
11446 	struct bmsafemap *bmsafemap;
11447 	struct buf *bp;
11448 {
11449 	struct newblk *newblk;
11450 	struct inodedep *inodedep;
11451 	struct jaddref *jaddref, *jatmp;
11452 	struct jnewblk *jnewblk, *jntmp;
11453 	struct ufsmount *ump;
11454 	uint8_t *inosused;
11455 	uint8_t *blksfree;
11456 	struct cg *cgp;
11457 	struct fs *fs;
11458 	ino_t ino;
11459 	int foreground;
11460 	int chgs;
11461 
11462 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11463 		panic("initiate_write_bmsafemap: Not started\n");
11464 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11465 	chgs = 0;
11466 	bmsafemap->sm_state &= ~IOSTARTED;
11467 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11468 	/*
11469 	 * Release journal work that was waiting on the write.
11470 	 */
11471 	handle_jwork(&bmsafemap->sm_freewr);
11472 
11473 	/*
11474 	 * Restore unwritten inode allocation pending jaddref writes.
11475 	 */
11476 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11477 		cgp = (struct cg *)bp->b_data;
11478 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11479 		inosused = cg_inosused(cgp);
11480 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11481 		    ja_bmdeps, jatmp) {
11482 			if ((jaddref->ja_state & UNDONE) == 0)
11483 				continue;
11484 			ino = jaddref->ja_ino % fs->fs_ipg;
11485 			if (isset(inosused, ino))
11486 				panic("handle_written_bmsafemap: "
11487 				    "re-allocated inode");
11488 			/* Do the roll-forward only if it's a real copy. */
11489 			if (foreground) {
11490 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11491 					cgp->cg_cs.cs_ndir++;
11492 				cgp->cg_cs.cs_nifree--;
11493 				setbit(inosused, ino);
11494 				chgs = 1;
11495 			}
11496 			jaddref->ja_state &= ~UNDONE;
11497 			jaddref->ja_state |= ATTACHED;
11498 			free_jaddref(jaddref);
11499 		}
11500 	}
11501 	/*
11502 	 * Restore any block allocations which are pending journal writes.
11503 	 */
11504 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11505 		cgp = (struct cg *)bp->b_data;
11506 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11507 		blksfree = cg_blksfree(cgp);
11508 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11509 		    jntmp) {
11510 			if ((jnewblk->jn_state & UNDONE) == 0)
11511 				continue;
11512 			/* Do the roll-forward only if it's a real copy. */
11513 			if (foreground &&
11514 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11515 				chgs = 1;
11516 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11517 			jnewblk->jn_state |= ATTACHED;
11518 			free_jnewblk(jnewblk);
11519 		}
11520 	}
11521 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11522 		newblk->nb_state |= DEPCOMPLETE;
11523 		newblk->nb_state &= ~ONDEPLIST;
11524 		newblk->nb_bmsafemap = NULL;
11525 		LIST_REMOVE(newblk, nb_deps);
11526 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11527 			handle_allocdirect_partdone(
11528 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11529 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11530 			handle_allocindir_partdone(
11531 			    WK_ALLOCINDIR(&newblk->nb_list));
11532 		else if (newblk->nb_list.wk_type != D_NEWBLK)
11533 			panic("handle_written_bmsafemap: Unexpected type: %s",
11534 			    TYPENAME(newblk->nb_list.wk_type));
11535 	}
11536 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11537 		inodedep->id_state |= DEPCOMPLETE;
11538 		inodedep->id_state &= ~ONDEPLIST;
11539 		LIST_REMOVE(inodedep, id_deps);
11540 		inodedep->id_bmsafemap = NULL;
11541 	}
11542 	LIST_REMOVE(bmsafemap, sm_next);
11543 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11544 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11545 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11546 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11547 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
11548 		LIST_REMOVE(bmsafemap, sm_hash);
11549 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11550 		return (0);
11551 	}
11552 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11553 	if (foreground)
11554 		bdirty(bp);
11555 	return (1);
11556 }
11557 
11558 /*
11559  * Try to free a mkdir dependency.
11560  */
11561 static void
11562 complete_mkdir(mkdir)
11563 	struct mkdir *mkdir;
11564 {
11565 	struct diradd *dap;
11566 
11567 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11568 		return;
11569 	LIST_REMOVE(mkdir, md_mkdirs);
11570 	dap = mkdir->md_diradd;
11571 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11572 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11573 		dap->da_state |= DEPCOMPLETE;
11574 		complete_diradd(dap);
11575 	}
11576 	WORKITEM_FREE(mkdir, D_MKDIR);
11577 }
11578 
11579 /*
11580  * Handle the completion of a mkdir dependency.
11581  */
11582 static void
11583 handle_written_mkdir(mkdir, type)
11584 	struct mkdir *mkdir;
11585 	int type;
11586 {
11587 
11588 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
11589 		panic("handle_written_mkdir: bad type");
11590 	mkdir->md_state |= COMPLETE;
11591 	complete_mkdir(mkdir);
11592 }
11593 
11594 static int
11595 free_pagedep(pagedep)
11596 	struct pagedep *pagedep;
11597 {
11598 	int i;
11599 
11600 	if (pagedep->pd_state & NEWBLOCK)
11601 		return (0);
11602 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
11603 		return (0);
11604 	for (i = 0; i < DAHASHSZ; i++)
11605 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
11606 			return (0);
11607 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
11608 		return (0);
11609 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
11610 		return (0);
11611 	if (pagedep->pd_state & ONWORKLIST)
11612 		WORKLIST_REMOVE(&pagedep->pd_list);
11613 	LIST_REMOVE(pagedep, pd_hash);
11614 	WORKITEM_FREE(pagedep, D_PAGEDEP);
11615 
11616 	return (1);
11617 }
11618 
11619 /*
11620  * Called from within softdep_disk_write_complete above.
11621  * A write operation was just completed. Removed inodes can
11622  * now be freed and associated block pointers may be committed.
11623  * Note that this routine is always called from interrupt level
11624  * with further splbio interrupts blocked.
11625  */
11626 static int
11627 handle_written_filepage(pagedep, bp)
11628 	struct pagedep *pagedep;
11629 	struct buf *bp;		/* buffer containing the written page */
11630 {
11631 	struct dirrem *dirrem;
11632 	struct diradd *dap, *nextdap;
11633 	struct direct *ep;
11634 	int i, chgs;
11635 
11636 	if ((pagedep->pd_state & IOSTARTED) == 0)
11637 		panic("handle_written_filepage: not started");
11638 	pagedep->pd_state &= ~IOSTARTED;
11639 	/*
11640 	 * Process any directory removals that have been committed.
11641 	 */
11642 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
11643 		LIST_REMOVE(dirrem, dm_next);
11644 		dirrem->dm_state |= COMPLETE;
11645 		dirrem->dm_dirinum = pagedep->pd_ino;
11646 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
11647 		    ("handle_written_filepage: Journal entries not written."));
11648 		add_to_worklist(&dirrem->dm_list, 0);
11649 	}
11650 	/*
11651 	 * Free any directory additions that have been committed.
11652 	 * If it is a newly allocated block, we have to wait until
11653 	 * the on-disk directory inode claims the new block.
11654 	 */
11655 	if ((pagedep->pd_state & NEWBLOCK) == 0)
11656 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
11657 			free_diradd(dap, NULL);
11658 	/*
11659 	 * Uncommitted directory entries must be restored.
11660 	 */
11661 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
11662 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
11663 		     dap = nextdap) {
11664 			nextdap = LIST_NEXT(dap, da_pdlist);
11665 			if (dap->da_state & ATTACHED)
11666 				panic("handle_written_filepage: attached");
11667 			ep = (struct direct *)
11668 			    ((char *)bp->b_data + dap->da_offset);
11669 			ep->d_ino = dap->da_newinum;
11670 			dap->da_state &= ~UNDONE;
11671 			dap->da_state |= ATTACHED;
11672 			chgs = 1;
11673 			/*
11674 			 * If the inode referenced by the directory has
11675 			 * been written out, then the dependency can be
11676 			 * moved to the pending list.
11677 			 */
11678 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
11679 				LIST_REMOVE(dap, da_pdlist);
11680 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
11681 				    da_pdlist);
11682 			}
11683 		}
11684 	}
11685 	/*
11686 	 * If there were any rollbacks in the directory, then it must be
11687 	 * marked dirty so that its will eventually get written back in
11688 	 * its correct form.
11689 	 */
11690 	if (chgs) {
11691 		if ((bp->b_flags & B_DELWRI) == 0)
11692 			stat_dir_entry++;
11693 		bdirty(bp);
11694 		return (1);
11695 	}
11696 	/*
11697 	 * If we are not waiting for a new directory block to be
11698 	 * claimed by its inode, then the pagedep will be freed.
11699 	 * Otherwise it will remain to track any new entries on
11700 	 * the page in case they are fsync'ed.
11701 	 */
11702 	free_pagedep(pagedep);
11703 	return (0);
11704 }
11705 
11706 /*
11707  * Writing back in-core inode structures.
11708  *
11709  * The filesystem only accesses an inode's contents when it occupies an
11710  * "in-core" inode structure.  These "in-core" structures are separate from
11711  * the page frames used to cache inode blocks.  Only the latter are
11712  * transferred to/from the disk.  So, when the updated contents of the
11713  * "in-core" inode structure are copied to the corresponding in-memory inode
11714  * block, the dependencies are also transferred.  The following procedure is
11715  * called when copying a dirty "in-core" inode to a cached inode block.
11716  */
11717 
11718 /*
11719  * Called when an inode is loaded from disk. If the effective link count
11720  * differed from the actual link count when it was last flushed, then we
11721  * need to ensure that the correct effective link count is put back.
11722  */
11723 void
11724 softdep_load_inodeblock(ip)
11725 	struct inode *ip;	/* the "in_core" copy of the inode */
11726 {
11727 	struct inodedep *inodedep;
11728 
11729 	/*
11730 	 * Check for alternate nlink count.
11731 	 */
11732 	ip->i_effnlink = ip->i_nlink;
11733 	ACQUIRE_LOCK(&lk);
11734 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
11735 	    &inodedep) == 0) {
11736 		FREE_LOCK(&lk);
11737 		return;
11738 	}
11739 	ip->i_effnlink -= inodedep->id_nlinkdelta;
11740 	FREE_LOCK(&lk);
11741 }
11742 
11743 /*
11744  * This routine is called just before the "in-core" inode
11745  * information is to be copied to the in-memory inode block.
11746  * Recall that an inode block contains several inodes. If
11747  * the force flag is set, then the dependencies will be
11748  * cleared so that the update can always be made. Note that
11749  * the buffer is locked when this routine is called, so we
11750  * will never be in the middle of writing the inode block
11751  * to disk.
11752  */
11753 void
11754 softdep_update_inodeblock(ip, bp, waitfor)
11755 	struct inode *ip;	/* the "in_core" copy of the inode */
11756 	struct buf *bp;		/* the buffer containing the inode block */
11757 	int waitfor;		/* nonzero => update must be allowed */
11758 {
11759 	struct inodedep *inodedep;
11760 	struct inoref *inoref;
11761 	struct worklist *wk;
11762 	struct mount *mp;
11763 	struct buf *ibp;
11764 	struct fs *fs;
11765 	int error;
11766 
11767 	mp = UFSTOVFS(ip->i_ump);
11768 	fs = ip->i_fs;
11769 	/*
11770 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
11771 	 * does not have access to the in-core ip so must write directly into
11772 	 * the inode block buffer when setting freelink.
11773 	 */
11774 	if (fs->fs_magic == FS_UFS1_MAGIC)
11775 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
11776 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
11777 	else
11778 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
11779 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
11780 	/*
11781 	 * If the effective link count is not equal to the actual link
11782 	 * count, then we must track the difference in an inodedep while
11783 	 * the inode is (potentially) tossed out of the cache. Otherwise,
11784 	 * if there is no existing inodedep, then there are no dependencies
11785 	 * to track.
11786 	 */
11787 	ACQUIRE_LOCK(&lk);
11788 again:
11789 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
11790 		FREE_LOCK(&lk);
11791 		if (ip->i_effnlink != ip->i_nlink)
11792 			panic("softdep_update_inodeblock: bad link count");
11793 		return;
11794 	}
11795 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
11796 		panic("softdep_update_inodeblock: bad delta");
11797 	/*
11798 	 * If we're flushing all dependencies we must also move any waiting
11799 	 * for journal writes onto the bufwait list prior to I/O.
11800 	 */
11801 	if (waitfor) {
11802 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
11803 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
11804 			    == DEPCOMPLETE) {
11805 				jwait(&inoref->if_list, MNT_WAIT);
11806 				goto again;
11807 			}
11808 		}
11809 	}
11810 	/*
11811 	 * Changes have been initiated. Anything depending on these
11812 	 * changes cannot occur until this inode has been written.
11813 	 */
11814 	inodedep->id_state &= ~COMPLETE;
11815 	if ((inodedep->id_state & ONWORKLIST) == 0)
11816 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
11817 	/*
11818 	 * Any new dependencies associated with the incore inode must
11819 	 * now be moved to the list associated with the buffer holding
11820 	 * the in-memory copy of the inode. Once merged process any
11821 	 * allocdirects that are completed by the merger.
11822 	 */
11823 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
11824 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
11825 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
11826 		    NULL);
11827 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
11828 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
11829 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
11830 		    NULL);
11831 	/*
11832 	 * Now that the inode has been pushed into the buffer, the
11833 	 * operations dependent on the inode being written to disk
11834 	 * can be moved to the id_bufwait so that they will be
11835 	 * processed when the buffer I/O completes.
11836 	 */
11837 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
11838 		WORKLIST_REMOVE(wk);
11839 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
11840 	}
11841 	/*
11842 	 * Newly allocated inodes cannot be written until the bitmap
11843 	 * that allocates them have been written (indicated by
11844 	 * DEPCOMPLETE being set in id_state). If we are doing a
11845 	 * forced sync (e.g., an fsync on a file), we force the bitmap
11846 	 * to be written so that the update can be done.
11847 	 */
11848 	if (waitfor == 0) {
11849 		FREE_LOCK(&lk);
11850 		return;
11851 	}
11852 retry:
11853 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
11854 		FREE_LOCK(&lk);
11855 		return;
11856 	}
11857 	ibp = inodedep->id_bmsafemap->sm_buf;
11858 	ibp = getdirtybuf(ibp, &lk, MNT_WAIT);
11859 	if (ibp == NULL) {
11860 		/*
11861 		 * If ibp came back as NULL, the dependency could have been
11862 		 * freed while we slept.  Look it up again, and check to see
11863 		 * that it has completed.
11864 		 */
11865 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
11866 			goto retry;
11867 		FREE_LOCK(&lk);
11868 		return;
11869 	}
11870 	FREE_LOCK(&lk);
11871 	if ((error = bwrite(ibp)) != 0)
11872 		softdep_error("softdep_update_inodeblock: bwrite", error);
11873 }
11874 
11875 /*
11876  * Merge the a new inode dependency list (such as id_newinoupdt) into an
11877  * old inode dependency list (such as id_inoupdt). This routine must be
11878  * called with splbio interrupts blocked.
11879  */
11880 static void
11881 merge_inode_lists(newlisthead, oldlisthead)
11882 	struct allocdirectlst *newlisthead;
11883 	struct allocdirectlst *oldlisthead;
11884 {
11885 	struct allocdirect *listadp, *newadp;
11886 
11887 	newadp = TAILQ_FIRST(newlisthead);
11888 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
11889 		if (listadp->ad_offset < newadp->ad_offset) {
11890 			listadp = TAILQ_NEXT(listadp, ad_next);
11891 			continue;
11892 		}
11893 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
11894 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
11895 		if (listadp->ad_offset == newadp->ad_offset) {
11896 			allocdirect_merge(oldlisthead, newadp,
11897 			    listadp);
11898 			listadp = newadp;
11899 		}
11900 		newadp = TAILQ_FIRST(newlisthead);
11901 	}
11902 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
11903 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
11904 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
11905 	}
11906 }
11907 
11908 /*
11909  * If we are doing an fsync, then we must ensure that any directory
11910  * entries for the inode have been written after the inode gets to disk.
11911  */
11912 int
11913 softdep_fsync(vp)
11914 	struct vnode *vp;	/* the "in_core" copy of the inode */
11915 {
11916 	struct inodedep *inodedep;
11917 	struct pagedep *pagedep;
11918 	struct inoref *inoref;
11919 	struct worklist *wk;
11920 	struct diradd *dap;
11921 	struct mount *mp;
11922 	struct vnode *pvp;
11923 	struct inode *ip;
11924 	struct buf *bp;
11925 	struct fs *fs;
11926 	struct thread *td = curthread;
11927 	int error, flushparent, pagedep_new_block;
11928 	ino_t parentino;
11929 	ufs_lbn_t lbn;
11930 
11931 	ip = VTOI(vp);
11932 	fs = ip->i_fs;
11933 	mp = vp->v_mount;
11934 	ACQUIRE_LOCK(&lk);
11935 restart:
11936 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
11937 		FREE_LOCK(&lk);
11938 		return (0);
11939 	}
11940 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
11941 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
11942 		    == DEPCOMPLETE) {
11943 			jwait(&inoref->if_list, MNT_WAIT);
11944 			goto restart;
11945 		}
11946 	}
11947 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
11948 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
11949 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
11950 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
11951 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
11952 		panic("softdep_fsync: pending ops %p", inodedep);
11953 	for (error = 0, flushparent = 0; ; ) {
11954 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
11955 			break;
11956 		if (wk->wk_type != D_DIRADD)
11957 			panic("softdep_fsync: Unexpected type %s",
11958 			    TYPENAME(wk->wk_type));
11959 		dap = WK_DIRADD(wk);
11960 		/*
11961 		 * Flush our parent if this directory entry has a MKDIR_PARENT
11962 		 * dependency or is contained in a newly allocated block.
11963 		 */
11964 		if (dap->da_state & DIRCHG)
11965 			pagedep = dap->da_previous->dm_pagedep;
11966 		else
11967 			pagedep = dap->da_pagedep;
11968 		parentino = pagedep->pd_ino;
11969 		lbn = pagedep->pd_lbn;
11970 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
11971 			panic("softdep_fsync: dirty");
11972 		if ((dap->da_state & MKDIR_PARENT) ||
11973 		    (pagedep->pd_state & NEWBLOCK))
11974 			flushparent = 1;
11975 		else
11976 			flushparent = 0;
11977 		/*
11978 		 * If we are being fsync'ed as part of vgone'ing this vnode,
11979 		 * then we will not be able to release and recover the
11980 		 * vnode below, so we just have to give up on writing its
11981 		 * directory entry out. It will eventually be written, just
11982 		 * not now, but then the user was not asking to have it
11983 		 * written, so we are not breaking any promises.
11984 		 */
11985 		if (vp->v_iflag & VI_DOOMED)
11986 			break;
11987 		/*
11988 		 * We prevent deadlock by always fetching inodes from the
11989 		 * root, moving down the directory tree. Thus, when fetching
11990 		 * our parent directory, we first try to get the lock. If
11991 		 * that fails, we must unlock ourselves before requesting
11992 		 * the lock on our parent. See the comment in ufs_lookup
11993 		 * for details on possible races.
11994 		 */
11995 		FREE_LOCK(&lk);
11996 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
11997 		    FFSV_FORCEINSMQ)) {
11998 			error = vfs_busy(mp, MBF_NOWAIT);
11999 			if (error != 0) {
12000 				vfs_ref(mp);
12001 				VOP_UNLOCK(vp, 0);
12002 				error = vfs_busy(mp, 0);
12003 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12004 				vfs_rel(mp);
12005 				if (error != 0)
12006 					return (ENOENT);
12007 				if (vp->v_iflag & VI_DOOMED) {
12008 					vfs_unbusy(mp);
12009 					return (ENOENT);
12010 				}
12011 			}
12012 			VOP_UNLOCK(vp, 0);
12013 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12014 			    &pvp, FFSV_FORCEINSMQ);
12015 			vfs_unbusy(mp);
12016 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12017 			if (vp->v_iflag & VI_DOOMED) {
12018 				if (error == 0)
12019 					vput(pvp);
12020 				error = ENOENT;
12021 			}
12022 			if (error != 0)
12023 				return (error);
12024 		}
12025 		/*
12026 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12027 		 * that are contained in direct blocks will be resolved by
12028 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12029 		 * may require a complete sync'ing of the directory. So, we
12030 		 * try the cheap and fast ffs_update first, and if that fails,
12031 		 * then we do the slower ffs_syncvnode of the directory.
12032 		 */
12033 		if (flushparent) {
12034 			int locked;
12035 
12036 			if ((error = ffs_update(pvp, 1)) != 0) {
12037 				vput(pvp);
12038 				return (error);
12039 			}
12040 			ACQUIRE_LOCK(&lk);
12041 			locked = 1;
12042 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12043 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12044 					if (wk->wk_type != D_DIRADD)
12045 						panic("softdep_fsync: Unexpected type %s",
12046 						      TYPENAME(wk->wk_type));
12047 					dap = WK_DIRADD(wk);
12048 					if (dap->da_state & DIRCHG)
12049 						pagedep = dap->da_previous->dm_pagedep;
12050 					else
12051 						pagedep = dap->da_pagedep;
12052 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12053 					FREE_LOCK(&lk);
12054 					locked = 0;
12055 					if (pagedep_new_block && (error =
12056 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12057 						vput(pvp);
12058 						return (error);
12059 					}
12060 				}
12061 			}
12062 			if (locked)
12063 				FREE_LOCK(&lk);
12064 		}
12065 		/*
12066 		 * Flush directory page containing the inode's name.
12067 		 */
12068 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12069 		    &bp);
12070 		if (error == 0)
12071 			error = bwrite(bp);
12072 		else
12073 			brelse(bp);
12074 		vput(pvp);
12075 		if (error != 0)
12076 			return (error);
12077 		ACQUIRE_LOCK(&lk);
12078 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12079 			break;
12080 	}
12081 	FREE_LOCK(&lk);
12082 	return (0);
12083 }
12084 
12085 /*
12086  * Flush all the dirty bitmaps associated with the block device
12087  * before flushing the rest of the dirty blocks so as to reduce
12088  * the number of dependencies that will have to be rolled back.
12089  *
12090  * XXX Unused?
12091  */
12092 void
12093 softdep_fsync_mountdev(vp)
12094 	struct vnode *vp;
12095 {
12096 	struct buf *bp, *nbp;
12097 	struct worklist *wk;
12098 	struct bufobj *bo;
12099 
12100 	if (!vn_isdisk(vp, NULL))
12101 		panic("softdep_fsync_mountdev: vnode not a disk");
12102 	bo = &vp->v_bufobj;
12103 restart:
12104 	BO_LOCK(bo);
12105 	ACQUIRE_LOCK(&lk);
12106 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12107 		/*
12108 		 * If it is already scheduled, skip to the next buffer.
12109 		 */
12110 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12111 			continue;
12112 
12113 		if ((bp->b_flags & B_DELWRI) == 0)
12114 			panic("softdep_fsync_mountdev: not dirty");
12115 		/*
12116 		 * We are only interested in bitmaps with outstanding
12117 		 * dependencies.
12118 		 */
12119 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12120 		    wk->wk_type != D_BMSAFEMAP ||
12121 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12122 			BUF_UNLOCK(bp);
12123 			continue;
12124 		}
12125 		FREE_LOCK(&lk);
12126 		BO_UNLOCK(bo);
12127 		bremfree(bp);
12128 		(void) bawrite(bp);
12129 		goto restart;
12130 	}
12131 	FREE_LOCK(&lk);
12132 	drain_output(vp);
12133 	BO_UNLOCK(bo);
12134 }
12135 
12136 /*
12137  * Sync all cylinder groups that were dirty at the time this function is
12138  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12139  * is used to flush freedep activity that may be holding up writes to a
12140  * indirect block.
12141  */
12142 static int
12143 sync_cgs(mp, waitfor)
12144 	struct mount *mp;
12145 	int waitfor;
12146 {
12147 	struct bmsafemap *bmsafemap;
12148 	struct bmsafemap *sentinel;
12149 	struct ufsmount *ump;
12150 	struct buf *bp;
12151 	int error;
12152 
12153 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12154 	sentinel->sm_cg = -1;
12155 	ump = VFSTOUFS(mp);
12156 	error = 0;
12157 	ACQUIRE_LOCK(&lk);
12158 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12159 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12160 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12161 		/* Skip sentinels and cgs with no work to release. */
12162 		if (bmsafemap->sm_cg == -1 ||
12163 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12164 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12165 			LIST_REMOVE(sentinel, sm_next);
12166 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12167 			continue;
12168 		}
12169 		/*
12170 		 * If we don't get the lock and we're waiting try again, if
12171 		 * not move on to the next buf and try to sync it.
12172 		 */
12173 		bp = getdirtybuf(bmsafemap->sm_buf, &lk, waitfor);
12174 		if (bp == NULL && waitfor == MNT_WAIT)
12175 			continue;
12176 		LIST_REMOVE(sentinel, sm_next);
12177 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12178 		if (bp == NULL)
12179 			continue;
12180 		FREE_LOCK(&lk);
12181 		if (waitfor == MNT_NOWAIT)
12182 			bawrite(bp);
12183 		else
12184 			error = bwrite(bp);
12185 		ACQUIRE_LOCK(&lk);
12186 		if (error)
12187 			break;
12188 	}
12189 	LIST_REMOVE(sentinel, sm_next);
12190 	FREE_LOCK(&lk);
12191 	free(sentinel, M_BMSAFEMAP);
12192 	return (error);
12193 }
12194 
12195 /*
12196  * This routine is called when we are trying to synchronously flush a
12197  * file. This routine must eliminate any filesystem metadata dependencies
12198  * so that the syncing routine can succeed.
12199  */
12200 int
12201 softdep_sync_metadata(struct vnode *vp)
12202 {
12203 	int error;
12204 
12205 	/*
12206 	 * Ensure that any direct block dependencies have been cleared,
12207 	 * truncations are started, and inode references are journaled.
12208 	 */
12209 	ACQUIRE_LOCK(&lk);
12210 	/*
12211 	 * Write all journal records to prevent rollbacks on devvp.
12212 	 */
12213 	if (vp->v_type == VCHR)
12214 		softdep_flushjournal(vp->v_mount);
12215 	error = flush_inodedep_deps(vp, vp->v_mount, VTOI(vp)->i_number);
12216 	/*
12217 	 * Ensure that all truncates are written so we won't find deps on
12218 	 * indirect blocks.
12219 	 */
12220 	process_truncates(vp);
12221 	FREE_LOCK(&lk);
12222 
12223 	return (error);
12224 }
12225 
12226 /*
12227  * This routine is called when we are attempting to sync a buf with
12228  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12229  * other IO it can but returns EBUSY if the buffer is not yet able to
12230  * be written.  Dependencies which will not cause rollbacks will always
12231  * return 0.
12232  */
12233 int
12234 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12235 {
12236 	struct indirdep *indirdep;
12237 	struct pagedep *pagedep;
12238 	struct allocindir *aip;
12239 	struct newblk *newblk;
12240 	struct buf *nbp;
12241 	struct worklist *wk;
12242 	int i, error;
12243 
12244 	/*
12245 	 * For VCHR we just don't want to force flush any dependencies that
12246 	 * will cause rollbacks.
12247 	 */
12248 	if (vp->v_type == VCHR) {
12249 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12250 			return (EBUSY);
12251 		return (0);
12252 	}
12253 	ACQUIRE_LOCK(&lk);
12254 	/*
12255 	 * As we hold the buffer locked, none of its dependencies
12256 	 * will disappear.
12257 	 */
12258 	error = 0;
12259 top:
12260 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12261 		switch (wk->wk_type) {
12262 
12263 		case D_ALLOCDIRECT:
12264 		case D_ALLOCINDIR:
12265 			newblk = WK_NEWBLK(wk);
12266 			if (newblk->nb_jnewblk != NULL) {
12267 				if (waitfor == MNT_NOWAIT) {
12268 					error = EBUSY;
12269 					goto out_unlock;
12270 				}
12271 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12272 				goto top;
12273 			}
12274 			if (newblk->nb_state & DEPCOMPLETE ||
12275 			    waitfor == MNT_NOWAIT)
12276 				continue;
12277 			nbp = newblk->nb_bmsafemap->sm_buf;
12278 			nbp = getdirtybuf(nbp, &lk, waitfor);
12279 			if (nbp == NULL)
12280 				goto top;
12281 			FREE_LOCK(&lk);
12282 			if ((error = bwrite(nbp)) != 0)
12283 				goto out;
12284 			ACQUIRE_LOCK(&lk);
12285 			continue;
12286 
12287 		case D_INDIRDEP:
12288 			indirdep = WK_INDIRDEP(wk);
12289 			if (waitfor == MNT_NOWAIT) {
12290 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12291 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12292 					error = EBUSY;
12293 					goto out_unlock;
12294 				}
12295 			}
12296 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12297 				panic("softdep_sync_buf: truncation pending.");
12298 		restart:
12299 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12300 				newblk = (struct newblk *)aip;
12301 				if (newblk->nb_jnewblk != NULL) {
12302 					jwait(&newblk->nb_jnewblk->jn_list,
12303 					    waitfor);
12304 					goto restart;
12305 				}
12306 				if (newblk->nb_state & DEPCOMPLETE)
12307 					continue;
12308 				nbp = newblk->nb_bmsafemap->sm_buf;
12309 				nbp = getdirtybuf(nbp, &lk, waitfor);
12310 				if (nbp == NULL)
12311 					goto restart;
12312 				FREE_LOCK(&lk);
12313 				if ((error = bwrite(nbp)) != 0)
12314 					goto out;
12315 				ACQUIRE_LOCK(&lk);
12316 				goto restart;
12317 			}
12318 			continue;
12319 
12320 		case D_PAGEDEP:
12321 			/*
12322 			 * Only flush directory entries in synchronous passes.
12323 			 */
12324 			if (waitfor != MNT_WAIT) {
12325 				error = EBUSY;
12326 				goto out_unlock;
12327 			}
12328 			/*
12329 			 * While syncing snapshots, we must allow recursive
12330 			 * lookups.
12331 			 */
12332 			BUF_AREC(bp);
12333 			/*
12334 			 * We are trying to sync a directory that may
12335 			 * have dependencies on both its own metadata
12336 			 * and/or dependencies on the inodes of any
12337 			 * recently allocated files. We walk its diradd
12338 			 * lists pushing out the associated inode.
12339 			 */
12340 			pagedep = WK_PAGEDEP(wk);
12341 			for (i = 0; i < DAHASHSZ; i++) {
12342 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12343 					continue;
12344 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12345 				    &pagedep->pd_diraddhd[i]))) {
12346 					BUF_NOREC(bp);
12347 					goto out_unlock;
12348 				}
12349 			}
12350 			BUF_NOREC(bp);
12351 			continue;
12352 
12353 		case D_FREEWORK:
12354 		case D_FREEDEP:
12355 		case D_JSEGDEP:
12356 		case D_JNEWBLK:
12357 			continue;
12358 
12359 		default:
12360 			panic("softdep_sync_buf: Unknown type %s",
12361 			    TYPENAME(wk->wk_type));
12362 			/* NOTREACHED */
12363 		}
12364 	}
12365 out_unlock:
12366 	FREE_LOCK(&lk);
12367 out:
12368 	return (error);
12369 }
12370 
12371 /*
12372  * Flush the dependencies associated with an inodedep.
12373  * Called with splbio blocked.
12374  */
12375 static int
12376 flush_inodedep_deps(vp, mp, ino)
12377 	struct vnode *vp;
12378 	struct mount *mp;
12379 	ino_t ino;
12380 {
12381 	struct inodedep *inodedep;
12382 	struct inoref *inoref;
12383 	int error, waitfor;
12384 
12385 	/*
12386 	 * This work is done in two passes. The first pass grabs most
12387 	 * of the buffers and begins asynchronously writing them. The
12388 	 * only way to wait for these asynchronous writes is to sleep
12389 	 * on the filesystem vnode which may stay busy for a long time
12390 	 * if the filesystem is active. So, instead, we make a second
12391 	 * pass over the dependencies blocking on each write. In the
12392 	 * usual case we will be blocking against a write that we
12393 	 * initiated, so when it is done the dependency will have been
12394 	 * resolved. Thus the second pass is expected to end quickly.
12395 	 * We give a brief window at the top of the loop to allow
12396 	 * any pending I/O to complete.
12397 	 */
12398 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12399 		if (error)
12400 			return (error);
12401 		FREE_LOCK(&lk);
12402 		ACQUIRE_LOCK(&lk);
12403 restart:
12404 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12405 			return (0);
12406 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12407 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12408 			    == DEPCOMPLETE) {
12409 				jwait(&inoref->if_list, MNT_WAIT);
12410 				goto restart;
12411 			}
12412 		}
12413 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12414 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12415 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12416 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12417 			continue;
12418 		/*
12419 		 * If pass2, we are done, otherwise do pass 2.
12420 		 */
12421 		if (waitfor == MNT_WAIT)
12422 			break;
12423 		waitfor = MNT_WAIT;
12424 	}
12425 	/*
12426 	 * Try freeing inodedep in case all dependencies have been removed.
12427 	 */
12428 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12429 		(void) free_inodedep(inodedep);
12430 	return (0);
12431 }
12432 
12433 /*
12434  * Flush an inode dependency list.
12435  * Called with splbio blocked.
12436  */
12437 static int
12438 flush_deplist(listhead, waitfor, errorp)
12439 	struct allocdirectlst *listhead;
12440 	int waitfor;
12441 	int *errorp;
12442 {
12443 	struct allocdirect *adp;
12444 	struct newblk *newblk;
12445 	struct buf *bp;
12446 
12447 	mtx_assert(&lk, MA_OWNED);
12448 	TAILQ_FOREACH(adp, listhead, ad_next) {
12449 		newblk = (struct newblk *)adp;
12450 		if (newblk->nb_jnewblk != NULL) {
12451 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12452 			return (1);
12453 		}
12454 		if (newblk->nb_state & DEPCOMPLETE)
12455 			continue;
12456 		bp = newblk->nb_bmsafemap->sm_buf;
12457 		bp = getdirtybuf(bp, &lk, waitfor);
12458 		if (bp == NULL) {
12459 			if (waitfor == MNT_NOWAIT)
12460 				continue;
12461 			return (1);
12462 		}
12463 		FREE_LOCK(&lk);
12464 		if (waitfor == MNT_NOWAIT)
12465 			bawrite(bp);
12466 		else
12467 			*errorp = bwrite(bp);
12468 		ACQUIRE_LOCK(&lk);
12469 		return (1);
12470 	}
12471 	return (0);
12472 }
12473 
12474 /*
12475  * Flush dependencies associated with an allocdirect block.
12476  */
12477 static int
12478 flush_newblk_dep(vp, mp, lbn)
12479 	struct vnode *vp;
12480 	struct mount *mp;
12481 	ufs_lbn_t lbn;
12482 {
12483 	struct newblk *newblk;
12484 	struct bufobj *bo;
12485 	struct inode *ip;
12486 	struct buf *bp;
12487 	ufs2_daddr_t blkno;
12488 	int error;
12489 
12490 	error = 0;
12491 	bo = &vp->v_bufobj;
12492 	ip = VTOI(vp);
12493 	blkno = DIP(ip, i_db[lbn]);
12494 	if (blkno == 0)
12495 		panic("flush_newblk_dep: Missing block");
12496 	ACQUIRE_LOCK(&lk);
12497 	/*
12498 	 * Loop until all dependencies related to this block are satisfied.
12499 	 * We must be careful to restart after each sleep in case a write
12500 	 * completes some part of this process for us.
12501 	 */
12502 	for (;;) {
12503 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12504 			FREE_LOCK(&lk);
12505 			break;
12506 		}
12507 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12508 			panic("flush_newblk_deps: Bad newblk %p", newblk);
12509 		/*
12510 		 * Flush the journal.
12511 		 */
12512 		if (newblk->nb_jnewblk != NULL) {
12513 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12514 			continue;
12515 		}
12516 		/*
12517 		 * Write the bitmap dependency.
12518 		 */
12519 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12520 			bp = newblk->nb_bmsafemap->sm_buf;
12521 			bp = getdirtybuf(bp, &lk, MNT_WAIT);
12522 			if (bp == NULL)
12523 				continue;
12524 			FREE_LOCK(&lk);
12525 			error = bwrite(bp);
12526 			if (error)
12527 				break;
12528 			ACQUIRE_LOCK(&lk);
12529 			continue;
12530 		}
12531 		/*
12532 		 * Write the buffer.
12533 		 */
12534 		FREE_LOCK(&lk);
12535 		BO_LOCK(bo);
12536 		bp = gbincore(bo, lbn);
12537 		if (bp != NULL) {
12538 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12539 			    LK_INTERLOCK, BO_MTX(bo));
12540 			if (error == ENOLCK) {
12541 				ACQUIRE_LOCK(&lk);
12542 				continue; /* Slept, retry */
12543 			}
12544 			if (error != 0)
12545 				break;	/* Failed */
12546 			if (bp->b_flags & B_DELWRI) {
12547 				bremfree(bp);
12548 				error = bwrite(bp);
12549 				if (error)
12550 					break;
12551 			} else
12552 				BUF_UNLOCK(bp);
12553 		} else
12554 			BO_UNLOCK(bo);
12555 		/*
12556 		 * We have to wait for the direct pointers to
12557 		 * point at the newdirblk before the dependency
12558 		 * will go away.
12559 		 */
12560 		error = ffs_update(vp, 1);
12561 		if (error)
12562 			break;
12563 		ACQUIRE_LOCK(&lk);
12564 	}
12565 	return (error);
12566 }
12567 
12568 /*
12569  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
12570  * Called with splbio blocked.
12571  */
12572 static int
12573 flush_pagedep_deps(pvp, mp, diraddhdp)
12574 	struct vnode *pvp;
12575 	struct mount *mp;
12576 	struct diraddhd *diraddhdp;
12577 {
12578 	struct inodedep *inodedep;
12579 	struct inoref *inoref;
12580 	struct ufsmount *ump;
12581 	struct diradd *dap;
12582 	struct vnode *vp;
12583 	int error = 0;
12584 	struct buf *bp;
12585 	ino_t inum;
12586 
12587 	ump = VFSTOUFS(mp);
12588 restart:
12589 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
12590 		/*
12591 		 * Flush ourselves if this directory entry
12592 		 * has a MKDIR_PARENT dependency.
12593 		 */
12594 		if (dap->da_state & MKDIR_PARENT) {
12595 			FREE_LOCK(&lk);
12596 			if ((error = ffs_update(pvp, 1)) != 0)
12597 				break;
12598 			ACQUIRE_LOCK(&lk);
12599 			/*
12600 			 * If that cleared dependencies, go on to next.
12601 			 */
12602 			if (dap != LIST_FIRST(diraddhdp))
12603 				continue;
12604 			if (dap->da_state & MKDIR_PARENT)
12605 				panic("flush_pagedep_deps: MKDIR_PARENT");
12606 		}
12607 		/*
12608 		 * A newly allocated directory must have its "." and
12609 		 * ".." entries written out before its name can be
12610 		 * committed in its parent.
12611 		 */
12612 		inum = dap->da_newinum;
12613 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12614 			panic("flush_pagedep_deps: lost inode1");
12615 		/*
12616 		 * Wait for any pending journal adds to complete so we don't
12617 		 * cause rollbacks while syncing.
12618 		 */
12619 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12620 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12621 			    == DEPCOMPLETE) {
12622 				jwait(&inoref->if_list, MNT_WAIT);
12623 				goto restart;
12624 			}
12625 		}
12626 		if (dap->da_state & MKDIR_BODY) {
12627 			FREE_LOCK(&lk);
12628 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12629 			    FFSV_FORCEINSMQ)))
12630 				break;
12631 			error = flush_newblk_dep(vp, mp, 0);
12632 			/*
12633 			 * If we still have the dependency we might need to
12634 			 * update the vnode to sync the new link count to
12635 			 * disk.
12636 			 */
12637 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
12638 				error = ffs_update(vp, 1);
12639 			vput(vp);
12640 			if (error != 0)
12641 				break;
12642 			ACQUIRE_LOCK(&lk);
12643 			/*
12644 			 * If that cleared dependencies, go on to next.
12645 			 */
12646 			if (dap != LIST_FIRST(diraddhdp))
12647 				continue;
12648 			if (dap->da_state & MKDIR_BODY) {
12649 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
12650 				    &inodedep);
12651 				panic("flush_pagedep_deps: MKDIR_BODY "
12652 				    "inodedep %p dap %p vp %p",
12653 				    inodedep, dap, vp);
12654 			}
12655 		}
12656 		/*
12657 		 * Flush the inode on which the directory entry depends.
12658 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
12659 		 * the only remaining dependency is that the updated inode
12660 		 * count must get pushed to disk. The inode has already
12661 		 * been pushed into its inode buffer (via VOP_UPDATE) at
12662 		 * the time of the reference count change. So we need only
12663 		 * locate that buffer, ensure that there will be no rollback
12664 		 * caused by a bitmap dependency, then write the inode buffer.
12665 		 */
12666 retry:
12667 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12668 			panic("flush_pagedep_deps: lost inode");
12669 		/*
12670 		 * If the inode still has bitmap dependencies,
12671 		 * push them to disk.
12672 		 */
12673 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
12674 			bp = inodedep->id_bmsafemap->sm_buf;
12675 			bp = getdirtybuf(bp, &lk, MNT_WAIT);
12676 			if (bp == NULL)
12677 				goto retry;
12678 			FREE_LOCK(&lk);
12679 			if ((error = bwrite(bp)) != 0)
12680 				break;
12681 			ACQUIRE_LOCK(&lk);
12682 			if (dap != LIST_FIRST(diraddhdp))
12683 				continue;
12684 		}
12685 		/*
12686 		 * If the inode is still sitting in a buffer waiting
12687 		 * to be written or waiting for the link count to be
12688 		 * adjusted update it here to flush it to disk.
12689 		 */
12690 		if (dap == LIST_FIRST(diraddhdp)) {
12691 			FREE_LOCK(&lk);
12692 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12693 			    FFSV_FORCEINSMQ)))
12694 				break;
12695 			error = ffs_update(vp, 1);
12696 			vput(vp);
12697 			if (error)
12698 				break;
12699 			ACQUIRE_LOCK(&lk);
12700 		}
12701 		/*
12702 		 * If we have failed to get rid of all the dependencies
12703 		 * then something is seriously wrong.
12704 		 */
12705 		if (dap == LIST_FIRST(diraddhdp)) {
12706 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
12707 			panic("flush_pagedep_deps: failed to flush "
12708 			    "inodedep %p ino %ju dap %p",
12709 			    inodedep, (uintmax_t)inum, dap);
12710 		}
12711 	}
12712 	if (error)
12713 		ACQUIRE_LOCK(&lk);
12714 	return (error);
12715 }
12716 
12717 /*
12718  * A large burst of file addition or deletion activity can drive the
12719  * memory load excessively high. First attempt to slow things down
12720  * using the techniques below. If that fails, this routine requests
12721  * the offending operations to fall back to running synchronously
12722  * until the memory load returns to a reasonable level.
12723  */
12724 int
12725 softdep_slowdown(vp)
12726 	struct vnode *vp;
12727 {
12728 	struct ufsmount *ump;
12729 	int jlow;
12730 	int max_softdeps_hard;
12731 
12732 	ACQUIRE_LOCK(&lk);
12733 	jlow = 0;
12734 	/*
12735 	 * Check for journal space if needed.
12736 	 */
12737 	if (DOINGSUJ(vp)) {
12738 		ump = VFSTOUFS(vp->v_mount);
12739 		if (journal_space(ump, 0) == 0)
12740 			jlow = 1;
12741 	}
12742 	max_softdeps_hard = max_softdeps * 11 / 10;
12743 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
12744 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
12745 	    VFSTOUFS(vp->v_mount)->um_numindirdeps < maxindirdeps &&
12746 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0) {
12747 		FREE_LOCK(&lk);
12748   		return (0);
12749 	}
12750 	if (VFSTOUFS(vp->v_mount)->um_numindirdeps >= maxindirdeps || jlow)
12751 		softdep_speedup();
12752 	stat_sync_limit_hit += 1;
12753 	FREE_LOCK(&lk);
12754 	if (DOINGSUJ(vp))
12755 		return (0);
12756 	return (1);
12757 }
12758 
12759 /*
12760  * Called by the allocation routines when they are about to fail
12761  * in the hope that we can free up the requested resource (inodes
12762  * or disk space).
12763  *
12764  * First check to see if the work list has anything on it. If it has,
12765  * clean up entries until we successfully free the requested resource.
12766  * Because this process holds inodes locked, we cannot handle any remove
12767  * requests that might block on a locked inode as that could lead to
12768  * deadlock. If the worklist yields none of the requested resource,
12769  * start syncing out vnodes to free up the needed space.
12770  */
12771 int
12772 softdep_request_cleanup(fs, vp, cred, resource)
12773 	struct fs *fs;
12774 	struct vnode *vp;
12775 	struct ucred *cred;
12776 	int resource;
12777 {
12778 	struct ufsmount *ump;
12779 	struct mount *mp;
12780 	struct vnode *lvp, *mvp;
12781 	long starttime;
12782 	ufs2_daddr_t needed;
12783 	int error;
12784 
12785 	/*
12786 	 * If we are being called because of a process doing a
12787 	 * copy-on-write, then it is not safe to process any
12788 	 * worklist items as we will recurse into the copyonwrite
12789 	 * routine.  This will result in an incoherent snapshot.
12790 	 * If the vnode that we hold is a snapshot, we must avoid
12791 	 * handling other resources that could cause deadlock.
12792 	 */
12793 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
12794 		return (0);
12795 
12796 	if (resource == FLUSH_BLOCKS_WAIT)
12797 		stat_cleanup_blkrequests += 1;
12798 	else
12799 		stat_cleanup_inorequests += 1;
12800 
12801 	mp = vp->v_mount;
12802 	ump = VFSTOUFS(mp);
12803 	mtx_assert(UFS_MTX(ump), MA_OWNED);
12804 	UFS_UNLOCK(ump);
12805 	error = ffs_update(vp, 1);
12806 	if (error != 0) {
12807 		UFS_LOCK(ump);
12808 		return (0);
12809 	}
12810 	/*
12811 	 * If we are in need of resources, consider pausing for
12812 	 * tickdelay to give ourselves some breathing room.
12813 	 */
12814 	ACQUIRE_LOCK(&lk);
12815 	process_removes(vp);
12816 	process_truncates(vp);
12817 	request_cleanup(UFSTOVFS(ump), resource);
12818 	FREE_LOCK(&lk);
12819 	/*
12820 	 * Now clean up at least as many resources as we will need.
12821 	 *
12822 	 * When requested to clean up inodes, the number that are needed
12823 	 * is set by the number of simultaneous writers (mnt_writeopcount)
12824 	 * plus a bit of slop (2) in case some more writers show up while
12825 	 * we are cleaning.
12826 	 *
12827 	 * When requested to free up space, the amount of space that
12828 	 * we need is enough blocks to allocate a full-sized segment
12829 	 * (fs_contigsumsize). The number of such segments that will
12830 	 * be needed is set by the number of simultaneous writers
12831 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
12832 	 * writers show up while we are cleaning.
12833 	 *
12834 	 * Additionally, if we are unpriviledged and allocating space,
12835 	 * we need to ensure that we clean up enough blocks to get the
12836 	 * needed number of blocks over the threshhold of the minimum
12837 	 * number of blocks required to be kept free by the filesystem
12838 	 * (fs_minfree).
12839 	 */
12840 	if (resource == FLUSH_INODES_WAIT) {
12841 		needed = vp->v_mount->mnt_writeopcount + 2;
12842 	} else if (resource == FLUSH_BLOCKS_WAIT) {
12843 		needed = (vp->v_mount->mnt_writeopcount + 2) *
12844 		    fs->fs_contigsumsize;
12845 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
12846 			needed += fragstoblks(fs,
12847 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
12848 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
12849 	} else {
12850 		UFS_LOCK(ump);
12851 		printf("softdep_request_cleanup: Unknown resource type %d\n",
12852 		    resource);
12853 		return (0);
12854 	}
12855 	starttime = time_second;
12856 retry:
12857 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
12858 	    fs->fs_cstotal.cs_nbfree <= needed) ||
12859 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
12860 	    fs->fs_cstotal.cs_nifree <= needed)) {
12861 		ACQUIRE_LOCK(&lk);
12862 		if (ump->softdep_on_worklist > 0 &&
12863 		    process_worklist_item(UFSTOVFS(ump),
12864 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
12865 			stat_worklist_push += 1;
12866 		FREE_LOCK(&lk);
12867 	}
12868 	/*
12869 	 * If we still need resources and there are no more worklist
12870 	 * entries to process to obtain them, we have to start flushing
12871 	 * the dirty vnodes to force the release of additional requests
12872 	 * to the worklist that we can then process to reap addition
12873 	 * resources. We walk the vnodes associated with the mount point
12874 	 * until we get the needed worklist requests that we can reap.
12875 	 */
12876 	if ((resource == FLUSH_BLOCKS_WAIT &&
12877 	     fs->fs_cstotal.cs_nbfree <= needed) ||
12878 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
12879 	     fs->fs_cstotal.cs_nifree <= needed)) {
12880 		MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
12881 			if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
12882 				VI_UNLOCK(lvp);
12883 				continue;
12884 			}
12885 			if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
12886 			    curthread))
12887 				continue;
12888 			if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
12889 				vput(lvp);
12890 				continue;
12891 			}
12892 			(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
12893 			vput(lvp);
12894 		}
12895 		lvp = ump->um_devvp;
12896 		if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
12897 			VOP_FSYNC(lvp, MNT_NOWAIT, curthread);
12898 			VOP_UNLOCK(lvp, 0);
12899 		}
12900 		if (ump->softdep_on_worklist > 0) {
12901 			stat_cleanup_retries += 1;
12902 			goto retry;
12903 		}
12904 		stat_cleanup_failures += 1;
12905 	}
12906 	if (time_second - starttime > stat_cleanup_high_delay)
12907 		stat_cleanup_high_delay = time_second - starttime;
12908 	UFS_LOCK(ump);
12909 	return (1);
12910 }
12911 
12912 /*
12913  * If memory utilization has gotten too high, deliberately slow things
12914  * down and speed up the I/O processing.
12915  */
12916 extern struct thread *syncertd;
12917 static int
12918 request_cleanup(mp, resource)
12919 	struct mount *mp;
12920 	int resource;
12921 {
12922 	struct thread *td = curthread;
12923 	struct ufsmount *ump;
12924 
12925 	mtx_assert(&lk, MA_OWNED);
12926 	/*
12927 	 * We never hold up the filesystem syncer or buf daemon.
12928 	 */
12929 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
12930 		return (0);
12931 	ump = VFSTOUFS(mp);
12932 	/*
12933 	 * First check to see if the work list has gotten backlogged.
12934 	 * If it has, co-opt this process to help clean up two entries.
12935 	 * Because this process may hold inodes locked, we cannot
12936 	 * handle any remove requests that might block on a locked
12937 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
12938 	 * to avoid recursively processing the worklist.
12939 	 */
12940 	if (ump->softdep_on_worklist > max_softdeps / 10) {
12941 		td->td_pflags |= TDP_SOFTDEP;
12942 		process_worklist_item(mp, 2, LK_NOWAIT);
12943 		td->td_pflags &= ~TDP_SOFTDEP;
12944 		stat_worklist_push += 2;
12945 		return(1);
12946 	}
12947 	/*
12948 	 * Next, we attempt to speed up the syncer process. If that
12949 	 * is successful, then we allow the process to continue.
12950 	 */
12951 	if (softdep_speedup() &&
12952 	    resource != FLUSH_BLOCKS_WAIT &&
12953 	    resource != FLUSH_INODES_WAIT)
12954 		return(0);
12955 	/*
12956 	 * If we are resource constrained on inode dependencies, try
12957 	 * flushing some dirty inodes. Otherwise, we are constrained
12958 	 * by file deletions, so try accelerating flushes of directories
12959 	 * with removal dependencies. We would like to do the cleanup
12960 	 * here, but we probably hold an inode locked at this point and
12961 	 * that might deadlock against one that we try to clean. So,
12962 	 * the best that we can do is request the syncer daemon to do
12963 	 * the cleanup for us.
12964 	 */
12965 	switch (resource) {
12966 
12967 	case FLUSH_INODES:
12968 	case FLUSH_INODES_WAIT:
12969 		stat_ino_limit_push += 1;
12970 		req_clear_inodedeps += 1;
12971 		stat_countp = &stat_ino_limit_hit;
12972 		break;
12973 
12974 	case FLUSH_BLOCKS:
12975 	case FLUSH_BLOCKS_WAIT:
12976 		stat_blk_limit_push += 1;
12977 		req_clear_remove += 1;
12978 		stat_countp = &stat_blk_limit_hit;
12979 		break;
12980 
12981 	default:
12982 		panic("request_cleanup: unknown type");
12983 	}
12984 	/*
12985 	 * Hopefully the syncer daemon will catch up and awaken us.
12986 	 * We wait at most tickdelay before proceeding in any case.
12987 	 */
12988 	proc_waiting += 1;
12989 	if (callout_pending(&softdep_callout) == FALSE)
12990 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
12991 		    pause_timer, 0);
12992 
12993 	msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
12994 	proc_waiting -= 1;
12995 	return (1);
12996 }
12997 
12998 /*
12999  * Awaken processes pausing in request_cleanup and clear proc_waiting
13000  * to indicate that there is no longer a timer running.
13001  */
13002 static void
13003 pause_timer(arg)
13004 	void *arg;
13005 {
13006 
13007 	/*
13008 	 * The callout_ API has acquired mtx and will hold it around this
13009 	 * function call.
13010 	 */
13011 	*stat_countp += 1;
13012 	wakeup_one(&proc_waiting);
13013 	if (proc_waiting > 0)
13014 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13015 		    pause_timer, 0);
13016 }
13017 
13018 /*
13019  * Flush out a directory with at least one removal dependency in an effort to
13020  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13021  */
13022 static void
13023 clear_remove(void)
13024 {
13025 	struct pagedep_hashhead *pagedephd;
13026 	struct pagedep *pagedep;
13027 	static int next = 0;
13028 	struct mount *mp;
13029 	struct vnode *vp;
13030 	struct bufobj *bo;
13031 	int error, cnt;
13032 	ino_t ino;
13033 
13034 	mtx_assert(&lk, MA_OWNED);
13035 
13036 	for (cnt = 0; cnt <= pagedep_hash; cnt++) {
13037 		pagedephd = &pagedep_hashtbl[next++];
13038 		if (next > pagedep_hash)
13039 			next = 0;
13040 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13041 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13042 				continue;
13043 			mp = pagedep->pd_list.wk_mp;
13044 			ino = pagedep->pd_ino;
13045 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13046 				continue;
13047 			FREE_LOCK(&lk);
13048 
13049 			/*
13050 			 * Let unmount clear deps
13051 			 */
13052 			error = vfs_busy(mp, MBF_NOWAIT);
13053 			if (error != 0)
13054 				goto finish_write;
13055 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13056 			     FFSV_FORCEINSMQ);
13057 			vfs_unbusy(mp);
13058 			if (error != 0) {
13059 				softdep_error("clear_remove: vget", error);
13060 				goto finish_write;
13061 			}
13062 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13063 				softdep_error("clear_remove: fsync", error);
13064 			bo = &vp->v_bufobj;
13065 			BO_LOCK(bo);
13066 			drain_output(vp);
13067 			BO_UNLOCK(bo);
13068 			vput(vp);
13069 		finish_write:
13070 			vn_finished_write(mp);
13071 			ACQUIRE_LOCK(&lk);
13072 			return;
13073 		}
13074 	}
13075 }
13076 
13077 /*
13078  * Clear out a block of dirty inodes in an effort to reduce
13079  * the number of inodedep dependency structures.
13080  */
13081 static void
13082 clear_inodedeps(void)
13083 {
13084 	struct inodedep_hashhead *inodedephd;
13085 	struct inodedep *inodedep;
13086 	static int next = 0;
13087 	struct mount *mp;
13088 	struct vnode *vp;
13089 	struct fs *fs;
13090 	int error, cnt;
13091 	ino_t firstino, lastino, ino;
13092 
13093 	mtx_assert(&lk, MA_OWNED);
13094 	/*
13095 	 * Pick a random inode dependency to be cleared.
13096 	 * We will then gather up all the inodes in its block
13097 	 * that have dependencies and flush them out.
13098 	 */
13099 	for (cnt = 0; cnt <= inodedep_hash; cnt++) {
13100 		inodedephd = &inodedep_hashtbl[next++];
13101 		if (next > inodedep_hash)
13102 			next = 0;
13103 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13104 			break;
13105 	}
13106 	if (inodedep == NULL)
13107 		return;
13108 	fs = inodedep->id_fs;
13109 	mp = inodedep->id_list.wk_mp;
13110 	/*
13111 	 * Find the last inode in the block with dependencies.
13112 	 */
13113 	firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
13114 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13115 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13116 			break;
13117 	/*
13118 	 * Asynchronously push all but the last inode with dependencies.
13119 	 * Synchronously push the last inode with dependencies to ensure
13120 	 * that the inode block gets written to free up the inodedeps.
13121 	 */
13122 	for (ino = firstino; ino <= lastino; ino++) {
13123 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13124 			continue;
13125 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13126 			continue;
13127 		FREE_LOCK(&lk);
13128 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13129 		if (error != 0) {
13130 			vn_finished_write(mp);
13131 			ACQUIRE_LOCK(&lk);
13132 			return;
13133 		}
13134 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13135 		    FFSV_FORCEINSMQ)) != 0) {
13136 			softdep_error("clear_inodedeps: vget", error);
13137 			vfs_unbusy(mp);
13138 			vn_finished_write(mp);
13139 			ACQUIRE_LOCK(&lk);
13140 			return;
13141 		}
13142 		vfs_unbusy(mp);
13143 		if (ino == lastino) {
13144 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13145 				softdep_error("clear_inodedeps: fsync1", error);
13146 		} else {
13147 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13148 				softdep_error("clear_inodedeps: fsync2", error);
13149 			BO_LOCK(&vp->v_bufobj);
13150 			drain_output(vp);
13151 			BO_UNLOCK(&vp->v_bufobj);
13152 		}
13153 		vput(vp);
13154 		vn_finished_write(mp);
13155 		ACQUIRE_LOCK(&lk);
13156 	}
13157 }
13158 
13159 void
13160 softdep_buf_append(bp, wkhd)
13161 	struct buf *bp;
13162 	struct workhead *wkhd;
13163 {
13164 	struct worklist *wk;
13165 
13166 	ACQUIRE_LOCK(&lk);
13167 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13168 		WORKLIST_REMOVE(wk);
13169 		WORKLIST_INSERT(&bp->b_dep, wk);
13170 	}
13171 	FREE_LOCK(&lk);
13172 
13173 }
13174 
13175 void
13176 softdep_inode_append(ip, cred, wkhd)
13177 	struct inode *ip;
13178 	struct ucred *cred;
13179 	struct workhead *wkhd;
13180 {
13181 	struct buf *bp;
13182 	struct fs *fs;
13183 	int error;
13184 
13185 	fs = ip->i_fs;
13186 	error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13187 	    (int)fs->fs_bsize, cred, &bp);
13188 	if (error) {
13189 		bqrelse(bp);
13190 		softdep_freework(wkhd);
13191 		return;
13192 	}
13193 	softdep_buf_append(bp, wkhd);
13194 	bqrelse(bp);
13195 }
13196 
13197 void
13198 softdep_freework(wkhd)
13199 	struct workhead *wkhd;
13200 {
13201 
13202 	ACQUIRE_LOCK(&lk);
13203 	handle_jwork(wkhd);
13204 	FREE_LOCK(&lk);
13205 }
13206 
13207 /*
13208  * Function to determine if the buffer has outstanding dependencies
13209  * that will cause a roll-back if the buffer is written. If wantcount
13210  * is set, return number of dependencies, otherwise just yes or no.
13211  */
13212 static int
13213 softdep_count_dependencies(bp, wantcount)
13214 	struct buf *bp;
13215 	int wantcount;
13216 {
13217 	struct worklist *wk;
13218 	struct bmsafemap *bmsafemap;
13219 	struct freework *freework;
13220 	struct inodedep *inodedep;
13221 	struct indirdep *indirdep;
13222 	struct freeblks *freeblks;
13223 	struct allocindir *aip;
13224 	struct pagedep *pagedep;
13225 	struct dirrem *dirrem;
13226 	struct newblk *newblk;
13227 	struct mkdir *mkdir;
13228 	struct diradd *dap;
13229 	int i, retval;
13230 
13231 	retval = 0;
13232 	ACQUIRE_LOCK(&lk);
13233 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13234 		switch (wk->wk_type) {
13235 
13236 		case D_INODEDEP:
13237 			inodedep = WK_INODEDEP(wk);
13238 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13239 				/* bitmap allocation dependency */
13240 				retval += 1;
13241 				if (!wantcount)
13242 					goto out;
13243 			}
13244 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13245 				/* direct block pointer dependency */
13246 				retval += 1;
13247 				if (!wantcount)
13248 					goto out;
13249 			}
13250 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13251 				/* direct block pointer dependency */
13252 				retval += 1;
13253 				if (!wantcount)
13254 					goto out;
13255 			}
13256 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13257 				/* Add reference dependency. */
13258 				retval += 1;
13259 				if (!wantcount)
13260 					goto out;
13261 			}
13262 			continue;
13263 
13264 		case D_INDIRDEP:
13265 			indirdep = WK_INDIRDEP(wk);
13266 
13267 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
13268 				/* indirect truncation dependency */
13269 				retval += 1;
13270 				if (!wantcount)
13271 					goto out;
13272 			}
13273 
13274 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13275 				/* indirect block pointer dependency */
13276 				retval += 1;
13277 				if (!wantcount)
13278 					goto out;
13279 			}
13280 			continue;
13281 
13282 		case D_PAGEDEP:
13283 			pagedep = WK_PAGEDEP(wk);
13284 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
13285 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
13286 					/* Journal remove ref dependency. */
13287 					retval += 1;
13288 					if (!wantcount)
13289 						goto out;
13290 				}
13291 			}
13292 			for (i = 0; i < DAHASHSZ; i++) {
13293 
13294 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
13295 					/* directory entry dependency */
13296 					retval += 1;
13297 					if (!wantcount)
13298 						goto out;
13299 				}
13300 			}
13301 			continue;
13302 
13303 		case D_BMSAFEMAP:
13304 			bmsafemap = WK_BMSAFEMAP(wk);
13305 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
13306 				/* Add reference dependency. */
13307 				retval += 1;
13308 				if (!wantcount)
13309 					goto out;
13310 			}
13311 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
13312 				/* Allocate block dependency. */
13313 				retval += 1;
13314 				if (!wantcount)
13315 					goto out;
13316 			}
13317 			continue;
13318 
13319 		case D_FREEBLKS:
13320 			freeblks = WK_FREEBLKS(wk);
13321 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
13322 				/* Freeblk journal dependency. */
13323 				retval += 1;
13324 				if (!wantcount)
13325 					goto out;
13326 			}
13327 			continue;
13328 
13329 		case D_ALLOCDIRECT:
13330 		case D_ALLOCINDIR:
13331 			newblk = WK_NEWBLK(wk);
13332 			if (newblk->nb_jnewblk) {
13333 				/* Journal allocate dependency. */
13334 				retval += 1;
13335 				if (!wantcount)
13336 					goto out;
13337 			}
13338 			continue;
13339 
13340 		case D_MKDIR:
13341 			mkdir = WK_MKDIR(wk);
13342 			if (mkdir->md_jaddref) {
13343 				/* Journal reference dependency. */
13344 				retval += 1;
13345 				if (!wantcount)
13346 					goto out;
13347 			}
13348 			continue;
13349 
13350 		case D_FREEWORK:
13351 		case D_FREEDEP:
13352 		case D_JSEGDEP:
13353 		case D_JSEG:
13354 		case D_SBDEP:
13355 			/* never a dependency on these blocks */
13356 			continue;
13357 
13358 		default:
13359 			panic("softdep_count_dependencies: Unexpected type %s",
13360 			    TYPENAME(wk->wk_type));
13361 			/* NOTREACHED */
13362 		}
13363 	}
13364 out:
13365 	FREE_LOCK(&lk);
13366 	return retval;
13367 }
13368 
13369 /*
13370  * Acquire exclusive access to a buffer.
13371  * Must be called with a locked mtx parameter.
13372  * Return acquired buffer or NULL on failure.
13373  */
13374 static struct buf *
13375 getdirtybuf(bp, mtx, waitfor)
13376 	struct buf *bp;
13377 	struct mtx *mtx;
13378 	int waitfor;
13379 {
13380 	int error;
13381 
13382 	mtx_assert(mtx, MA_OWNED);
13383 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
13384 		if (waitfor != MNT_WAIT)
13385 			return (NULL);
13386 		error = BUF_LOCK(bp,
13387 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, mtx);
13388 		/*
13389 		 * Even if we sucessfully acquire bp here, we have dropped
13390 		 * mtx, which may violates our guarantee.
13391 		 */
13392 		if (error == 0)
13393 			BUF_UNLOCK(bp);
13394 		else if (error != ENOLCK)
13395 			panic("getdirtybuf: inconsistent lock: %d", error);
13396 		mtx_lock(mtx);
13397 		return (NULL);
13398 	}
13399 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13400 		if (mtx == &lk && waitfor == MNT_WAIT) {
13401 			mtx_unlock(mtx);
13402 			BO_LOCK(bp->b_bufobj);
13403 			BUF_UNLOCK(bp);
13404 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13405 				bp->b_vflags |= BV_BKGRDWAIT;
13406 				msleep(&bp->b_xflags, BO_MTX(bp->b_bufobj),
13407 				       PRIBIO | PDROP, "getbuf", 0);
13408 			} else
13409 				BO_UNLOCK(bp->b_bufobj);
13410 			mtx_lock(mtx);
13411 			return (NULL);
13412 		}
13413 		BUF_UNLOCK(bp);
13414 		if (waitfor != MNT_WAIT)
13415 			return (NULL);
13416 		/*
13417 		 * The mtx argument must be bp->b_vp's mutex in
13418 		 * this case.
13419 		 */
13420 #ifdef	DEBUG_VFS_LOCKS
13421 		if (bp->b_vp->v_type != VCHR)
13422 			ASSERT_BO_LOCKED(bp->b_bufobj);
13423 #endif
13424 		bp->b_vflags |= BV_BKGRDWAIT;
13425 		msleep(&bp->b_xflags, mtx, PRIBIO, "getbuf", 0);
13426 		return (NULL);
13427 	}
13428 	if ((bp->b_flags & B_DELWRI) == 0) {
13429 		BUF_UNLOCK(bp);
13430 		return (NULL);
13431 	}
13432 	bremfree(bp);
13433 	return (bp);
13434 }
13435 
13436 
13437 /*
13438  * Check if it is safe to suspend the file system now.  On entry,
13439  * the vnode interlock for devvp should be held.  Return 0 with
13440  * the mount interlock held if the file system can be suspended now,
13441  * otherwise return EAGAIN with the mount interlock held.
13442  */
13443 int
13444 softdep_check_suspend(struct mount *mp,
13445 		      struct vnode *devvp,
13446 		      int softdep_deps,
13447 		      int softdep_accdeps,
13448 		      int secondary_writes,
13449 		      int secondary_accwrites)
13450 {
13451 	struct bufobj *bo;
13452 	struct ufsmount *ump;
13453 	int error;
13454 
13455 	ump = VFSTOUFS(mp);
13456 	bo = &devvp->v_bufobj;
13457 	ASSERT_BO_LOCKED(bo);
13458 
13459 	for (;;) {
13460 		if (!TRY_ACQUIRE_LOCK(&lk)) {
13461 			BO_UNLOCK(bo);
13462 			ACQUIRE_LOCK(&lk);
13463 			FREE_LOCK(&lk);
13464 			BO_LOCK(bo);
13465 			continue;
13466 		}
13467 		MNT_ILOCK(mp);
13468 		if (mp->mnt_secondary_writes != 0) {
13469 			FREE_LOCK(&lk);
13470 			BO_UNLOCK(bo);
13471 			msleep(&mp->mnt_secondary_writes,
13472 			       MNT_MTX(mp),
13473 			       (PUSER - 1) | PDROP, "secwr", 0);
13474 			BO_LOCK(bo);
13475 			continue;
13476 		}
13477 		break;
13478 	}
13479 
13480 	/*
13481 	 * Reasons for needing more work before suspend:
13482 	 * - Dirty buffers on devvp.
13483 	 * - Softdep activity occurred after start of vnode sync loop
13484 	 * - Secondary writes occurred after start of vnode sync loop
13485 	 */
13486 	error = 0;
13487 	if (bo->bo_numoutput > 0 ||
13488 	    bo->bo_dirty.bv_cnt > 0 ||
13489 	    softdep_deps != 0 ||
13490 	    ump->softdep_deps != 0 ||
13491 	    softdep_accdeps != ump->softdep_accdeps ||
13492 	    secondary_writes != 0 ||
13493 	    mp->mnt_secondary_writes != 0 ||
13494 	    secondary_accwrites != mp->mnt_secondary_accwrites)
13495 		error = EAGAIN;
13496 	FREE_LOCK(&lk);
13497 	BO_UNLOCK(bo);
13498 	return (error);
13499 }
13500 
13501 
13502 /*
13503  * Get the number of dependency structures for the file system, both
13504  * the current number and the total number allocated.  These will
13505  * later be used to detect that softdep processing has occurred.
13506  */
13507 void
13508 softdep_get_depcounts(struct mount *mp,
13509 		      int *softdep_depsp,
13510 		      int *softdep_accdepsp)
13511 {
13512 	struct ufsmount *ump;
13513 
13514 	ump = VFSTOUFS(mp);
13515 	ACQUIRE_LOCK(&lk);
13516 	*softdep_depsp = ump->softdep_deps;
13517 	*softdep_accdepsp = ump->softdep_accdeps;
13518 	FREE_LOCK(&lk);
13519 }
13520 
13521 /*
13522  * Wait for pending output on a vnode to complete.
13523  * Must be called with vnode lock and interlock locked.
13524  *
13525  * XXX: Should just be a call to bufobj_wwait().
13526  */
13527 static void
13528 drain_output(vp)
13529 	struct vnode *vp;
13530 {
13531 	struct bufobj *bo;
13532 
13533 	bo = &vp->v_bufobj;
13534 	ASSERT_VOP_LOCKED(vp, "drain_output");
13535 	ASSERT_BO_LOCKED(bo);
13536 
13537 	while (bo->bo_numoutput) {
13538 		bo->bo_flag |= BO_WWAIT;
13539 		msleep((caddr_t)&bo->bo_numoutput,
13540 		    BO_MTX(bo), PRIBIO + 1, "drainvp", 0);
13541 	}
13542 }
13543 
13544 /*
13545  * Called whenever a buffer that is being invalidated or reallocated
13546  * contains dependencies. This should only happen if an I/O error has
13547  * occurred. The routine is called with the buffer locked.
13548  */
13549 static void
13550 softdep_deallocate_dependencies(bp)
13551 	struct buf *bp;
13552 {
13553 
13554 	if ((bp->b_ioflags & BIO_ERROR) == 0)
13555 		panic("softdep_deallocate_dependencies: dangling deps");
13556 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
13557 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
13558 	else
13559 		printf("softdep_deallocate_dependencies: "
13560 		    "got error %d while accessing filesystem\n", bp->b_error);
13561 	if (bp->b_error != ENXIO)
13562 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
13563 }
13564 
13565 /*
13566  * Function to handle asynchronous write errors in the filesystem.
13567  */
13568 static void
13569 softdep_error(func, error)
13570 	char *func;
13571 	int error;
13572 {
13573 
13574 	/* XXX should do something better! */
13575 	printf("%s: got error %d while accessing filesystem\n", func, error);
13576 }
13577 
13578 #ifdef DDB
13579 
13580 static void
13581 inodedep_print(struct inodedep *inodedep, int verbose)
13582 {
13583 	db_printf("%p fs %p st %x ino %jd inoblk %jd delta %d nlink %d"
13584 	    " saveino %p\n",
13585 	    inodedep, inodedep->id_fs, inodedep->id_state,
13586 	    (intmax_t)inodedep->id_ino,
13587 	    (intmax_t)fsbtodb(inodedep->id_fs,
13588 	    ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
13589 	    inodedep->id_nlinkdelta, inodedep->id_savednlink,
13590 	    inodedep->id_savedino1);
13591 
13592 	if (verbose == 0)
13593 		return;
13594 
13595 	db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
13596 	    "mkdiradd %p\n",
13597 	    LIST_FIRST(&inodedep->id_pendinghd),
13598 	    LIST_FIRST(&inodedep->id_bufwait),
13599 	    LIST_FIRST(&inodedep->id_inowait),
13600 	    TAILQ_FIRST(&inodedep->id_inoreflst),
13601 	    inodedep->id_mkdiradd);
13602 	db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
13603 	    TAILQ_FIRST(&inodedep->id_inoupdt),
13604 	    TAILQ_FIRST(&inodedep->id_newinoupdt),
13605 	    TAILQ_FIRST(&inodedep->id_extupdt),
13606 	    TAILQ_FIRST(&inodedep->id_newextupdt));
13607 }
13608 
13609 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
13610 {
13611 
13612 	if (have_addr == 0) {
13613 		db_printf("Address required\n");
13614 		return;
13615 	}
13616 	inodedep_print((struct inodedep*)addr, 1);
13617 }
13618 
13619 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
13620 {
13621 	struct inodedep_hashhead *inodedephd;
13622 	struct inodedep *inodedep;
13623 	struct fs *fs;
13624 	int cnt;
13625 
13626 	fs = have_addr ? (struct fs *)addr : NULL;
13627 	for (cnt = 0; cnt < inodedep_hash; cnt++) {
13628 		inodedephd = &inodedep_hashtbl[cnt];
13629 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
13630 			if (fs != NULL && fs != inodedep->id_fs)
13631 				continue;
13632 			inodedep_print(inodedep, 0);
13633 		}
13634 	}
13635 }
13636 
13637 DB_SHOW_COMMAND(worklist, db_show_worklist)
13638 {
13639 	struct worklist *wk;
13640 
13641 	if (have_addr == 0) {
13642 		db_printf("Address required\n");
13643 		return;
13644 	}
13645 	wk = (struct worklist *)addr;
13646 	printf("worklist: %p type %s state 0x%X\n",
13647 	    wk, TYPENAME(wk->wk_type), wk->wk_state);
13648 }
13649 
13650 DB_SHOW_COMMAND(workhead, db_show_workhead)
13651 {
13652 	struct workhead *wkhd;
13653 	struct worklist *wk;
13654 	int i;
13655 
13656 	if (have_addr == 0) {
13657 		db_printf("Address required\n");
13658 		return;
13659 	}
13660 	wkhd = (struct workhead *)addr;
13661 	wk = LIST_FIRST(wkhd);
13662 	for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
13663 		db_printf("worklist: %p type %s state 0x%X",
13664 		    wk, TYPENAME(wk->wk_type), wk->wk_state);
13665 	if (i == 100)
13666 		db_printf("workhead overflow");
13667 	printf("\n");
13668 }
13669 
13670 
13671 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
13672 {
13673 	struct jaddref *jaddref;
13674 	struct diradd *diradd;
13675 	struct mkdir *mkdir;
13676 
13677 	LIST_FOREACH(mkdir, &mkdirlisthd, md_mkdirs) {
13678 		diradd = mkdir->md_diradd;
13679 		db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
13680 		    mkdir, mkdir->md_state, diradd, diradd->da_state);
13681 		if ((jaddref = mkdir->md_jaddref) != NULL)
13682 			db_printf(" jaddref %p jaddref state 0x%X",
13683 			    jaddref, jaddref->ja_state);
13684 		db_printf("\n");
13685 	}
13686 }
13687 
13688 #endif /* DDB */
13689 
13690 #endif /* SOFTUPDATES */
13691