xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 5596f836e7e04a272113e57b3a80f1f67c0fec7f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1998, 2000 Marshall Kirk McKusick.
5  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
6  * All rights reserved.
7  *
8  * The soft updates code is derived from the appendix of a University
9  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
10  * "Soft Updates: A Solution to the Metadata Update Problem in File
11  * Systems", CSE-TR-254-95, August 1995).
12  *
13  * Further information about soft updates can be obtained from:
14  *
15  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
16  *	1614 Oxford Street		mckusick@mckusick.com
17  *	Berkeley, CA 94709-1608		+1-510-843-9542
18  *	USA
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
35  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
36  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
42  */
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include "opt_ffs.h"
48 #include "opt_quota.h"
49 #include "opt_ddb.h"
50 
51 #include <sys/param.h>
52 #include <sys/kernel.h>
53 #include <sys/systm.h>
54 #include <sys/bio.h>
55 #include <sys/buf.h>
56 #include <sys/kdb.h>
57 #include <sys/kthread.h>
58 #include <sys/ktr.h>
59 #include <sys/limits.h>
60 #include <sys/lock.h>
61 #include <sys/malloc.h>
62 #include <sys/mount.h>
63 #include <sys/mutex.h>
64 #include <sys/namei.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/racct.h>
68 #include <sys/rwlock.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/syslog.h>
72 #include <sys/vnode.h>
73 #include <sys/conf.h>
74 
75 #include <ufs/ufs/dir.h>
76 #include <ufs/ufs/extattr.h>
77 #include <ufs/ufs/quota.h>
78 #include <ufs/ufs/inode.h>
79 #include <ufs/ufs/ufsmount.h>
80 #include <ufs/ffs/fs.h>
81 #include <ufs/ffs/softdep.h>
82 #include <ufs/ffs/ffs_extern.h>
83 #include <ufs/ufs/ufs_extern.h>
84 
85 #include <vm/vm.h>
86 #include <vm/vm_extern.h>
87 #include <vm/vm_object.h>
88 
89 #include <geom/geom.h>
90 #include <geom/geom_vfs.h>
91 
92 #include <ddb/ddb.h>
93 
94 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
95 
96 #ifndef SOFTUPDATES
97 
98 int
99 softdep_flushfiles(oldmnt, flags, td)
100 	struct mount *oldmnt;
101 	int flags;
102 	struct thread *td;
103 {
104 
105 	panic("softdep_flushfiles called");
106 }
107 
108 int
109 softdep_mount(devvp, mp, fs, cred)
110 	struct vnode *devvp;
111 	struct mount *mp;
112 	struct fs *fs;
113 	struct ucred *cred;
114 {
115 
116 	return (0);
117 }
118 
119 void
120 softdep_initialize()
121 {
122 
123 	return;
124 }
125 
126 void
127 softdep_uninitialize()
128 {
129 
130 	return;
131 }
132 
133 void
134 softdep_unmount(mp)
135 	struct mount *mp;
136 {
137 
138 	panic("softdep_unmount called");
139 }
140 
141 void
142 softdep_setup_sbupdate(ump, fs, bp)
143 	struct ufsmount *ump;
144 	struct fs *fs;
145 	struct buf *bp;
146 {
147 
148 	panic("softdep_setup_sbupdate called");
149 }
150 
151 void
152 softdep_setup_inomapdep(bp, ip, newinum, mode)
153 	struct buf *bp;
154 	struct inode *ip;
155 	ino_t newinum;
156 	int mode;
157 {
158 
159 	panic("softdep_setup_inomapdep called");
160 }
161 
162 void
163 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
164 	struct buf *bp;
165 	struct mount *mp;
166 	ufs2_daddr_t newblkno;
167 	int frags;
168 	int oldfrags;
169 {
170 
171 	panic("softdep_setup_blkmapdep called");
172 }
173 
174 void
175 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
176 	struct inode *ip;
177 	ufs_lbn_t lbn;
178 	ufs2_daddr_t newblkno;
179 	ufs2_daddr_t oldblkno;
180 	long newsize;
181 	long oldsize;
182 	struct buf *bp;
183 {
184 
185 	panic("softdep_setup_allocdirect called");
186 }
187 
188 void
189 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
190 	struct inode *ip;
191 	ufs_lbn_t lbn;
192 	ufs2_daddr_t newblkno;
193 	ufs2_daddr_t oldblkno;
194 	long newsize;
195 	long oldsize;
196 	struct buf *bp;
197 {
198 
199 	panic("softdep_setup_allocext called");
200 }
201 
202 void
203 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
204 	struct inode *ip;
205 	ufs_lbn_t lbn;
206 	struct buf *bp;
207 	int ptrno;
208 	ufs2_daddr_t newblkno;
209 	ufs2_daddr_t oldblkno;
210 	struct buf *nbp;
211 {
212 
213 	panic("softdep_setup_allocindir_page called");
214 }
215 
216 void
217 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
218 	struct buf *nbp;
219 	struct inode *ip;
220 	struct buf *bp;
221 	int ptrno;
222 	ufs2_daddr_t newblkno;
223 {
224 
225 	panic("softdep_setup_allocindir_meta called");
226 }
227 
228 void
229 softdep_journal_freeblocks(ip, cred, length, flags)
230 	struct inode *ip;
231 	struct ucred *cred;
232 	off_t length;
233 	int flags;
234 {
235 
236 	panic("softdep_journal_freeblocks called");
237 }
238 
239 void
240 softdep_journal_fsync(ip)
241 	struct inode *ip;
242 {
243 
244 	panic("softdep_journal_fsync called");
245 }
246 
247 void
248 softdep_setup_freeblocks(ip, length, flags)
249 	struct inode *ip;
250 	off_t length;
251 	int flags;
252 {
253 
254 	panic("softdep_setup_freeblocks called");
255 }
256 
257 void
258 softdep_freefile(pvp, ino, mode)
259 		struct vnode *pvp;
260 		ino_t ino;
261 		int mode;
262 {
263 
264 	panic("softdep_freefile called");
265 }
266 
267 int
268 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
269 	struct buf *bp;
270 	struct inode *dp;
271 	off_t diroffset;
272 	ino_t newinum;
273 	struct buf *newdirbp;
274 	int isnewblk;
275 {
276 
277 	panic("softdep_setup_directory_add called");
278 }
279 
280 void
281 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
282 	struct buf *bp;
283 	struct inode *dp;
284 	caddr_t base;
285 	caddr_t oldloc;
286 	caddr_t newloc;
287 	int entrysize;
288 {
289 
290 	panic("softdep_change_directoryentry_offset called");
291 }
292 
293 void
294 softdep_setup_remove(bp, dp, ip, isrmdir)
295 	struct buf *bp;
296 	struct inode *dp;
297 	struct inode *ip;
298 	int isrmdir;
299 {
300 
301 	panic("softdep_setup_remove called");
302 }
303 
304 void
305 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
306 	struct buf *bp;
307 	struct inode *dp;
308 	struct inode *ip;
309 	ino_t newinum;
310 	int isrmdir;
311 {
312 
313 	panic("softdep_setup_directory_change called");
314 }
315 
316 void
317 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
318 	struct mount *mp;
319 	struct buf *bp;
320 	ufs2_daddr_t blkno;
321 	int frags;
322 	struct workhead *wkhd;
323 {
324 
325 	panic("%s called", __FUNCTION__);
326 }
327 
328 void
329 softdep_setup_inofree(mp, bp, ino, wkhd)
330 	struct mount *mp;
331 	struct buf *bp;
332 	ino_t ino;
333 	struct workhead *wkhd;
334 {
335 
336 	panic("%s called", __FUNCTION__);
337 }
338 
339 void
340 softdep_setup_unlink(dp, ip)
341 	struct inode *dp;
342 	struct inode *ip;
343 {
344 
345 	panic("%s called", __FUNCTION__);
346 }
347 
348 void
349 softdep_setup_link(dp, ip)
350 	struct inode *dp;
351 	struct inode *ip;
352 {
353 
354 	panic("%s called", __FUNCTION__);
355 }
356 
357 void
358 softdep_revert_link(dp, ip)
359 	struct inode *dp;
360 	struct inode *ip;
361 {
362 
363 	panic("%s called", __FUNCTION__);
364 }
365 
366 void
367 softdep_setup_rmdir(dp, ip)
368 	struct inode *dp;
369 	struct inode *ip;
370 {
371 
372 	panic("%s called", __FUNCTION__);
373 }
374 
375 void
376 softdep_revert_rmdir(dp, ip)
377 	struct inode *dp;
378 	struct inode *ip;
379 {
380 
381 	panic("%s called", __FUNCTION__);
382 }
383 
384 void
385 softdep_setup_create(dp, ip)
386 	struct inode *dp;
387 	struct inode *ip;
388 {
389 
390 	panic("%s called", __FUNCTION__);
391 }
392 
393 void
394 softdep_revert_create(dp, ip)
395 	struct inode *dp;
396 	struct inode *ip;
397 {
398 
399 	panic("%s called", __FUNCTION__);
400 }
401 
402 void
403 softdep_setup_mkdir(dp, ip)
404 	struct inode *dp;
405 	struct inode *ip;
406 {
407 
408 	panic("%s called", __FUNCTION__);
409 }
410 
411 void
412 softdep_revert_mkdir(dp, ip)
413 	struct inode *dp;
414 	struct inode *ip;
415 {
416 
417 	panic("%s called", __FUNCTION__);
418 }
419 
420 void
421 softdep_setup_dotdot_link(dp, ip)
422 	struct inode *dp;
423 	struct inode *ip;
424 {
425 
426 	panic("%s called", __FUNCTION__);
427 }
428 
429 int
430 softdep_prealloc(vp, waitok)
431 	struct vnode *vp;
432 	int waitok;
433 {
434 
435 	panic("%s called", __FUNCTION__);
436 }
437 
438 int
439 softdep_journal_lookup(mp, vpp)
440 	struct mount *mp;
441 	struct vnode **vpp;
442 {
443 
444 	return (ENOENT);
445 }
446 
447 void
448 softdep_change_linkcnt(ip)
449 	struct inode *ip;
450 {
451 
452 	panic("softdep_change_linkcnt called");
453 }
454 
455 void
456 softdep_load_inodeblock(ip)
457 	struct inode *ip;
458 {
459 
460 	panic("softdep_load_inodeblock called");
461 }
462 
463 void
464 softdep_update_inodeblock(ip, bp, waitfor)
465 	struct inode *ip;
466 	struct buf *bp;
467 	int waitfor;
468 {
469 
470 	panic("softdep_update_inodeblock called");
471 }
472 
473 int
474 softdep_fsync(vp)
475 	struct vnode *vp;	/* the "in_core" copy of the inode */
476 {
477 
478 	return (0);
479 }
480 
481 void
482 softdep_fsync_mountdev(vp)
483 	struct vnode *vp;
484 {
485 
486 	return;
487 }
488 
489 int
490 softdep_flushworklist(oldmnt, countp, td)
491 	struct mount *oldmnt;
492 	int *countp;
493 	struct thread *td;
494 {
495 
496 	*countp = 0;
497 	return (0);
498 }
499 
500 int
501 softdep_sync_metadata(struct vnode *vp)
502 {
503 
504 	panic("softdep_sync_metadata called");
505 }
506 
507 int
508 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
509 {
510 
511 	panic("softdep_sync_buf called");
512 }
513 
514 int
515 softdep_slowdown(vp)
516 	struct vnode *vp;
517 {
518 
519 	panic("softdep_slowdown called");
520 }
521 
522 int
523 softdep_request_cleanup(fs, vp, cred, resource)
524 	struct fs *fs;
525 	struct vnode *vp;
526 	struct ucred *cred;
527 	int resource;
528 {
529 
530 	return (0);
531 }
532 
533 int
534 softdep_check_suspend(struct mount *mp,
535 		      struct vnode *devvp,
536 		      int softdep_depcnt,
537 		      int softdep_accdepcnt,
538 		      int secondary_writes,
539 		      int secondary_accwrites)
540 {
541 	struct bufobj *bo;
542 	int error;
543 
544 	(void) softdep_depcnt,
545 	(void) softdep_accdepcnt;
546 
547 	bo = &devvp->v_bufobj;
548 	ASSERT_BO_WLOCKED(bo);
549 
550 	MNT_ILOCK(mp);
551 	while (mp->mnt_secondary_writes != 0) {
552 		BO_UNLOCK(bo);
553 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
554 		    (PUSER - 1) | PDROP, "secwr", 0);
555 		BO_LOCK(bo);
556 		MNT_ILOCK(mp);
557 	}
558 
559 	/*
560 	 * Reasons for needing more work before suspend:
561 	 * - Dirty buffers on devvp.
562 	 * - Secondary writes occurred after start of vnode sync loop
563 	 */
564 	error = 0;
565 	if (bo->bo_numoutput > 0 ||
566 	    bo->bo_dirty.bv_cnt > 0 ||
567 	    secondary_writes != 0 ||
568 	    mp->mnt_secondary_writes != 0 ||
569 	    secondary_accwrites != mp->mnt_secondary_accwrites)
570 		error = EAGAIN;
571 	BO_UNLOCK(bo);
572 	return (error);
573 }
574 
575 void
576 softdep_get_depcounts(struct mount *mp,
577 		      int *softdepactivep,
578 		      int *softdepactiveaccp)
579 {
580 	(void) mp;
581 	*softdepactivep = 0;
582 	*softdepactiveaccp = 0;
583 }
584 
585 void
586 softdep_buf_append(bp, wkhd)
587 	struct buf *bp;
588 	struct workhead *wkhd;
589 {
590 
591 	panic("softdep_buf_appendwork called");
592 }
593 
594 void
595 softdep_inode_append(ip, cred, wkhd)
596 	struct inode *ip;
597 	struct ucred *cred;
598 	struct workhead *wkhd;
599 {
600 
601 	panic("softdep_inode_appendwork called");
602 }
603 
604 void
605 softdep_freework(wkhd)
606 	struct workhead *wkhd;
607 {
608 
609 	panic("softdep_freework called");
610 }
611 
612 int
613 softdep_prerename(fdvp, fvp, tdvp, tvp)
614 	struct vnode *fdvp;
615 	struct vnode *fvp;
616 	struct vnode *tdvp;
617 	struct vnode *tvp;
618 {
619 
620 	panic("softdep_prerename called");
621 }
622 
623 int
624 softdep_prelink(dvp, vp, will_direnter)
625 	struct vnode *dvp;
626 	struct vnode *vp;
627 	int will_direnter;
628 {
629 
630 	panic("softdep_prelink called");
631 }
632 
633 #else
634 
635 FEATURE(softupdates, "FFS soft-updates support");
636 
637 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
638     "soft updates stats");
639 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total,
640     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
641     "total dependencies allocated");
642 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse,
643     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
644     "high use dependencies allocated");
645 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current,
646     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
647     "current dependencies allocated");
648 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write,
649     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
650     "current dependencies written");
651 
652 unsigned long dep_current[D_LAST + 1];
653 unsigned long dep_highuse[D_LAST + 1];
654 unsigned long dep_total[D_LAST + 1];
655 unsigned long dep_write[D_LAST + 1];
656 
657 #define	SOFTDEP_TYPE(type, str, long)					\
658     static MALLOC_DEFINE(M_ ## type, #str, long);			\
659     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
660 	&dep_total[D_ ## type], 0, "");					\
661     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
662 	&dep_current[D_ ## type], 0, "");				\
663     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
664 	&dep_highuse[D_ ## type], 0, "");				\
665     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
666 	&dep_write[D_ ## type], 0, "");
667 
668 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
669 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
670 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
671     "Block or frag allocated from cyl group map");
672 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
673 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
674 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
675 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
676 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
677 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
678 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
679 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
680 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
681 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
682 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
683 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
684 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
685 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
686 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
687 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
688 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
689 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
690 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
691 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
692 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
693 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
694 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
695 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
696 
697 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
698 
699 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
700 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
701 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
702 
703 #define M_SOFTDEP_FLAGS	(M_WAITOK)
704 
705 /*
706  * translate from workitem type to memory type
707  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
708  */
709 static struct malloc_type *memtype[] = {
710 	NULL,
711 	M_PAGEDEP,
712 	M_INODEDEP,
713 	M_BMSAFEMAP,
714 	M_NEWBLK,
715 	M_ALLOCDIRECT,
716 	M_INDIRDEP,
717 	M_ALLOCINDIR,
718 	M_FREEFRAG,
719 	M_FREEBLKS,
720 	M_FREEFILE,
721 	M_DIRADD,
722 	M_MKDIR,
723 	M_DIRREM,
724 	M_NEWDIRBLK,
725 	M_FREEWORK,
726 	M_FREEDEP,
727 	M_JADDREF,
728 	M_JREMREF,
729 	M_JMVREF,
730 	M_JNEWBLK,
731 	M_JFREEBLK,
732 	M_JFREEFRAG,
733 	M_JSEG,
734 	M_JSEGDEP,
735 	M_SBDEP,
736 	M_JTRUNC,
737 	M_JFSYNC,
738 	M_SENTINEL
739 };
740 
741 #define DtoM(type) (memtype[type])
742 
743 /*
744  * Names of malloc types.
745  */
746 #define TYPENAME(type)  \
747 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
748 	memtype[type]->ks_shortdesc : "???")
749 /*
750  * End system adaptation definitions.
751  */
752 
753 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
754 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
755 
756 /*
757  * Internal function prototypes.
758  */
759 static	void check_clear_deps(struct mount *);
760 static	void softdep_error(char *, int);
761 static	int softdep_process_worklist(struct mount *, int);
762 static	int softdep_waitidle(struct mount *, int);
763 static	void drain_output(struct vnode *);
764 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
765 static	int check_inodedep_free(struct inodedep *);
766 static	void clear_remove(struct mount *);
767 static	void clear_inodedeps(struct mount *);
768 static	void unlinked_inodedep(struct mount *, struct inodedep *);
769 static	void clear_unlinked_inodedep(struct inodedep *);
770 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
771 static	int flush_pagedep_deps(struct vnode *, struct mount *,
772 	    struct diraddhd *, struct buf *);
773 static	int free_pagedep(struct pagedep *);
774 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
775 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
776 static	int flush_deplist(struct allocdirectlst *, int, int *);
777 static	int sync_cgs(struct mount *, int);
778 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
779 static	int handle_written_sbdep(struct sbdep *, struct buf *);
780 static	void initiate_write_sbdep(struct sbdep *);
781 static	void diradd_inode_written(struct diradd *, struct inodedep *);
782 static	int handle_written_indirdep(struct indirdep *, struct buf *,
783 	    struct buf**, int);
784 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
785 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
786 	    uint8_t *);
787 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
788 static	void handle_written_jaddref(struct jaddref *);
789 static	void handle_written_jremref(struct jremref *);
790 static	void handle_written_jseg(struct jseg *, struct buf *);
791 static	void handle_written_jnewblk(struct jnewblk *);
792 static	void handle_written_jblkdep(struct jblkdep *);
793 static	void handle_written_jfreefrag(struct jfreefrag *);
794 static	void complete_jseg(struct jseg *);
795 static	void complete_jsegs(struct jseg *);
796 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
797 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
798 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
799 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
800 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
801 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
802 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
803 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
804 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
805 static	inline void inoref_write(struct inoref *, struct jseg *,
806 	    struct jrefrec *);
807 static	void handle_allocdirect_partdone(struct allocdirect *,
808 	    struct workhead *);
809 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
810 	    struct workhead *);
811 static	void indirdep_complete(struct indirdep *);
812 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
813 static	void indirblk_insert(struct freework *);
814 static	void indirblk_remove(struct freework *);
815 static	void handle_allocindir_partdone(struct allocindir *);
816 static	void initiate_write_filepage(struct pagedep *, struct buf *);
817 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
818 static	void handle_written_mkdir(struct mkdir *, int);
819 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
820 	    uint8_t *);
821 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
822 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
823 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
824 static	void handle_workitem_freefile(struct freefile *);
825 static	int handle_workitem_remove(struct dirrem *, int);
826 static	struct dirrem *newdirrem(struct buf *, struct inode *,
827 	    struct inode *, int, struct dirrem **);
828 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
829 	    struct buf *);
830 static	void cancel_indirdep(struct indirdep *, struct buf *,
831 	    struct freeblks *);
832 static	void free_indirdep(struct indirdep *);
833 static	void free_diradd(struct diradd *, struct workhead *);
834 static	void merge_diradd(struct inodedep *, struct diradd *);
835 static	void complete_diradd(struct diradd *);
836 static	struct diradd *diradd_lookup(struct pagedep *, int);
837 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
838 	    struct jremref *);
839 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
840 	    struct jremref *);
841 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
842 	    struct jremref *, struct jremref *);
843 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
844 	    struct jremref *);
845 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
846 	    struct freeblks *, int);
847 static	int setup_trunc_indir(struct freeblks *, struct inode *,
848 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
849 static	void complete_trunc_indir(struct freework *);
850 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
851 	    int);
852 static	void complete_mkdir(struct mkdir *);
853 static	void free_newdirblk(struct newdirblk *);
854 static	void free_jremref(struct jremref *);
855 static	void free_jaddref(struct jaddref *);
856 static	void free_jsegdep(struct jsegdep *);
857 static	void free_jsegs(struct jblocks *);
858 static	void rele_jseg(struct jseg *);
859 static	void free_jseg(struct jseg *, struct jblocks *);
860 static	void free_jnewblk(struct jnewblk *);
861 static	void free_jblkdep(struct jblkdep *);
862 static	void free_jfreefrag(struct jfreefrag *);
863 static	void free_freedep(struct freedep *);
864 static	void journal_jremref(struct dirrem *, struct jremref *,
865 	    struct inodedep *);
866 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
867 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
868 	    struct workhead *);
869 static	void cancel_jfreefrag(struct jfreefrag *);
870 static	inline void setup_freedirect(struct freeblks *, struct inode *,
871 	    int, int);
872 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
873 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
874 	    ufs_lbn_t, int);
875 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
876 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
877 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
878 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
879 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
880 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
881 	    int, int);
882 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
883 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
884 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
885 static	void newblk_freefrag(struct newblk*);
886 static	void free_newblk(struct newblk *);
887 static	void cancel_allocdirect(struct allocdirectlst *,
888 	    struct allocdirect *, struct freeblks *);
889 static	int check_inode_unwritten(struct inodedep *);
890 static	int free_inodedep(struct inodedep *);
891 static	void freework_freeblock(struct freework *, u_long);
892 static	void freework_enqueue(struct freework *);
893 static	int handle_workitem_freeblocks(struct freeblks *, int);
894 static	int handle_complete_freeblocks(struct freeblks *, int);
895 static	void handle_workitem_indirblk(struct freework *);
896 static	void handle_written_freework(struct freework *);
897 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
898 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
899 	    struct workhead *);
900 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
901 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
902 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
903 	    ufs2_daddr_t, ufs_lbn_t);
904 static	void handle_workitem_freefrag(struct freefrag *);
905 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
906 	    ufs_lbn_t, u_long);
907 static	void allocdirect_merge(struct allocdirectlst *,
908 	    struct allocdirect *, struct allocdirect *);
909 static	struct freefrag *allocindir_merge(struct allocindir *,
910 	    struct allocindir *);
911 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
912 	    struct bmsafemap **);
913 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
914 	    int cg, struct bmsafemap *);
915 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
916 	    struct newblk **);
917 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
918 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
919 	    struct inodedep **);
920 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
921 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
922 	    int, struct pagedep **);
923 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
924 	    struct pagedep **);
925 static	void pause_timer(void *);
926 static	int request_cleanup(struct mount *, int);
927 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
928 static	void schedule_cleanup(struct mount *);
929 static void softdep_ast_cleanup_proc(struct thread *);
930 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
931 static	int process_worklist_item(struct mount *, int, int);
932 static	void process_removes(struct vnode *);
933 static	void process_truncates(struct vnode *);
934 static	void jwork_move(struct workhead *, struct workhead *);
935 static	void jwork_insert(struct workhead *, struct jsegdep *);
936 static	void add_to_worklist(struct worklist *, int);
937 static	void wake_worklist(struct worklist *);
938 static	void wait_worklist(struct worklist *, char *);
939 static	void remove_from_worklist(struct worklist *);
940 static	void softdep_flush(void *);
941 static	void softdep_flushjournal(struct mount *);
942 static	int softdep_speedup(struct ufsmount *);
943 static	void worklist_speedup(struct mount *);
944 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
945 static	void journal_unmount(struct ufsmount *);
946 static	int journal_space(struct ufsmount *, int);
947 static	void journal_suspend(struct ufsmount *);
948 static	int journal_unsuspend(struct ufsmount *ump);
949 static	void add_to_journal(struct worklist *);
950 static	void remove_from_journal(struct worklist *);
951 static	bool softdep_excess_items(struct ufsmount *, int);
952 static	void softdep_process_journal(struct mount *, struct worklist *, int);
953 static	struct jremref *newjremref(struct dirrem *, struct inode *,
954 	    struct inode *ip, off_t, nlink_t);
955 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
956 	    uint16_t);
957 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
958 	    uint16_t);
959 static	inline struct jsegdep *inoref_jseg(struct inoref *);
960 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
961 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
962 	    ufs2_daddr_t, int);
963 static	void adjust_newfreework(struct freeblks *, int);
964 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
965 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
966 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
967 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
968 	    ufs2_daddr_t, long, ufs_lbn_t);
969 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
970 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
971 static	int jwait(struct worklist *, int);
972 static	struct inodedep *inodedep_lookup_ip(struct inode *);
973 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
974 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
975 static	void handle_jwork(struct workhead *);
976 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
977 	    struct mkdir **);
978 static	struct jblocks *jblocks_create(void);
979 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
980 static	void jblocks_free(struct jblocks *, struct mount *, int);
981 static	void jblocks_destroy(struct jblocks *);
982 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
983 
984 /*
985  * Exported softdep operations.
986  */
987 static	void softdep_disk_io_initiation(struct buf *);
988 static	void softdep_disk_write_complete(struct buf *);
989 static	void softdep_deallocate_dependencies(struct buf *);
990 static	int softdep_count_dependencies(struct buf *bp, int);
991 
992 /*
993  * Global lock over all of soft updates.
994  */
995 static struct mtx lk;
996 MTX_SYSINIT(softdep_lock, &lk, "global softdep", MTX_DEF);
997 
998 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
999 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
1000 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
1001 
1002 /*
1003  * Per-filesystem soft-updates locking.
1004  */
1005 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
1006 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
1007 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
1008 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
1009 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
1010 				    RA_WLOCKED)
1011 
1012 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
1013 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
1014 
1015 /*
1016  * Worklist queue management.
1017  * These routines require that the lock be held.
1018  */
1019 #ifndef /* NOT */ INVARIANTS
1020 #define WORKLIST_INSERT(head, item) do {	\
1021 	(item)->wk_state |= ONWORKLIST;		\
1022 	LIST_INSERT_HEAD(head, item, wk_list);	\
1023 } while (0)
1024 #define WORKLIST_REMOVE(item) do {		\
1025 	(item)->wk_state &= ~ONWORKLIST;	\
1026 	LIST_REMOVE(item, wk_list);		\
1027 } while (0)
1028 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1029 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1030 
1031 #else /* INVARIANTS */
1032 static	void worklist_insert(struct workhead *, struct worklist *, int,
1033 	const char *, int);
1034 static	void worklist_remove(struct worklist *, int, const char *, int);
1035 
1036 #define WORKLIST_INSERT(head, item) \
1037 	worklist_insert(head, item, 1, __func__, __LINE__)
1038 #define WORKLIST_INSERT_UNLOCKED(head, item)\
1039 	worklist_insert(head, item, 0, __func__, __LINE__)
1040 #define WORKLIST_REMOVE(item)\
1041 	worklist_remove(item, 1, __func__, __LINE__)
1042 #define WORKLIST_REMOVE_UNLOCKED(item)\
1043 	worklist_remove(item, 0, __func__, __LINE__)
1044 
1045 static void
1046 worklist_insert(head, item, locked, func, line)
1047 	struct workhead *head;
1048 	struct worklist *item;
1049 	int locked;
1050 	const char *func;
1051 	int line;
1052 {
1053 
1054 	if (locked)
1055 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1056 	if (item->wk_state & ONWORKLIST)
1057 		panic("worklist_insert: %p %s(0x%X) already on list, "
1058 		    "added in function %s at line %d",
1059 		    item, TYPENAME(item->wk_type), item->wk_state,
1060 		    item->wk_func, item->wk_line);
1061 	item->wk_state |= ONWORKLIST;
1062 	item->wk_func = func;
1063 	item->wk_line = line;
1064 	LIST_INSERT_HEAD(head, item, wk_list);
1065 }
1066 
1067 static void
1068 worklist_remove(item, locked, func, line)
1069 	struct worklist *item;
1070 	int locked;
1071 	const char *func;
1072 	int line;
1073 {
1074 
1075 	if (locked)
1076 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1077 	if ((item->wk_state & ONWORKLIST) == 0)
1078 		panic("worklist_remove: %p %s(0x%X) not on list, "
1079 		    "removed in function %s at line %d",
1080 		    item, TYPENAME(item->wk_type), item->wk_state,
1081 		    item->wk_func, item->wk_line);
1082 	item->wk_state &= ~ONWORKLIST;
1083 	item->wk_func = func;
1084 	item->wk_line = line;
1085 	LIST_REMOVE(item, wk_list);
1086 }
1087 #endif /* INVARIANTS */
1088 
1089 /*
1090  * Merge two jsegdeps keeping only the oldest one as newer references
1091  * can't be discarded until after older references.
1092  */
1093 static inline struct jsegdep *
1094 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1095 {
1096 	struct jsegdep *swp;
1097 
1098 	if (two == NULL)
1099 		return (one);
1100 
1101 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1102 		swp = one;
1103 		one = two;
1104 		two = swp;
1105 	}
1106 	WORKLIST_REMOVE(&two->jd_list);
1107 	free_jsegdep(two);
1108 
1109 	return (one);
1110 }
1111 
1112 /*
1113  * If two freedeps are compatible free one to reduce list size.
1114  */
1115 static inline struct freedep *
1116 freedep_merge(struct freedep *one, struct freedep *two)
1117 {
1118 	if (two == NULL)
1119 		return (one);
1120 
1121 	if (one->fd_freework == two->fd_freework) {
1122 		WORKLIST_REMOVE(&two->fd_list);
1123 		free_freedep(two);
1124 	}
1125 	return (one);
1126 }
1127 
1128 /*
1129  * Move journal work from one list to another.  Duplicate freedeps and
1130  * jsegdeps are coalesced to keep the lists as small as possible.
1131  */
1132 static void
1133 jwork_move(dst, src)
1134 	struct workhead *dst;
1135 	struct workhead *src;
1136 {
1137 	struct freedep *freedep;
1138 	struct jsegdep *jsegdep;
1139 	struct worklist *wkn;
1140 	struct worklist *wk;
1141 
1142 	KASSERT(dst != src,
1143 	    ("jwork_move: dst == src"));
1144 	freedep = NULL;
1145 	jsegdep = NULL;
1146 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1147 		if (wk->wk_type == D_JSEGDEP)
1148 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1149 		else if (wk->wk_type == D_FREEDEP)
1150 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1151 	}
1152 
1153 	while ((wk = LIST_FIRST(src)) != NULL) {
1154 		WORKLIST_REMOVE(wk);
1155 		WORKLIST_INSERT(dst, wk);
1156 		if (wk->wk_type == D_JSEGDEP) {
1157 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1158 			continue;
1159 		}
1160 		if (wk->wk_type == D_FREEDEP)
1161 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1162 	}
1163 }
1164 
1165 static void
1166 jwork_insert(dst, jsegdep)
1167 	struct workhead *dst;
1168 	struct jsegdep *jsegdep;
1169 {
1170 	struct jsegdep *jsegdepn;
1171 	struct worklist *wk;
1172 
1173 	LIST_FOREACH(wk, dst, wk_list)
1174 		if (wk->wk_type == D_JSEGDEP)
1175 			break;
1176 	if (wk == NULL) {
1177 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1178 		return;
1179 	}
1180 	jsegdepn = WK_JSEGDEP(wk);
1181 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1182 		WORKLIST_REMOVE(wk);
1183 		free_jsegdep(jsegdepn);
1184 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1185 	} else
1186 		free_jsegdep(jsegdep);
1187 }
1188 
1189 /*
1190  * Routines for tracking and managing workitems.
1191  */
1192 static	void workitem_free(struct worklist *, int);
1193 static	void workitem_alloc(struct worklist *, int, struct mount *);
1194 static	void workitem_reassign(struct worklist *, int);
1195 
1196 #define	WORKITEM_FREE(item, type) \
1197 	workitem_free((struct worklist *)(item), (type))
1198 #define	WORKITEM_REASSIGN(item, type) \
1199 	workitem_reassign((struct worklist *)(item), (type))
1200 
1201 static void
1202 workitem_free(item, type)
1203 	struct worklist *item;
1204 	int type;
1205 {
1206 	struct ufsmount *ump;
1207 
1208 #ifdef INVARIANTS
1209 	if (item->wk_state & ONWORKLIST)
1210 		panic("workitem_free: %s(0x%X) still on list, "
1211 		    "added in function %s at line %d",
1212 		    TYPENAME(item->wk_type), item->wk_state,
1213 		    item->wk_func, item->wk_line);
1214 	if (item->wk_type != type && type != D_NEWBLK)
1215 		panic("workitem_free: type mismatch %s != %s",
1216 		    TYPENAME(item->wk_type), TYPENAME(type));
1217 #endif
1218 	if (item->wk_state & IOWAITING)
1219 		wakeup(item);
1220 	ump = VFSTOUFS(item->wk_mp);
1221 	LOCK_OWNED(ump);
1222 	KASSERT(ump->softdep_deps > 0,
1223 	    ("workitem_free: %s: softdep_deps going negative",
1224 	    ump->um_fs->fs_fsmnt));
1225 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1226 		wakeup(&ump->softdep_deps);
1227 	KASSERT(dep_current[item->wk_type] > 0,
1228 	    ("workitem_free: %s: dep_current[%s] going negative",
1229 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1230 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1231 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1232 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1233 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1234 	ump->softdep_curdeps[item->wk_type] -= 1;
1235 #ifdef INVARIANTS
1236 	LIST_REMOVE(item, wk_all);
1237 #endif
1238 	free(item, DtoM(type));
1239 }
1240 
1241 static void
1242 workitem_alloc(item, type, mp)
1243 	struct worklist *item;
1244 	int type;
1245 	struct mount *mp;
1246 {
1247 	struct ufsmount *ump;
1248 
1249 	item->wk_type = type;
1250 	item->wk_mp = mp;
1251 	item->wk_state = 0;
1252 
1253 	ump = VFSTOUFS(mp);
1254 	ACQUIRE_GBLLOCK(&lk);
1255 	dep_current[type]++;
1256 	if (dep_current[type] > dep_highuse[type])
1257 		dep_highuse[type] = dep_current[type];
1258 	dep_total[type]++;
1259 	FREE_GBLLOCK(&lk);
1260 	ACQUIRE_LOCK(ump);
1261 	ump->softdep_curdeps[type] += 1;
1262 	ump->softdep_deps++;
1263 	ump->softdep_accdeps++;
1264 #ifdef INVARIANTS
1265 	LIST_INSERT_HEAD(&ump->softdep_alldeps[type], item, wk_all);
1266 #endif
1267 	FREE_LOCK(ump);
1268 }
1269 
1270 static void
1271 workitem_reassign(item, newtype)
1272 	struct worklist *item;
1273 	int newtype;
1274 {
1275 	struct ufsmount *ump;
1276 
1277 	ump = VFSTOUFS(item->wk_mp);
1278 	LOCK_OWNED(ump);
1279 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1280 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1281 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1282 	ump->softdep_curdeps[item->wk_type] -= 1;
1283 	ump->softdep_curdeps[newtype] += 1;
1284 	KASSERT(dep_current[item->wk_type] > 0,
1285 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1286 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1287 	ACQUIRE_GBLLOCK(&lk);
1288 	dep_current[newtype]++;
1289 	dep_current[item->wk_type]--;
1290 	if (dep_current[newtype] > dep_highuse[newtype])
1291 		dep_highuse[newtype] = dep_current[newtype];
1292 	dep_total[newtype]++;
1293 	FREE_GBLLOCK(&lk);
1294 	item->wk_type = newtype;
1295 }
1296 
1297 /*
1298  * Workitem queue management
1299  */
1300 static int max_softdeps;	/* maximum number of structs before slowdown */
1301 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1302 static int proc_waiting;	/* tracks whether we have a timeout posted */
1303 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1304 static struct callout softdep_callout;
1305 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1306 static int req_clear_remove;	/* syncer process flush some freeblks */
1307 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1308 
1309 /*
1310  * runtime statistics
1311  */
1312 static int stat_flush_threads;	/* number of softdep flushing threads */
1313 static int stat_worklist_push;	/* number of worklist cleanups */
1314 static int stat_blk_limit_push;	/* number of times block limit neared */
1315 static int stat_ino_limit_push;	/* number of times inode limit neared */
1316 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1317 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1318 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1319 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1320 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1321 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1322 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1323 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1324 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1325 static int stat_journal_min;	/* Times hit journal min threshold */
1326 static int stat_journal_low;	/* Times hit journal low threshold */
1327 static int stat_journal_wait;	/* Times blocked in jwait(). */
1328 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1329 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1330 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1331 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1332 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1333 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1334 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1335 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1336 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1337 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1338 
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1340     &max_softdeps, 0, "");
1341 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1342     &tickdelay, 0, "");
1343 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1344     &stat_flush_threads, 0, "");
1345 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1346     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1347 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1348     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1349 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1350     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1351 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1352     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1353 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1354     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1355 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1356     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1357 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1358     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1359 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1360     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1361 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1362     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1363 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1364     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1365 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1366     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1367 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1368     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1369 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1370     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1371 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1372     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1373 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1374     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1375 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1376     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1377 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1378     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1379 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1380     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1381 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1382     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1383 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1384     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1385 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1386     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1387 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1388     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1389 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1390     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1391 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1392     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1393 
1394 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1395     &softdep_flushcache, 0, "");
1396 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1397     &stat_emptyjblocks, 0, "");
1398 
1399 SYSCTL_DECL(_vfs_ffs);
1400 
1401 /* Whether to recompute the summary at mount time */
1402 static int compute_summary_at_mount = 0;
1403 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1404 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1405 static int print_threads = 0;
1406 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1407     &print_threads, 0, "Notify flusher thread start/stop");
1408 
1409 /* List of all filesystems mounted with soft updates */
1410 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1411 
1412 /*
1413  * This function fetches inode inum on mount point mp.  We already
1414  * hold a locked vnode vp, and might have a locked buffer bp belonging
1415  * to vp.
1416 
1417  * We must not block on acquiring the new inode lock as we will get
1418  * into a lock-order reversal with the buffer lock and possibly get a
1419  * deadlock.  Thus if we cannot instantiate the requested vnode
1420  * without sleeping on its lock, we must unlock the vnode and the
1421  * buffer before doing a blocking on the vnode lock.  We return
1422  * ERELOOKUP if we have had to unlock either the vnode or the buffer so
1423  * that the caller can reassess its state.
1424  *
1425  * Top-level VFS code (for syscalls and other consumers, e.g. callers
1426  * of VOP_FSYNC() in syncer) check for ERELOOKUP and restart at safe
1427  * point.
1428  *
1429  * Since callers expect to operate on fully constructed vnode, we also
1430  * recheck v_data after relock, and return ENOENT if NULL.
1431  *
1432  * If unlocking bp, we must unroll dequeueing its unfinished
1433  * dependencies, and clear scan flag, before unlocking.  If unlocking
1434  * vp while it is under deactivation, we re-queue deactivation.
1435  */
1436 static int
1437 get_parent_vp(struct vnode *vp, struct mount *mp, ino_t inum, struct buf *bp,
1438     struct diraddhd *diraddhdp, struct diraddhd *unfinishedp,
1439     struct vnode **rvp)
1440 {
1441 	struct vnode *pvp;
1442 	struct diradd *dap;
1443 	int error;
1444 	bool bplocked;
1445 
1446 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked");
1447 	for (bplocked = true, pvp = NULL;;) {
1448 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE | LK_NOWAIT, &pvp,
1449 		    FFSV_FORCEINSMQ);
1450 		if (error == 0) {
1451 			/*
1452 			 * Since we could have unlocked vp, the inode
1453 			 * number could no longer indicate a
1454 			 * constructed node.  In this case, we must
1455 			 * restart the syscall.
1456 			 */
1457 			if (VTOI(pvp)->i_mode == 0 || !bplocked) {
1458 				if (VTOI(pvp)->i_mode == 0)
1459 					vgone(pvp);
1460 				vput(pvp);
1461 				error = ERELOOKUP;
1462 				goto out;
1463 			}
1464 
1465 			error = 0;
1466 			goto out1;
1467 		}
1468 		if (bp != NULL && bplocked) {
1469 			/*
1470 			 * Requeue unfinished dependencies before
1471 			 * unlocking buffer, which could make
1472 			 * diraddhdp invalid.
1473 			 */
1474 			ACQUIRE_LOCK(VFSTOUFS(mp));
1475 			while ((dap = LIST_FIRST(unfinishedp)) != NULL) {
1476 				LIST_REMOVE(dap, da_pdlist);
1477 				LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
1478 			}
1479 			FREE_LOCK(VFSTOUFS(mp));
1480 			bp->b_vflags &= ~BV_SCANNED;
1481 			BUF_NOREC(bp);
1482 			BUF_UNLOCK(bp);
1483 			bplocked = false;
1484 		}
1485 
1486 		/*
1487 		 * Do not drop vnode lock while inactivating.  This
1488 		 * would result in leaks of the VI flags and
1489 		 * reclaiming of non-truncated vnode.  Instead,
1490 		 * re-schedule inactivation hoping that we would be
1491 		 * able to sync inode later.
1492 		 */
1493 		if ((vp->v_iflag & VI_DOINGINACT) != 0) {
1494 			VI_LOCK(vp);
1495 			vp->v_iflag |= VI_OWEINACT;
1496 			VI_UNLOCK(vp);
1497 			return (ERELOOKUP);
1498 		}
1499 
1500 		VOP_UNLOCK(vp);
1501 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &pvp,
1502 		    FFSV_FORCEINSMQ);
1503 		if (error != 0) {
1504 			MPASS(error != ERELOOKUP);
1505 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1506 			break;
1507 		}
1508 		if (VTOI(pvp)->i_mode == 0) {
1509 			vgone(pvp);
1510 			vput(pvp);
1511 			pvp = NULL;
1512 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1513 			error = ERELOOKUP;
1514 			break;
1515 		}
1516 		error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
1517 		if (error == 0)
1518 			break;
1519 		vput(pvp);
1520 		pvp = NULL;
1521 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1522 		if (vp->v_data == NULL) {
1523 			error = ENOENT;
1524 			break;
1525 		}
1526 	}
1527 	if (bp != NULL) {
1528 		MPASS(!bplocked);
1529 		error = ERELOOKUP;
1530 	}
1531 	if (error != 0 && pvp != NULL) {
1532 		vput(pvp);
1533 		pvp = NULL;
1534 	}
1535 out1:
1536 	*rvp = pvp;
1537 out:
1538 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked on return");
1539 	return (error);
1540 }
1541 
1542 /*
1543  * This function cleans the worklist for a filesystem.
1544  * Each filesystem running with soft dependencies gets its own
1545  * thread to run in this function. The thread is started up in
1546  * softdep_mount and shutdown in softdep_unmount. They show up
1547  * as part of the kernel "bufdaemon" process whose process
1548  * entry is available in bufdaemonproc.
1549  */
1550 static int searchfailed;
1551 extern struct proc *bufdaemonproc;
1552 static void
1553 softdep_flush(addr)
1554 	void *addr;
1555 {
1556 	struct mount *mp;
1557 	struct thread *td;
1558 	struct ufsmount *ump;
1559 
1560 	td = curthread;
1561 	td->td_pflags |= TDP_NORUNNINGBUF;
1562 	mp = (struct mount *)addr;
1563 	ump = VFSTOUFS(mp);
1564 	atomic_add_int(&stat_flush_threads, 1);
1565 	ACQUIRE_LOCK(ump);
1566 	ump->softdep_flags &= ~FLUSH_STARTING;
1567 	wakeup(&ump->softdep_flushtd);
1568 	FREE_LOCK(ump);
1569 	if (print_threads) {
1570 		if (stat_flush_threads == 1)
1571 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1572 			    bufdaemonproc->p_pid);
1573 		printf("Start thread %s\n", td->td_name);
1574 	}
1575 	for (;;) {
1576 		while (softdep_process_worklist(mp, 0) > 0 ||
1577 		    (MOUNTEDSUJ(mp) &&
1578 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1579 			kthread_suspend_check();
1580 		ACQUIRE_LOCK(ump);
1581 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1582 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1583 			    "sdflush", hz / 2);
1584 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1585 		/*
1586 		 * Check to see if we are done and need to exit.
1587 		 */
1588 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1589 			FREE_LOCK(ump);
1590 			continue;
1591 		}
1592 		ump->softdep_flags &= ~FLUSH_EXIT;
1593 		FREE_LOCK(ump);
1594 		wakeup(&ump->softdep_flags);
1595 		if (print_threads)
1596 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1597 		atomic_subtract_int(&stat_flush_threads, 1);
1598 		kthread_exit();
1599 		panic("kthread_exit failed\n");
1600 	}
1601 }
1602 
1603 static void
1604 worklist_speedup(mp)
1605 	struct mount *mp;
1606 {
1607 	struct ufsmount *ump;
1608 
1609 	ump = VFSTOUFS(mp);
1610 	LOCK_OWNED(ump);
1611 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1612 		ump->softdep_flags |= FLUSH_CLEANUP;
1613 	wakeup(&ump->softdep_flushtd);
1614 }
1615 
1616 static void
1617 softdep_send_speedup(struct ufsmount *ump, off_t shortage, u_int flags)
1618 {
1619 	struct buf *bp;
1620 
1621 	if ((ump->um_flags & UM_CANSPEEDUP) == 0)
1622 		return;
1623 
1624 	bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
1625 	bp->b_iocmd = BIO_SPEEDUP;
1626 	bp->b_ioflags = flags;
1627 	bp->b_bcount = omin(shortage, LONG_MAX);
1628 	g_vfs_strategy(ump->um_bo, bp);
1629 	bufwait(bp);
1630 	free(bp, M_TRIM);
1631 }
1632 
1633 static int
1634 softdep_speedup(ump)
1635 	struct ufsmount *ump;
1636 {
1637 	struct ufsmount *altump;
1638 	struct mount_softdeps *sdp;
1639 
1640 	LOCK_OWNED(ump);
1641 	worklist_speedup(ump->um_mountp);
1642 	bd_speedup();
1643 	/*
1644 	 * If we have global shortages, then we need other
1645 	 * filesystems to help with the cleanup. Here we wakeup a
1646 	 * flusher thread for a filesystem that is over its fair
1647 	 * share of resources.
1648 	 */
1649 	if (req_clear_inodedeps || req_clear_remove) {
1650 		ACQUIRE_GBLLOCK(&lk);
1651 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1652 			if ((altump = sdp->sd_ump) == ump)
1653 				continue;
1654 			if (((req_clear_inodedeps &&
1655 			    altump->softdep_curdeps[D_INODEDEP] >
1656 			    max_softdeps / stat_flush_threads) ||
1657 			    (req_clear_remove &&
1658 			    altump->softdep_curdeps[D_DIRREM] >
1659 			    (max_softdeps / 2) / stat_flush_threads)) &&
1660 			    TRY_ACQUIRE_LOCK(altump))
1661 				break;
1662 		}
1663 		if (sdp == NULL) {
1664 			searchfailed++;
1665 			FREE_GBLLOCK(&lk);
1666 		} else {
1667 			/*
1668 			 * Move to the end of the list so we pick a
1669 			 * different one on out next try.
1670 			 */
1671 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1672 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1673 			FREE_GBLLOCK(&lk);
1674 			if ((altump->softdep_flags &
1675 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1676 				altump->softdep_flags |= FLUSH_CLEANUP;
1677 			altump->um_softdep->sd_cleanups++;
1678 			wakeup(&altump->softdep_flushtd);
1679 			FREE_LOCK(altump);
1680 		}
1681 	}
1682 	return (speedup_syncer());
1683 }
1684 
1685 /*
1686  * Add an item to the end of the work queue.
1687  * This routine requires that the lock be held.
1688  * This is the only routine that adds items to the list.
1689  * The following routine is the only one that removes items
1690  * and does so in order from first to last.
1691  */
1692 
1693 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1694 #define	WK_NODELAY	0x0002	/* Process immediately. */
1695 
1696 static void
1697 add_to_worklist(wk, flags)
1698 	struct worklist *wk;
1699 	int flags;
1700 {
1701 	struct ufsmount *ump;
1702 
1703 	ump = VFSTOUFS(wk->wk_mp);
1704 	LOCK_OWNED(ump);
1705 	if (wk->wk_state & ONWORKLIST)
1706 		panic("add_to_worklist: %s(0x%X) already on list",
1707 		    TYPENAME(wk->wk_type), wk->wk_state);
1708 	wk->wk_state |= ONWORKLIST;
1709 	if (ump->softdep_on_worklist == 0) {
1710 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1711 		ump->softdep_worklist_tail = wk;
1712 	} else if (flags & WK_HEAD) {
1713 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1714 	} else {
1715 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1716 		ump->softdep_worklist_tail = wk;
1717 	}
1718 	ump->softdep_on_worklist += 1;
1719 	if (flags & WK_NODELAY)
1720 		worklist_speedup(wk->wk_mp);
1721 }
1722 
1723 /*
1724  * Remove the item to be processed. If we are removing the last
1725  * item on the list, we need to recalculate the tail pointer.
1726  */
1727 static void
1728 remove_from_worklist(wk)
1729 	struct worklist *wk;
1730 {
1731 	struct ufsmount *ump;
1732 
1733 	ump = VFSTOUFS(wk->wk_mp);
1734 	if (ump->softdep_worklist_tail == wk)
1735 		ump->softdep_worklist_tail =
1736 		    (struct worklist *)wk->wk_list.le_prev;
1737 	WORKLIST_REMOVE(wk);
1738 	ump->softdep_on_worklist -= 1;
1739 }
1740 
1741 static void
1742 wake_worklist(wk)
1743 	struct worklist *wk;
1744 {
1745 	if (wk->wk_state & IOWAITING) {
1746 		wk->wk_state &= ~IOWAITING;
1747 		wakeup(wk);
1748 	}
1749 }
1750 
1751 static void
1752 wait_worklist(wk, wmesg)
1753 	struct worklist *wk;
1754 	char *wmesg;
1755 {
1756 	struct ufsmount *ump;
1757 
1758 	ump = VFSTOUFS(wk->wk_mp);
1759 	wk->wk_state |= IOWAITING;
1760 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1761 }
1762 
1763 /*
1764  * Process that runs once per second to handle items in the background queue.
1765  *
1766  * Note that we ensure that everything is done in the order in which they
1767  * appear in the queue. The code below depends on this property to ensure
1768  * that blocks of a file are freed before the inode itself is freed. This
1769  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1770  * until all the old ones have been purged from the dependency lists.
1771  */
1772 static int
1773 softdep_process_worklist(mp, full)
1774 	struct mount *mp;
1775 	int full;
1776 {
1777 	int cnt, matchcnt;
1778 	struct ufsmount *ump;
1779 	long starttime;
1780 
1781 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1782 	if (MOUNTEDSOFTDEP(mp) == 0)
1783 		return (0);
1784 	matchcnt = 0;
1785 	ump = VFSTOUFS(mp);
1786 	ACQUIRE_LOCK(ump);
1787 	starttime = time_second;
1788 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1789 	check_clear_deps(mp);
1790 	while (ump->softdep_on_worklist > 0) {
1791 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1792 			break;
1793 		else
1794 			matchcnt += cnt;
1795 		check_clear_deps(mp);
1796 		/*
1797 		 * We do not generally want to stop for buffer space, but if
1798 		 * we are really being a buffer hog, we will stop and wait.
1799 		 */
1800 		if (should_yield()) {
1801 			FREE_LOCK(ump);
1802 			kern_yield(PRI_USER);
1803 			bwillwrite();
1804 			ACQUIRE_LOCK(ump);
1805 		}
1806 		/*
1807 		 * Never allow processing to run for more than one
1808 		 * second. This gives the syncer thread the opportunity
1809 		 * to pause if appropriate.
1810 		 */
1811 		if (!full && starttime != time_second)
1812 			break;
1813 	}
1814 	if (full == 0)
1815 		journal_unsuspend(ump);
1816 	FREE_LOCK(ump);
1817 	return (matchcnt);
1818 }
1819 
1820 /*
1821  * Process all removes associated with a vnode if we are running out of
1822  * journal space.  Any other process which attempts to flush these will
1823  * be unable as we have the vnodes locked.
1824  */
1825 static void
1826 process_removes(vp)
1827 	struct vnode *vp;
1828 {
1829 	struct inodedep *inodedep;
1830 	struct dirrem *dirrem;
1831 	struct ufsmount *ump;
1832 	struct mount *mp;
1833 	ino_t inum;
1834 
1835 	mp = vp->v_mount;
1836 	ump = VFSTOUFS(mp);
1837 	LOCK_OWNED(ump);
1838 	inum = VTOI(vp)->i_number;
1839 	for (;;) {
1840 top:
1841 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1842 			return;
1843 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1844 			/*
1845 			 * If another thread is trying to lock this vnode
1846 			 * it will fail but we must wait for it to do so
1847 			 * before we can proceed.
1848 			 */
1849 			if (dirrem->dm_state & INPROGRESS) {
1850 				wait_worklist(&dirrem->dm_list, "pwrwait");
1851 				goto top;
1852 			}
1853 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1854 			    (COMPLETE | ONWORKLIST))
1855 				break;
1856 		}
1857 		if (dirrem == NULL)
1858 			return;
1859 		remove_from_worklist(&dirrem->dm_list);
1860 		FREE_LOCK(ump);
1861 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1862 			panic("process_removes: suspended filesystem");
1863 		handle_workitem_remove(dirrem, 0);
1864 		vn_finished_secondary_write(mp);
1865 		ACQUIRE_LOCK(ump);
1866 	}
1867 }
1868 
1869 /*
1870  * Process all truncations associated with a vnode if we are running out
1871  * of journal space.  This is called when the vnode lock is already held
1872  * and no other process can clear the truncation.  This function returns
1873  * a value greater than zero if it did any work.
1874  */
1875 static void
1876 process_truncates(vp)
1877 	struct vnode *vp;
1878 {
1879 	struct inodedep *inodedep;
1880 	struct freeblks *freeblks;
1881 	struct ufsmount *ump;
1882 	struct mount *mp;
1883 	ino_t inum;
1884 	int cgwait;
1885 
1886 	mp = vp->v_mount;
1887 	ump = VFSTOUFS(mp);
1888 	LOCK_OWNED(ump);
1889 	inum = VTOI(vp)->i_number;
1890 	for (;;) {
1891 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1892 			return;
1893 		cgwait = 0;
1894 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1895 			/* Journal entries not yet written.  */
1896 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1897 				jwait(&LIST_FIRST(
1898 				    &freeblks->fb_jblkdephd)->jb_list,
1899 				    MNT_WAIT);
1900 				break;
1901 			}
1902 			/* Another thread is executing this item. */
1903 			if (freeblks->fb_state & INPROGRESS) {
1904 				wait_worklist(&freeblks->fb_list, "ptrwait");
1905 				break;
1906 			}
1907 			/* Freeblks is waiting on a inode write. */
1908 			if ((freeblks->fb_state & COMPLETE) == 0) {
1909 				FREE_LOCK(ump);
1910 				ffs_update(vp, 1);
1911 				ACQUIRE_LOCK(ump);
1912 				break;
1913 			}
1914 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1915 			    (ALLCOMPLETE | ONWORKLIST)) {
1916 				remove_from_worklist(&freeblks->fb_list);
1917 				freeblks->fb_state |= INPROGRESS;
1918 				FREE_LOCK(ump);
1919 				if (vn_start_secondary_write(NULL, &mp,
1920 				    V_NOWAIT))
1921 					panic("process_truncates: "
1922 					    "suspended filesystem");
1923 				handle_workitem_freeblocks(freeblks, 0);
1924 				vn_finished_secondary_write(mp);
1925 				ACQUIRE_LOCK(ump);
1926 				break;
1927 			}
1928 			if (freeblks->fb_cgwait)
1929 				cgwait++;
1930 		}
1931 		if (cgwait) {
1932 			FREE_LOCK(ump);
1933 			sync_cgs(mp, MNT_WAIT);
1934 			ffs_sync_snap(mp, MNT_WAIT);
1935 			ACQUIRE_LOCK(ump);
1936 			continue;
1937 		}
1938 		if (freeblks == NULL)
1939 			break;
1940 	}
1941 	return;
1942 }
1943 
1944 /*
1945  * Process one item on the worklist.
1946  */
1947 static int
1948 process_worklist_item(mp, target, flags)
1949 	struct mount *mp;
1950 	int target;
1951 	int flags;
1952 {
1953 	struct worklist sentinel;
1954 	struct worklist *wk;
1955 	struct ufsmount *ump;
1956 	int matchcnt;
1957 	int error;
1958 
1959 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1960 	/*
1961 	 * If we are being called because of a process doing a
1962 	 * copy-on-write, then it is not safe to write as we may
1963 	 * recurse into the copy-on-write routine.
1964 	 */
1965 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1966 		return (-1);
1967 	PHOLD(curproc);	/* Don't let the stack go away. */
1968 	ump = VFSTOUFS(mp);
1969 	LOCK_OWNED(ump);
1970 	matchcnt = 0;
1971 	sentinel.wk_mp = NULL;
1972 	sentinel.wk_type = D_SENTINEL;
1973 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1974 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1975 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1976 		if (wk->wk_type == D_SENTINEL) {
1977 			LIST_REMOVE(&sentinel, wk_list);
1978 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1979 			continue;
1980 		}
1981 		if (wk->wk_state & INPROGRESS)
1982 			panic("process_worklist_item: %p already in progress.",
1983 			    wk);
1984 		wk->wk_state |= INPROGRESS;
1985 		remove_from_worklist(wk);
1986 		FREE_LOCK(ump);
1987 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1988 			panic("process_worklist_item: suspended filesystem");
1989 		switch (wk->wk_type) {
1990 		case D_DIRREM:
1991 			/* removal of a directory entry */
1992 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1993 			break;
1994 
1995 		case D_FREEBLKS:
1996 			/* releasing blocks and/or fragments from a file */
1997 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1998 			    flags);
1999 			break;
2000 
2001 		case D_FREEFRAG:
2002 			/* releasing a fragment when replaced as a file grows */
2003 			handle_workitem_freefrag(WK_FREEFRAG(wk));
2004 			error = 0;
2005 			break;
2006 
2007 		case D_FREEFILE:
2008 			/* releasing an inode when its link count drops to 0 */
2009 			handle_workitem_freefile(WK_FREEFILE(wk));
2010 			error = 0;
2011 			break;
2012 
2013 		default:
2014 			panic("%s_process_worklist: Unknown type %s",
2015 			    "softdep", TYPENAME(wk->wk_type));
2016 			/* NOTREACHED */
2017 		}
2018 		vn_finished_secondary_write(mp);
2019 		ACQUIRE_LOCK(ump);
2020 		if (error == 0) {
2021 			if (++matchcnt == target)
2022 				break;
2023 			continue;
2024 		}
2025 		/*
2026 		 * We have to retry the worklist item later.  Wake up any
2027 		 * waiters who may be able to complete it immediately and
2028 		 * add the item back to the head so we don't try to execute
2029 		 * it again.
2030 		 */
2031 		wk->wk_state &= ~INPROGRESS;
2032 		wake_worklist(wk);
2033 		add_to_worklist(wk, WK_HEAD);
2034 	}
2035 	/* Sentinal could've become the tail from remove_from_worklist. */
2036 	if (ump->softdep_worklist_tail == &sentinel)
2037 		ump->softdep_worklist_tail =
2038 		    (struct worklist *)sentinel.wk_list.le_prev;
2039 	LIST_REMOVE(&sentinel, wk_list);
2040 	PRELE(curproc);
2041 	return (matchcnt);
2042 }
2043 
2044 /*
2045  * Move dependencies from one buffer to another.
2046  */
2047 int
2048 softdep_move_dependencies(oldbp, newbp)
2049 	struct buf *oldbp;
2050 	struct buf *newbp;
2051 {
2052 	struct worklist *wk, *wktail;
2053 	struct ufsmount *ump;
2054 	int dirty;
2055 
2056 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
2057 		return (0);
2058 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
2059 	    ("softdep_move_dependencies called on non-softdep filesystem"));
2060 	dirty = 0;
2061 	wktail = NULL;
2062 	ump = VFSTOUFS(wk->wk_mp);
2063 	ACQUIRE_LOCK(ump);
2064 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
2065 		LIST_REMOVE(wk, wk_list);
2066 		if (wk->wk_type == D_BMSAFEMAP &&
2067 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
2068 			dirty = 1;
2069 		if (wktail == NULL)
2070 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
2071 		else
2072 			LIST_INSERT_AFTER(wktail, wk, wk_list);
2073 		wktail = wk;
2074 	}
2075 	FREE_LOCK(ump);
2076 
2077 	return (dirty);
2078 }
2079 
2080 /*
2081  * Purge the work list of all items associated with a particular mount point.
2082  */
2083 int
2084 softdep_flushworklist(oldmnt, countp, td)
2085 	struct mount *oldmnt;
2086 	int *countp;
2087 	struct thread *td;
2088 {
2089 	struct vnode *devvp;
2090 	struct ufsmount *ump;
2091 	int count, error;
2092 
2093 	/*
2094 	 * Alternately flush the block device associated with the mount
2095 	 * point and process any dependencies that the flushing
2096 	 * creates. We continue until no more worklist dependencies
2097 	 * are found.
2098 	 */
2099 	*countp = 0;
2100 	error = 0;
2101 	ump = VFSTOUFS(oldmnt);
2102 	devvp = ump->um_devvp;
2103 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
2104 		*countp += count;
2105 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2106 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2107 		VOP_UNLOCK(devvp);
2108 		if (error != 0)
2109 			break;
2110 	}
2111 	return (error);
2112 }
2113 
2114 #define	SU_WAITIDLE_RETRIES	20
2115 static int
2116 softdep_waitidle(struct mount *mp, int flags __unused)
2117 {
2118 	struct ufsmount *ump;
2119 	struct vnode *devvp;
2120 	struct thread *td;
2121 	int error, i;
2122 
2123 	ump = VFSTOUFS(mp);
2124 	devvp = ump->um_devvp;
2125 	td = curthread;
2126 	error = 0;
2127 	ACQUIRE_LOCK(ump);
2128 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
2129 		ump->softdep_req = 1;
2130 		KASSERT((flags & FORCECLOSE) == 0 ||
2131 		    ump->softdep_on_worklist == 0,
2132 		    ("softdep_waitidle: work added after flush"));
2133 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
2134 		    "softdeps", 10 * hz);
2135 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2136 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2137 		VOP_UNLOCK(devvp);
2138 		ACQUIRE_LOCK(ump);
2139 		if (error != 0)
2140 			break;
2141 	}
2142 	ump->softdep_req = 0;
2143 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
2144 		error = EBUSY;
2145 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
2146 		    mp);
2147 	}
2148 	FREE_LOCK(ump);
2149 	return (error);
2150 }
2151 
2152 /*
2153  * Flush all vnodes and worklist items associated with a specified mount point.
2154  */
2155 int
2156 softdep_flushfiles(oldmnt, flags, td)
2157 	struct mount *oldmnt;
2158 	int flags;
2159 	struct thread *td;
2160 {
2161 #ifdef QUOTA
2162 	struct ufsmount *ump;
2163 	int i;
2164 #endif
2165 	int error, early, depcount, loopcnt, retry_flush_count, retry;
2166 	int morework;
2167 
2168 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
2169 	    ("softdep_flushfiles called on non-softdep filesystem"));
2170 	loopcnt = 10;
2171 	retry_flush_count = 3;
2172 retry_flush:
2173 	error = 0;
2174 
2175 	/*
2176 	 * Alternately flush the vnodes associated with the mount
2177 	 * point and process any dependencies that the flushing
2178 	 * creates. In theory, this loop can happen at most twice,
2179 	 * but we give it a few extra just to be sure.
2180 	 */
2181 	for (; loopcnt > 0; loopcnt--) {
2182 		/*
2183 		 * Do another flush in case any vnodes were brought in
2184 		 * as part of the cleanup operations.
2185 		 */
2186 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2187 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2188 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2189 			break;
2190 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2191 		    depcount == 0)
2192 			break;
2193 	}
2194 	/*
2195 	 * If we are unmounting then it is an error to fail. If we
2196 	 * are simply trying to downgrade to read-only, then filesystem
2197 	 * activity can keep us busy forever, so we just fail with EBUSY.
2198 	 */
2199 	if (loopcnt == 0) {
2200 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2201 			panic("softdep_flushfiles: looping");
2202 		error = EBUSY;
2203 	}
2204 	if (!error)
2205 		error = softdep_waitidle(oldmnt, flags);
2206 	if (!error) {
2207 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2208 			retry = 0;
2209 			MNT_ILOCK(oldmnt);
2210 			morework = oldmnt->mnt_nvnodelistsize > 0;
2211 #ifdef QUOTA
2212 			ump = VFSTOUFS(oldmnt);
2213 			UFS_LOCK(ump);
2214 			for (i = 0; i < MAXQUOTAS; i++) {
2215 				if (ump->um_quotas[i] != NULLVP)
2216 					morework = 1;
2217 			}
2218 			UFS_UNLOCK(ump);
2219 #endif
2220 			if (morework) {
2221 				if (--retry_flush_count > 0) {
2222 					retry = 1;
2223 					loopcnt = 3;
2224 				} else
2225 					error = EBUSY;
2226 			}
2227 			MNT_IUNLOCK(oldmnt);
2228 			if (retry)
2229 				goto retry_flush;
2230 		}
2231 	}
2232 	return (error);
2233 }
2234 
2235 /*
2236  * Structure hashing.
2237  *
2238  * There are four types of structures that can be looked up:
2239  *	1) pagedep structures identified by mount point, inode number,
2240  *	   and logical block.
2241  *	2) inodedep structures identified by mount point and inode number.
2242  *	3) newblk structures identified by mount point and
2243  *	   physical block number.
2244  *	4) bmsafemap structures identified by mount point and
2245  *	   cylinder group number.
2246  *
2247  * The "pagedep" and "inodedep" dependency structures are hashed
2248  * separately from the file blocks and inodes to which they correspond.
2249  * This separation helps when the in-memory copy of an inode or
2250  * file block must be replaced. It also obviates the need to access
2251  * an inode or file page when simply updating (or de-allocating)
2252  * dependency structures. Lookup of newblk structures is needed to
2253  * find newly allocated blocks when trying to associate them with
2254  * their allocdirect or allocindir structure.
2255  *
2256  * The lookup routines optionally create and hash a new instance when
2257  * an existing entry is not found. The bmsafemap lookup routine always
2258  * allocates a new structure if an existing one is not found.
2259  */
2260 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2261 
2262 /*
2263  * Structures and routines associated with pagedep caching.
2264  */
2265 #define	PAGEDEP_HASH(ump, inum, lbn) \
2266 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2267 
2268 static int
2269 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2270 	struct pagedep_hashhead *pagedephd;
2271 	ino_t ino;
2272 	ufs_lbn_t lbn;
2273 	struct pagedep **pagedeppp;
2274 {
2275 	struct pagedep *pagedep;
2276 
2277 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2278 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2279 			*pagedeppp = pagedep;
2280 			return (1);
2281 		}
2282 	}
2283 	*pagedeppp = NULL;
2284 	return (0);
2285 }
2286 /*
2287  * Look up a pagedep. Return 1 if found, 0 otherwise.
2288  * If not found, allocate if DEPALLOC flag is passed.
2289  * Found or allocated entry is returned in pagedeppp.
2290  */
2291 static int
2292 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2293 	struct mount *mp;
2294 	struct buf *bp;
2295 	ino_t ino;
2296 	ufs_lbn_t lbn;
2297 	int flags;
2298 	struct pagedep **pagedeppp;
2299 {
2300 	struct pagedep *pagedep;
2301 	struct pagedep_hashhead *pagedephd;
2302 	struct worklist *wk;
2303 	struct ufsmount *ump;
2304 	int ret;
2305 	int i;
2306 
2307 	ump = VFSTOUFS(mp);
2308 	LOCK_OWNED(ump);
2309 	if (bp) {
2310 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2311 			if (wk->wk_type == D_PAGEDEP) {
2312 				*pagedeppp = WK_PAGEDEP(wk);
2313 				return (1);
2314 			}
2315 		}
2316 	}
2317 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2318 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2319 	if (ret) {
2320 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2321 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2322 		return (1);
2323 	}
2324 	if ((flags & DEPALLOC) == 0)
2325 		return (0);
2326 	FREE_LOCK(ump);
2327 	pagedep = malloc(sizeof(struct pagedep),
2328 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2329 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2330 	ACQUIRE_LOCK(ump);
2331 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2332 	if (*pagedeppp) {
2333 		/*
2334 		 * This should never happen since we only create pagedeps
2335 		 * with the vnode lock held.  Could be an assert.
2336 		 */
2337 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2338 		return (ret);
2339 	}
2340 	pagedep->pd_ino = ino;
2341 	pagedep->pd_lbn = lbn;
2342 	LIST_INIT(&pagedep->pd_dirremhd);
2343 	LIST_INIT(&pagedep->pd_pendinghd);
2344 	for (i = 0; i < DAHASHSZ; i++)
2345 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2346 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2347 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2348 	*pagedeppp = pagedep;
2349 	return (0);
2350 }
2351 
2352 /*
2353  * Structures and routines associated with inodedep caching.
2354  */
2355 #define	INODEDEP_HASH(ump, inum) \
2356       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2357 
2358 static int
2359 inodedep_find(inodedephd, inum, inodedeppp)
2360 	struct inodedep_hashhead *inodedephd;
2361 	ino_t inum;
2362 	struct inodedep **inodedeppp;
2363 {
2364 	struct inodedep *inodedep;
2365 
2366 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2367 		if (inum == inodedep->id_ino)
2368 			break;
2369 	if (inodedep) {
2370 		*inodedeppp = inodedep;
2371 		return (1);
2372 	}
2373 	*inodedeppp = NULL;
2374 
2375 	return (0);
2376 }
2377 /*
2378  * Look up an inodedep. Return 1 if found, 0 if not found.
2379  * If not found, allocate if DEPALLOC flag is passed.
2380  * Found or allocated entry is returned in inodedeppp.
2381  */
2382 static int
2383 inodedep_lookup(mp, inum, flags, inodedeppp)
2384 	struct mount *mp;
2385 	ino_t inum;
2386 	int flags;
2387 	struct inodedep **inodedeppp;
2388 {
2389 	struct inodedep *inodedep;
2390 	struct inodedep_hashhead *inodedephd;
2391 	struct ufsmount *ump;
2392 	struct fs *fs;
2393 
2394 	ump = VFSTOUFS(mp);
2395 	LOCK_OWNED(ump);
2396 	fs = ump->um_fs;
2397 	inodedephd = INODEDEP_HASH(ump, inum);
2398 
2399 	if (inodedep_find(inodedephd, inum, inodedeppp))
2400 		return (1);
2401 	if ((flags & DEPALLOC) == 0)
2402 		return (0);
2403 	/*
2404 	 * If the system is over its limit and our filesystem is
2405 	 * responsible for more than our share of that usage and
2406 	 * we are not in a rush, request some inodedep cleanup.
2407 	 */
2408 	if (softdep_excess_items(ump, D_INODEDEP))
2409 		schedule_cleanup(mp);
2410 	else
2411 		FREE_LOCK(ump);
2412 	inodedep = malloc(sizeof(struct inodedep),
2413 		M_INODEDEP, M_SOFTDEP_FLAGS);
2414 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2415 	ACQUIRE_LOCK(ump);
2416 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2417 		WORKITEM_FREE(inodedep, D_INODEDEP);
2418 		return (1);
2419 	}
2420 	inodedep->id_fs = fs;
2421 	inodedep->id_ino = inum;
2422 	inodedep->id_state = ALLCOMPLETE;
2423 	inodedep->id_nlinkdelta = 0;
2424 	inodedep->id_nlinkwrote = -1;
2425 	inodedep->id_savedino1 = NULL;
2426 	inodedep->id_savedsize = -1;
2427 	inodedep->id_savedextsize = -1;
2428 	inodedep->id_savednlink = -1;
2429 	inodedep->id_bmsafemap = NULL;
2430 	inodedep->id_mkdiradd = NULL;
2431 	LIST_INIT(&inodedep->id_dirremhd);
2432 	LIST_INIT(&inodedep->id_pendinghd);
2433 	LIST_INIT(&inodedep->id_inowait);
2434 	LIST_INIT(&inodedep->id_bufwait);
2435 	TAILQ_INIT(&inodedep->id_inoreflst);
2436 	TAILQ_INIT(&inodedep->id_inoupdt);
2437 	TAILQ_INIT(&inodedep->id_newinoupdt);
2438 	TAILQ_INIT(&inodedep->id_extupdt);
2439 	TAILQ_INIT(&inodedep->id_newextupdt);
2440 	TAILQ_INIT(&inodedep->id_freeblklst);
2441 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2442 	*inodedeppp = inodedep;
2443 	return (0);
2444 }
2445 
2446 /*
2447  * Structures and routines associated with newblk caching.
2448  */
2449 #define	NEWBLK_HASH(ump, inum) \
2450 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2451 
2452 static int
2453 newblk_find(newblkhd, newblkno, flags, newblkpp)
2454 	struct newblk_hashhead *newblkhd;
2455 	ufs2_daddr_t newblkno;
2456 	int flags;
2457 	struct newblk **newblkpp;
2458 {
2459 	struct newblk *newblk;
2460 
2461 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2462 		if (newblkno != newblk->nb_newblkno)
2463 			continue;
2464 		/*
2465 		 * If we're creating a new dependency don't match those that
2466 		 * have already been converted to allocdirects.  This is for
2467 		 * a frag extend.
2468 		 */
2469 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2470 			continue;
2471 		break;
2472 	}
2473 	if (newblk) {
2474 		*newblkpp = newblk;
2475 		return (1);
2476 	}
2477 	*newblkpp = NULL;
2478 	return (0);
2479 }
2480 
2481 /*
2482  * Look up a newblk. Return 1 if found, 0 if not found.
2483  * If not found, allocate if DEPALLOC flag is passed.
2484  * Found or allocated entry is returned in newblkpp.
2485  */
2486 static int
2487 newblk_lookup(mp, newblkno, flags, newblkpp)
2488 	struct mount *mp;
2489 	ufs2_daddr_t newblkno;
2490 	int flags;
2491 	struct newblk **newblkpp;
2492 {
2493 	struct newblk *newblk;
2494 	struct newblk_hashhead *newblkhd;
2495 	struct ufsmount *ump;
2496 
2497 	ump = VFSTOUFS(mp);
2498 	LOCK_OWNED(ump);
2499 	newblkhd = NEWBLK_HASH(ump, newblkno);
2500 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2501 		return (1);
2502 	if ((flags & DEPALLOC) == 0)
2503 		return (0);
2504 	if (softdep_excess_items(ump, D_NEWBLK) ||
2505 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2506 	    softdep_excess_items(ump, D_ALLOCINDIR))
2507 		schedule_cleanup(mp);
2508 	else
2509 		FREE_LOCK(ump);
2510 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2511 	    M_SOFTDEP_FLAGS | M_ZERO);
2512 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2513 	ACQUIRE_LOCK(ump);
2514 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2515 		WORKITEM_FREE(newblk, D_NEWBLK);
2516 		return (1);
2517 	}
2518 	newblk->nb_freefrag = NULL;
2519 	LIST_INIT(&newblk->nb_indirdeps);
2520 	LIST_INIT(&newblk->nb_newdirblk);
2521 	LIST_INIT(&newblk->nb_jwork);
2522 	newblk->nb_state = ATTACHED;
2523 	newblk->nb_newblkno = newblkno;
2524 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2525 	*newblkpp = newblk;
2526 	return (0);
2527 }
2528 
2529 /*
2530  * Structures and routines associated with freed indirect block caching.
2531  */
2532 #define	INDIR_HASH(ump, blkno) \
2533 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2534 
2535 /*
2536  * Lookup an indirect block in the indir hash table.  The freework is
2537  * removed and potentially freed.  The caller must do a blocking journal
2538  * write before writing to the blkno.
2539  */
2540 static int
2541 indirblk_lookup(mp, blkno)
2542 	struct mount *mp;
2543 	ufs2_daddr_t blkno;
2544 {
2545 	struct freework *freework;
2546 	struct indir_hashhead *wkhd;
2547 	struct ufsmount *ump;
2548 
2549 	ump = VFSTOUFS(mp);
2550 	wkhd = INDIR_HASH(ump, blkno);
2551 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2552 		if (freework->fw_blkno != blkno)
2553 			continue;
2554 		indirblk_remove(freework);
2555 		return (1);
2556 	}
2557 	return (0);
2558 }
2559 
2560 /*
2561  * Insert an indirect block represented by freework into the indirblk
2562  * hash table so that it may prevent the block from being re-used prior
2563  * to the journal being written.
2564  */
2565 static void
2566 indirblk_insert(freework)
2567 	struct freework *freework;
2568 {
2569 	struct jblocks *jblocks;
2570 	struct jseg *jseg;
2571 	struct ufsmount *ump;
2572 
2573 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2574 	jblocks = ump->softdep_jblocks;
2575 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2576 	if (jseg == NULL)
2577 		return;
2578 
2579 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2580 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2581 	    fw_next);
2582 	freework->fw_state &= ~DEPCOMPLETE;
2583 }
2584 
2585 static void
2586 indirblk_remove(freework)
2587 	struct freework *freework;
2588 {
2589 	struct ufsmount *ump;
2590 
2591 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2592 	LIST_REMOVE(freework, fw_segs);
2593 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2594 	freework->fw_state |= DEPCOMPLETE;
2595 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2596 		WORKITEM_FREE(freework, D_FREEWORK);
2597 }
2598 
2599 /*
2600  * Executed during filesystem system initialization before
2601  * mounting any filesystems.
2602  */
2603 void
2604 softdep_initialize()
2605 {
2606 
2607 	TAILQ_INIT(&softdepmounts);
2608 #ifdef __LP64__
2609 	max_softdeps = desiredvnodes * 4;
2610 #else
2611 	max_softdeps = desiredvnodes * 2;
2612 #endif
2613 
2614 	/* initialise bioops hack */
2615 	bioops.io_start = softdep_disk_io_initiation;
2616 	bioops.io_complete = softdep_disk_write_complete;
2617 	bioops.io_deallocate = softdep_deallocate_dependencies;
2618 	bioops.io_countdeps = softdep_count_dependencies;
2619 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2620 
2621 	/* Initialize the callout with an mtx. */
2622 	callout_init_mtx(&softdep_callout, &lk, 0);
2623 }
2624 
2625 /*
2626  * Executed after all filesystems have been unmounted during
2627  * filesystem module unload.
2628  */
2629 void
2630 softdep_uninitialize()
2631 {
2632 
2633 	/* clear bioops hack */
2634 	bioops.io_start = NULL;
2635 	bioops.io_complete = NULL;
2636 	bioops.io_deallocate = NULL;
2637 	bioops.io_countdeps = NULL;
2638 	softdep_ast_cleanup = NULL;
2639 
2640 	callout_drain(&softdep_callout);
2641 }
2642 
2643 /*
2644  * Called at mount time to notify the dependency code that a
2645  * filesystem wishes to use it.
2646  */
2647 int
2648 softdep_mount(devvp, mp, fs, cred)
2649 	struct vnode *devvp;
2650 	struct mount *mp;
2651 	struct fs *fs;
2652 	struct ucred *cred;
2653 {
2654 	struct csum_total cstotal;
2655 	struct mount_softdeps *sdp;
2656 	struct ufsmount *ump;
2657 	struct cg *cgp;
2658 	struct buf *bp;
2659 	u_int cyl, i;
2660 	int error;
2661 
2662 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2663 	    M_WAITOK | M_ZERO);
2664 	MNT_ILOCK(mp);
2665 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2666 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2667 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2668 			MNTK_SOFTDEP | MNTK_NOASYNC;
2669 	}
2670 	ump = VFSTOUFS(mp);
2671 	ump->um_softdep = sdp;
2672 	MNT_IUNLOCK(mp);
2673 	rw_init(LOCK_PTR(ump), "per-fs softdep");
2674 	sdp->sd_ump = ump;
2675 	LIST_INIT(&ump->softdep_workitem_pending);
2676 	LIST_INIT(&ump->softdep_journal_pending);
2677 	TAILQ_INIT(&ump->softdep_unlinked);
2678 	LIST_INIT(&ump->softdep_dirtycg);
2679 	ump->softdep_worklist_tail = NULL;
2680 	ump->softdep_on_worklist = 0;
2681 	ump->softdep_deps = 0;
2682 	LIST_INIT(&ump->softdep_mkdirlisthd);
2683 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2684 	    &ump->pagedep_hash_size);
2685 	ump->pagedep_nextclean = 0;
2686 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2687 	    &ump->inodedep_hash_size);
2688 	ump->inodedep_nextclean = 0;
2689 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2690 	    &ump->newblk_hash_size);
2691 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2692 	    &ump->bmsafemap_hash_size);
2693 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2694 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2695 	    M_FREEWORK, M_WAITOK);
2696 	ump->indir_hash_size = i - 1;
2697 	for (i = 0; i <= ump->indir_hash_size; i++)
2698 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2699 #ifdef INVARIANTS
2700 	for (i = 0; i <= D_LAST; i++)
2701 		LIST_INIT(&ump->softdep_alldeps[i]);
2702 #endif
2703 	ACQUIRE_GBLLOCK(&lk);
2704 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2705 	FREE_GBLLOCK(&lk);
2706 	if ((fs->fs_flags & FS_SUJ) &&
2707 	    (error = journal_mount(mp, fs, cred)) != 0) {
2708 		printf("Failed to start journal: %d\n", error);
2709 		softdep_unmount(mp);
2710 		return (error);
2711 	}
2712 	/*
2713 	 * Start our flushing thread in the bufdaemon process.
2714 	 */
2715 	ACQUIRE_LOCK(ump);
2716 	ump->softdep_flags |= FLUSH_STARTING;
2717 	FREE_LOCK(ump);
2718 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2719 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2720 	    mp->mnt_stat.f_mntonname);
2721 	ACQUIRE_LOCK(ump);
2722 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2723 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2724 		    hz / 2);
2725 	}
2726 	FREE_LOCK(ump);
2727 	/*
2728 	 * When doing soft updates, the counters in the
2729 	 * superblock may have gotten out of sync. Recomputation
2730 	 * can take a long time and can be deferred for background
2731 	 * fsck.  However, the old behavior of scanning the cylinder
2732 	 * groups and recalculating them at mount time is available
2733 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2734 	 */
2735 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2736 		return (0);
2737 	bzero(&cstotal, sizeof cstotal);
2738 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2739 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2740 		    fs->fs_cgsize, cred, &bp)) != 0) {
2741 			brelse(bp);
2742 			softdep_unmount(mp);
2743 			return (error);
2744 		}
2745 		cgp = (struct cg *)bp->b_data;
2746 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2747 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2748 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2749 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2750 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2751 		brelse(bp);
2752 	}
2753 #ifdef INVARIANTS
2754 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2755 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2756 #endif
2757 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2758 	return (0);
2759 }
2760 
2761 void
2762 softdep_unmount(mp)
2763 	struct mount *mp;
2764 {
2765 	struct ufsmount *ump;
2766 #ifdef INVARIANTS
2767 	int i;
2768 #endif
2769 
2770 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2771 	    ("softdep_unmount called on non-softdep filesystem"));
2772 	ump = VFSTOUFS(mp);
2773 	MNT_ILOCK(mp);
2774 	mp->mnt_flag &= ~MNT_SOFTDEP;
2775 	if (MOUNTEDSUJ(mp) == 0) {
2776 		MNT_IUNLOCK(mp);
2777 	} else {
2778 		mp->mnt_flag &= ~MNT_SUJ;
2779 		MNT_IUNLOCK(mp);
2780 		journal_unmount(ump);
2781 	}
2782 	/*
2783 	 * Shut down our flushing thread. Check for NULL is if
2784 	 * softdep_mount errors out before the thread has been created.
2785 	 */
2786 	if (ump->softdep_flushtd != NULL) {
2787 		ACQUIRE_LOCK(ump);
2788 		ump->softdep_flags |= FLUSH_EXIT;
2789 		wakeup(&ump->softdep_flushtd);
2790 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2791 		    "sdwait", 0);
2792 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2793 		    ("Thread shutdown failed"));
2794 	}
2795 	/*
2796 	 * Free up our resources.
2797 	 */
2798 	ACQUIRE_GBLLOCK(&lk);
2799 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2800 	FREE_GBLLOCK(&lk);
2801 	rw_destroy(LOCK_PTR(ump));
2802 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2803 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2804 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2805 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2806 	    ump->bmsafemap_hash_size);
2807 	free(ump->indir_hashtbl, M_FREEWORK);
2808 #ifdef INVARIANTS
2809 	for (i = 0; i <= D_LAST; i++) {
2810 		KASSERT(ump->softdep_curdeps[i] == 0,
2811 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2812 		    TYPENAME(i), ump->softdep_curdeps[i]));
2813 		KASSERT(LIST_EMPTY(&ump->softdep_alldeps[i]),
2814 		    ("Unmount %s: Dep type %s not empty (%p)", ump->um_fs->fs_fsmnt,
2815 		    TYPENAME(i), LIST_FIRST(&ump->softdep_alldeps[i])));
2816 	}
2817 #endif
2818 	free(ump->um_softdep, M_MOUNTDATA);
2819 }
2820 
2821 static struct jblocks *
2822 jblocks_create(void)
2823 {
2824 	struct jblocks *jblocks;
2825 
2826 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2827 	TAILQ_INIT(&jblocks->jb_segs);
2828 	jblocks->jb_avail = 10;
2829 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2830 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2831 
2832 	return (jblocks);
2833 }
2834 
2835 static ufs2_daddr_t
2836 jblocks_alloc(jblocks, bytes, actual)
2837 	struct jblocks *jblocks;
2838 	int bytes;
2839 	int *actual;
2840 {
2841 	ufs2_daddr_t daddr;
2842 	struct jextent *jext;
2843 	int freecnt;
2844 	int blocks;
2845 
2846 	blocks = bytes / DEV_BSIZE;
2847 	jext = &jblocks->jb_extent[jblocks->jb_head];
2848 	freecnt = jext->je_blocks - jblocks->jb_off;
2849 	if (freecnt == 0) {
2850 		jblocks->jb_off = 0;
2851 		if (++jblocks->jb_head > jblocks->jb_used)
2852 			jblocks->jb_head = 0;
2853 		jext = &jblocks->jb_extent[jblocks->jb_head];
2854 		freecnt = jext->je_blocks;
2855 	}
2856 	if (freecnt > blocks)
2857 		freecnt = blocks;
2858 	*actual = freecnt * DEV_BSIZE;
2859 	daddr = jext->je_daddr + jblocks->jb_off;
2860 	jblocks->jb_off += freecnt;
2861 	jblocks->jb_free -= freecnt;
2862 
2863 	return (daddr);
2864 }
2865 
2866 static void
2867 jblocks_free(jblocks, mp, bytes)
2868 	struct jblocks *jblocks;
2869 	struct mount *mp;
2870 	int bytes;
2871 {
2872 
2873 	LOCK_OWNED(VFSTOUFS(mp));
2874 	jblocks->jb_free += bytes / DEV_BSIZE;
2875 	if (jblocks->jb_suspended)
2876 		worklist_speedup(mp);
2877 	wakeup(jblocks);
2878 }
2879 
2880 static void
2881 jblocks_destroy(jblocks)
2882 	struct jblocks *jblocks;
2883 {
2884 
2885 	if (jblocks->jb_extent)
2886 		free(jblocks->jb_extent, M_JBLOCKS);
2887 	free(jblocks, M_JBLOCKS);
2888 }
2889 
2890 static void
2891 jblocks_add(jblocks, daddr, blocks)
2892 	struct jblocks *jblocks;
2893 	ufs2_daddr_t daddr;
2894 	int blocks;
2895 {
2896 	struct jextent *jext;
2897 
2898 	jblocks->jb_blocks += blocks;
2899 	jblocks->jb_free += blocks;
2900 	jext = &jblocks->jb_extent[jblocks->jb_used];
2901 	/* Adding the first block. */
2902 	if (jext->je_daddr == 0) {
2903 		jext->je_daddr = daddr;
2904 		jext->je_blocks = blocks;
2905 		return;
2906 	}
2907 	/* Extending the last extent. */
2908 	if (jext->je_daddr + jext->je_blocks == daddr) {
2909 		jext->je_blocks += blocks;
2910 		return;
2911 	}
2912 	/* Adding a new extent. */
2913 	if (++jblocks->jb_used == jblocks->jb_avail) {
2914 		jblocks->jb_avail *= 2;
2915 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2916 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2917 		memcpy(jext, jblocks->jb_extent,
2918 		    sizeof(struct jextent) * jblocks->jb_used);
2919 		free(jblocks->jb_extent, M_JBLOCKS);
2920 		jblocks->jb_extent = jext;
2921 	}
2922 	jext = &jblocks->jb_extent[jblocks->jb_used];
2923 	jext->je_daddr = daddr;
2924 	jext->je_blocks = blocks;
2925 	return;
2926 }
2927 
2928 int
2929 softdep_journal_lookup(mp, vpp)
2930 	struct mount *mp;
2931 	struct vnode **vpp;
2932 {
2933 	struct componentname cnp;
2934 	struct vnode *dvp;
2935 	ino_t sujournal;
2936 	int error;
2937 
2938 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2939 	if (error)
2940 		return (error);
2941 	bzero(&cnp, sizeof(cnp));
2942 	cnp.cn_nameiop = LOOKUP;
2943 	cnp.cn_flags = ISLASTCN;
2944 	cnp.cn_thread = curthread;
2945 	cnp.cn_cred = curthread->td_ucred;
2946 	cnp.cn_pnbuf = SUJ_FILE;
2947 	cnp.cn_nameptr = SUJ_FILE;
2948 	cnp.cn_namelen = strlen(SUJ_FILE);
2949 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2950 	vput(dvp);
2951 	if (error != 0)
2952 		return (error);
2953 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2954 	return (error);
2955 }
2956 
2957 /*
2958  * Open and verify the journal file.
2959  */
2960 static int
2961 journal_mount(mp, fs, cred)
2962 	struct mount *mp;
2963 	struct fs *fs;
2964 	struct ucred *cred;
2965 {
2966 	struct jblocks *jblocks;
2967 	struct ufsmount *ump;
2968 	struct vnode *vp;
2969 	struct inode *ip;
2970 	ufs2_daddr_t blkno;
2971 	int bcount;
2972 	int error;
2973 	int i;
2974 
2975 	ump = VFSTOUFS(mp);
2976 	ump->softdep_journal_tail = NULL;
2977 	ump->softdep_on_journal = 0;
2978 	ump->softdep_accdeps = 0;
2979 	ump->softdep_req = 0;
2980 	ump->softdep_jblocks = NULL;
2981 	error = softdep_journal_lookup(mp, &vp);
2982 	if (error != 0) {
2983 		printf("Failed to find journal.  Use tunefs to create one\n");
2984 		return (error);
2985 	}
2986 	ip = VTOI(vp);
2987 	if (ip->i_size < SUJ_MIN) {
2988 		error = ENOSPC;
2989 		goto out;
2990 	}
2991 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2992 	jblocks = jblocks_create();
2993 	for (i = 0; i < bcount; i++) {
2994 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2995 		if (error)
2996 			break;
2997 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2998 	}
2999 	if (error) {
3000 		jblocks_destroy(jblocks);
3001 		goto out;
3002 	}
3003 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
3004 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
3005 	ump->softdep_jblocks = jblocks;
3006 out:
3007 	if (error == 0) {
3008 		MNT_ILOCK(mp);
3009 		mp->mnt_flag |= MNT_SUJ;
3010 		mp->mnt_flag &= ~MNT_SOFTDEP;
3011 		MNT_IUNLOCK(mp);
3012 		/*
3013 		 * Only validate the journal contents if the
3014 		 * filesystem is clean, otherwise we write the logs
3015 		 * but they'll never be used.  If the filesystem was
3016 		 * still dirty when we mounted it the journal is
3017 		 * invalid and a new journal can only be valid if it
3018 		 * starts from a clean mount.
3019 		 */
3020 		if (fs->fs_clean) {
3021 			DIP_SET(ip, i_modrev, fs->fs_mtime);
3022 			ip->i_flags |= IN_MODIFIED;
3023 			ffs_update(vp, 1);
3024 		}
3025 	}
3026 	vput(vp);
3027 	return (error);
3028 }
3029 
3030 static void
3031 journal_unmount(ump)
3032 	struct ufsmount *ump;
3033 {
3034 
3035 	if (ump->softdep_jblocks)
3036 		jblocks_destroy(ump->softdep_jblocks);
3037 	ump->softdep_jblocks = NULL;
3038 }
3039 
3040 /*
3041  * Called when a journal record is ready to be written.  Space is allocated
3042  * and the journal entry is created when the journal is flushed to stable
3043  * store.
3044  */
3045 static void
3046 add_to_journal(wk)
3047 	struct worklist *wk;
3048 {
3049 	struct ufsmount *ump;
3050 
3051 	ump = VFSTOUFS(wk->wk_mp);
3052 	LOCK_OWNED(ump);
3053 	if (wk->wk_state & ONWORKLIST)
3054 		panic("add_to_journal: %s(0x%X) already on list",
3055 		    TYPENAME(wk->wk_type), wk->wk_state);
3056 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
3057 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
3058 		ump->softdep_jblocks->jb_age = ticks;
3059 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
3060 	} else
3061 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
3062 	ump->softdep_journal_tail = wk;
3063 	ump->softdep_on_journal += 1;
3064 }
3065 
3066 /*
3067  * Remove an arbitrary item for the journal worklist maintain the tail
3068  * pointer.  This happens when a new operation obviates the need to
3069  * journal an old operation.
3070  */
3071 static void
3072 remove_from_journal(wk)
3073 	struct worklist *wk;
3074 {
3075 	struct ufsmount *ump;
3076 
3077 	ump = VFSTOUFS(wk->wk_mp);
3078 	LOCK_OWNED(ump);
3079 #ifdef INVARIANTS
3080 	{
3081 		struct worklist *wkn;
3082 
3083 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
3084 			if (wkn == wk)
3085 				break;
3086 		if (wkn == NULL)
3087 			panic("remove_from_journal: %p is not in journal", wk);
3088 	}
3089 #endif
3090 	/*
3091 	 * We emulate a TAILQ to save space in most structures which do not
3092 	 * require TAILQ semantics.  Here we must update the tail position
3093 	 * when removing the tail which is not the final entry. This works
3094 	 * only if the worklist linkage are at the beginning of the structure.
3095 	 */
3096 	if (ump->softdep_journal_tail == wk)
3097 		ump->softdep_journal_tail =
3098 		    (struct worklist *)wk->wk_list.le_prev;
3099 	WORKLIST_REMOVE(wk);
3100 	ump->softdep_on_journal -= 1;
3101 }
3102 
3103 /*
3104  * Check for journal space as well as dependency limits so the prelink
3105  * code can throttle both journaled and non-journaled filesystems.
3106  * Threshold is 0 for low and 1 for min.
3107  */
3108 static int
3109 journal_space(ump, thresh)
3110 	struct ufsmount *ump;
3111 	int thresh;
3112 {
3113 	struct jblocks *jblocks;
3114 	int limit, avail;
3115 
3116 	jblocks = ump->softdep_jblocks;
3117 	if (jblocks == NULL)
3118 		return (1);
3119 	/*
3120 	 * We use a tighter restriction here to prevent request_cleanup()
3121 	 * running in threads from running into locks we currently hold.
3122 	 * We have to be over the limit and our filesystem has to be
3123 	 * responsible for more than our share of that usage.
3124 	 */
3125 	limit = (max_softdeps / 10) * 9;
3126 	if (dep_current[D_INODEDEP] > limit &&
3127 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
3128 		return (0);
3129 	if (thresh)
3130 		thresh = jblocks->jb_min;
3131 	else
3132 		thresh = jblocks->jb_low;
3133 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
3134 	avail = jblocks->jb_free - avail;
3135 
3136 	return (avail > thresh);
3137 }
3138 
3139 static void
3140 journal_suspend(ump)
3141 	struct ufsmount *ump;
3142 {
3143 	struct jblocks *jblocks;
3144 	struct mount *mp;
3145 	bool set;
3146 
3147 	mp = UFSTOVFS(ump);
3148 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
3149 		return;
3150 
3151 	jblocks = ump->softdep_jblocks;
3152 	vfs_op_enter(mp);
3153 	set = false;
3154 	MNT_ILOCK(mp);
3155 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
3156 		stat_journal_min++;
3157 		mp->mnt_kern_flag |= MNTK_SUSPEND;
3158 		mp->mnt_susp_owner = ump->softdep_flushtd;
3159 		set = true;
3160 	}
3161 	jblocks->jb_suspended = 1;
3162 	MNT_IUNLOCK(mp);
3163 	if (!set)
3164 		vfs_op_exit(mp);
3165 }
3166 
3167 static int
3168 journal_unsuspend(struct ufsmount *ump)
3169 {
3170 	struct jblocks *jblocks;
3171 	struct mount *mp;
3172 
3173 	mp = UFSTOVFS(ump);
3174 	jblocks = ump->softdep_jblocks;
3175 
3176 	if (jblocks != NULL && jblocks->jb_suspended &&
3177 	    journal_space(ump, jblocks->jb_min)) {
3178 		jblocks->jb_suspended = 0;
3179 		FREE_LOCK(ump);
3180 		mp->mnt_susp_owner = curthread;
3181 		vfs_write_resume(mp, 0);
3182 		ACQUIRE_LOCK(ump);
3183 		return (1);
3184 	}
3185 	return (0);
3186 }
3187 
3188 /*
3189  * Called before any allocation function to be certain that there is
3190  * sufficient space in the journal prior to creating any new records.
3191  * Since in the case of block allocation we may have multiple locked
3192  * buffers at the time of the actual allocation we can not block
3193  * when the journal records are created.  Doing so would create a deadlock
3194  * if any of these buffers needed to be flushed to reclaim space.  Instead
3195  * we require a sufficiently large amount of available space such that
3196  * each thread in the system could have passed this allocation check and
3197  * still have sufficient free space.  With 20% of a minimum journal size
3198  * of 1MB we have 6553 records available.
3199  */
3200 int
3201 softdep_prealloc(vp, waitok)
3202 	struct vnode *vp;
3203 	int waitok;
3204 {
3205 	struct ufsmount *ump;
3206 
3207 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3208 	    ("softdep_prealloc called on non-softdep filesystem"));
3209 	/*
3210 	 * Nothing to do if we are not running journaled soft updates.
3211 	 * If we currently hold the snapshot lock, we must avoid
3212 	 * handling other resources that could cause deadlock.  Do not
3213 	 * touch quotas vnode since it is typically recursed with
3214 	 * other vnode locks held.
3215 	 */
3216 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3217 	    (vp->v_vflag & VV_SYSTEM) != 0)
3218 		return (0);
3219 	ump = VFSTOUFS(vp->v_mount);
3220 	ACQUIRE_LOCK(ump);
3221 	if (journal_space(ump, 0)) {
3222 		FREE_LOCK(ump);
3223 		return (0);
3224 	}
3225 	stat_journal_low++;
3226 	FREE_LOCK(ump);
3227 	if (waitok == MNT_NOWAIT)
3228 		return (ENOSPC);
3229 	/*
3230 	 * Attempt to sync this vnode once to flush any journal
3231 	 * work attached to it.
3232 	 */
3233 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3234 		ffs_syncvnode(vp, waitok, 0);
3235 	ACQUIRE_LOCK(ump);
3236 	process_removes(vp);
3237 	process_truncates(vp);
3238 	if (journal_space(ump, 0) == 0) {
3239 		softdep_speedup(ump);
3240 		if (journal_space(ump, 1) == 0)
3241 			journal_suspend(ump);
3242 	}
3243 	FREE_LOCK(ump);
3244 
3245 	return (0);
3246 }
3247 
3248 /*
3249  * Try hard to sync all data and metadata for the vnode, and workitems
3250  * flushing which might conflict with the vnode lock.  This is a
3251  * helper for softdep_prerename().
3252  */
3253 static int
3254 softdep_prerename_vnode(ump, vp)
3255 	struct ufsmount *ump;
3256 	struct vnode *vp;
3257 {
3258 	int error;
3259 
3260 	ASSERT_VOP_ELOCKED(vp, "prehandle");
3261 	if (vp->v_data == NULL)
3262 		return (0);
3263 	error = VOP_FSYNC(vp, MNT_WAIT, curthread);
3264 	if (error != 0)
3265 		return (error);
3266 	ACQUIRE_LOCK(ump);
3267 	process_removes(vp);
3268 	process_truncates(vp);
3269 	FREE_LOCK(ump);
3270 	return (0);
3271 }
3272 
3273 /*
3274  * Must be called from VOP_RENAME() after all vnodes are locked.
3275  * Ensures that there is enough journal space for rename.  It is
3276  * sufficiently different from softdep_prelink() by having to handle
3277  * four vnodes.
3278  */
3279 int
3280 softdep_prerename(fdvp, fvp, tdvp, tvp)
3281 	struct vnode *fdvp;
3282 	struct vnode *fvp;
3283 	struct vnode *tdvp;
3284 	struct vnode *tvp;
3285 {
3286 	struct ufsmount *ump;
3287 	int error;
3288 
3289 	ump = VFSTOUFS(fdvp->v_mount);
3290 
3291 	if (journal_space(ump, 0))
3292 		return (0);
3293 
3294 	VOP_UNLOCK(tdvp);
3295 	VOP_UNLOCK(fvp);
3296 	if (tvp != NULL && tvp != tdvp)
3297 		VOP_UNLOCK(tvp);
3298 
3299 	error = softdep_prerename_vnode(ump, fdvp);
3300 	VOP_UNLOCK(fdvp);
3301 	if (error != 0)
3302 		return (error);
3303 
3304 	VOP_LOCK(fvp, LK_EXCLUSIVE | LK_RETRY);
3305 	error = softdep_prerename_vnode(ump, fvp);
3306 	VOP_UNLOCK(fvp);
3307 	if (error != 0)
3308 		return (error);
3309 
3310 	if (tdvp != fdvp) {
3311 		VOP_LOCK(tdvp, LK_EXCLUSIVE | LK_RETRY);
3312 		error = softdep_prerename_vnode(ump, tdvp);
3313 		VOP_UNLOCK(tdvp);
3314 		if (error != 0)
3315 			return (error);
3316 	}
3317 
3318 	if (tvp != fvp && tvp != NULL) {
3319 		VOP_LOCK(tvp, LK_EXCLUSIVE | LK_RETRY);
3320 		error = softdep_prerename_vnode(ump, tvp);
3321 		VOP_UNLOCK(tvp);
3322 		if (error != 0)
3323 			return (error);
3324 	}
3325 
3326 	ACQUIRE_LOCK(ump);
3327 	softdep_speedup(ump);
3328 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3329 	if (journal_space(ump, 0) == 0) {
3330 		softdep_speedup(ump);
3331 		if (journal_space(ump, 1) == 0)
3332 			journal_suspend(ump);
3333 	}
3334 	FREE_LOCK(ump);
3335 	return (ERELOOKUP);
3336 }
3337 
3338 /*
3339  * Before adjusting a link count on a vnode verify that we have sufficient
3340  * journal space.  If not, process operations that depend on the currently
3341  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3342  * and softdep flush threads can not acquire these locks to reclaim space.
3343  *
3344  * Returns 0 if all owned locks are still valid and were not dropped
3345  * in the process, in other case it returns either an error from sync,
3346  * or ERELOOKUP if any of the locks were re-acquired.  In the later
3347  * case, the state of the vnodes cannot be relied upon and our VFS
3348  * syscall must be restarted at top level from the lookup.
3349  */
3350 int
3351 softdep_prelink(dvp, vp, will_direnter)
3352 	struct vnode *dvp;
3353 	struct vnode *vp;
3354 	int will_direnter;
3355 {
3356 	struct ufsmount *ump;
3357 	int error, error1;
3358 
3359 	ASSERT_VOP_ELOCKED(dvp, "prelink dvp");
3360 	if (vp != NULL)
3361 		ASSERT_VOP_ELOCKED(vp, "prelink vp");
3362 	ump = VFSTOUFS(dvp->v_mount);
3363 
3364 	/*
3365 	 * Nothing to do if we have sufficient journal space.
3366 	 * If we currently hold the snapshot lock, we must avoid
3367 	 * handling other resources that could cause deadlock.
3368 	 *
3369 	 * will_direnter == 1: In case allocated a directory block in
3370 	 * an indirect block, we must prevent holes in the directory
3371 	 * created if directory entries are written out of order.  To
3372 	 * accomplish this we fsync when we extend a directory into
3373 	 * indirects.  During rename it's not safe to drop the tvp
3374 	 * lock so sync must be delayed until it is.
3375 	 *
3376 	 * This synchronous step could be removed if fsck and the
3377 	 * kernel were taught to fill in sparse directories rather
3378 	 * than panic.
3379 	 */
3380 	if (journal_space(ump, 0) || (vp != NULL && IS_SNAPSHOT(VTOI(vp)))) {
3381 		error = 0;
3382 		if (will_direnter && (vp == NULL || !IS_SNAPSHOT(VTOI(vp)))) {
3383 			if (vp != NULL)
3384 				VOP_UNLOCK(vp);
3385 			error = ffs_syncvnode(dvp, MNT_WAIT, 0);
3386 			if (vp != NULL) {
3387 				error1 = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3388 				if (error1 != 0) {
3389 					vn_lock_pair(dvp, true, vp, false);
3390 					if (error == 0)
3391 						error = ERELOOKUP;
3392 				} else if (vp->v_data == NULL) {
3393 					error = ERELOOKUP;
3394 				}
3395 			}
3396 		}
3397 		return (error);
3398 	}
3399 
3400 	stat_journal_low++;
3401 	if (vp != NULL) {
3402 		VOP_UNLOCK(dvp);
3403 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3404 		vn_lock_pair(dvp, false, vp, true);
3405 		if (dvp->v_data == NULL)
3406 			return (ERELOOKUP);
3407 	}
3408 	if (vp != NULL)
3409 		VOP_UNLOCK(vp);
3410 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3411 	VOP_UNLOCK(dvp);
3412 
3413 	/* Process vp before dvp as it may create .. removes. */
3414 	if (vp != NULL) {
3415 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3416 		if (vp->v_data == NULL) {
3417 			vn_lock_pair(dvp, false, vp, true);
3418 			return (ERELOOKUP);
3419 		}
3420 		ACQUIRE_LOCK(ump);
3421 		process_removes(vp);
3422 		process_truncates(vp);
3423 		FREE_LOCK(ump);
3424 		VOP_UNLOCK(vp);
3425 	}
3426 
3427 	vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
3428 	if (dvp->v_data == NULL) {
3429 		vn_lock_pair(dvp, true, vp, false);
3430 		return (ERELOOKUP);
3431 	}
3432 
3433 	ACQUIRE_LOCK(ump);
3434 	process_removes(dvp);
3435 	process_truncates(dvp);
3436 	VOP_UNLOCK(dvp);
3437 	softdep_speedup(ump);
3438 
3439 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3440 	if (journal_space(ump, 0) == 0) {
3441 		softdep_speedup(ump);
3442 		if (journal_space(ump, 1) == 0)
3443 			journal_suspend(ump);
3444 	}
3445 	FREE_LOCK(ump);
3446 
3447 	vn_lock_pair(dvp, false, vp, false);
3448 	return (ERELOOKUP);
3449 }
3450 
3451 static void
3452 jseg_write(ump, jseg, data)
3453 	struct ufsmount *ump;
3454 	struct jseg *jseg;
3455 	uint8_t *data;
3456 {
3457 	struct jsegrec *rec;
3458 
3459 	rec = (struct jsegrec *)data;
3460 	rec->jsr_seq = jseg->js_seq;
3461 	rec->jsr_oldest = jseg->js_oldseq;
3462 	rec->jsr_cnt = jseg->js_cnt;
3463 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3464 	rec->jsr_crc = 0;
3465 	rec->jsr_time = ump->um_fs->fs_mtime;
3466 }
3467 
3468 static inline void
3469 inoref_write(inoref, jseg, rec)
3470 	struct inoref *inoref;
3471 	struct jseg *jseg;
3472 	struct jrefrec *rec;
3473 {
3474 
3475 	inoref->if_jsegdep->jd_seg = jseg;
3476 	rec->jr_ino = inoref->if_ino;
3477 	rec->jr_parent = inoref->if_parent;
3478 	rec->jr_nlink = inoref->if_nlink;
3479 	rec->jr_mode = inoref->if_mode;
3480 	rec->jr_diroff = inoref->if_diroff;
3481 }
3482 
3483 static void
3484 jaddref_write(jaddref, jseg, data)
3485 	struct jaddref *jaddref;
3486 	struct jseg *jseg;
3487 	uint8_t *data;
3488 {
3489 	struct jrefrec *rec;
3490 
3491 	rec = (struct jrefrec *)data;
3492 	rec->jr_op = JOP_ADDREF;
3493 	inoref_write(&jaddref->ja_ref, jseg, rec);
3494 }
3495 
3496 static void
3497 jremref_write(jremref, jseg, data)
3498 	struct jremref *jremref;
3499 	struct jseg *jseg;
3500 	uint8_t *data;
3501 {
3502 	struct jrefrec *rec;
3503 
3504 	rec = (struct jrefrec *)data;
3505 	rec->jr_op = JOP_REMREF;
3506 	inoref_write(&jremref->jr_ref, jseg, rec);
3507 }
3508 
3509 static void
3510 jmvref_write(jmvref, jseg, data)
3511 	struct jmvref *jmvref;
3512 	struct jseg *jseg;
3513 	uint8_t *data;
3514 {
3515 	struct jmvrec *rec;
3516 
3517 	rec = (struct jmvrec *)data;
3518 	rec->jm_op = JOP_MVREF;
3519 	rec->jm_ino = jmvref->jm_ino;
3520 	rec->jm_parent = jmvref->jm_parent;
3521 	rec->jm_oldoff = jmvref->jm_oldoff;
3522 	rec->jm_newoff = jmvref->jm_newoff;
3523 }
3524 
3525 static void
3526 jnewblk_write(jnewblk, jseg, data)
3527 	struct jnewblk *jnewblk;
3528 	struct jseg *jseg;
3529 	uint8_t *data;
3530 {
3531 	struct jblkrec *rec;
3532 
3533 	jnewblk->jn_jsegdep->jd_seg = jseg;
3534 	rec = (struct jblkrec *)data;
3535 	rec->jb_op = JOP_NEWBLK;
3536 	rec->jb_ino = jnewblk->jn_ino;
3537 	rec->jb_blkno = jnewblk->jn_blkno;
3538 	rec->jb_lbn = jnewblk->jn_lbn;
3539 	rec->jb_frags = jnewblk->jn_frags;
3540 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3541 }
3542 
3543 static void
3544 jfreeblk_write(jfreeblk, jseg, data)
3545 	struct jfreeblk *jfreeblk;
3546 	struct jseg *jseg;
3547 	uint8_t *data;
3548 {
3549 	struct jblkrec *rec;
3550 
3551 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3552 	rec = (struct jblkrec *)data;
3553 	rec->jb_op = JOP_FREEBLK;
3554 	rec->jb_ino = jfreeblk->jf_ino;
3555 	rec->jb_blkno = jfreeblk->jf_blkno;
3556 	rec->jb_lbn = jfreeblk->jf_lbn;
3557 	rec->jb_frags = jfreeblk->jf_frags;
3558 	rec->jb_oldfrags = 0;
3559 }
3560 
3561 static void
3562 jfreefrag_write(jfreefrag, jseg, data)
3563 	struct jfreefrag *jfreefrag;
3564 	struct jseg *jseg;
3565 	uint8_t *data;
3566 {
3567 	struct jblkrec *rec;
3568 
3569 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3570 	rec = (struct jblkrec *)data;
3571 	rec->jb_op = JOP_FREEBLK;
3572 	rec->jb_ino = jfreefrag->fr_ino;
3573 	rec->jb_blkno = jfreefrag->fr_blkno;
3574 	rec->jb_lbn = jfreefrag->fr_lbn;
3575 	rec->jb_frags = jfreefrag->fr_frags;
3576 	rec->jb_oldfrags = 0;
3577 }
3578 
3579 static void
3580 jtrunc_write(jtrunc, jseg, data)
3581 	struct jtrunc *jtrunc;
3582 	struct jseg *jseg;
3583 	uint8_t *data;
3584 {
3585 	struct jtrncrec *rec;
3586 
3587 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3588 	rec = (struct jtrncrec *)data;
3589 	rec->jt_op = JOP_TRUNC;
3590 	rec->jt_ino = jtrunc->jt_ino;
3591 	rec->jt_size = jtrunc->jt_size;
3592 	rec->jt_extsize = jtrunc->jt_extsize;
3593 }
3594 
3595 static void
3596 jfsync_write(jfsync, jseg, data)
3597 	struct jfsync *jfsync;
3598 	struct jseg *jseg;
3599 	uint8_t *data;
3600 {
3601 	struct jtrncrec *rec;
3602 
3603 	rec = (struct jtrncrec *)data;
3604 	rec->jt_op = JOP_SYNC;
3605 	rec->jt_ino = jfsync->jfs_ino;
3606 	rec->jt_size = jfsync->jfs_size;
3607 	rec->jt_extsize = jfsync->jfs_extsize;
3608 }
3609 
3610 static void
3611 softdep_flushjournal(mp)
3612 	struct mount *mp;
3613 {
3614 	struct jblocks *jblocks;
3615 	struct ufsmount *ump;
3616 
3617 	if (MOUNTEDSUJ(mp) == 0)
3618 		return;
3619 	ump = VFSTOUFS(mp);
3620 	jblocks = ump->softdep_jblocks;
3621 	ACQUIRE_LOCK(ump);
3622 	while (ump->softdep_on_journal) {
3623 		jblocks->jb_needseg = 1;
3624 		softdep_process_journal(mp, NULL, MNT_WAIT);
3625 	}
3626 	FREE_LOCK(ump);
3627 }
3628 
3629 static void softdep_synchronize_completed(struct bio *);
3630 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3631 
3632 static void
3633 softdep_synchronize_completed(bp)
3634         struct bio *bp;
3635 {
3636 	struct jseg *oldest;
3637 	struct jseg *jseg;
3638 	struct ufsmount *ump;
3639 
3640 	/*
3641 	 * caller1 marks the last segment written before we issued the
3642 	 * synchronize cache.
3643 	 */
3644 	jseg = bp->bio_caller1;
3645 	if (jseg == NULL) {
3646 		g_destroy_bio(bp);
3647 		return;
3648 	}
3649 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3650 	ACQUIRE_LOCK(ump);
3651 	oldest = NULL;
3652 	/*
3653 	 * Mark all the journal entries waiting on the synchronize cache
3654 	 * as completed so they may continue on.
3655 	 */
3656 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3657 		jseg->js_state |= COMPLETE;
3658 		oldest = jseg;
3659 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3660 	}
3661 	/*
3662 	 * Restart deferred journal entry processing from the oldest
3663 	 * completed jseg.
3664 	 */
3665 	if (oldest)
3666 		complete_jsegs(oldest);
3667 
3668 	FREE_LOCK(ump);
3669 	g_destroy_bio(bp);
3670 }
3671 
3672 /*
3673  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3674  * barriers.  The journal must be written prior to any blocks that depend
3675  * on it and the journal can not be released until the blocks have be
3676  * written.  This code handles both barriers simultaneously.
3677  */
3678 static void
3679 softdep_synchronize(bp, ump, caller1)
3680 	struct bio *bp;
3681 	struct ufsmount *ump;
3682 	void *caller1;
3683 {
3684 
3685 	bp->bio_cmd = BIO_FLUSH;
3686 	bp->bio_flags |= BIO_ORDERED;
3687 	bp->bio_data = NULL;
3688 	bp->bio_offset = ump->um_cp->provider->mediasize;
3689 	bp->bio_length = 0;
3690 	bp->bio_done = softdep_synchronize_completed;
3691 	bp->bio_caller1 = caller1;
3692 	g_io_request(bp, ump->um_cp);
3693 }
3694 
3695 /*
3696  * Flush some journal records to disk.
3697  */
3698 static void
3699 softdep_process_journal(mp, needwk, flags)
3700 	struct mount *mp;
3701 	struct worklist *needwk;
3702 	int flags;
3703 {
3704 	struct jblocks *jblocks;
3705 	struct ufsmount *ump;
3706 	struct worklist *wk;
3707 	struct jseg *jseg;
3708 	struct buf *bp;
3709 	struct bio *bio;
3710 	uint8_t *data;
3711 	struct fs *fs;
3712 	int shouldflush;
3713 	int segwritten;
3714 	int jrecmin;	/* Minimum records per block. */
3715 	int jrecmax;	/* Maximum records per block. */
3716 	int size;
3717 	int cnt;
3718 	int off;
3719 	int devbsize;
3720 
3721 	if (MOUNTEDSUJ(mp) == 0)
3722 		return;
3723 	shouldflush = softdep_flushcache;
3724 	bio = NULL;
3725 	jseg = NULL;
3726 	ump = VFSTOUFS(mp);
3727 	LOCK_OWNED(ump);
3728 	fs = ump->um_fs;
3729 	jblocks = ump->softdep_jblocks;
3730 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3731 	/*
3732 	 * We write anywhere between a disk block and fs block.  The upper
3733 	 * bound is picked to prevent buffer cache fragmentation and limit
3734 	 * processing time per I/O.
3735 	 */
3736 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3737 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3738 	segwritten = 0;
3739 	for (;;) {
3740 		cnt = ump->softdep_on_journal;
3741 		/*
3742 		 * Criteria for writing a segment:
3743 		 * 1) We have a full block.
3744 		 * 2) We're called from jwait() and haven't found the
3745 		 *    journal item yet.
3746 		 * 3) Always write if needseg is set.
3747 		 * 4) If we are called from process_worklist and have
3748 		 *    not yet written anything we write a partial block
3749 		 *    to enforce a 1 second maximum latency on journal
3750 		 *    entries.
3751 		 */
3752 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3753 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3754 			break;
3755 		cnt++;
3756 		/*
3757 		 * Verify some free journal space.  softdep_prealloc() should
3758 		 * guarantee that we don't run out so this is indicative of
3759 		 * a problem with the flow control.  Try to recover
3760 		 * gracefully in any event.
3761 		 */
3762 		while (jblocks->jb_free == 0) {
3763 			if (flags != MNT_WAIT)
3764 				break;
3765 			printf("softdep: Out of journal space!\n");
3766 			softdep_speedup(ump);
3767 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3768 		}
3769 		FREE_LOCK(ump);
3770 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3771 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3772 		LIST_INIT(&jseg->js_entries);
3773 		LIST_INIT(&jseg->js_indirs);
3774 		jseg->js_state = ATTACHED;
3775 		if (shouldflush == 0)
3776 			jseg->js_state |= COMPLETE;
3777 		else if (bio == NULL)
3778 			bio = g_alloc_bio();
3779 		jseg->js_jblocks = jblocks;
3780 		bp = geteblk(fs->fs_bsize, 0);
3781 		ACQUIRE_LOCK(ump);
3782 		/*
3783 		 * If there was a race while we were allocating the block
3784 		 * and jseg the entry we care about was likely written.
3785 		 * We bail out in both the WAIT and NOWAIT case and assume
3786 		 * the caller will loop if the entry it cares about is
3787 		 * not written.
3788 		 */
3789 		cnt = ump->softdep_on_journal;
3790 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3791 			bp->b_flags |= B_INVAL | B_NOCACHE;
3792 			WORKITEM_FREE(jseg, D_JSEG);
3793 			FREE_LOCK(ump);
3794 			brelse(bp);
3795 			ACQUIRE_LOCK(ump);
3796 			break;
3797 		}
3798 		/*
3799 		 * Calculate the disk block size required for the available
3800 		 * records rounded to the min size.
3801 		 */
3802 		if (cnt == 0)
3803 			size = devbsize;
3804 		else if (cnt < jrecmax)
3805 			size = howmany(cnt, jrecmin) * devbsize;
3806 		else
3807 			size = fs->fs_bsize;
3808 		/*
3809 		 * Allocate a disk block for this journal data and account
3810 		 * for truncation of the requested size if enough contiguous
3811 		 * space was not available.
3812 		 */
3813 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3814 		bp->b_lblkno = bp->b_blkno;
3815 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3816 		bp->b_bcount = size;
3817 		bp->b_flags &= ~B_INVAL;
3818 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3819 		/*
3820 		 * Initialize our jseg with cnt records.  Assign the next
3821 		 * sequence number to it and link it in-order.
3822 		 */
3823 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3824 		jseg->js_buf = bp;
3825 		jseg->js_cnt = cnt;
3826 		jseg->js_refs = cnt + 1;	/* Self ref. */
3827 		jseg->js_size = size;
3828 		jseg->js_seq = jblocks->jb_nextseq++;
3829 		if (jblocks->jb_oldestseg == NULL)
3830 			jblocks->jb_oldestseg = jseg;
3831 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3832 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3833 		if (jblocks->jb_writeseg == NULL)
3834 			jblocks->jb_writeseg = jseg;
3835 		/*
3836 		 * Start filling in records from the pending list.
3837 		 */
3838 		data = bp->b_data;
3839 		off = 0;
3840 
3841 		/*
3842 		 * Always put a header on the first block.
3843 		 * XXX As with below, there might not be a chance to get
3844 		 * into the loop.  Ensure that something valid is written.
3845 		 */
3846 		jseg_write(ump, jseg, data);
3847 		off += JREC_SIZE;
3848 		data = bp->b_data + off;
3849 
3850 		/*
3851 		 * XXX Something is wrong here.  There's no work to do,
3852 		 * but we need to perform and I/O and allow it to complete
3853 		 * anyways.
3854 		 */
3855 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3856 			stat_emptyjblocks++;
3857 
3858 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3859 		    != NULL) {
3860 			if (cnt == 0)
3861 				break;
3862 			/* Place a segment header on every device block. */
3863 			if ((off % devbsize) == 0) {
3864 				jseg_write(ump, jseg, data);
3865 				off += JREC_SIZE;
3866 				data = bp->b_data + off;
3867 			}
3868 			if (wk == needwk)
3869 				needwk = NULL;
3870 			remove_from_journal(wk);
3871 			wk->wk_state |= INPROGRESS;
3872 			WORKLIST_INSERT(&jseg->js_entries, wk);
3873 			switch (wk->wk_type) {
3874 			case D_JADDREF:
3875 				jaddref_write(WK_JADDREF(wk), jseg, data);
3876 				break;
3877 			case D_JREMREF:
3878 				jremref_write(WK_JREMREF(wk), jseg, data);
3879 				break;
3880 			case D_JMVREF:
3881 				jmvref_write(WK_JMVREF(wk), jseg, data);
3882 				break;
3883 			case D_JNEWBLK:
3884 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3885 				break;
3886 			case D_JFREEBLK:
3887 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3888 				break;
3889 			case D_JFREEFRAG:
3890 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3891 				break;
3892 			case D_JTRUNC:
3893 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3894 				break;
3895 			case D_JFSYNC:
3896 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3897 				break;
3898 			default:
3899 				panic("process_journal: Unknown type %s",
3900 				    TYPENAME(wk->wk_type));
3901 				/* NOTREACHED */
3902 			}
3903 			off += JREC_SIZE;
3904 			data = bp->b_data + off;
3905 			cnt--;
3906 		}
3907 
3908 		/* Clear any remaining space so we don't leak kernel data */
3909 		if (size > off)
3910 			bzero(data, size - off);
3911 
3912 		/*
3913 		 * Write this one buffer and continue.
3914 		 */
3915 		segwritten = 1;
3916 		jblocks->jb_needseg = 0;
3917 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3918 		FREE_LOCK(ump);
3919 		bp->b_xflags |= BX_CVTENXIO;
3920 		pbgetvp(ump->um_devvp, bp);
3921 		/*
3922 		 * We only do the blocking wait once we find the journal
3923 		 * entry we're looking for.
3924 		 */
3925 		if (needwk == NULL && flags == MNT_WAIT)
3926 			bwrite(bp);
3927 		else
3928 			bawrite(bp);
3929 		ACQUIRE_LOCK(ump);
3930 	}
3931 	/*
3932 	 * If we wrote a segment issue a synchronize cache so the journal
3933 	 * is reflected on disk before the data is written.  Since reclaiming
3934 	 * journal space also requires writing a journal record this
3935 	 * process also enforces a barrier before reclamation.
3936 	 */
3937 	if (segwritten && shouldflush) {
3938 		softdep_synchronize(bio, ump,
3939 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3940 	} else if (bio)
3941 		g_destroy_bio(bio);
3942 	/*
3943 	 * If we've suspended the filesystem because we ran out of journal
3944 	 * space either try to sync it here to make some progress or
3945 	 * unsuspend it if we already have.
3946 	 */
3947 	if (flags == 0 && jblocks->jb_suspended) {
3948 		if (journal_unsuspend(ump))
3949 			return;
3950 		FREE_LOCK(ump);
3951 		VFS_SYNC(mp, MNT_NOWAIT);
3952 		ffs_sbupdate(ump, MNT_WAIT, 0);
3953 		ACQUIRE_LOCK(ump);
3954 	}
3955 }
3956 
3957 /*
3958  * Complete a jseg, allowing all dependencies awaiting journal writes
3959  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3960  * structures so that the journal segment can be freed to reclaim space.
3961  */
3962 static void
3963 complete_jseg(jseg)
3964 	struct jseg *jseg;
3965 {
3966 	struct worklist *wk;
3967 	struct jmvref *jmvref;
3968 #ifdef INVARIANTS
3969 	int i = 0;
3970 #endif
3971 
3972 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3973 		WORKLIST_REMOVE(wk);
3974 		wk->wk_state &= ~INPROGRESS;
3975 		wk->wk_state |= COMPLETE;
3976 		KASSERT(i++ < jseg->js_cnt,
3977 		    ("handle_written_jseg: overflow %d >= %d",
3978 		    i - 1, jseg->js_cnt));
3979 		switch (wk->wk_type) {
3980 		case D_JADDREF:
3981 			handle_written_jaddref(WK_JADDREF(wk));
3982 			break;
3983 		case D_JREMREF:
3984 			handle_written_jremref(WK_JREMREF(wk));
3985 			break;
3986 		case D_JMVREF:
3987 			rele_jseg(jseg);	/* No jsegdep. */
3988 			jmvref = WK_JMVREF(wk);
3989 			LIST_REMOVE(jmvref, jm_deps);
3990 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3991 				free_pagedep(jmvref->jm_pagedep);
3992 			WORKITEM_FREE(jmvref, D_JMVREF);
3993 			break;
3994 		case D_JNEWBLK:
3995 			handle_written_jnewblk(WK_JNEWBLK(wk));
3996 			break;
3997 		case D_JFREEBLK:
3998 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3999 			break;
4000 		case D_JTRUNC:
4001 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
4002 			break;
4003 		case D_JFSYNC:
4004 			rele_jseg(jseg);	/* No jsegdep. */
4005 			WORKITEM_FREE(wk, D_JFSYNC);
4006 			break;
4007 		case D_JFREEFRAG:
4008 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
4009 			break;
4010 		default:
4011 			panic("handle_written_jseg: Unknown type %s",
4012 			    TYPENAME(wk->wk_type));
4013 			/* NOTREACHED */
4014 		}
4015 	}
4016 	/* Release the self reference so the structure may be freed. */
4017 	rele_jseg(jseg);
4018 }
4019 
4020 /*
4021  * Determine which jsegs are ready for completion processing.  Waits for
4022  * synchronize cache to complete as well as forcing in-order completion
4023  * of journal entries.
4024  */
4025 static void
4026 complete_jsegs(jseg)
4027 	struct jseg *jseg;
4028 {
4029 	struct jblocks *jblocks;
4030 	struct jseg *jsegn;
4031 
4032 	jblocks = jseg->js_jblocks;
4033 	/*
4034 	 * Don't allow out of order completions.  If this isn't the first
4035 	 * block wait for it to write before we're done.
4036 	 */
4037 	if (jseg != jblocks->jb_writeseg)
4038 		return;
4039 	/* Iterate through available jsegs processing their entries. */
4040 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
4041 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
4042 		jsegn = TAILQ_NEXT(jseg, js_next);
4043 		complete_jseg(jseg);
4044 		jseg = jsegn;
4045 	}
4046 	jblocks->jb_writeseg = jseg;
4047 	/*
4048 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
4049 	 */
4050 	free_jsegs(jblocks);
4051 }
4052 
4053 /*
4054  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
4055  * the final completions.
4056  */
4057 static void
4058 handle_written_jseg(jseg, bp)
4059 	struct jseg *jseg;
4060 	struct buf *bp;
4061 {
4062 
4063 	if (jseg->js_refs == 0)
4064 		panic("handle_written_jseg: No self-reference on %p", jseg);
4065 	jseg->js_state |= DEPCOMPLETE;
4066 	/*
4067 	 * We'll never need this buffer again, set flags so it will be
4068 	 * discarded.
4069 	 */
4070 	bp->b_flags |= B_INVAL | B_NOCACHE;
4071 	pbrelvp(bp);
4072 	complete_jsegs(jseg);
4073 }
4074 
4075 static inline struct jsegdep *
4076 inoref_jseg(inoref)
4077 	struct inoref *inoref;
4078 {
4079 	struct jsegdep *jsegdep;
4080 
4081 	jsegdep = inoref->if_jsegdep;
4082 	inoref->if_jsegdep = NULL;
4083 
4084 	return (jsegdep);
4085 }
4086 
4087 /*
4088  * Called once a jremref has made it to stable store.  The jremref is marked
4089  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
4090  * for the jremref to complete will be awoken by free_jremref.
4091  */
4092 static void
4093 handle_written_jremref(jremref)
4094 	struct jremref *jremref;
4095 {
4096 	struct inodedep *inodedep;
4097 	struct jsegdep *jsegdep;
4098 	struct dirrem *dirrem;
4099 
4100 	/* Grab the jsegdep. */
4101 	jsegdep = inoref_jseg(&jremref->jr_ref);
4102 	/*
4103 	 * Remove us from the inoref list.
4104 	 */
4105 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
4106 	    0, &inodedep) == 0)
4107 		panic("handle_written_jremref: Lost inodedep");
4108 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
4109 	/*
4110 	 * Complete the dirrem.
4111 	 */
4112 	dirrem = jremref->jr_dirrem;
4113 	jremref->jr_dirrem = NULL;
4114 	LIST_REMOVE(jremref, jr_deps);
4115 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
4116 	jwork_insert(&dirrem->dm_jwork, jsegdep);
4117 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
4118 	    (dirrem->dm_state & COMPLETE) != 0)
4119 		add_to_worklist(&dirrem->dm_list, 0);
4120 	free_jremref(jremref);
4121 }
4122 
4123 /*
4124  * Called once a jaddref has made it to stable store.  The dependency is
4125  * marked complete and any dependent structures are added to the inode
4126  * bufwait list to be completed as soon as it is written.  If a bitmap write
4127  * depends on this entry we move the inode into the inodedephd of the
4128  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
4129  */
4130 static void
4131 handle_written_jaddref(jaddref)
4132 	struct jaddref *jaddref;
4133 {
4134 	struct jsegdep *jsegdep;
4135 	struct inodedep *inodedep;
4136 	struct diradd *diradd;
4137 	struct mkdir *mkdir;
4138 
4139 	/* Grab the jsegdep. */
4140 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4141 	mkdir = NULL;
4142 	diradd = NULL;
4143 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4144 	    0, &inodedep) == 0)
4145 		panic("handle_written_jaddref: Lost inodedep.");
4146 	if (jaddref->ja_diradd == NULL)
4147 		panic("handle_written_jaddref: No dependency");
4148 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
4149 		diradd = jaddref->ja_diradd;
4150 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
4151 	} else if (jaddref->ja_state & MKDIR_PARENT) {
4152 		mkdir = jaddref->ja_mkdir;
4153 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
4154 	} else if (jaddref->ja_state & MKDIR_BODY)
4155 		mkdir = jaddref->ja_mkdir;
4156 	else
4157 		panic("handle_written_jaddref: Unknown dependency %p",
4158 		    jaddref->ja_diradd);
4159 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
4160 	/*
4161 	 * Remove us from the inode list.
4162 	 */
4163 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
4164 	/*
4165 	 * The mkdir may be waiting on the jaddref to clear before freeing.
4166 	 */
4167 	if (mkdir) {
4168 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
4169 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
4170 		    TYPENAME(mkdir->md_list.wk_type)));
4171 		mkdir->md_jaddref = NULL;
4172 		diradd = mkdir->md_diradd;
4173 		mkdir->md_state |= DEPCOMPLETE;
4174 		complete_mkdir(mkdir);
4175 	}
4176 	jwork_insert(&diradd->da_jwork, jsegdep);
4177 	if (jaddref->ja_state & NEWBLOCK) {
4178 		inodedep->id_state |= ONDEPLIST;
4179 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
4180 		    inodedep, id_deps);
4181 	}
4182 	free_jaddref(jaddref);
4183 }
4184 
4185 /*
4186  * Called once a jnewblk journal is written.  The allocdirect or allocindir
4187  * is placed in the bmsafemap to await notification of a written bitmap.  If
4188  * the operation was canceled we add the segdep to the appropriate
4189  * dependency to free the journal space once the canceling operation
4190  * completes.
4191  */
4192 static void
4193 handle_written_jnewblk(jnewblk)
4194 	struct jnewblk *jnewblk;
4195 {
4196 	struct bmsafemap *bmsafemap;
4197 	struct freefrag *freefrag;
4198 	struct freework *freework;
4199 	struct jsegdep *jsegdep;
4200 	struct newblk *newblk;
4201 
4202 	/* Grab the jsegdep. */
4203 	jsegdep = jnewblk->jn_jsegdep;
4204 	jnewblk->jn_jsegdep = NULL;
4205 	if (jnewblk->jn_dep == NULL)
4206 		panic("handle_written_jnewblk: No dependency for the segdep.");
4207 	switch (jnewblk->jn_dep->wk_type) {
4208 	case D_NEWBLK:
4209 	case D_ALLOCDIRECT:
4210 	case D_ALLOCINDIR:
4211 		/*
4212 		 * Add the written block to the bmsafemap so it can
4213 		 * be notified when the bitmap is on disk.
4214 		 */
4215 		newblk = WK_NEWBLK(jnewblk->jn_dep);
4216 		newblk->nb_jnewblk = NULL;
4217 		if ((newblk->nb_state & GOINGAWAY) == 0) {
4218 			bmsafemap = newblk->nb_bmsafemap;
4219 			newblk->nb_state |= ONDEPLIST;
4220 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
4221 			    nb_deps);
4222 		}
4223 		jwork_insert(&newblk->nb_jwork, jsegdep);
4224 		break;
4225 	case D_FREEFRAG:
4226 		/*
4227 		 * A newblock being removed by a freefrag when replaced by
4228 		 * frag extension.
4229 		 */
4230 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
4231 		freefrag->ff_jdep = NULL;
4232 		jwork_insert(&freefrag->ff_jwork, jsegdep);
4233 		break;
4234 	case D_FREEWORK:
4235 		/*
4236 		 * A direct block was removed by truncate.
4237 		 */
4238 		freework = WK_FREEWORK(jnewblk->jn_dep);
4239 		freework->fw_jnewblk = NULL;
4240 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
4241 		break;
4242 	default:
4243 		panic("handle_written_jnewblk: Unknown type %d.",
4244 		    jnewblk->jn_dep->wk_type);
4245 	}
4246 	jnewblk->jn_dep = NULL;
4247 	free_jnewblk(jnewblk);
4248 }
4249 
4250 /*
4251  * Cancel a jfreefrag that won't be needed, probably due to colliding with
4252  * an in-flight allocation that has not yet been committed.  Divorce us
4253  * from the freefrag and mark it DEPCOMPLETE so that it may be added
4254  * to the worklist.
4255  */
4256 static void
4257 cancel_jfreefrag(jfreefrag)
4258 	struct jfreefrag *jfreefrag;
4259 {
4260 	struct freefrag *freefrag;
4261 
4262 	if (jfreefrag->fr_jsegdep) {
4263 		free_jsegdep(jfreefrag->fr_jsegdep);
4264 		jfreefrag->fr_jsegdep = NULL;
4265 	}
4266 	freefrag = jfreefrag->fr_freefrag;
4267 	jfreefrag->fr_freefrag = NULL;
4268 	free_jfreefrag(jfreefrag);
4269 	freefrag->ff_state |= DEPCOMPLETE;
4270 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
4271 }
4272 
4273 /*
4274  * Free a jfreefrag when the parent freefrag is rendered obsolete.
4275  */
4276 static void
4277 free_jfreefrag(jfreefrag)
4278 	struct jfreefrag *jfreefrag;
4279 {
4280 
4281 	if (jfreefrag->fr_state & INPROGRESS)
4282 		WORKLIST_REMOVE(&jfreefrag->fr_list);
4283 	else if (jfreefrag->fr_state & ONWORKLIST)
4284 		remove_from_journal(&jfreefrag->fr_list);
4285 	if (jfreefrag->fr_freefrag != NULL)
4286 		panic("free_jfreefrag:  Still attached to a freefrag.");
4287 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
4288 }
4289 
4290 /*
4291  * Called when the journal write for a jfreefrag completes.  The parent
4292  * freefrag is added to the worklist if this completes its dependencies.
4293  */
4294 static void
4295 handle_written_jfreefrag(jfreefrag)
4296 	struct jfreefrag *jfreefrag;
4297 {
4298 	struct jsegdep *jsegdep;
4299 	struct freefrag *freefrag;
4300 
4301 	/* Grab the jsegdep. */
4302 	jsegdep = jfreefrag->fr_jsegdep;
4303 	jfreefrag->fr_jsegdep = NULL;
4304 	freefrag = jfreefrag->fr_freefrag;
4305 	if (freefrag == NULL)
4306 		panic("handle_written_jfreefrag: No freefrag.");
4307 	freefrag->ff_state |= DEPCOMPLETE;
4308 	freefrag->ff_jdep = NULL;
4309 	jwork_insert(&freefrag->ff_jwork, jsegdep);
4310 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
4311 		add_to_worklist(&freefrag->ff_list, 0);
4312 	jfreefrag->fr_freefrag = NULL;
4313 	free_jfreefrag(jfreefrag);
4314 }
4315 
4316 /*
4317  * Called when the journal write for a jfreeblk completes.  The jfreeblk
4318  * is removed from the freeblks list of pending journal writes and the
4319  * jsegdep is moved to the freeblks jwork to be completed when all blocks
4320  * have been reclaimed.
4321  */
4322 static void
4323 handle_written_jblkdep(jblkdep)
4324 	struct jblkdep *jblkdep;
4325 {
4326 	struct freeblks *freeblks;
4327 	struct jsegdep *jsegdep;
4328 
4329 	/* Grab the jsegdep. */
4330 	jsegdep = jblkdep->jb_jsegdep;
4331 	jblkdep->jb_jsegdep = NULL;
4332 	freeblks = jblkdep->jb_freeblks;
4333 	LIST_REMOVE(jblkdep, jb_deps);
4334 	jwork_insert(&freeblks->fb_jwork, jsegdep);
4335 	/*
4336 	 * If the freeblks is all journaled, we can add it to the worklist.
4337 	 */
4338 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4339 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4340 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4341 
4342 	free_jblkdep(jblkdep);
4343 }
4344 
4345 static struct jsegdep *
4346 newjsegdep(struct worklist *wk)
4347 {
4348 	struct jsegdep *jsegdep;
4349 
4350 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4351 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4352 	jsegdep->jd_seg = NULL;
4353 
4354 	return (jsegdep);
4355 }
4356 
4357 static struct jmvref *
4358 newjmvref(dp, ino, oldoff, newoff)
4359 	struct inode *dp;
4360 	ino_t ino;
4361 	off_t oldoff;
4362 	off_t newoff;
4363 {
4364 	struct jmvref *jmvref;
4365 
4366 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4367 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4368 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4369 	jmvref->jm_parent = dp->i_number;
4370 	jmvref->jm_ino = ino;
4371 	jmvref->jm_oldoff = oldoff;
4372 	jmvref->jm_newoff = newoff;
4373 
4374 	return (jmvref);
4375 }
4376 
4377 /*
4378  * Allocate a new jremref that tracks the removal of ip from dp with the
4379  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4380  * DEPCOMPLETE as we have all the information required for the journal write
4381  * and the directory has already been removed from the buffer.  The caller
4382  * is responsible for linking the jremref into the pagedep and adding it
4383  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4384  * a DOTDOT addition so handle_workitem_remove() can properly assign
4385  * the jsegdep when we're done.
4386  */
4387 static struct jremref *
4388 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4389     off_t diroff, nlink_t nlink)
4390 {
4391 	struct jremref *jremref;
4392 
4393 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4394 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4395 	jremref->jr_state = ATTACHED;
4396 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4397 	   nlink, ip->i_mode);
4398 	jremref->jr_dirrem = dirrem;
4399 
4400 	return (jremref);
4401 }
4402 
4403 static inline void
4404 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4405     nlink_t nlink, uint16_t mode)
4406 {
4407 
4408 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4409 	inoref->if_diroff = diroff;
4410 	inoref->if_ino = ino;
4411 	inoref->if_parent = parent;
4412 	inoref->if_nlink = nlink;
4413 	inoref->if_mode = mode;
4414 }
4415 
4416 /*
4417  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4418  * directory offset may not be known until later.  The caller is responsible
4419  * adding the entry to the journal when this information is available.  nlink
4420  * should be the link count prior to the addition and mode is only required
4421  * to have the correct FMT.
4422  */
4423 static struct jaddref *
4424 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4425     uint16_t mode)
4426 {
4427 	struct jaddref *jaddref;
4428 
4429 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4430 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4431 	jaddref->ja_state = ATTACHED;
4432 	jaddref->ja_mkdir = NULL;
4433 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4434 
4435 	return (jaddref);
4436 }
4437 
4438 /*
4439  * Create a new free dependency for a freework.  The caller is responsible
4440  * for adjusting the reference count when it has the lock held.  The freedep
4441  * will track an outstanding bitmap write that will ultimately clear the
4442  * freework to continue.
4443  */
4444 static struct freedep *
4445 newfreedep(struct freework *freework)
4446 {
4447 	struct freedep *freedep;
4448 
4449 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4450 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4451 	freedep->fd_freework = freework;
4452 
4453 	return (freedep);
4454 }
4455 
4456 /*
4457  * Free a freedep structure once the buffer it is linked to is written.  If
4458  * this is the last reference to the freework schedule it for completion.
4459  */
4460 static void
4461 free_freedep(freedep)
4462 	struct freedep *freedep;
4463 {
4464 	struct freework *freework;
4465 
4466 	freework = freedep->fd_freework;
4467 	freework->fw_freeblks->fb_cgwait--;
4468 	if (--freework->fw_ref == 0)
4469 		freework_enqueue(freework);
4470 	WORKITEM_FREE(freedep, D_FREEDEP);
4471 }
4472 
4473 /*
4474  * Allocate a new freework structure that may be a level in an indirect
4475  * when parent is not NULL or a top level block when it is.  The top level
4476  * freework structures are allocated without the per-filesystem lock held
4477  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4478  */
4479 static struct freework *
4480 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4481 	struct ufsmount *ump;
4482 	struct freeblks *freeblks;
4483 	struct freework *parent;
4484 	ufs_lbn_t lbn;
4485 	ufs2_daddr_t nb;
4486 	int frags;
4487 	int off;
4488 	int journal;
4489 {
4490 	struct freework *freework;
4491 
4492 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4493 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4494 	freework->fw_state = ATTACHED;
4495 	freework->fw_jnewblk = NULL;
4496 	freework->fw_freeblks = freeblks;
4497 	freework->fw_parent = parent;
4498 	freework->fw_lbn = lbn;
4499 	freework->fw_blkno = nb;
4500 	freework->fw_frags = frags;
4501 	freework->fw_indir = NULL;
4502 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4503 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4504 	freework->fw_start = freework->fw_off = off;
4505 	if (journal)
4506 		newjfreeblk(freeblks, lbn, nb, frags);
4507 	if (parent == NULL) {
4508 		ACQUIRE_LOCK(ump);
4509 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4510 		freeblks->fb_ref++;
4511 		FREE_LOCK(ump);
4512 	}
4513 
4514 	return (freework);
4515 }
4516 
4517 /*
4518  * Eliminate a jfreeblk for a block that does not need journaling.
4519  */
4520 static void
4521 cancel_jfreeblk(freeblks, blkno)
4522 	struct freeblks *freeblks;
4523 	ufs2_daddr_t blkno;
4524 {
4525 	struct jfreeblk *jfreeblk;
4526 	struct jblkdep *jblkdep;
4527 
4528 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4529 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4530 			continue;
4531 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4532 		if (jfreeblk->jf_blkno == blkno)
4533 			break;
4534 	}
4535 	if (jblkdep == NULL)
4536 		return;
4537 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4538 	free_jsegdep(jblkdep->jb_jsegdep);
4539 	LIST_REMOVE(jblkdep, jb_deps);
4540 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4541 }
4542 
4543 /*
4544  * Allocate a new jfreeblk to journal top level block pointer when truncating
4545  * a file.  The caller must add this to the worklist when the per-filesystem
4546  * lock is held.
4547  */
4548 static struct jfreeblk *
4549 newjfreeblk(freeblks, lbn, blkno, frags)
4550 	struct freeblks *freeblks;
4551 	ufs_lbn_t lbn;
4552 	ufs2_daddr_t blkno;
4553 	int frags;
4554 {
4555 	struct jfreeblk *jfreeblk;
4556 
4557 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4558 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4559 	    freeblks->fb_list.wk_mp);
4560 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4561 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4562 	jfreeblk->jf_ino = freeblks->fb_inum;
4563 	jfreeblk->jf_lbn = lbn;
4564 	jfreeblk->jf_blkno = blkno;
4565 	jfreeblk->jf_frags = frags;
4566 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4567 
4568 	return (jfreeblk);
4569 }
4570 
4571 /*
4572  * The journal is only prepared to handle full-size block numbers, so we
4573  * have to adjust the record to reflect the change to a full-size block.
4574  * For example, suppose we have a block made up of fragments 8-15 and
4575  * want to free its last two fragments. We are given a request that says:
4576  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4577  * where frags are the number of fragments to free and oldfrags are the
4578  * number of fragments to keep. To block align it, we have to change it to
4579  * have a valid full-size blkno, so it becomes:
4580  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4581  */
4582 static void
4583 adjust_newfreework(freeblks, frag_offset)
4584 	struct freeblks *freeblks;
4585 	int frag_offset;
4586 {
4587 	struct jfreeblk *jfreeblk;
4588 
4589 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4590 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4591 	    ("adjust_newfreework: Missing freeblks dependency"));
4592 
4593 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4594 	jfreeblk->jf_blkno -= frag_offset;
4595 	jfreeblk->jf_frags += frag_offset;
4596 }
4597 
4598 /*
4599  * Allocate a new jtrunc to track a partial truncation.
4600  */
4601 static struct jtrunc *
4602 newjtrunc(freeblks, size, extsize)
4603 	struct freeblks *freeblks;
4604 	off_t size;
4605 	int extsize;
4606 {
4607 	struct jtrunc *jtrunc;
4608 
4609 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4610 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4611 	    freeblks->fb_list.wk_mp);
4612 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4613 	jtrunc->jt_dep.jb_freeblks = freeblks;
4614 	jtrunc->jt_ino = freeblks->fb_inum;
4615 	jtrunc->jt_size = size;
4616 	jtrunc->jt_extsize = extsize;
4617 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4618 
4619 	return (jtrunc);
4620 }
4621 
4622 /*
4623  * If we're canceling a new bitmap we have to search for another ref
4624  * to move into the bmsafemap dep.  This might be better expressed
4625  * with another structure.
4626  */
4627 static void
4628 move_newblock_dep(jaddref, inodedep)
4629 	struct jaddref *jaddref;
4630 	struct inodedep *inodedep;
4631 {
4632 	struct inoref *inoref;
4633 	struct jaddref *jaddrefn;
4634 
4635 	jaddrefn = NULL;
4636 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4637 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4638 		if ((jaddref->ja_state & NEWBLOCK) &&
4639 		    inoref->if_list.wk_type == D_JADDREF) {
4640 			jaddrefn = (struct jaddref *)inoref;
4641 			break;
4642 		}
4643 	}
4644 	if (jaddrefn == NULL)
4645 		return;
4646 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4647 	jaddrefn->ja_state |= jaddref->ja_state &
4648 	    (ATTACHED | UNDONE | NEWBLOCK);
4649 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4650 	jaddref->ja_state |= ATTACHED;
4651 	LIST_REMOVE(jaddref, ja_bmdeps);
4652 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4653 	    ja_bmdeps);
4654 }
4655 
4656 /*
4657  * Cancel a jaddref either before it has been written or while it is being
4658  * written.  This happens when a link is removed before the add reaches
4659  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4660  * and inode to prevent the link count or bitmap from reaching the disk
4661  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4662  * required.
4663  *
4664  * Returns 1 if the canceled addref requires journaling of the remove and
4665  * 0 otherwise.
4666  */
4667 static int
4668 cancel_jaddref(jaddref, inodedep, wkhd)
4669 	struct jaddref *jaddref;
4670 	struct inodedep *inodedep;
4671 	struct workhead *wkhd;
4672 {
4673 	struct inoref *inoref;
4674 	struct jsegdep *jsegdep;
4675 	int needsj;
4676 
4677 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4678 	    ("cancel_jaddref: Canceling complete jaddref"));
4679 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4680 		needsj = 1;
4681 	else
4682 		needsj = 0;
4683 	if (inodedep == NULL)
4684 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4685 		    0, &inodedep) == 0)
4686 			panic("cancel_jaddref: Lost inodedep");
4687 	/*
4688 	 * We must adjust the nlink of any reference operation that follows
4689 	 * us so that it is consistent with the in-memory reference.  This
4690 	 * ensures that inode nlink rollbacks always have the correct link.
4691 	 */
4692 	if (needsj == 0) {
4693 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4694 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4695 			if (inoref->if_state & GOINGAWAY)
4696 				break;
4697 			inoref->if_nlink--;
4698 		}
4699 	}
4700 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4701 	if (jaddref->ja_state & NEWBLOCK)
4702 		move_newblock_dep(jaddref, inodedep);
4703 	wake_worklist(&jaddref->ja_list);
4704 	jaddref->ja_mkdir = NULL;
4705 	if (jaddref->ja_state & INPROGRESS) {
4706 		jaddref->ja_state &= ~INPROGRESS;
4707 		WORKLIST_REMOVE(&jaddref->ja_list);
4708 		jwork_insert(wkhd, jsegdep);
4709 	} else {
4710 		free_jsegdep(jsegdep);
4711 		if (jaddref->ja_state & DEPCOMPLETE)
4712 			remove_from_journal(&jaddref->ja_list);
4713 	}
4714 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4715 	/*
4716 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4717 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4718 	 * no longer need this addref attached to the inoreflst and it
4719 	 * will incorrectly adjust nlink if we leave it.
4720 	 */
4721 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4722 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4723 		    if_deps);
4724 		jaddref->ja_state |= COMPLETE;
4725 		free_jaddref(jaddref);
4726 		return (needsj);
4727 	}
4728 	/*
4729 	 * Leave the head of the list for jsegdeps for fast merging.
4730 	 */
4731 	if (LIST_FIRST(wkhd) != NULL) {
4732 		jaddref->ja_state |= ONWORKLIST;
4733 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4734 	} else
4735 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4736 
4737 	return (needsj);
4738 }
4739 
4740 /*
4741  * Attempt to free a jaddref structure when some work completes.  This
4742  * should only succeed once the entry is written and all dependencies have
4743  * been notified.
4744  */
4745 static void
4746 free_jaddref(jaddref)
4747 	struct jaddref *jaddref;
4748 {
4749 
4750 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4751 		return;
4752 	if (jaddref->ja_ref.if_jsegdep)
4753 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4754 		    jaddref, jaddref->ja_state);
4755 	if (jaddref->ja_state & NEWBLOCK)
4756 		LIST_REMOVE(jaddref, ja_bmdeps);
4757 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4758 		panic("free_jaddref: Bad state %p(0x%X)",
4759 		    jaddref, jaddref->ja_state);
4760 	if (jaddref->ja_mkdir != NULL)
4761 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4762 	WORKITEM_FREE(jaddref, D_JADDREF);
4763 }
4764 
4765 /*
4766  * Free a jremref structure once it has been written or discarded.
4767  */
4768 static void
4769 free_jremref(jremref)
4770 	struct jremref *jremref;
4771 {
4772 
4773 	if (jremref->jr_ref.if_jsegdep)
4774 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4775 	if (jremref->jr_state & INPROGRESS)
4776 		panic("free_jremref: IO still pending");
4777 	WORKITEM_FREE(jremref, D_JREMREF);
4778 }
4779 
4780 /*
4781  * Free a jnewblk structure.
4782  */
4783 static void
4784 free_jnewblk(jnewblk)
4785 	struct jnewblk *jnewblk;
4786 {
4787 
4788 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4789 		return;
4790 	LIST_REMOVE(jnewblk, jn_deps);
4791 	if (jnewblk->jn_dep != NULL)
4792 		panic("free_jnewblk: Dependency still attached.");
4793 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4794 }
4795 
4796 /*
4797  * Cancel a jnewblk which has been been made redundant by frag extension.
4798  */
4799 static void
4800 cancel_jnewblk(jnewblk, wkhd)
4801 	struct jnewblk *jnewblk;
4802 	struct workhead *wkhd;
4803 {
4804 	struct jsegdep *jsegdep;
4805 
4806 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4807 	jsegdep = jnewblk->jn_jsegdep;
4808 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4809 		panic("cancel_jnewblk: Invalid state");
4810 	jnewblk->jn_jsegdep  = NULL;
4811 	jnewblk->jn_dep = NULL;
4812 	jnewblk->jn_state |= GOINGAWAY;
4813 	if (jnewblk->jn_state & INPROGRESS) {
4814 		jnewblk->jn_state &= ~INPROGRESS;
4815 		WORKLIST_REMOVE(&jnewblk->jn_list);
4816 		jwork_insert(wkhd, jsegdep);
4817 	} else {
4818 		free_jsegdep(jsegdep);
4819 		remove_from_journal(&jnewblk->jn_list);
4820 	}
4821 	wake_worklist(&jnewblk->jn_list);
4822 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4823 }
4824 
4825 static void
4826 free_jblkdep(jblkdep)
4827 	struct jblkdep *jblkdep;
4828 {
4829 
4830 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4831 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4832 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4833 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4834 	else
4835 		panic("free_jblkdep: Unexpected type %s",
4836 		    TYPENAME(jblkdep->jb_list.wk_type));
4837 }
4838 
4839 /*
4840  * Free a single jseg once it is no longer referenced in memory or on
4841  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4842  * to disappear.
4843  */
4844 static void
4845 free_jseg(jseg, jblocks)
4846 	struct jseg *jseg;
4847 	struct jblocks *jblocks;
4848 {
4849 	struct freework *freework;
4850 
4851 	/*
4852 	 * Free freework structures that were lingering to indicate freed
4853 	 * indirect blocks that forced journal write ordering on reallocate.
4854 	 */
4855 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4856 		indirblk_remove(freework);
4857 	if (jblocks->jb_oldestseg == jseg)
4858 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4859 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4860 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4861 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4862 	    ("free_jseg: Freed jseg has valid entries."));
4863 	WORKITEM_FREE(jseg, D_JSEG);
4864 }
4865 
4866 /*
4867  * Free all jsegs that meet the criteria for being reclaimed and update
4868  * oldestseg.
4869  */
4870 static void
4871 free_jsegs(jblocks)
4872 	struct jblocks *jblocks;
4873 {
4874 	struct jseg *jseg;
4875 
4876 	/*
4877 	 * Free only those jsegs which have none allocated before them to
4878 	 * preserve the journal space ordering.
4879 	 */
4880 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4881 		/*
4882 		 * Only reclaim space when nothing depends on this journal
4883 		 * set and another set has written that it is no longer
4884 		 * valid.
4885 		 */
4886 		if (jseg->js_refs != 0) {
4887 			jblocks->jb_oldestseg = jseg;
4888 			return;
4889 		}
4890 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4891 			break;
4892 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4893 			break;
4894 		/*
4895 		 * We can free jsegs that didn't write entries when
4896 		 * oldestwrseq == js_seq.
4897 		 */
4898 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4899 		    jseg->js_cnt != 0)
4900 			break;
4901 		free_jseg(jseg, jblocks);
4902 	}
4903 	/*
4904 	 * If we exited the loop above we still must discover the
4905 	 * oldest valid segment.
4906 	 */
4907 	if (jseg)
4908 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4909 		     jseg = TAILQ_NEXT(jseg, js_next))
4910 			if (jseg->js_refs != 0)
4911 				break;
4912 	jblocks->jb_oldestseg = jseg;
4913 	/*
4914 	 * The journal has no valid records but some jsegs may still be
4915 	 * waiting on oldestwrseq to advance.  We force a small record
4916 	 * out to permit these lingering records to be reclaimed.
4917 	 */
4918 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4919 		jblocks->jb_needseg = 1;
4920 }
4921 
4922 /*
4923  * Release one reference to a jseg and free it if the count reaches 0.  This
4924  * should eventually reclaim journal space as well.
4925  */
4926 static void
4927 rele_jseg(jseg)
4928 	struct jseg *jseg;
4929 {
4930 
4931 	KASSERT(jseg->js_refs > 0,
4932 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4933 	if (--jseg->js_refs != 0)
4934 		return;
4935 	free_jsegs(jseg->js_jblocks);
4936 }
4937 
4938 /*
4939  * Release a jsegdep and decrement the jseg count.
4940  */
4941 static void
4942 free_jsegdep(jsegdep)
4943 	struct jsegdep *jsegdep;
4944 {
4945 
4946 	if (jsegdep->jd_seg)
4947 		rele_jseg(jsegdep->jd_seg);
4948 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4949 }
4950 
4951 /*
4952  * Wait for a journal item to make it to disk.  Initiate journal processing
4953  * if required.
4954  */
4955 static int
4956 jwait(wk, waitfor)
4957 	struct worklist *wk;
4958 	int waitfor;
4959 {
4960 
4961 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4962 	/*
4963 	 * Blocking journal waits cause slow synchronous behavior.  Record
4964 	 * stats on the frequency of these blocking operations.
4965 	 */
4966 	if (waitfor == MNT_WAIT) {
4967 		stat_journal_wait++;
4968 		switch (wk->wk_type) {
4969 		case D_JREMREF:
4970 		case D_JMVREF:
4971 			stat_jwait_filepage++;
4972 			break;
4973 		case D_JTRUNC:
4974 		case D_JFREEBLK:
4975 			stat_jwait_freeblks++;
4976 			break;
4977 		case D_JNEWBLK:
4978 			stat_jwait_newblk++;
4979 			break;
4980 		case D_JADDREF:
4981 			stat_jwait_inode++;
4982 			break;
4983 		default:
4984 			break;
4985 		}
4986 	}
4987 	/*
4988 	 * If IO has not started we process the journal.  We can't mark the
4989 	 * worklist item as IOWAITING because we drop the lock while
4990 	 * processing the journal and the worklist entry may be freed after
4991 	 * this point.  The caller may call back in and re-issue the request.
4992 	 */
4993 	if ((wk->wk_state & INPROGRESS) == 0) {
4994 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4995 		if (waitfor != MNT_WAIT)
4996 			return (EBUSY);
4997 		return (0);
4998 	}
4999 	if (waitfor != MNT_WAIT)
5000 		return (EBUSY);
5001 	wait_worklist(wk, "jwait");
5002 	return (0);
5003 }
5004 
5005 /*
5006  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
5007  * appropriate.  This is a convenience function to reduce duplicate code
5008  * for the setup and revert functions below.
5009  */
5010 static struct inodedep *
5011 inodedep_lookup_ip(ip)
5012 	struct inode *ip;
5013 {
5014 	struct inodedep *inodedep;
5015 
5016 	KASSERT(ip->i_nlink >= ip->i_effnlink,
5017 	    ("inodedep_lookup_ip: bad delta"));
5018 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
5019 	    &inodedep);
5020 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
5021 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
5022 
5023 	return (inodedep);
5024 }
5025 
5026 /*
5027  * Called prior to creating a new inode and linking it to a directory.  The
5028  * jaddref structure must already be allocated by softdep_setup_inomapdep
5029  * and it is discovered here so we can initialize the mode and update
5030  * nlinkdelta.
5031  */
5032 void
5033 softdep_setup_create(dp, ip)
5034 	struct inode *dp;
5035 	struct inode *ip;
5036 {
5037 	struct inodedep *inodedep;
5038 	struct jaddref *jaddref;
5039 	struct vnode *dvp;
5040 
5041 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5042 	    ("softdep_setup_create called on non-softdep filesystem"));
5043 	KASSERT(ip->i_nlink == 1,
5044 	    ("softdep_setup_create: Invalid link count."));
5045 	dvp = ITOV(dp);
5046 	ACQUIRE_LOCK(ITOUMP(dp));
5047 	inodedep = inodedep_lookup_ip(ip);
5048 	if (DOINGSUJ(dvp)) {
5049 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5050 		    inoreflst);
5051 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
5052 		    ("softdep_setup_create: No addref structure present."));
5053 	}
5054 	FREE_LOCK(ITOUMP(dp));
5055 }
5056 
5057 /*
5058  * Create a jaddref structure to track the addition of a DOTDOT link when
5059  * we are reparenting an inode as part of a rename.  This jaddref will be
5060  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
5061  * non-journaling softdep.
5062  */
5063 void
5064 softdep_setup_dotdot_link(dp, ip)
5065 	struct inode *dp;
5066 	struct inode *ip;
5067 {
5068 	struct inodedep *inodedep;
5069 	struct jaddref *jaddref;
5070 	struct vnode *dvp;
5071 
5072 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5073 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
5074 	dvp = ITOV(dp);
5075 	jaddref = NULL;
5076 	/*
5077 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
5078 	 * is used as a normal link would be.
5079 	 */
5080 	if (DOINGSUJ(dvp))
5081 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5082 		    dp->i_effnlink - 1, dp->i_mode);
5083 	ACQUIRE_LOCK(ITOUMP(dp));
5084 	inodedep = inodedep_lookup_ip(dp);
5085 	if (jaddref)
5086 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5087 		    if_deps);
5088 	FREE_LOCK(ITOUMP(dp));
5089 }
5090 
5091 /*
5092  * Create a jaddref structure to track a new link to an inode.  The directory
5093  * offset is not known until softdep_setup_directory_add or
5094  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
5095  * softdep.
5096  */
5097 void
5098 softdep_setup_link(dp, ip)
5099 	struct inode *dp;
5100 	struct inode *ip;
5101 {
5102 	struct inodedep *inodedep;
5103 	struct jaddref *jaddref;
5104 	struct vnode *dvp;
5105 
5106 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5107 	    ("softdep_setup_link called on non-softdep filesystem"));
5108 	dvp = ITOV(dp);
5109 	jaddref = NULL;
5110 	if (DOINGSUJ(dvp))
5111 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
5112 		    ip->i_mode);
5113 	ACQUIRE_LOCK(ITOUMP(dp));
5114 	inodedep = inodedep_lookup_ip(ip);
5115 	if (jaddref)
5116 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5117 		    if_deps);
5118 	FREE_LOCK(ITOUMP(dp));
5119 }
5120 
5121 /*
5122  * Called to create the jaddref structures to track . and .. references as
5123  * well as lookup and further initialize the incomplete jaddref created
5124  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
5125  * nlinkdelta for non-journaling softdep.
5126  */
5127 void
5128 softdep_setup_mkdir(dp, ip)
5129 	struct inode *dp;
5130 	struct inode *ip;
5131 {
5132 	struct inodedep *inodedep;
5133 	struct jaddref *dotdotaddref;
5134 	struct jaddref *dotaddref;
5135 	struct jaddref *jaddref;
5136 	struct vnode *dvp;
5137 
5138 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5139 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
5140 	dvp = ITOV(dp);
5141 	dotaddref = dotdotaddref = NULL;
5142 	if (DOINGSUJ(dvp)) {
5143 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
5144 		    ip->i_mode);
5145 		dotaddref->ja_state |= MKDIR_BODY;
5146 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5147 		    dp->i_effnlink - 1, dp->i_mode);
5148 		dotdotaddref->ja_state |= MKDIR_PARENT;
5149 	}
5150 	ACQUIRE_LOCK(ITOUMP(dp));
5151 	inodedep = inodedep_lookup_ip(ip);
5152 	if (DOINGSUJ(dvp)) {
5153 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5154 		    inoreflst);
5155 		KASSERT(jaddref != NULL,
5156 		    ("softdep_setup_mkdir: No addref structure present."));
5157 		KASSERT(jaddref->ja_parent == dp->i_number,
5158 		    ("softdep_setup_mkdir: bad parent %ju",
5159 		    (uintmax_t)jaddref->ja_parent));
5160 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
5161 		    if_deps);
5162 	}
5163 	inodedep = inodedep_lookup_ip(dp);
5164 	if (DOINGSUJ(dvp))
5165 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
5166 		    &dotdotaddref->ja_ref, if_deps);
5167 	FREE_LOCK(ITOUMP(dp));
5168 }
5169 
5170 /*
5171  * Called to track nlinkdelta of the inode and parent directories prior to
5172  * unlinking a directory.
5173  */
5174 void
5175 softdep_setup_rmdir(dp, ip)
5176 	struct inode *dp;
5177 	struct inode *ip;
5178 {
5179 	struct vnode *dvp;
5180 
5181 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5182 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
5183 	dvp = ITOV(dp);
5184 	ACQUIRE_LOCK(ITOUMP(dp));
5185 	(void) inodedep_lookup_ip(ip);
5186 	(void) inodedep_lookup_ip(dp);
5187 	FREE_LOCK(ITOUMP(dp));
5188 }
5189 
5190 /*
5191  * Called to track nlinkdelta of the inode and parent directories prior to
5192  * unlink.
5193  */
5194 void
5195 softdep_setup_unlink(dp, ip)
5196 	struct inode *dp;
5197 	struct inode *ip;
5198 {
5199 	struct vnode *dvp;
5200 
5201 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5202 	    ("softdep_setup_unlink called on non-softdep filesystem"));
5203 	dvp = ITOV(dp);
5204 	ACQUIRE_LOCK(ITOUMP(dp));
5205 	(void) inodedep_lookup_ip(ip);
5206 	(void) inodedep_lookup_ip(dp);
5207 	FREE_LOCK(ITOUMP(dp));
5208 }
5209 
5210 /*
5211  * Called to release the journal structures created by a failed non-directory
5212  * creation.  Adjusts nlinkdelta for non-journaling softdep.
5213  */
5214 void
5215 softdep_revert_create(dp, ip)
5216 	struct inode *dp;
5217 	struct inode *ip;
5218 {
5219 	struct inodedep *inodedep;
5220 	struct jaddref *jaddref;
5221 	struct vnode *dvp;
5222 
5223 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
5224 	    ("softdep_revert_create called on non-softdep filesystem"));
5225 	dvp = ITOV(dp);
5226 	ACQUIRE_LOCK(ITOUMP(dp));
5227 	inodedep = inodedep_lookup_ip(ip);
5228 	if (DOINGSUJ(dvp)) {
5229 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5230 		    inoreflst);
5231 		KASSERT(jaddref->ja_parent == dp->i_number,
5232 		    ("softdep_revert_create: addref parent mismatch"));
5233 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5234 	}
5235 	FREE_LOCK(ITOUMP(dp));
5236 }
5237 
5238 /*
5239  * Called to release the journal structures created by a failed link
5240  * addition.  Adjusts nlinkdelta for non-journaling softdep.
5241  */
5242 void
5243 softdep_revert_link(dp, ip)
5244 	struct inode *dp;
5245 	struct inode *ip;
5246 {
5247 	struct inodedep *inodedep;
5248 	struct jaddref *jaddref;
5249 	struct vnode *dvp;
5250 
5251 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5252 	    ("softdep_revert_link called on non-softdep filesystem"));
5253 	dvp = ITOV(dp);
5254 	ACQUIRE_LOCK(ITOUMP(dp));
5255 	inodedep = inodedep_lookup_ip(ip);
5256 	if (DOINGSUJ(dvp)) {
5257 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5258 		    inoreflst);
5259 		KASSERT(jaddref->ja_parent == dp->i_number,
5260 		    ("softdep_revert_link: addref parent mismatch"));
5261 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5262 	}
5263 	FREE_LOCK(ITOUMP(dp));
5264 }
5265 
5266 /*
5267  * Called to release the journal structures created by a failed mkdir
5268  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
5269  */
5270 void
5271 softdep_revert_mkdir(dp, ip)
5272 	struct inode *dp;
5273 	struct inode *ip;
5274 {
5275 	struct inodedep *inodedep;
5276 	struct jaddref *jaddref;
5277 	struct jaddref *dotaddref;
5278 	struct vnode *dvp;
5279 
5280 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5281 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
5282 	dvp = ITOV(dp);
5283 
5284 	ACQUIRE_LOCK(ITOUMP(dp));
5285 	inodedep = inodedep_lookup_ip(dp);
5286 	if (DOINGSUJ(dvp)) {
5287 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5288 		    inoreflst);
5289 		KASSERT(jaddref->ja_parent == ip->i_number,
5290 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
5291 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5292 	}
5293 	inodedep = inodedep_lookup_ip(ip);
5294 	if (DOINGSUJ(dvp)) {
5295 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5296 		    inoreflst);
5297 		KASSERT(jaddref->ja_parent == dp->i_number,
5298 		    ("softdep_revert_mkdir: addref parent mismatch"));
5299 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
5300 		    inoreflst, if_deps);
5301 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5302 		KASSERT(dotaddref->ja_parent == ip->i_number,
5303 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
5304 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
5305 	}
5306 	FREE_LOCK(ITOUMP(dp));
5307 }
5308 
5309 /*
5310  * Called to correct nlinkdelta after a failed rmdir.
5311  */
5312 void
5313 softdep_revert_rmdir(dp, ip)
5314 	struct inode *dp;
5315 	struct inode *ip;
5316 {
5317 
5318 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5319 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
5320 	ACQUIRE_LOCK(ITOUMP(dp));
5321 	(void) inodedep_lookup_ip(ip);
5322 	(void) inodedep_lookup_ip(dp);
5323 	FREE_LOCK(ITOUMP(dp));
5324 }
5325 
5326 /*
5327  * Protecting the freemaps (or bitmaps).
5328  *
5329  * To eliminate the need to execute fsck before mounting a filesystem
5330  * after a power failure, one must (conservatively) guarantee that the
5331  * on-disk copy of the bitmaps never indicate that a live inode or block is
5332  * free.  So, when a block or inode is allocated, the bitmap should be
5333  * updated (on disk) before any new pointers.  When a block or inode is
5334  * freed, the bitmap should not be updated until all pointers have been
5335  * reset.  The latter dependency is handled by the delayed de-allocation
5336  * approach described below for block and inode de-allocation.  The former
5337  * dependency is handled by calling the following procedure when a block or
5338  * inode is allocated. When an inode is allocated an "inodedep" is created
5339  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5340  * Each "inodedep" is also inserted into the hash indexing structure so
5341  * that any additional link additions can be made dependent on the inode
5342  * allocation.
5343  *
5344  * The ufs filesystem maintains a number of free block counts (e.g., per
5345  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5346  * in addition to the bitmaps.  These counts are used to improve efficiency
5347  * during allocation and therefore must be consistent with the bitmaps.
5348  * There is no convenient way to guarantee post-crash consistency of these
5349  * counts with simple update ordering, for two main reasons: (1) The counts
5350  * and bitmaps for a single cylinder group block are not in the same disk
5351  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5352  * be written and the other not.  (2) Some of the counts are located in the
5353  * superblock rather than the cylinder group block. So, we focus our soft
5354  * updates implementation on protecting the bitmaps. When mounting a
5355  * filesystem, we recompute the auxiliary counts from the bitmaps.
5356  */
5357 
5358 /*
5359  * Called just after updating the cylinder group block to allocate an inode.
5360  */
5361 void
5362 softdep_setup_inomapdep(bp, ip, newinum, mode)
5363 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5364 	struct inode *ip;	/* inode related to allocation */
5365 	ino_t newinum;		/* new inode number being allocated */
5366 	int mode;
5367 {
5368 	struct inodedep *inodedep;
5369 	struct bmsafemap *bmsafemap;
5370 	struct jaddref *jaddref;
5371 	struct mount *mp;
5372 	struct fs *fs;
5373 
5374 	mp = ITOVFS(ip);
5375 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5376 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5377 	fs = VFSTOUFS(mp)->um_fs;
5378 	jaddref = NULL;
5379 
5380 	/*
5381 	 * Allocate the journal reference add structure so that the bitmap
5382 	 * can be dependent on it.
5383 	 */
5384 	if (MOUNTEDSUJ(mp)) {
5385 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5386 		jaddref->ja_state |= NEWBLOCK;
5387 	}
5388 
5389 	/*
5390 	 * Create a dependency for the newly allocated inode.
5391 	 * Panic if it already exists as something is seriously wrong.
5392 	 * Otherwise add it to the dependency list for the buffer holding
5393 	 * the cylinder group map from which it was allocated.
5394 	 *
5395 	 * We have to preallocate a bmsafemap entry in case it is needed
5396 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5397 	 * have to finish initializing it before we can FREE_LOCK().
5398 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5399 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5400 	 * creating the inodedep as it can be freed during the time
5401 	 * that we FREE_LOCK() while allocating the inodedep. We must
5402 	 * call workitem_alloc() before entering the locked section as
5403 	 * it also acquires the lock and we must avoid trying doing so
5404 	 * recursively.
5405 	 */
5406 	bmsafemap = malloc(sizeof(struct bmsafemap),
5407 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5408 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5409 	ACQUIRE_LOCK(ITOUMP(ip));
5410 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5411 		panic("softdep_setup_inomapdep: dependency %p for new"
5412 		    "inode already exists", inodedep);
5413 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5414 	if (jaddref) {
5415 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5416 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5417 		    if_deps);
5418 	} else {
5419 		inodedep->id_state |= ONDEPLIST;
5420 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5421 	}
5422 	inodedep->id_bmsafemap = bmsafemap;
5423 	inodedep->id_state &= ~DEPCOMPLETE;
5424 	FREE_LOCK(ITOUMP(ip));
5425 }
5426 
5427 /*
5428  * Called just after updating the cylinder group block to
5429  * allocate block or fragment.
5430  */
5431 void
5432 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5433 	struct buf *bp;		/* buffer for cylgroup block with block map */
5434 	struct mount *mp;	/* filesystem doing allocation */
5435 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5436 	int frags;		/* Number of fragments. */
5437 	int oldfrags;		/* Previous number of fragments for extend. */
5438 {
5439 	struct newblk *newblk;
5440 	struct bmsafemap *bmsafemap;
5441 	struct jnewblk *jnewblk;
5442 	struct ufsmount *ump;
5443 	struct fs *fs;
5444 
5445 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5446 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5447 	ump = VFSTOUFS(mp);
5448 	fs = ump->um_fs;
5449 	jnewblk = NULL;
5450 	/*
5451 	 * Create a dependency for the newly allocated block.
5452 	 * Add it to the dependency list for the buffer holding
5453 	 * the cylinder group map from which it was allocated.
5454 	 */
5455 	if (MOUNTEDSUJ(mp)) {
5456 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5457 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5458 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5459 		jnewblk->jn_state = ATTACHED;
5460 		jnewblk->jn_blkno = newblkno;
5461 		jnewblk->jn_frags = frags;
5462 		jnewblk->jn_oldfrags = oldfrags;
5463 #ifdef INVARIANTS
5464 		{
5465 			struct cg *cgp;
5466 			uint8_t *blksfree;
5467 			long bno;
5468 			int i;
5469 
5470 			cgp = (struct cg *)bp->b_data;
5471 			blksfree = cg_blksfree(cgp);
5472 			bno = dtogd(fs, jnewblk->jn_blkno);
5473 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5474 			    i++) {
5475 				if (isset(blksfree, bno + i))
5476 					panic("softdep_setup_blkmapdep: "
5477 					    "free fragment %d from %d-%d "
5478 					    "state 0x%X dep %p", i,
5479 					    jnewblk->jn_oldfrags,
5480 					    jnewblk->jn_frags,
5481 					    jnewblk->jn_state,
5482 					    jnewblk->jn_dep);
5483 			}
5484 		}
5485 #endif
5486 	}
5487 
5488 	CTR3(KTR_SUJ,
5489 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5490 	    newblkno, frags, oldfrags);
5491 	ACQUIRE_LOCK(ump);
5492 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5493 		panic("softdep_setup_blkmapdep: found block");
5494 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5495 	    dtog(fs, newblkno), NULL);
5496 	if (jnewblk) {
5497 		jnewblk->jn_dep = (struct worklist *)newblk;
5498 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5499 	} else {
5500 		newblk->nb_state |= ONDEPLIST;
5501 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5502 	}
5503 	newblk->nb_bmsafemap = bmsafemap;
5504 	newblk->nb_jnewblk = jnewblk;
5505 	FREE_LOCK(ump);
5506 }
5507 
5508 #define	BMSAFEMAP_HASH(ump, cg) \
5509       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5510 
5511 static int
5512 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5513 	struct bmsafemap_hashhead *bmsafemaphd;
5514 	int cg;
5515 	struct bmsafemap **bmsafemapp;
5516 {
5517 	struct bmsafemap *bmsafemap;
5518 
5519 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5520 		if (bmsafemap->sm_cg == cg)
5521 			break;
5522 	if (bmsafemap) {
5523 		*bmsafemapp = bmsafemap;
5524 		return (1);
5525 	}
5526 	*bmsafemapp = NULL;
5527 
5528 	return (0);
5529 }
5530 
5531 /*
5532  * Find the bmsafemap associated with a cylinder group buffer.
5533  * If none exists, create one. The buffer must be locked when
5534  * this routine is called and this routine must be called with
5535  * the softdep lock held. To avoid giving up the lock while
5536  * allocating a new bmsafemap, a preallocated bmsafemap may be
5537  * provided. If it is provided but not needed, it is freed.
5538  */
5539 static struct bmsafemap *
5540 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5541 	struct mount *mp;
5542 	struct buf *bp;
5543 	int cg;
5544 	struct bmsafemap *newbmsafemap;
5545 {
5546 	struct bmsafemap_hashhead *bmsafemaphd;
5547 	struct bmsafemap *bmsafemap, *collision;
5548 	struct worklist *wk;
5549 	struct ufsmount *ump;
5550 
5551 	ump = VFSTOUFS(mp);
5552 	LOCK_OWNED(ump);
5553 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5554 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5555 		if (wk->wk_type == D_BMSAFEMAP) {
5556 			if (newbmsafemap)
5557 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5558 			return (WK_BMSAFEMAP(wk));
5559 		}
5560 	}
5561 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5562 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5563 		if (newbmsafemap)
5564 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5565 		return (bmsafemap);
5566 	}
5567 	if (newbmsafemap) {
5568 		bmsafemap = newbmsafemap;
5569 	} else {
5570 		FREE_LOCK(ump);
5571 		bmsafemap = malloc(sizeof(struct bmsafemap),
5572 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5573 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5574 		ACQUIRE_LOCK(ump);
5575 	}
5576 	bmsafemap->sm_buf = bp;
5577 	LIST_INIT(&bmsafemap->sm_inodedephd);
5578 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5579 	LIST_INIT(&bmsafemap->sm_newblkhd);
5580 	LIST_INIT(&bmsafemap->sm_newblkwr);
5581 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5582 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5583 	LIST_INIT(&bmsafemap->sm_freehd);
5584 	LIST_INIT(&bmsafemap->sm_freewr);
5585 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5586 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5587 		return (collision);
5588 	}
5589 	bmsafemap->sm_cg = cg;
5590 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5591 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5592 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5593 	return (bmsafemap);
5594 }
5595 
5596 /*
5597  * Direct block allocation dependencies.
5598  *
5599  * When a new block is allocated, the corresponding disk locations must be
5600  * initialized (with zeros or new data) before the on-disk inode points to
5601  * them.  Also, the freemap from which the block was allocated must be
5602  * updated (on disk) before the inode's pointer. These two dependencies are
5603  * independent of each other and are needed for all file blocks and indirect
5604  * blocks that are pointed to directly by the inode.  Just before the
5605  * "in-core" version of the inode is updated with a newly allocated block
5606  * number, a procedure (below) is called to setup allocation dependency
5607  * structures.  These structures are removed when the corresponding
5608  * dependencies are satisfied or when the block allocation becomes obsolete
5609  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5610  * fragment that gets upgraded).  All of these cases are handled in
5611  * procedures described later.
5612  *
5613  * When a file extension causes a fragment to be upgraded, either to a larger
5614  * fragment or to a full block, the on-disk location may change (if the
5615  * previous fragment could not simply be extended). In this case, the old
5616  * fragment must be de-allocated, but not until after the inode's pointer has
5617  * been updated. In most cases, this is handled by later procedures, which
5618  * will construct a "freefrag" structure to be added to the workitem queue
5619  * when the inode update is complete (or obsolete).  The main exception to
5620  * this is when an allocation occurs while a pending allocation dependency
5621  * (for the same block pointer) remains.  This case is handled in the main
5622  * allocation dependency setup procedure by immediately freeing the
5623  * unreferenced fragments.
5624  */
5625 void
5626 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5627 	struct inode *ip;	/* inode to which block is being added */
5628 	ufs_lbn_t off;		/* block pointer within inode */
5629 	ufs2_daddr_t newblkno;	/* disk block number being added */
5630 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5631 	long newsize;		/* size of new block */
5632 	long oldsize;		/* size of new block */
5633 	struct buf *bp;		/* bp for allocated block */
5634 {
5635 	struct allocdirect *adp, *oldadp;
5636 	struct allocdirectlst *adphead;
5637 	struct freefrag *freefrag;
5638 	struct inodedep *inodedep;
5639 	struct pagedep *pagedep;
5640 	struct jnewblk *jnewblk;
5641 	struct newblk *newblk;
5642 	struct mount *mp;
5643 	ufs_lbn_t lbn;
5644 
5645 	lbn = bp->b_lblkno;
5646 	mp = ITOVFS(ip);
5647 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5648 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5649 	if (oldblkno && oldblkno != newblkno)
5650 		/*
5651 		 * The usual case is that a smaller fragment that
5652 		 * was just allocated has been replaced with a bigger
5653 		 * fragment or a full-size block. If it is marked as
5654 		 * B_DELWRI, the current contents have not been written
5655 		 * to disk. It is possible that the block was written
5656 		 * earlier, but very uncommon. If the block has never
5657 		 * been written, there is no need to send a BIO_DELETE
5658 		 * for it when it is freed. The gain from avoiding the
5659 		 * TRIMs for the common case of unwritten blocks far
5660 		 * exceeds the cost of the write amplification for the
5661 		 * uncommon case of failing to send a TRIM for a block
5662 		 * that had been written.
5663 		 */
5664 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5665 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5666 	else
5667 		freefrag = NULL;
5668 
5669 	CTR6(KTR_SUJ,
5670 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5671 	    "off %jd newsize %ld oldsize %d",
5672 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5673 	ACQUIRE_LOCK(ITOUMP(ip));
5674 	if (off >= UFS_NDADDR) {
5675 		if (lbn > 0)
5676 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5677 			    lbn, off);
5678 		/* allocating an indirect block */
5679 		if (oldblkno != 0)
5680 			panic("softdep_setup_allocdirect: non-zero indir");
5681 	} else {
5682 		if (off != lbn)
5683 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5684 			    lbn, off);
5685 		/*
5686 		 * Allocating a direct block.
5687 		 *
5688 		 * If we are allocating a directory block, then we must
5689 		 * allocate an associated pagedep to track additions and
5690 		 * deletions.
5691 		 */
5692 		if ((ip->i_mode & IFMT) == IFDIR)
5693 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5694 			    &pagedep);
5695 	}
5696 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5697 		panic("softdep_setup_allocdirect: lost block");
5698 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5699 	    ("softdep_setup_allocdirect: newblk already initialized"));
5700 	/*
5701 	 * Convert the newblk to an allocdirect.
5702 	 */
5703 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5704 	adp = (struct allocdirect *)newblk;
5705 	newblk->nb_freefrag = freefrag;
5706 	adp->ad_offset = off;
5707 	adp->ad_oldblkno = oldblkno;
5708 	adp->ad_newsize = newsize;
5709 	adp->ad_oldsize = oldsize;
5710 
5711 	/*
5712 	 * Finish initializing the journal.
5713 	 */
5714 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5715 		jnewblk->jn_ino = ip->i_number;
5716 		jnewblk->jn_lbn = lbn;
5717 		add_to_journal(&jnewblk->jn_list);
5718 	}
5719 	if (freefrag && freefrag->ff_jdep != NULL &&
5720 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5721 		add_to_journal(freefrag->ff_jdep);
5722 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5723 	adp->ad_inodedep = inodedep;
5724 
5725 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5726 	/*
5727 	 * The list of allocdirects must be kept in sorted and ascending
5728 	 * order so that the rollback routines can quickly determine the
5729 	 * first uncommitted block (the size of the file stored on disk
5730 	 * ends at the end of the lowest committed fragment, or if there
5731 	 * are no fragments, at the end of the highest committed block).
5732 	 * Since files generally grow, the typical case is that the new
5733 	 * block is to be added at the end of the list. We speed this
5734 	 * special case by checking against the last allocdirect in the
5735 	 * list before laboriously traversing the list looking for the
5736 	 * insertion point.
5737 	 */
5738 	adphead = &inodedep->id_newinoupdt;
5739 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5740 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5741 		/* insert at end of list */
5742 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5743 		if (oldadp != NULL && oldadp->ad_offset == off)
5744 			allocdirect_merge(adphead, adp, oldadp);
5745 		FREE_LOCK(ITOUMP(ip));
5746 		return;
5747 	}
5748 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5749 		if (oldadp->ad_offset >= off)
5750 			break;
5751 	}
5752 	if (oldadp == NULL)
5753 		panic("softdep_setup_allocdirect: lost entry");
5754 	/* insert in middle of list */
5755 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5756 	if (oldadp->ad_offset == off)
5757 		allocdirect_merge(adphead, adp, oldadp);
5758 
5759 	FREE_LOCK(ITOUMP(ip));
5760 }
5761 
5762 /*
5763  * Merge a newer and older journal record to be stored either in a
5764  * newblock or freefrag.  This handles aggregating journal records for
5765  * fragment allocation into a second record as well as replacing a
5766  * journal free with an aborted journal allocation.  A segment for the
5767  * oldest record will be placed on wkhd if it has been written.  If not
5768  * the segment for the newer record will suffice.
5769  */
5770 static struct worklist *
5771 jnewblk_merge(new, old, wkhd)
5772 	struct worklist *new;
5773 	struct worklist *old;
5774 	struct workhead *wkhd;
5775 {
5776 	struct jnewblk *njnewblk;
5777 	struct jnewblk *jnewblk;
5778 
5779 	/* Handle NULLs to simplify callers. */
5780 	if (new == NULL)
5781 		return (old);
5782 	if (old == NULL)
5783 		return (new);
5784 	/* Replace a jfreefrag with a jnewblk. */
5785 	if (new->wk_type == D_JFREEFRAG) {
5786 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5787 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5788 			    old, new);
5789 		cancel_jfreefrag(WK_JFREEFRAG(new));
5790 		return (old);
5791 	}
5792 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5793 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5794 		    old->wk_type, new->wk_type);
5795 	/*
5796 	 * Handle merging of two jnewblk records that describe
5797 	 * different sets of fragments in the same block.
5798 	 */
5799 	jnewblk = WK_JNEWBLK(old);
5800 	njnewblk = WK_JNEWBLK(new);
5801 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5802 		panic("jnewblk_merge: Merging disparate blocks.");
5803 	/*
5804 	 * The record may be rolled back in the cg.
5805 	 */
5806 	if (jnewblk->jn_state & UNDONE) {
5807 		jnewblk->jn_state &= ~UNDONE;
5808 		njnewblk->jn_state |= UNDONE;
5809 		njnewblk->jn_state &= ~ATTACHED;
5810 	}
5811 	/*
5812 	 * We modify the newer addref and free the older so that if neither
5813 	 * has been written the most up-to-date copy will be on disk.  If
5814 	 * both have been written but rolled back we only temporarily need
5815 	 * one of them to fix the bits when the cg write completes.
5816 	 */
5817 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5818 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5819 	cancel_jnewblk(jnewblk, wkhd);
5820 	WORKLIST_REMOVE(&jnewblk->jn_list);
5821 	free_jnewblk(jnewblk);
5822 	return (new);
5823 }
5824 
5825 /*
5826  * Replace an old allocdirect dependency with a newer one.
5827  */
5828 static void
5829 allocdirect_merge(adphead, newadp, oldadp)
5830 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5831 	struct allocdirect *newadp;	/* allocdirect being added */
5832 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5833 {
5834 	struct worklist *wk;
5835 	struct freefrag *freefrag;
5836 
5837 	freefrag = NULL;
5838 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5839 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5840 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5841 	    newadp->ad_offset >= UFS_NDADDR)
5842 		panic("%s %jd != new %jd || old size %ld != new %ld",
5843 		    "allocdirect_merge: old blkno",
5844 		    (intmax_t)newadp->ad_oldblkno,
5845 		    (intmax_t)oldadp->ad_newblkno,
5846 		    newadp->ad_oldsize, oldadp->ad_newsize);
5847 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5848 	newadp->ad_oldsize = oldadp->ad_oldsize;
5849 	/*
5850 	 * If the old dependency had a fragment to free or had never
5851 	 * previously had a block allocated, then the new dependency
5852 	 * can immediately post its freefrag and adopt the old freefrag.
5853 	 * This action is done by swapping the freefrag dependencies.
5854 	 * The new dependency gains the old one's freefrag, and the
5855 	 * old one gets the new one and then immediately puts it on
5856 	 * the worklist when it is freed by free_newblk. It is
5857 	 * not possible to do this swap when the old dependency had a
5858 	 * non-zero size but no previous fragment to free. This condition
5859 	 * arises when the new block is an extension of the old block.
5860 	 * Here, the first part of the fragment allocated to the new
5861 	 * dependency is part of the block currently claimed on disk by
5862 	 * the old dependency, so cannot legitimately be freed until the
5863 	 * conditions for the new dependency are fulfilled.
5864 	 */
5865 	freefrag = newadp->ad_freefrag;
5866 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5867 		newadp->ad_freefrag = oldadp->ad_freefrag;
5868 		oldadp->ad_freefrag = freefrag;
5869 	}
5870 	/*
5871 	 * If we are tracking a new directory-block allocation,
5872 	 * move it from the old allocdirect to the new allocdirect.
5873 	 */
5874 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5875 		WORKLIST_REMOVE(wk);
5876 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5877 			panic("allocdirect_merge: extra newdirblk");
5878 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5879 	}
5880 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5881 	/*
5882 	 * We need to move any journal dependencies over to the freefrag
5883 	 * that releases this block if it exists.  Otherwise we are
5884 	 * extending an existing block and we'll wait until that is
5885 	 * complete to release the journal space and extend the
5886 	 * new journal to cover this old space as well.
5887 	 */
5888 	if (freefrag == NULL) {
5889 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5890 			panic("allocdirect_merge: %jd != %jd",
5891 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5892 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5893 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5894 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5895 		    &newadp->ad_block.nb_jwork);
5896 		oldadp->ad_block.nb_jnewblk = NULL;
5897 		cancel_newblk(&oldadp->ad_block, NULL,
5898 		    &newadp->ad_block.nb_jwork);
5899 	} else {
5900 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5901 		    &freefrag->ff_list, &freefrag->ff_jwork);
5902 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5903 		    &freefrag->ff_jwork);
5904 	}
5905 	free_newblk(&oldadp->ad_block);
5906 }
5907 
5908 /*
5909  * Allocate a jfreefrag structure to journal a single block free.
5910  */
5911 static struct jfreefrag *
5912 newjfreefrag(freefrag, ip, blkno, size, lbn)
5913 	struct freefrag *freefrag;
5914 	struct inode *ip;
5915 	ufs2_daddr_t blkno;
5916 	long size;
5917 	ufs_lbn_t lbn;
5918 {
5919 	struct jfreefrag *jfreefrag;
5920 	struct fs *fs;
5921 
5922 	fs = ITOFS(ip);
5923 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5924 	    M_SOFTDEP_FLAGS);
5925 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5926 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5927 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5928 	jfreefrag->fr_ino = ip->i_number;
5929 	jfreefrag->fr_lbn = lbn;
5930 	jfreefrag->fr_blkno = blkno;
5931 	jfreefrag->fr_frags = numfrags(fs, size);
5932 	jfreefrag->fr_freefrag = freefrag;
5933 
5934 	return (jfreefrag);
5935 }
5936 
5937 /*
5938  * Allocate a new freefrag structure.
5939  */
5940 static struct freefrag *
5941 newfreefrag(ip, blkno, size, lbn, key)
5942 	struct inode *ip;
5943 	ufs2_daddr_t blkno;
5944 	long size;
5945 	ufs_lbn_t lbn;
5946 	u_long key;
5947 {
5948 	struct freefrag *freefrag;
5949 	struct ufsmount *ump;
5950 	struct fs *fs;
5951 
5952 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5953 	    ip->i_number, blkno, size, lbn);
5954 	ump = ITOUMP(ip);
5955 	fs = ump->um_fs;
5956 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5957 		panic("newfreefrag: frag size");
5958 	freefrag = malloc(sizeof(struct freefrag),
5959 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5960 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5961 	freefrag->ff_state = ATTACHED;
5962 	LIST_INIT(&freefrag->ff_jwork);
5963 	freefrag->ff_inum = ip->i_number;
5964 	freefrag->ff_vtype = ITOV(ip)->v_type;
5965 	freefrag->ff_blkno = blkno;
5966 	freefrag->ff_fragsize = size;
5967 	freefrag->ff_key = key;
5968 
5969 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5970 		freefrag->ff_jdep = (struct worklist *)
5971 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5972 	} else {
5973 		freefrag->ff_state |= DEPCOMPLETE;
5974 		freefrag->ff_jdep = NULL;
5975 	}
5976 
5977 	return (freefrag);
5978 }
5979 
5980 /*
5981  * This workitem de-allocates fragments that were replaced during
5982  * file block allocation.
5983  */
5984 static void
5985 handle_workitem_freefrag(freefrag)
5986 	struct freefrag *freefrag;
5987 {
5988 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5989 	struct workhead wkhd;
5990 
5991 	CTR3(KTR_SUJ,
5992 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5993 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5994 	/*
5995 	 * It would be illegal to add new completion items to the
5996 	 * freefrag after it was schedule to be done so it must be
5997 	 * safe to modify the list head here.
5998 	 */
5999 	LIST_INIT(&wkhd);
6000 	ACQUIRE_LOCK(ump);
6001 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
6002 	/*
6003 	 * If the journal has not been written we must cancel it here.
6004 	 */
6005 	if (freefrag->ff_jdep) {
6006 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
6007 			panic("handle_workitem_freefrag: Unexpected type %d\n",
6008 			    freefrag->ff_jdep->wk_type);
6009 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
6010 	}
6011 	FREE_LOCK(ump);
6012 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
6013 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
6014 	   &wkhd, freefrag->ff_key);
6015 	ACQUIRE_LOCK(ump);
6016 	WORKITEM_FREE(freefrag, D_FREEFRAG);
6017 	FREE_LOCK(ump);
6018 }
6019 
6020 /*
6021  * Set up a dependency structure for an external attributes data block.
6022  * This routine follows much of the structure of softdep_setup_allocdirect.
6023  * See the description of softdep_setup_allocdirect above for details.
6024  */
6025 void
6026 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
6027 	struct inode *ip;
6028 	ufs_lbn_t off;
6029 	ufs2_daddr_t newblkno;
6030 	ufs2_daddr_t oldblkno;
6031 	long newsize;
6032 	long oldsize;
6033 	struct buf *bp;
6034 {
6035 	struct allocdirect *adp, *oldadp;
6036 	struct allocdirectlst *adphead;
6037 	struct freefrag *freefrag;
6038 	struct inodedep *inodedep;
6039 	struct jnewblk *jnewblk;
6040 	struct newblk *newblk;
6041 	struct mount *mp;
6042 	struct ufsmount *ump;
6043 	ufs_lbn_t lbn;
6044 
6045 	mp = ITOVFS(ip);
6046 	ump = VFSTOUFS(mp);
6047 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6048 	    ("softdep_setup_allocext called on non-softdep filesystem"));
6049 	KASSERT(off < UFS_NXADDR,
6050 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
6051 
6052 	lbn = bp->b_lblkno;
6053 	if (oldblkno && oldblkno != newblkno)
6054 		/*
6055 		 * The usual case is that a smaller fragment that
6056 		 * was just allocated has been replaced with a bigger
6057 		 * fragment or a full-size block. If it is marked as
6058 		 * B_DELWRI, the current contents have not been written
6059 		 * to disk. It is possible that the block was written
6060 		 * earlier, but very uncommon. If the block has never
6061 		 * been written, there is no need to send a BIO_DELETE
6062 		 * for it when it is freed. The gain from avoiding the
6063 		 * TRIMs for the common case of unwritten blocks far
6064 		 * exceeds the cost of the write amplification for the
6065 		 * uncommon case of failing to send a TRIM for a block
6066 		 * that had been written.
6067 		 */
6068 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
6069 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
6070 	else
6071 		freefrag = NULL;
6072 
6073 	ACQUIRE_LOCK(ump);
6074 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
6075 		panic("softdep_setup_allocext: lost block");
6076 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6077 	    ("softdep_setup_allocext: newblk already initialized"));
6078 	/*
6079 	 * Convert the newblk to an allocdirect.
6080 	 */
6081 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
6082 	adp = (struct allocdirect *)newblk;
6083 	newblk->nb_freefrag = freefrag;
6084 	adp->ad_offset = off;
6085 	adp->ad_oldblkno = oldblkno;
6086 	adp->ad_newsize = newsize;
6087 	adp->ad_oldsize = oldsize;
6088 	adp->ad_state |=  EXTDATA;
6089 
6090 	/*
6091 	 * Finish initializing the journal.
6092 	 */
6093 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6094 		jnewblk->jn_ino = ip->i_number;
6095 		jnewblk->jn_lbn = lbn;
6096 		add_to_journal(&jnewblk->jn_list);
6097 	}
6098 	if (freefrag && freefrag->ff_jdep != NULL &&
6099 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6100 		add_to_journal(freefrag->ff_jdep);
6101 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6102 	adp->ad_inodedep = inodedep;
6103 
6104 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
6105 	/*
6106 	 * The list of allocdirects must be kept in sorted and ascending
6107 	 * order so that the rollback routines can quickly determine the
6108 	 * first uncommitted block (the size of the file stored on disk
6109 	 * ends at the end of the lowest committed fragment, or if there
6110 	 * are no fragments, at the end of the highest committed block).
6111 	 * Since files generally grow, the typical case is that the new
6112 	 * block is to be added at the end of the list. We speed this
6113 	 * special case by checking against the last allocdirect in the
6114 	 * list before laboriously traversing the list looking for the
6115 	 * insertion point.
6116 	 */
6117 	adphead = &inodedep->id_newextupdt;
6118 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
6119 	if (oldadp == NULL || oldadp->ad_offset <= off) {
6120 		/* insert at end of list */
6121 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
6122 		if (oldadp != NULL && oldadp->ad_offset == off)
6123 			allocdirect_merge(adphead, adp, oldadp);
6124 		FREE_LOCK(ump);
6125 		return;
6126 	}
6127 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
6128 		if (oldadp->ad_offset >= off)
6129 			break;
6130 	}
6131 	if (oldadp == NULL)
6132 		panic("softdep_setup_allocext: lost entry");
6133 	/* insert in middle of list */
6134 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
6135 	if (oldadp->ad_offset == off)
6136 		allocdirect_merge(adphead, adp, oldadp);
6137 	FREE_LOCK(ump);
6138 }
6139 
6140 /*
6141  * Indirect block allocation dependencies.
6142  *
6143  * The same dependencies that exist for a direct block also exist when
6144  * a new block is allocated and pointed to by an entry in a block of
6145  * indirect pointers. The undo/redo states described above are also
6146  * used here. Because an indirect block contains many pointers that
6147  * may have dependencies, a second copy of the entire in-memory indirect
6148  * block is kept. The buffer cache copy is always completely up-to-date.
6149  * The second copy, which is used only as a source for disk writes,
6150  * contains only the safe pointers (i.e., those that have no remaining
6151  * update dependencies). The second copy is freed when all pointers
6152  * are safe. The cache is not allowed to replace indirect blocks with
6153  * pending update dependencies. If a buffer containing an indirect
6154  * block with dependencies is written, these routines will mark it
6155  * dirty again. It can only be successfully written once all the
6156  * dependencies are removed. The ffs_fsync routine in conjunction with
6157  * softdep_sync_metadata work together to get all the dependencies
6158  * removed so that a file can be successfully written to disk. Three
6159  * procedures are used when setting up indirect block pointer
6160  * dependencies. The division is necessary because of the organization
6161  * of the "balloc" routine and because of the distinction between file
6162  * pages and file metadata blocks.
6163  */
6164 
6165 /*
6166  * Allocate a new allocindir structure.
6167  */
6168 static struct allocindir *
6169 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
6170 	struct inode *ip;	/* inode for file being extended */
6171 	int ptrno;		/* offset of pointer in indirect block */
6172 	ufs2_daddr_t newblkno;	/* disk block number being added */
6173 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
6174 	ufs_lbn_t lbn;
6175 {
6176 	struct newblk *newblk;
6177 	struct allocindir *aip;
6178 	struct freefrag *freefrag;
6179 	struct jnewblk *jnewblk;
6180 
6181 	if (oldblkno)
6182 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
6183 		    SINGLETON_KEY);
6184 	else
6185 		freefrag = NULL;
6186 	ACQUIRE_LOCK(ITOUMP(ip));
6187 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
6188 		panic("new_allocindir: lost block");
6189 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6190 	    ("newallocindir: newblk already initialized"));
6191 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
6192 	newblk->nb_freefrag = freefrag;
6193 	aip = (struct allocindir *)newblk;
6194 	aip->ai_offset = ptrno;
6195 	aip->ai_oldblkno = oldblkno;
6196 	aip->ai_lbn = lbn;
6197 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6198 		jnewblk->jn_ino = ip->i_number;
6199 		jnewblk->jn_lbn = lbn;
6200 		add_to_journal(&jnewblk->jn_list);
6201 	}
6202 	if (freefrag && freefrag->ff_jdep != NULL &&
6203 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6204 		add_to_journal(freefrag->ff_jdep);
6205 	return (aip);
6206 }
6207 
6208 /*
6209  * Called just before setting an indirect block pointer
6210  * to a newly allocated file page.
6211  */
6212 void
6213 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
6214 	struct inode *ip;	/* inode for file being extended */
6215 	ufs_lbn_t lbn;		/* allocated block number within file */
6216 	struct buf *bp;		/* buffer with indirect blk referencing page */
6217 	int ptrno;		/* offset of pointer in indirect block */
6218 	ufs2_daddr_t newblkno;	/* disk block number being added */
6219 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
6220 	struct buf *nbp;	/* buffer holding allocated page */
6221 {
6222 	struct inodedep *inodedep;
6223 	struct freefrag *freefrag;
6224 	struct allocindir *aip;
6225 	struct pagedep *pagedep;
6226 	struct mount *mp;
6227 	struct ufsmount *ump;
6228 
6229 	mp = ITOVFS(ip);
6230 	ump = VFSTOUFS(mp);
6231 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6232 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
6233 	KASSERT(lbn == nbp->b_lblkno,
6234 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
6235 	    lbn, bp->b_lblkno));
6236 	CTR4(KTR_SUJ,
6237 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
6238 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
6239 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
6240 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
6241 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6242 	/*
6243 	 * If we are allocating a directory page, then we must
6244 	 * allocate an associated pagedep to track additions and
6245 	 * deletions.
6246 	 */
6247 	if ((ip->i_mode & IFMT) == IFDIR)
6248 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
6249 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6250 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
6251 	FREE_LOCK(ump);
6252 	if (freefrag)
6253 		handle_workitem_freefrag(freefrag);
6254 }
6255 
6256 /*
6257  * Called just before setting an indirect block pointer to a
6258  * newly allocated indirect block.
6259  */
6260 void
6261 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
6262 	struct buf *nbp;	/* newly allocated indirect block */
6263 	struct inode *ip;	/* inode for file being extended */
6264 	struct buf *bp;		/* indirect block referencing allocated block */
6265 	int ptrno;		/* offset of pointer in indirect block */
6266 	ufs2_daddr_t newblkno;	/* disk block number being added */
6267 {
6268 	struct inodedep *inodedep;
6269 	struct allocindir *aip;
6270 	struct ufsmount *ump;
6271 	ufs_lbn_t lbn;
6272 
6273 	ump = ITOUMP(ip);
6274 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6275 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
6276 	CTR3(KTR_SUJ,
6277 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
6278 	    ip->i_number, newblkno, ptrno);
6279 	lbn = nbp->b_lblkno;
6280 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
6281 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
6282 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
6283 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6284 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
6285 		panic("softdep_setup_allocindir_meta: Block already existed");
6286 	FREE_LOCK(ump);
6287 }
6288 
6289 static void
6290 indirdep_complete(indirdep)
6291 	struct indirdep *indirdep;
6292 {
6293 	struct allocindir *aip;
6294 
6295 	LIST_REMOVE(indirdep, ir_next);
6296 	indirdep->ir_state |= DEPCOMPLETE;
6297 
6298 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
6299 		LIST_REMOVE(aip, ai_next);
6300 		free_newblk(&aip->ai_block);
6301 	}
6302 	/*
6303 	 * If this indirdep is not attached to a buf it was simply waiting
6304 	 * on completion to clear completehd.  free_indirdep() asserts
6305 	 * that nothing is dangling.
6306 	 */
6307 	if ((indirdep->ir_state & ONWORKLIST) == 0)
6308 		free_indirdep(indirdep);
6309 }
6310 
6311 static struct indirdep *
6312 indirdep_lookup(mp, ip, bp)
6313 	struct mount *mp;
6314 	struct inode *ip;
6315 	struct buf *bp;
6316 {
6317 	struct indirdep *indirdep, *newindirdep;
6318 	struct newblk *newblk;
6319 	struct ufsmount *ump;
6320 	struct worklist *wk;
6321 	struct fs *fs;
6322 	ufs2_daddr_t blkno;
6323 
6324 	ump = VFSTOUFS(mp);
6325 	LOCK_OWNED(ump);
6326 	indirdep = NULL;
6327 	newindirdep = NULL;
6328 	fs = ump->um_fs;
6329 	for (;;) {
6330 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6331 			if (wk->wk_type != D_INDIRDEP)
6332 				continue;
6333 			indirdep = WK_INDIRDEP(wk);
6334 			break;
6335 		}
6336 		/* Found on the buffer worklist, no new structure to free. */
6337 		if (indirdep != NULL && newindirdep == NULL)
6338 			return (indirdep);
6339 		if (indirdep != NULL && newindirdep != NULL)
6340 			panic("indirdep_lookup: simultaneous create");
6341 		/* None found on the buffer and a new structure is ready. */
6342 		if (indirdep == NULL && newindirdep != NULL)
6343 			break;
6344 		/* None found and no new structure available. */
6345 		FREE_LOCK(ump);
6346 		newindirdep = malloc(sizeof(struct indirdep),
6347 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
6348 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6349 		newindirdep->ir_state = ATTACHED;
6350 		if (I_IS_UFS1(ip))
6351 			newindirdep->ir_state |= UFS1FMT;
6352 		TAILQ_INIT(&newindirdep->ir_trunc);
6353 		newindirdep->ir_saveddata = NULL;
6354 		LIST_INIT(&newindirdep->ir_deplisthd);
6355 		LIST_INIT(&newindirdep->ir_donehd);
6356 		LIST_INIT(&newindirdep->ir_writehd);
6357 		LIST_INIT(&newindirdep->ir_completehd);
6358 		if (bp->b_blkno == bp->b_lblkno) {
6359 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6360 			    NULL, NULL);
6361 			bp->b_blkno = blkno;
6362 		}
6363 		newindirdep->ir_freeblks = NULL;
6364 		newindirdep->ir_savebp =
6365 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6366 		newindirdep->ir_bp = bp;
6367 		BUF_KERNPROC(newindirdep->ir_savebp);
6368 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6369 		ACQUIRE_LOCK(ump);
6370 	}
6371 	indirdep = newindirdep;
6372 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6373 	/*
6374 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6375 	 * that we don't free dependencies until the pointers are valid.
6376 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6377 	 * than using the hash.
6378 	 */
6379 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6380 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6381 	else
6382 		indirdep->ir_state |= DEPCOMPLETE;
6383 	return (indirdep);
6384 }
6385 
6386 /*
6387  * Called to finish the allocation of the "aip" allocated
6388  * by one of the two routines above.
6389  */
6390 static struct freefrag *
6391 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6392 	struct buf *bp;		/* in-memory copy of the indirect block */
6393 	struct inode *ip;	/* inode for file being extended */
6394 	struct inodedep *inodedep; /* Inodedep for ip */
6395 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6396 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6397 {
6398 	struct fs *fs;
6399 	struct indirdep *indirdep;
6400 	struct allocindir *oldaip;
6401 	struct freefrag *freefrag;
6402 	struct mount *mp;
6403 	struct ufsmount *ump;
6404 
6405 	mp = ITOVFS(ip);
6406 	ump = VFSTOUFS(mp);
6407 	LOCK_OWNED(ump);
6408 	fs = ump->um_fs;
6409 	if (bp->b_lblkno >= 0)
6410 		panic("setup_allocindir_phase2: not indir blk");
6411 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6412 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6413 	indirdep = indirdep_lookup(mp, ip, bp);
6414 	KASSERT(indirdep->ir_savebp != NULL,
6415 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6416 	aip->ai_indirdep = indirdep;
6417 	/*
6418 	 * Check for an unwritten dependency for this indirect offset.  If
6419 	 * there is, merge the old dependency into the new one.  This happens
6420 	 * as a result of reallocblk only.
6421 	 */
6422 	freefrag = NULL;
6423 	if (aip->ai_oldblkno != 0) {
6424 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6425 			if (oldaip->ai_offset == aip->ai_offset) {
6426 				freefrag = allocindir_merge(aip, oldaip);
6427 				goto done;
6428 			}
6429 		}
6430 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6431 			if (oldaip->ai_offset == aip->ai_offset) {
6432 				freefrag = allocindir_merge(aip, oldaip);
6433 				goto done;
6434 			}
6435 		}
6436 	}
6437 done:
6438 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6439 	return (freefrag);
6440 }
6441 
6442 /*
6443  * Merge two allocindirs which refer to the same block.  Move newblock
6444  * dependencies and setup the freefrags appropriately.
6445  */
6446 static struct freefrag *
6447 allocindir_merge(aip, oldaip)
6448 	struct allocindir *aip;
6449 	struct allocindir *oldaip;
6450 {
6451 	struct freefrag *freefrag;
6452 	struct worklist *wk;
6453 
6454 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6455 		panic("allocindir_merge: blkno");
6456 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6457 	freefrag = aip->ai_freefrag;
6458 	aip->ai_freefrag = oldaip->ai_freefrag;
6459 	oldaip->ai_freefrag = NULL;
6460 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6461 	/*
6462 	 * If we are tracking a new directory-block allocation,
6463 	 * move it from the old allocindir to the new allocindir.
6464 	 */
6465 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6466 		WORKLIST_REMOVE(wk);
6467 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6468 			panic("allocindir_merge: extra newdirblk");
6469 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6470 	}
6471 	/*
6472 	 * We can skip journaling for this freefrag and just complete
6473 	 * any pending journal work for the allocindir that is being
6474 	 * removed after the freefrag completes.
6475 	 */
6476 	if (freefrag->ff_jdep)
6477 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6478 	LIST_REMOVE(oldaip, ai_next);
6479 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6480 	    &freefrag->ff_list, &freefrag->ff_jwork);
6481 	free_newblk(&oldaip->ai_block);
6482 
6483 	return (freefrag);
6484 }
6485 
6486 static inline void
6487 setup_freedirect(freeblks, ip, i, needj)
6488 	struct freeblks *freeblks;
6489 	struct inode *ip;
6490 	int i;
6491 	int needj;
6492 {
6493 	struct ufsmount *ump;
6494 	ufs2_daddr_t blkno;
6495 	int frags;
6496 
6497 	blkno = DIP(ip, i_db[i]);
6498 	if (blkno == 0)
6499 		return;
6500 	DIP_SET(ip, i_db[i], 0);
6501 	ump = ITOUMP(ip);
6502 	frags = sblksize(ump->um_fs, ip->i_size, i);
6503 	frags = numfrags(ump->um_fs, frags);
6504 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6505 }
6506 
6507 static inline void
6508 setup_freeext(freeblks, ip, i, needj)
6509 	struct freeblks *freeblks;
6510 	struct inode *ip;
6511 	int i;
6512 	int needj;
6513 {
6514 	struct ufsmount *ump;
6515 	ufs2_daddr_t blkno;
6516 	int frags;
6517 
6518 	blkno = ip->i_din2->di_extb[i];
6519 	if (blkno == 0)
6520 		return;
6521 	ip->i_din2->di_extb[i] = 0;
6522 	ump = ITOUMP(ip);
6523 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6524 	frags = numfrags(ump->um_fs, frags);
6525 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6526 }
6527 
6528 static inline void
6529 setup_freeindir(freeblks, ip, i, lbn, needj)
6530 	struct freeblks *freeblks;
6531 	struct inode *ip;
6532 	int i;
6533 	ufs_lbn_t lbn;
6534 	int needj;
6535 {
6536 	struct ufsmount *ump;
6537 	ufs2_daddr_t blkno;
6538 
6539 	blkno = DIP(ip, i_ib[i]);
6540 	if (blkno == 0)
6541 		return;
6542 	DIP_SET(ip, i_ib[i], 0);
6543 	ump = ITOUMP(ip);
6544 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6545 	    0, needj);
6546 }
6547 
6548 static inline struct freeblks *
6549 newfreeblks(mp, ip)
6550 	struct mount *mp;
6551 	struct inode *ip;
6552 {
6553 	struct freeblks *freeblks;
6554 
6555 	freeblks = malloc(sizeof(struct freeblks),
6556 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6557 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6558 	LIST_INIT(&freeblks->fb_jblkdephd);
6559 	LIST_INIT(&freeblks->fb_jwork);
6560 	freeblks->fb_ref = 0;
6561 	freeblks->fb_cgwait = 0;
6562 	freeblks->fb_state = ATTACHED;
6563 	freeblks->fb_uid = ip->i_uid;
6564 	freeblks->fb_inum = ip->i_number;
6565 	freeblks->fb_vtype = ITOV(ip)->v_type;
6566 	freeblks->fb_modrev = DIP(ip, i_modrev);
6567 	freeblks->fb_devvp = ITODEVVP(ip);
6568 	freeblks->fb_chkcnt = 0;
6569 	freeblks->fb_len = 0;
6570 
6571 	return (freeblks);
6572 }
6573 
6574 static void
6575 trunc_indirdep(indirdep, freeblks, bp, off)
6576 	struct indirdep *indirdep;
6577 	struct freeblks *freeblks;
6578 	struct buf *bp;
6579 	int off;
6580 {
6581 	struct allocindir *aip, *aipn;
6582 
6583 	/*
6584 	 * The first set of allocindirs won't be in savedbp.
6585 	 */
6586 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6587 		if (aip->ai_offset > off)
6588 			cancel_allocindir(aip, bp, freeblks, 1);
6589 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6590 		if (aip->ai_offset > off)
6591 			cancel_allocindir(aip, bp, freeblks, 1);
6592 	/*
6593 	 * These will exist in savedbp.
6594 	 */
6595 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6596 		if (aip->ai_offset > off)
6597 			cancel_allocindir(aip, NULL, freeblks, 0);
6598 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6599 		if (aip->ai_offset > off)
6600 			cancel_allocindir(aip, NULL, freeblks, 0);
6601 }
6602 
6603 /*
6604  * Follow the chain of indirects down to lastlbn creating a freework
6605  * structure for each.  This will be used to start indir_trunc() at
6606  * the right offset and create the journal records for the parrtial
6607  * truncation.  A second step will handle the truncated dependencies.
6608  */
6609 static int
6610 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6611 	struct freeblks *freeblks;
6612 	struct inode *ip;
6613 	ufs_lbn_t lbn;
6614 	ufs_lbn_t lastlbn;
6615 	ufs2_daddr_t blkno;
6616 {
6617 	struct indirdep *indirdep;
6618 	struct indirdep *indirn;
6619 	struct freework *freework;
6620 	struct newblk *newblk;
6621 	struct mount *mp;
6622 	struct ufsmount *ump;
6623 	struct buf *bp;
6624 	uint8_t *start;
6625 	uint8_t *end;
6626 	ufs_lbn_t lbnadd;
6627 	int level;
6628 	int error;
6629 	int off;
6630 
6631 	freework = NULL;
6632 	if (blkno == 0)
6633 		return (0);
6634 	mp = freeblks->fb_list.wk_mp;
6635 	ump = VFSTOUFS(mp);
6636 	/*
6637 	 * Here, calls to VOP_BMAP() will fail.  However, we already have
6638 	 * the on-disk address, so we just pass it to bread() instead of
6639 	 * having bread() attempt to calculate it using VOP_BMAP().
6640 	 */
6641 	error = ffs_breadz(ump, ITOV(ip), lbn, blkptrtodb(ump, blkno),
6642 	    (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6643 	if (error)
6644 		return (error);
6645 	level = lbn_level(lbn);
6646 	lbnadd = lbn_offset(ump->um_fs, level);
6647 	/*
6648 	 * Compute the offset of the last block we want to keep.  Store
6649 	 * in the freework the first block we want to completely free.
6650 	 */
6651 	off = (lastlbn - -(lbn + level)) / lbnadd;
6652 	if (off + 1 == NINDIR(ump->um_fs))
6653 		goto nowork;
6654 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6655 	/*
6656 	 * Link the freework into the indirdep.  This will prevent any new
6657 	 * allocations from proceeding until we are finished with the
6658 	 * truncate and the block is written.
6659 	 */
6660 	ACQUIRE_LOCK(ump);
6661 	indirdep = indirdep_lookup(mp, ip, bp);
6662 	if (indirdep->ir_freeblks)
6663 		panic("setup_trunc_indir: indirdep already truncated.");
6664 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6665 	freework->fw_indir = indirdep;
6666 	/*
6667 	 * Cancel any allocindirs that will not make it to disk.
6668 	 * We have to do this for all copies of the indirdep that
6669 	 * live on this newblk.
6670 	 */
6671 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6672 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6673 		    &newblk) == 0)
6674 			panic("setup_trunc_indir: lost block");
6675 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6676 			trunc_indirdep(indirn, freeblks, bp, off);
6677 	} else
6678 		trunc_indirdep(indirdep, freeblks, bp, off);
6679 	FREE_LOCK(ump);
6680 	/*
6681 	 * Creation is protected by the buf lock. The saveddata is only
6682 	 * needed if a full truncation follows a partial truncation but it
6683 	 * is difficult to allocate in that case so we fetch it anyway.
6684 	 */
6685 	if (indirdep->ir_saveddata == NULL)
6686 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6687 		    M_SOFTDEP_FLAGS);
6688 nowork:
6689 	/* Fetch the blkno of the child and the zero start offset. */
6690 	if (I_IS_UFS1(ip)) {
6691 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6692 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6693 	} else {
6694 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6695 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6696 	}
6697 	if (freework) {
6698 		/* Zero the truncated pointers. */
6699 		end = bp->b_data + bp->b_bcount;
6700 		bzero(start, end - start);
6701 		bdwrite(bp);
6702 	} else
6703 		bqrelse(bp);
6704 	if (level == 0)
6705 		return (0);
6706 	lbn++; /* adjust level */
6707 	lbn -= (off * lbnadd);
6708 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6709 }
6710 
6711 /*
6712  * Complete the partial truncation of an indirect block setup by
6713  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6714  * copy and writes them to disk before the freeblks is allowed to complete.
6715  */
6716 static void
6717 complete_trunc_indir(freework)
6718 	struct freework *freework;
6719 {
6720 	struct freework *fwn;
6721 	struct indirdep *indirdep;
6722 	struct ufsmount *ump;
6723 	struct buf *bp;
6724 	uintptr_t start;
6725 	int count;
6726 
6727 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6728 	LOCK_OWNED(ump);
6729 	indirdep = freework->fw_indir;
6730 	for (;;) {
6731 		bp = indirdep->ir_bp;
6732 		/* See if the block was discarded. */
6733 		if (bp == NULL)
6734 			break;
6735 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6736 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6737 			break;
6738 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6739 		    LOCK_PTR(ump)) == 0)
6740 			BUF_UNLOCK(bp);
6741 		ACQUIRE_LOCK(ump);
6742 	}
6743 	freework->fw_state |= DEPCOMPLETE;
6744 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6745 	/*
6746 	 * Zero the pointers in the saved copy.
6747 	 */
6748 	if (indirdep->ir_state & UFS1FMT)
6749 		start = sizeof(ufs1_daddr_t);
6750 	else
6751 		start = sizeof(ufs2_daddr_t);
6752 	start *= freework->fw_start;
6753 	count = indirdep->ir_savebp->b_bcount - start;
6754 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6755 	bzero((char *)start, count);
6756 	/*
6757 	 * We need to start the next truncation in the list if it has not
6758 	 * been started yet.
6759 	 */
6760 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6761 	if (fwn != NULL) {
6762 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6763 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6764 		if ((fwn->fw_state & ONWORKLIST) == 0)
6765 			freework_enqueue(fwn);
6766 	}
6767 	/*
6768 	 * If bp is NULL the block was fully truncated, restore
6769 	 * the saved block list otherwise free it if it is no
6770 	 * longer needed.
6771 	 */
6772 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6773 		if (bp == NULL)
6774 			bcopy(indirdep->ir_saveddata,
6775 			    indirdep->ir_savebp->b_data,
6776 			    indirdep->ir_savebp->b_bcount);
6777 		free(indirdep->ir_saveddata, M_INDIRDEP);
6778 		indirdep->ir_saveddata = NULL;
6779 	}
6780 	/*
6781 	 * When bp is NULL there is a full truncation pending.  We
6782 	 * must wait for this full truncation to be journaled before
6783 	 * we can release this freework because the disk pointers will
6784 	 * never be written as zero.
6785 	 */
6786 	if (bp == NULL)  {
6787 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6788 			handle_written_freework(freework);
6789 		else
6790 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6791 			   &freework->fw_list);
6792 		if (fwn == NULL) {
6793 			freework->fw_indir = (void *)0x0000deadbeef0000;
6794 			bp = indirdep->ir_savebp;
6795 			indirdep->ir_savebp = NULL;
6796 			free_indirdep(indirdep);
6797 			FREE_LOCK(ump);
6798 			brelse(bp);
6799 			ACQUIRE_LOCK(ump);
6800 		}
6801 	} else {
6802 		/* Complete when the real copy is written. */
6803 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6804 		BUF_UNLOCK(bp);
6805 	}
6806 }
6807 
6808 /*
6809  * Calculate the number of blocks we are going to release where datablocks
6810  * is the current total and length is the new file size.
6811  */
6812 static ufs2_daddr_t
6813 blkcount(fs, datablocks, length)
6814 	struct fs *fs;
6815 	ufs2_daddr_t datablocks;
6816 	off_t length;
6817 {
6818 	off_t totblks, numblks;
6819 
6820 	totblks = 0;
6821 	numblks = howmany(length, fs->fs_bsize);
6822 	if (numblks <= UFS_NDADDR) {
6823 		totblks = howmany(length, fs->fs_fsize);
6824 		goto out;
6825 	}
6826         totblks = blkstofrags(fs, numblks);
6827 	numblks -= UFS_NDADDR;
6828 	/*
6829 	 * Count all single, then double, then triple indirects required.
6830 	 * Subtracting one indirects worth of blocks for each pass
6831 	 * acknowledges one of each pointed to by the inode.
6832 	 */
6833 	for (;;) {
6834 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6835 		numblks -= NINDIR(fs);
6836 		if (numblks <= 0)
6837 			break;
6838 		numblks = howmany(numblks, NINDIR(fs));
6839 	}
6840 out:
6841 	totblks = fsbtodb(fs, totblks);
6842 	/*
6843 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6844 	 * references.  We will correct it later in handle_complete_freeblks()
6845 	 * when we know the real count.
6846 	 */
6847 	if (totblks > datablocks)
6848 		return (0);
6849 	return (datablocks - totblks);
6850 }
6851 
6852 /*
6853  * Handle freeblocks for journaled softupdate filesystems.
6854  *
6855  * Contrary to normal softupdates, we must preserve the block pointers in
6856  * indirects until their subordinates are free.  This is to avoid journaling
6857  * every block that is freed which may consume more space than the journal
6858  * itself.  The recovery program will see the free block journals at the
6859  * base of the truncated area and traverse them to reclaim space.  The
6860  * pointers in the inode may be cleared immediately after the journal
6861  * records are written because each direct and indirect pointer in the
6862  * inode is recorded in a journal.  This permits full truncation to proceed
6863  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6864  *
6865  * The algorithm is as follows:
6866  * 1) Traverse the in-memory state and create journal entries to release
6867  *    the relevant blocks and full indirect trees.
6868  * 2) Traverse the indirect block chain adding partial truncation freework
6869  *    records to indirects in the path to lastlbn.  The freework will
6870  *    prevent new allocation dependencies from being satisfied in this
6871  *    indirect until the truncation completes.
6872  * 3) Read and lock the inode block, performing an update with the new size
6873  *    and pointers.  This prevents truncated data from becoming valid on
6874  *    disk through step 4.
6875  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6876  *    eliminate journal work for those records that do not require it.
6877  * 5) Schedule the journal records to be written followed by the inode block.
6878  * 6) Allocate any necessary frags for the end of file.
6879  * 7) Zero any partially truncated blocks.
6880  *
6881  * From this truncation proceeds asynchronously using the freework and
6882  * indir_trunc machinery.  The file will not be extended again into a
6883  * partially truncated indirect block until all work is completed but
6884  * the normal dependency mechanism ensures that it is rolled back/forward
6885  * as appropriate.  Further truncation may occur without delay and is
6886  * serialized in indir_trunc().
6887  */
6888 void
6889 softdep_journal_freeblocks(ip, cred, length, flags)
6890 	struct inode *ip;	/* The inode whose length is to be reduced */
6891 	struct ucred *cred;
6892 	off_t length;		/* The new length for the file */
6893 	int flags;		/* IO_EXT and/or IO_NORMAL */
6894 {
6895 	struct freeblks *freeblks, *fbn;
6896 	struct worklist *wk, *wkn;
6897 	struct inodedep *inodedep;
6898 	struct jblkdep *jblkdep;
6899 	struct allocdirect *adp, *adpn;
6900 	struct ufsmount *ump;
6901 	struct fs *fs;
6902 	struct buf *bp;
6903 	struct vnode *vp;
6904 	struct mount *mp;
6905 	daddr_t dbn;
6906 	ufs2_daddr_t extblocks, datablocks;
6907 	ufs_lbn_t tmpval, lbn, lastlbn;
6908 	int frags, lastoff, iboff, allocblock, needj, error, i;
6909 
6910 	ump = ITOUMP(ip);
6911 	mp = UFSTOVFS(ump);
6912 	fs = ump->um_fs;
6913 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6914 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6915 	vp = ITOV(ip);
6916 	needj = 1;
6917 	iboff = -1;
6918 	allocblock = 0;
6919 	extblocks = 0;
6920 	datablocks = 0;
6921 	frags = 0;
6922 	freeblks = newfreeblks(mp, ip);
6923 	ACQUIRE_LOCK(ump);
6924 	/*
6925 	 * If we're truncating a removed file that will never be written
6926 	 * we don't need to journal the block frees.  The canceled journals
6927 	 * for the allocations will suffice.
6928 	 */
6929 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6930 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6931 	    length == 0)
6932 		needj = 0;
6933 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6934 	    ip->i_number, length, needj);
6935 	FREE_LOCK(ump);
6936 	/*
6937 	 * Calculate the lbn that we are truncating to.  This results in -1
6938 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6939 	 * to keep, not the first lbn we want to truncate.
6940 	 */
6941 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6942 	lastoff = blkoff(fs, length);
6943 	/*
6944 	 * Compute frags we are keeping in lastlbn.  0 means all.
6945 	 */
6946 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6947 		frags = fragroundup(fs, lastoff);
6948 		/* adp offset of last valid allocdirect. */
6949 		iboff = lastlbn;
6950 	} else if (lastlbn > 0)
6951 		iboff = UFS_NDADDR;
6952 	if (fs->fs_magic == FS_UFS2_MAGIC)
6953 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6954 	/*
6955 	 * Handle normal data blocks and indirects.  This section saves
6956 	 * values used after the inode update to complete frag and indirect
6957 	 * truncation.
6958 	 */
6959 	if ((flags & IO_NORMAL) != 0) {
6960 		/*
6961 		 * Handle truncation of whole direct and indirect blocks.
6962 		 */
6963 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6964 			setup_freedirect(freeblks, ip, i, needj);
6965 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6966 		    i < UFS_NIADDR;
6967 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6968 			/* Release a whole indirect tree. */
6969 			if (lbn > lastlbn) {
6970 				setup_freeindir(freeblks, ip, i, -lbn -i,
6971 				    needj);
6972 				continue;
6973 			}
6974 			iboff = i + UFS_NDADDR;
6975 			/*
6976 			 * Traverse partially truncated indirect tree.
6977 			 */
6978 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6979 				setup_trunc_indir(freeblks, ip, -lbn - i,
6980 				    lastlbn, DIP(ip, i_ib[i]));
6981 		}
6982 		/*
6983 		 * Handle partial truncation to a frag boundary.
6984 		 */
6985 		if (frags) {
6986 			ufs2_daddr_t blkno;
6987 			long oldfrags;
6988 
6989 			oldfrags = blksize(fs, ip, lastlbn);
6990 			blkno = DIP(ip, i_db[lastlbn]);
6991 			if (blkno && oldfrags != frags) {
6992 				oldfrags -= frags;
6993 				oldfrags = numfrags(fs, oldfrags);
6994 				blkno += numfrags(fs, frags);
6995 				newfreework(ump, freeblks, NULL, lastlbn,
6996 				    blkno, oldfrags, 0, needj);
6997 				if (needj)
6998 					adjust_newfreework(freeblks,
6999 					    numfrags(fs, frags));
7000 			} else if (blkno == 0)
7001 				allocblock = 1;
7002 		}
7003 		/*
7004 		 * Add a journal record for partial truncate if we are
7005 		 * handling indirect blocks.  Non-indirects need no extra
7006 		 * journaling.
7007 		 */
7008 		if (length != 0 && lastlbn >= UFS_NDADDR) {
7009 			UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
7010 			newjtrunc(freeblks, length, 0);
7011 		}
7012 		ip->i_size = length;
7013 		DIP_SET(ip, i_size, ip->i_size);
7014 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7015 		datablocks = DIP(ip, i_blocks) - extblocks;
7016 		if (length != 0)
7017 			datablocks = blkcount(fs, datablocks, length);
7018 		freeblks->fb_len = length;
7019 	}
7020 	if ((flags & IO_EXT) != 0) {
7021 		for (i = 0; i < UFS_NXADDR; i++)
7022 			setup_freeext(freeblks, ip, i, needj);
7023 		ip->i_din2->di_extsize = 0;
7024 		datablocks += extblocks;
7025 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7026 	}
7027 #ifdef QUOTA
7028 	/* Reference the quotas in case the block count is wrong in the end. */
7029 	quotaref(vp, freeblks->fb_quota);
7030 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7031 #endif
7032 	freeblks->fb_chkcnt = -datablocks;
7033 	UFS_LOCK(ump);
7034 	fs->fs_pendingblocks += datablocks;
7035 	UFS_UNLOCK(ump);
7036 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7037 	/*
7038 	 * Handle truncation of incomplete alloc direct dependencies.  We
7039 	 * hold the inode block locked to prevent incomplete dependencies
7040 	 * from reaching the disk while we are eliminating those that
7041 	 * have been truncated.  This is a partially inlined ffs_update().
7042 	 */
7043 	ufs_itimes(vp);
7044 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
7045 	dbn = fsbtodb(fs, ino_to_fsba(fs, ip->i_number));
7046 	error = ffs_breadz(ump, ump->um_devvp, dbn, dbn, (int)fs->fs_bsize,
7047 	    NULL, NULL, 0, cred, 0, NULL, &bp);
7048 	if (error) {
7049 		softdep_error("softdep_journal_freeblocks", error);
7050 		return;
7051 	}
7052 	if (bp->b_bufsize == fs->fs_bsize)
7053 		bp->b_flags |= B_CLUSTEROK;
7054 	softdep_update_inodeblock(ip, bp, 0);
7055 	if (ump->um_fstype == UFS1) {
7056 		*((struct ufs1_dinode *)bp->b_data +
7057 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
7058 	} else {
7059 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7060 		*((struct ufs2_dinode *)bp->b_data +
7061 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
7062 	}
7063 	ACQUIRE_LOCK(ump);
7064 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7065 	if ((inodedep->id_state & IOSTARTED) != 0)
7066 		panic("softdep_setup_freeblocks: inode busy");
7067 	/*
7068 	 * Add the freeblks structure to the list of operations that
7069 	 * must await the zero'ed inode being written to disk. If we
7070 	 * still have a bitmap dependency (needj), then the inode
7071 	 * has never been written to disk, so we can process the
7072 	 * freeblks below once we have deleted the dependencies.
7073 	 */
7074 	if (needj)
7075 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7076 	else
7077 		freeblks->fb_state |= COMPLETE;
7078 	if ((flags & IO_NORMAL) != 0) {
7079 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
7080 			if (adp->ad_offset > iboff)
7081 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
7082 				    freeblks);
7083 			/*
7084 			 * Truncate the allocdirect.  We could eliminate
7085 			 * or modify journal records as well.
7086 			 */
7087 			else if (adp->ad_offset == iboff && frags)
7088 				adp->ad_newsize = frags;
7089 		}
7090 	}
7091 	if ((flags & IO_EXT) != 0)
7092 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7093 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7094 			    freeblks);
7095 	/*
7096 	 * Scan the bufwait list for newblock dependencies that will never
7097 	 * make it to disk.
7098 	 */
7099 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
7100 		if (wk->wk_type != D_ALLOCDIRECT)
7101 			continue;
7102 		adp = WK_ALLOCDIRECT(wk);
7103 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
7104 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
7105 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
7106 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
7107 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7108 		}
7109 	}
7110 	/*
7111 	 * Add journal work.
7112 	 */
7113 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
7114 		add_to_journal(&jblkdep->jb_list);
7115 	FREE_LOCK(ump);
7116 	bdwrite(bp);
7117 	/*
7118 	 * Truncate dependency structures beyond length.
7119 	 */
7120 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
7121 	/*
7122 	 * This is only set when we need to allocate a fragment because
7123 	 * none existed at the end of a frag-sized file.  It handles only
7124 	 * allocating a new, zero filled block.
7125 	 */
7126 	if (allocblock) {
7127 		ip->i_size = length - lastoff;
7128 		DIP_SET(ip, i_size, ip->i_size);
7129 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
7130 		if (error != 0) {
7131 			softdep_error("softdep_journal_freeblks", error);
7132 			return;
7133 		}
7134 		ip->i_size = length;
7135 		DIP_SET(ip, i_size, length);
7136 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
7137 		allocbuf(bp, frags);
7138 		ffs_update(vp, 0);
7139 		bawrite(bp);
7140 	} else if (lastoff != 0 && vp->v_type != VDIR) {
7141 		int size;
7142 
7143 		/*
7144 		 * Zero the end of a truncated frag or block.
7145 		 */
7146 		size = sblksize(fs, length, lastlbn);
7147 		error = bread(vp, lastlbn, size, cred, &bp);
7148 		if (error == 0) {
7149 			bzero((char *)bp->b_data + lastoff, size - lastoff);
7150 			bawrite(bp);
7151 		} else if (!ffs_fsfail_cleanup(ump, error)) {
7152 			softdep_error("softdep_journal_freeblks", error);
7153 			return;
7154 		}
7155 	}
7156 	ACQUIRE_LOCK(ump);
7157 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7158 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
7159 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
7160 	/*
7161 	 * We zero earlier truncations so they don't erroneously
7162 	 * update i_blocks.
7163 	 */
7164 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
7165 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
7166 			fbn->fb_len = 0;
7167 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
7168 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7169 		freeblks->fb_state |= INPROGRESS;
7170 	else
7171 		freeblks = NULL;
7172 	FREE_LOCK(ump);
7173 	if (freeblks)
7174 		handle_workitem_freeblocks(freeblks, 0);
7175 	trunc_pages(ip, length, extblocks, flags);
7176 
7177 }
7178 
7179 /*
7180  * Flush a JOP_SYNC to the journal.
7181  */
7182 void
7183 softdep_journal_fsync(ip)
7184 	struct inode *ip;
7185 {
7186 	struct jfsync *jfsync;
7187 	struct ufsmount *ump;
7188 
7189 	ump = ITOUMP(ip);
7190 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7191 	    ("softdep_journal_fsync called on non-softdep filesystem"));
7192 	if ((ip->i_flag & IN_TRUNCATED) == 0)
7193 		return;
7194 	ip->i_flag &= ~IN_TRUNCATED;
7195 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
7196 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
7197 	jfsync->jfs_size = ip->i_size;
7198 	jfsync->jfs_ino = ip->i_number;
7199 	ACQUIRE_LOCK(ump);
7200 	add_to_journal(&jfsync->jfs_list);
7201 	jwait(&jfsync->jfs_list, MNT_WAIT);
7202 	FREE_LOCK(ump);
7203 }
7204 
7205 /*
7206  * Block de-allocation dependencies.
7207  *
7208  * When blocks are de-allocated, the on-disk pointers must be nullified before
7209  * the blocks are made available for use by other files.  (The true
7210  * requirement is that old pointers must be nullified before new on-disk
7211  * pointers are set.  We chose this slightly more stringent requirement to
7212  * reduce complexity.) Our implementation handles this dependency by updating
7213  * the inode (or indirect block) appropriately but delaying the actual block
7214  * de-allocation (i.e., freemap and free space count manipulation) until
7215  * after the updated versions reach stable storage.  After the disk is
7216  * updated, the blocks can be safely de-allocated whenever it is convenient.
7217  * This implementation handles only the common case of reducing a file's
7218  * length to zero. Other cases are handled by the conventional synchronous
7219  * write approach.
7220  *
7221  * The ffs implementation with which we worked double-checks
7222  * the state of the block pointers and file size as it reduces
7223  * a file's length.  Some of this code is replicated here in our
7224  * soft updates implementation.  The freeblks->fb_chkcnt field is
7225  * used to transfer a part of this information to the procedure
7226  * that eventually de-allocates the blocks.
7227  *
7228  * This routine should be called from the routine that shortens
7229  * a file's length, before the inode's size or block pointers
7230  * are modified. It will save the block pointer information for
7231  * later release and zero the inode so that the calling routine
7232  * can release it.
7233  */
7234 void
7235 softdep_setup_freeblocks(ip, length, flags)
7236 	struct inode *ip;	/* The inode whose length is to be reduced */
7237 	off_t length;		/* The new length for the file */
7238 	int flags;		/* IO_EXT and/or IO_NORMAL */
7239 {
7240 	struct ufs1_dinode *dp1;
7241 	struct ufs2_dinode *dp2;
7242 	struct freeblks *freeblks;
7243 	struct inodedep *inodedep;
7244 	struct allocdirect *adp;
7245 	struct ufsmount *ump;
7246 	struct buf *bp;
7247 	struct fs *fs;
7248 	ufs2_daddr_t extblocks, datablocks;
7249 	struct mount *mp;
7250 	int i, delay, error;
7251 	ufs_lbn_t tmpval;
7252 	ufs_lbn_t lbn;
7253 
7254 	ump = ITOUMP(ip);
7255 	mp = UFSTOVFS(ump);
7256 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
7257 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
7258 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
7259 	    ip->i_number, length);
7260 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
7261 	fs = ump->um_fs;
7262 	if ((error = bread(ump->um_devvp,
7263 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
7264 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
7265 		if (!ffs_fsfail_cleanup(ump, error))
7266 			softdep_error("softdep_setup_freeblocks", error);
7267 		return;
7268 	}
7269 	freeblks = newfreeblks(mp, ip);
7270 	extblocks = 0;
7271 	datablocks = 0;
7272 	if (fs->fs_magic == FS_UFS2_MAGIC)
7273 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
7274 	if ((flags & IO_NORMAL) != 0) {
7275 		for (i = 0; i < UFS_NDADDR; i++)
7276 			setup_freedirect(freeblks, ip, i, 0);
7277 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
7278 		    i < UFS_NIADDR;
7279 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
7280 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
7281 		ip->i_size = 0;
7282 		DIP_SET(ip, i_size, 0);
7283 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7284 		datablocks = DIP(ip, i_blocks) - extblocks;
7285 	}
7286 	if ((flags & IO_EXT) != 0) {
7287 		for (i = 0; i < UFS_NXADDR; i++)
7288 			setup_freeext(freeblks, ip, i, 0);
7289 		ip->i_din2->di_extsize = 0;
7290 		datablocks += extblocks;
7291 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7292 	}
7293 #ifdef QUOTA
7294 	/* Reference the quotas in case the block count is wrong in the end. */
7295 	quotaref(ITOV(ip), freeblks->fb_quota);
7296 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7297 #endif
7298 	freeblks->fb_chkcnt = -datablocks;
7299 	UFS_LOCK(ump);
7300 	fs->fs_pendingblocks += datablocks;
7301 	UFS_UNLOCK(ump);
7302 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7303 	/*
7304 	 * Push the zero'ed inode to its disk buffer so that we are free
7305 	 * to delete its dependencies below. Once the dependencies are gone
7306 	 * the buffer can be safely released.
7307 	 */
7308 	if (ump->um_fstype == UFS1) {
7309 		dp1 = ((struct ufs1_dinode *)bp->b_data +
7310 		    ino_to_fsbo(fs, ip->i_number));
7311 		ip->i_din1->di_freelink = dp1->di_freelink;
7312 		*dp1 = *ip->i_din1;
7313 	} else {
7314 		dp2 = ((struct ufs2_dinode *)bp->b_data +
7315 		    ino_to_fsbo(fs, ip->i_number));
7316 		ip->i_din2->di_freelink = dp2->di_freelink;
7317 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7318 		*dp2 = *ip->i_din2;
7319 	}
7320 	/*
7321 	 * Find and eliminate any inode dependencies.
7322 	 */
7323 	ACQUIRE_LOCK(ump);
7324 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7325 	if ((inodedep->id_state & IOSTARTED) != 0)
7326 		panic("softdep_setup_freeblocks: inode busy");
7327 	/*
7328 	 * Add the freeblks structure to the list of operations that
7329 	 * must await the zero'ed inode being written to disk. If we
7330 	 * still have a bitmap dependency (delay == 0), then the inode
7331 	 * has never been written to disk, so we can process the
7332 	 * freeblks below once we have deleted the dependencies.
7333 	 */
7334 	delay = (inodedep->id_state & DEPCOMPLETE);
7335 	if (delay)
7336 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7337 	else
7338 		freeblks->fb_state |= COMPLETE;
7339 	/*
7340 	 * Because the file length has been truncated to zero, any
7341 	 * pending block allocation dependency structures associated
7342 	 * with this inode are obsolete and can simply be de-allocated.
7343 	 * We must first merge the two dependency lists to get rid of
7344 	 * any duplicate freefrag structures, then purge the merged list.
7345 	 * If we still have a bitmap dependency, then the inode has never
7346 	 * been written to disk, so we can free any fragments without delay.
7347 	 */
7348 	if (flags & IO_NORMAL) {
7349 		merge_inode_lists(&inodedep->id_newinoupdt,
7350 		    &inodedep->id_inoupdt);
7351 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7352 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7353 			    freeblks);
7354 	}
7355 	if (flags & IO_EXT) {
7356 		merge_inode_lists(&inodedep->id_newextupdt,
7357 		    &inodedep->id_extupdt);
7358 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7359 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7360 			    freeblks);
7361 	}
7362 	FREE_LOCK(ump);
7363 	bdwrite(bp);
7364 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7365 	ACQUIRE_LOCK(ump);
7366 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7367 		(void) free_inodedep(inodedep);
7368 	freeblks->fb_state |= DEPCOMPLETE;
7369 	/*
7370 	 * If the inode with zeroed block pointers is now on disk
7371 	 * we can start freeing blocks.
7372 	 */
7373 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7374 		freeblks->fb_state |= INPROGRESS;
7375 	else
7376 		freeblks = NULL;
7377 	FREE_LOCK(ump);
7378 	if (freeblks)
7379 		handle_workitem_freeblocks(freeblks, 0);
7380 	trunc_pages(ip, length, extblocks, flags);
7381 }
7382 
7383 /*
7384  * Eliminate pages from the page cache that back parts of this inode and
7385  * adjust the vnode pager's idea of our size.  This prevents stale data
7386  * from hanging around in the page cache.
7387  */
7388 static void
7389 trunc_pages(ip, length, extblocks, flags)
7390 	struct inode *ip;
7391 	off_t length;
7392 	ufs2_daddr_t extblocks;
7393 	int flags;
7394 {
7395 	struct vnode *vp;
7396 	struct fs *fs;
7397 	ufs_lbn_t lbn;
7398 	off_t end, extend;
7399 
7400 	vp = ITOV(ip);
7401 	fs = ITOFS(ip);
7402 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7403 	if ((flags & IO_EXT) != 0)
7404 		vn_pages_remove(vp, extend, 0);
7405 	if ((flags & IO_NORMAL) == 0)
7406 		return;
7407 	BO_LOCK(&vp->v_bufobj);
7408 	drain_output(vp);
7409 	BO_UNLOCK(&vp->v_bufobj);
7410 	/*
7411 	 * The vnode pager eliminates file pages we eliminate indirects
7412 	 * below.
7413 	 */
7414 	vnode_pager_setsize(vp, length);
7415 	/*
7416 	 * Calculate the end based on the last indirect we want to keep.  If
7417 	 * the block extends into indirects we can just use the negative of
7418 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7419 	 * be careful not to remove those, if they exist.  double and triple
7420 	 * indirect lbns do not overlap with others so it is not important
7421 	 * to verify how many levels are required.
7422 	 */
7423 	lbn = lblkno(fs, length);
7424 	if (lbn >= UFS_NDADDR) {
7425 		/* Calculate the virtual lbn of the triple indirect. */
7426 		lbn = -lbn - (UFS_NIADDR - 1);
7427 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7428 	} else
7429 		end = extend;
7430 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7431 }
7432 
7433 /*
7434  * See if the buf bp is in the range eliminated by truncation.
7435  */
7436 static int
7437 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7438 	struct buf *bp;
7439 	int *blkoffp;
7440 	ufs_lbn_t lastlbn;
7441 	int lastoff;
7442 	int flags;
7443 {
7444 	ufs_lbn_t lbn;
7445 
7446 	*blkoffp = 0;
7447 	/* Only match ext/normal blocks as appropriate. */
7448 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7449 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7450 		return (0);
7451 	/* ALTDATA is always a full truncation. */
7452 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7453 		return (1);
7454 	/* -1 is full truncation. */
7455 	if (lastlbn == -1)
7456 		return (1);
7457 	/*
7458 	 * If this is a partial truncate we only want those
7459 	 * blocks and indirect blocks that cover the range
7460 	 * we're after.
7461 	 */
7462 	lbn = bp->b_lblkno;
7463 	if (lbn < 0)
7464 		lbn = -(lbn + lbn_level(lbn));
7465 	if (lbn < lastlbn)
7466 		return (0);
7467 	/* Here we only truncate lblkno if it's partial. */
7468 	if (lbn == lastlbn) {
7469 		if (lastoff == 0)
7470 			return (0);
7471 		*blkoffp = lastoff;
7472 	}
7473 	return (1);
7474 }
7475 
7476 /*
7477  * Eliminate any dependencies that exist in memory beyond lblkno:off
7478  */
7479 static void
7480 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7481 	struct inode *ip;
7482 	struct freeblks *freeblks;
7483 	ufs_lbn_t lastlbn;
7484 	int lastoff;
7485 	int flags;
7486 {
7487 	struct bufobj *bo;
7488 	struct vnode *vp;
7489 	struct buf *bp;
7490 	int blkoff;
7491 
7492 	/*
7493 	 * We must wait for any I/O in progress to finish so that
7494 	 * all potential buffers on the dirty list will be visible.
7495 	 * Once they are all there, walk the list and get rid of
7496 	 * any dependencies.
7497 	 */
7498 	vp = ITOV(ip);
7499 	bo = &vp->v_bufobj;
7500 	BO_LOCK(bo);
7501 	drain_output(vp);
7502 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7503 		bp->b_vflags &= ~BV_SCANNED;
7504 restart:
7505 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7506 		if (bp->b_vflags & BV_SCANNED)
7507 			continue;
7508 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7509 			bp->b_vflags |= BV_SCANNED;
7510 			continue;
7511 		}
7512 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7513 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7514 			goto restart;
7515 		BO_UNLOCK(bo);
7516 		if (deallocate_dependencies(bp, freeblks, blkoff))
7517 			bqrelse(bp);
7518 		else
7519 			brelse(bp);
7520 		BO_LOCK(bo);
7521 		goto restart;
7522 	}
7523 	/*
7524 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7525 	 */
7526 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7527 		bp->b_vflags &= ~BV_SCANNED;
7528 cleanrestart:
7529 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7530 		if (bp->b_vflags & BV_SCANNED)
7531 			continue;
7532 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7533 			bp->b_vflags |= BV_SCANNED;
7534 			continue;
7535 		}
7536 		if (BUF_LOCK(bp,
7537 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7538 		    BO_LOCKPTR(bo)) == ENOLCK) {
7539 			BO_LOCK(bo);
7540 			goto cleanrestart;
7541 		}
7542 		bp->b_vflags |= BV_SCANNED;
7543 		bremfree(bp);
7544 		if (blkoff != 0) {
7545 			allocbuf(bp, blkoff);
7546 			bqrelse(bp);
7547 		} else {
7548 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7549 			brelse(bp);
7550 		}
7551 		BO_LOCK(bo);
7552 		goto cleanrestart;
7553 	}
7554 	drain_output(vp);
7555 	BO_UNLOCK(bo);
7556 }
7557 
7558 static int
7559 cancel_pagedep(pagedep, freeblks, blkoff)
7560 	struct pagedep *pagedep;
7561 	struct freeblks *freeblks;
7562 	int blkoff;
7563 {
7564 	struct jremref *jremref;
7565 	struct jmvref *jmvref;
7566 	struct dirrem *dirrem, *tmp;
7567 	int i;
7568 
7569 	/*
7570 	 * Copy any directory remove dependencies to the list
7571 	 * to be processed after the freeblks proceeds.  If
7572 	 * directory entry never made it to disk they
7573 	 * can be dumped directly onto the work list.
7574 	 */
7575 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7576 		/* Skip this directory removal if it is intended to remain. */
7577 		if (dirrem->dm_offset < blkoff)
7578 			continue;
7579 		/*
7580 		 * If there are any dirrems we wait for the journal write
7581 		 * to complete and then restart the buf scan as the lock
7582 		 * has been dropped.
7583 		 */
7584 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7585 			jwait(&jremref->jr_list, MNT_WAIT);
7586 			return (ERESTART);
7587 		}
7588 		LIST_REMOVE(dirrem, dm_next);
7589 		dirrem->dm_dirinum = pagedep->pd_ino;
7590 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7591 	}
7592 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7593 		jwait(&jmvref->jm_list, MNT_WAIT);
7594 		return (ERESTART);
7595 	}
7596 	/*
7597 	 * When we're partially truncating a pagedep we just want to flush
7598 	 * journal entries and return.  There can not be any adds in the
7599 	 * truncated portion of the directory and newblk must remain if
7600 	 * part of the block remains.
7601 	 */
7602 	if (blkoff != 0) {
7603 		struct diradd *dap;
7604 
7605 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7606 			if (dap->da_offset > blkoff)
7607 				panic("cancel_pagedep: diradd %p off %d > %d",
7608 				    dap, dap->da_offset, blkoff);
7609 		for (i = 0; i < DAHASHSZ; i++)
7610 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7611 				if (dap->da_offset > blkoff)
7612 					panic("cancel_pagedep: diradd %p off %d > %d",
7613 					    dap, dap->da_offset, blkoff);
7614 		return (0);
7615 	}
7616 	/*
7617 	 * There should be no directory add dependencies present
7618 	 * as the directory could not be truncated until all
7619 	 * children were removed.
7620 	 */
7621 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7622 	    ("deallocate_dependencies: pendinghd != NULL"));
7623 	for (i = 0; i < DAHASHSZ; i++)
7624 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7625 		    ("deallocate_dependencies: diraddhd != NULL"));
7626 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7627 		free_newdirblk(pagedep->pd_newdirblk);
7628 	if (free_pagedep(pagedep) == 0)
7629 		panic("Failed to free pagedep %p", pagedep);
7630 	return (0);
7631 }
7632 
7633 /*
7634  * Reclaim any dependency structures from a buffer that is about to
7635  * be reallocated to a new vnode. The buffer must be locked, thus,
7636  * no I/O completion operations can occur while we are manipulating
7637  * its associated dependencies. The mutex is held so that other I/O's
7638  * associated with related dependencies do not occur.
7639  */
7640 static int
7641 deallocate_dependencies(bp, freeblks, off)
7642 	struct buf *bp;
7643 	struct freeblks *freeblks;
7644 	int off;
7645 {
7646 	struct indirdep *indirdep;
7647 	struct pagedep *pagedep;
7648 	struct worklist *wk, *wkn;
7649 	struct ufsmount *ump;
7650 
7651 	ump = softdep_bp_to_mp(bp);
7652 	if (ump == NULL)
7653 		goto done;
7654 	ACQUIRE_LOCK(ump);
7655 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7656 		switch (wk->wk_type) {
7657 		case D_INDIRDEP:
7658 			indirdep = WK_INDIRDEP(wk);
7659 			if (bp->b_lblkno >= 0 ||
7660 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7661 				panic("deallocate_dependencies: not indir");
7662 			cancel_indirdep(indirdep, bp, freeblks);
7663 			continue;
7664 
7665 		case D_PAGEDEP:
7666 			pagedep = WK_PAGEDEP(wk);
7667 			if (cancel_pagedep(pagedep, freeblks, off)) {
7668 				FREE_LOCK(ump);
7669 				return (ERESTART);
7670 			}
7671 			continue;
7672 
7673 		case D_ALLOCINDIR:
7674 			/*
7675 			 * Simply remove the allocindir, we'll find it via
7676 			 * the indirdep where we can clear pointers if
7677 			 * needed.
7678 			 */
7679 			WORKLIST_REMOVE(wk);
7680 			continue;
7681 
7682 		case D_FREEWORK:
7683 			/*
7684 			 * A truncation is waiting for the zero'd pointers
7685 			 * to be written.  It can be freed when the freeblks
7686 			 * is journaled.
7687 			 */
7688 			WORKLIST_REMOVE(wk);
7689 			wk->wk_state |= ONDEPLIST;
7690 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7691 			break;
7692 
7693 		case D_ALLOCDIRECT:
7694 			if (off != 0)
7695 				continue;
7696 			/* FALLTHROUGH */
7697 		default:
7698 			panic("deallocate_dependencies: Unexpected type %s",
7699 			    TYPENAME(wk->wk_type));
7700 			/* NOTREACHED */
7701 		}
7702 	}
7703 	FREE_LOCK(ump);
7704 done:
7705 	/*
7706 	 * Don't throw away this buf, we were partially truncating and
7707 	 * some deps may always remain.
7708 	 */
7709 	if (off) {
7710 		allocbuf(bp, off);
7711 		bp->b_vflags |= BV_SCANNED;
7712 		return (EBUSY);
7713 	}
7714 	bp->b_flags |= B_INVAL | B_NOCACHE;
7715 
7716 	return (0);
7717 }
7718 
7719 /*
7720  * An allocdirect is being canceled due to a truncate.  We must make sure
7721  * the journal entry is released in concert with the blkfree that releases
7722  * the storage.  Completed journal entries must not be released until the
7723  * space is no longer pointed to by the inode or in the bitmap.
7724  */
7725 static void
7726 cancel_allocdirect(adphead, adp, freeblks)
7727 	struct allocdirectlst *adphead;
7728 	struct allocdirect *adp;
7729 	struct freeblks *freeblks;
7730 {
7731 	struct freework *freework;
7732 	struct newblk *newblk;
7733 	struct worklist *wk;
7734 
7735 	TAILQ_REMOVE(adphead, adp, ad_next);
7736 	newblk = (struct newblk *)adp;
7737 	freework = NULL;
7738 	/*
7739 	 * Find the correct freework structure.
7740 	 */
7741 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7742 		if (wk->wk_type != D_FREEWORK)
7743 			continue;
7744 		freework = WK_FREEWORK(wk);
7745 		if (freework->fw_blkno == newblk->nb_newblkno)
7746 			break;
7747 	}
7748 	if (freework == NULL)
7749 		panic("cancel_allocdirect: Freework not found");
7750 	/*
7751 	 * If a newblk exists at all we still have the journal entry that
7752 	 * initiated the allocation so we do not need to journal the free.
7753 	 */
7754 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7755 	/*
7756 	 * If the journal hasn't been written the jnewblk must be passed
7757 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7758 	 * this by linking the journal dependency into the freework to be
7759 	 * freed when freework_freeblock() is called.  If the journal has
7760 	 * been written we can simply reclaim the journal space when the
7761 	 * freeblks work is complete.
7762 	 */
7763 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7764 	    &freeblks->fb_jwork);
7765 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7766 }
7767 
7768 /*
7769  * Cancel a new block allocation.  May be an indirect or direct block.  We
7770  * remove it from various lists and return any journal record that needs to
7771  * be resolved by the caller.
7772  *
7773  * A special consideration is made for indirects which were never pointed
7774  * at on disk and will never be found once this block is released.
7775  */
7776 static struct jnewblk *
7777 cancel_newblk(newblk, wk, wkhd)
7778 	struct newblk *newblk;
7779 	struct worklist *wk;
7780 	struct workhead *wkhd;
7781 {
7782 	struct jnewblk *jnewblk;
7783 
7784 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7785 
7786 	newblk->nb_state |= GOINGAWAY;
7787 	/*
7788 	 * Previously we traversed the completedhd on each indirdep
7789 	 * attached to this newblk to cancel them and gather journal
7790 	 * work.  Since we need only the oldest journal segment and
7791 	 * the lowest point on the tree will always have the oldest
7792 	 * journal segment we are free to release the segments
7793 	 * of any subordinates and may leave the indirdep list to
7794 	 * indirdep_complete() when this newblk is freed.
7795 	 */
7796 	if (newblk->nb_state & ONDEPLIST) {
7797 		newblk->nb_state &= ~ONDEPLIST;
7798 		LIST_REMOVE(newblk, nb_deps);
7799 	}
7800 	if (newblk->nb_state & ONWORKLIST)
7801 		WORKLIST_REMOVE(&newblk->nb_list);
7802 	/*
7803 	 * If the journal entry hasn't been written we save a pointer to
7804 	 * the dependency that frees it until it is written or the
7805 	 * superseding operation completes.
7806 	 */
7807 	jnewblk = newblk->nb_jnewblk;
7808 	if (jnewblk != NULL && wk != NULL) {
7809 		newblk->nb_jnewblk = NULL;
7810 		jnewblk->jn_dep = wk;
7811 	}
7812 	if (!LIST_EMPTY(&newblk->nb_jwork))
7813 		jwork_move(wkhd, &newblk->nb_jwork);
7814 	/*
7815 	 * When truncating we must free the newdirblk early to remove
7816 	 * the pagedep from the hash before returning.
7817 	 */
7818 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7819 		free_newdirblk(WK_NEWDIRBLK(wk));
7820 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7821 		panic("cancel_newblk: extra newdirblk");
7822 
7823 	return (jnewblk);
7824 }
7825 
7826 /*
7827  * Schedule the freefrag associated with a newblk to be released once
7828  * the pointers are written and the previous block is no longer needed.
7829  */
7830 static void
7831 newblk_freefrag(newblk)
7832 	struct newblk *newblk;
7833 {
7834 	struct freefrag *freefrag;
7835 
7836 	if (newblk->nb_freefrag == NULL)
7837 		return;
7838 	freefrag = newblk->nb_freefrag;
7839 	newblk->nb_freefrag = NULL;
7840 	freefrag->ff_state |= COMPLETE;
7841 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7842 		add_to_worklist(&freefrag->ff_list, 0);
7843 }
7844 
7845 /*
7846  * Free a newblk. Generate a new freefrag work request if appropriate.
7847  * This must be called after the inode pointer and any direct block pointers
7848  * are valid or fully removed via truncate or frag extension.
7849  */
7850 static void
7851 free_newblk(newblk)
7852 	struct newblk *newblk;
7853 {
7854 	struct indirdep *indirdep;
7855 	struct worklist *wk;
7856 
7857 	KASSERT(newblk->nb_jnewblk == NULL,
7858 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7859 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7860 	    ("free_newblk: unclaimed newblk"));
7861 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7862 	newblk_freefrag(newblk);
7863 	if (newblk->nb_state & ONDEPLIST)
7864 		LIST_REMOVE(newblk, nb_deps);
7865 	if (newblk->nb_state & ONWORKLIST)
7866 		WORKLIST_REMOVE(&newblk->nb_list);
7867 	LIST_REMOVE(newblk, nb_hash);
7868 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7869 		free_newdirblk(WK_NEWDIRBLK(wk));
7870 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7871 		panic("free_newblk: extra newdirblk");
7872 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7873 		indirdep_complete(indirdep);
7874 	handle_jwork(&newblk->nb_jwork);
7875 	WORKITEM_FREE(newblk, D_NEWBLK);
7876 }
7877 
7878 /*
7879  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7880  */
7881 static void
7882 free_newdirblk(newdirblk)
7883 	struct newdirblk *newdirblk;
7884 {
7885 	struct pagedep *pagedep;
7886 	struct diradd *dap;
7887 	struct worklist *wk;
7888 
7889 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7890 	WORKLIST_REMOVE(&newdirblk->db_list);
7891 	/*
7892 	 * If the pagedep is still linked onto the directory buffer
7893 	 * dependency chain, then some of the entries on the
7894 	 * pd_pendinghd list may not be committed to disk yet. In
7895 	 * this case, we will simply clear the NEWBLOCK flag and
7896 	 * let the pd_pendinghd list be processed when the pagedep
7897 	 * is next written. If the pagedep is no longer on the buffer
7898 	 * dependency chain, then all the entries on the pd_pending
7899 	 * list are committed to disk and we can free them here.
7900 	 */
7901 	pagedep = newdirblk->db_pagedep;
7902 	pagedep->pd_state &= ~NEWBLOCK;
7903 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7904 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7905 			free_diradd(dap, NULL);
7906 		/*
7907 		 * If no dependencies remain, the pagedep will be freed.
7908 		 */
7909 		free_pagedep(pagedep);
7910 	}
7911 	/* Should only ever be one item in the list. */
7912 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7913 		WORKLIST_REMOVE(wk);
7914 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7915 	}
7916 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7917 }
7918 
7919 /*
7920  * Prepare an inode to be freed. The actual free operation is not
7921  * done until the zero'ed inode has been written to disk.
7922  */
7923 void
7924 softdep_freefile(pvp, ino, mode)
7925 	struct vnode *pvp;
7926 	ino_t ino;
7927 	int mode;
7928 {
7929 	struct inode *ip = VTOI(pvp);
7930 	struct inodedep *inodedep;
7931 	struct freefile *freefile;
7932 	struct freeblks *freeblks;
7933 	struct ufsmount *ump;
7934 
7935 	ump = ITOUMP(ip);
7936 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7937 	    ("softdep_freefile called on non-softdep filesystem"));
7938 	/*
7939 	 * This sets up the inode de-allocation dependency.
7940 	 */
7941 	freefile = malloc(sizeof(struct freefile),
7942 		M_FREEFILE, M_SOFTDEP_FLAGS);
7943 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7944 	freefile->fx_mode = mode;
7945 	freefile->fx_oldinum = ino;
7946 	freefile->fx_devvp = ump->um_devvp;
7947 	LIST_INIT(&freefile->fx_jwork);
7948 	UFS_LOCK(ump);
7949 	ump->um_fs->fs_pendinginodes += 1;
7950 	UFS_UNLOCK(ump);
7951 
7952 	/*
7953 	 * If the inodedep does not exist, then the zero'ed inode has
7954 	 * been written to disk. If the allocated inode has never been
7955 	 * written to disk, then the on-disk inode is zero'ed. In either
7956 	 * case we can free the file immediately.  If the journal was
7957 	 * canceled before being written the inode will never make it to
7958 	 * disk and we must send the canceled journal entrys to
7959 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7960 	 * Any blocks waiting on the inode to write can be safely freed
7961 	 * here as it will never been written.
7962 	 */
7963 	ACQUIRE_LOCK(ump);
7964 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7965 	if (inodedep) {
7966 		/*
7967 		 * Clear out freeblks that no longer need to reference
7968 		 * this inode.
7969 		 */
7970 		while ((freeblks =
7971 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7972 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7973 			    fb_next);
7974 			freeblks->fb_state &= ~ONDEPLIST;
7975 		}
7976 		/*
7977 		 * Remove this inode from the unlinked list.
7978 		 */
7979 		if (inodedep->id_state & UNLINKED) {
7980 			/*
7981 			 * Save the journal work to be freed with the bitmap
7982 			 * before we clear UNLINKED.  Otherwise it can be lost
7983 			 * if the inode block is written.
7984 			 */
7985 			handle_bufwait(inodedep, &freefile->fx_jwork);
7986 			clear_unlinked_inodedep(inodedep);
7987 			/*
7988 			 * Re-acquire inodedep as we've dropped the
7989 			 * per-filesystem lock in clear_unlinked_inodedep().
7990 			 */
7991 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7992 		}
7993 	}
7994 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7995 		FREE_LOCK(ump);
7996 		handle_workitem_freefile(freefile);
7997 		return;
7998 	}
7999 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
8000 		inodedep->id_state |= GOINGAWAY;
8001 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
8002 	FREE_LOCK(ump);
8003 	if (ip->i_number == ino)
8004 		UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
8005 }
8006 
8007 /*
8008  * Check to see if an inode has never been written to disk. If
8009  * so free the inodedep and return success, otherwise return failure.
8010  *
8011  * If we still have a bitmap dependency, then the inode has never
8012  * been written to disk. Drop the dependency as it is no longer
8013  * necessary since the inode is being deallocated. We set the
8014  * ALLCOMPLETE flags since the bitmap now properly shows that the
8015  * inode is not allocated. Even if the inode is actively being
8016  * written, it has been rolled back to its zero'ed state, so we
8017  * are ensured that a zero inode is what is on the disk. For short
8018  * lived files, this change will usually result in removing all the
8019  * dependencies from the inode so that it can be freed immediately.
8020  */
8021 static int
8022 check_inode_unwritten(inodedep)
8023 	struct inodedep *inodedep;
8024 {
8025 
8026 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8027 
8028 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
8029 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
8030 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
8031 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
8032 	    !LIST_EMPTY(&inodedep->id_inowait) ||
8033 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
8034 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
8035 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
8036 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
8037 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
8038 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
8039 	    inodedep->id_mkdiradd != NULL ||
8040 	    inodedep->id_nlinkdelta != 0)
8041 		return (0);
8042 	/*
8043 	 * Another process might be in initiate_write_inodeblock_ufs[12]
8044 	 * trying to allocate memory without holding "Softdep Lock".
8045 	 */
8046 	if ((inodedep->id_state & IOSTARTED) != 0 &&
8047 	    inodedep->id_savedino1 == NULL)
8048 		return (0);
8049 
8050 	if (inodedep->id_state & ONDEPLIST)
8051 		LIST_REMOVE(inodedep, id_deps);
8052 	inodedep->id_state &= ~ONDEPLIST;
8053 	inodedep->id_state |= ALLCOMPLETE;
8054 	inodedep->id_bmsafemap = NULL;
8055 	if (inodedep->id_state & ONWORKLIST)
8056 		WORKLIST_REMOVE(&inodedep->id_list);
8057 	if (inodedep->id_savedino1 != NULL) {
8058 		free(inodedep->id_savedino1, M_SAVEDINO);
8059 		inodedep->id_savedino1 = NULL;
8060 	}
8061 	if (free_inodedep(inodedep) == 0)
8062 		panic("check_inode_unwritten: busy inode");
8063 	return (1);
8064 }
8065 
8066 static int
8067 check_inodedep_free(inodedep)
8068 	struct inodedep *inodedep;
8069 {
8070 
8071 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8072 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
8073 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
8074 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
8075 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
8076 	    !LIST_EMPTY(&inodedep->id_inowait) ||
8077 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
8078 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
8079 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
8080 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
8081 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
8082 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
8083 	    inodedep->id_mkdiradd != NULL ||
8084 	    inodedep->id_nlinkdelta != 0 ||
8085 	    inodedep->id_savedino1 != NULL)
8086 		return (0);
8087 	return (1);
8088 }
8089 
8090 /*
8091  * Try to free an inodedep structure. Return 1 if it could be freed.
8092  */
8093 static int
8094 free_inodedep(inodedep)
8095 	struct inodedep *inodedep;
8096 {
8097 
8098 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8099 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
8100 	    !check_inodedep_free(inodedep))
8101 		return (0);
8102 	if (inodedep->id_state & ONDEPLIST)
8103 		LIST_REMOVE(inodedep, id_deps);
8104 	LIST_REMOVE(inodedep, id_hash);
8105 	WORKITEM_FREE(inodedep, D_INODEDEP);
8106 	return (1);
8107 }
8108 
8109 /*
8110  * Free the block referenced by a freework structure.  The parent freeblks
8111  * structure is released and completed when the final cg bitmap reaches
8112  * the disk.  This routine may be freeing a jnewblk which never made it to
8113  * disk in which case we do not have to wait as the operation is undone
8114  * in memory immediately.
8115  */
8116 static void
8117 freework_freeblock(freework, key)
8118 	struct freework *freework;
8119 	u_long key;
8120 {
8121 	struct freeblks *freeblks;
8122 	struct jnewblk *jnewblk;
8123 	struct ufsmount *ump;
8124 	struct workhead wkhd;
8125 	struct fs *fs;
8126 	int bsize;
8127 	int needj;
8128 
8129 	ump = VFSTOUFS(freework->fw_list.wk_mp);
8130 	LOCK_OWNED(ump);
8131 	/*
8132 	 * Handle partial truncate separately.
8133 	 */
8134 	if (freework->fw_indir) {
8135 		complete_trunc_indir(freework);
8136 		return;
8137 	}
8138 	freeblks = freework->fw_freeblks;
8139 	fs = ump->um_fs;
8140 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
8141 	bsize = lfragtosize(fs, freework->fw_frags);
8142 	LIST_INIT(&wkhd);
8143 	/*
8144 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
8145 	 * on the indirblk hashtable and prevents premature freeing.
8146 	 */
8147 	freework->fw_state |= DEPCOMPLETE;
8148 	/*
8149 	 * SUJ needs to wait for the segment referencing freed indirect
8150 	 * blocks to expire so that we know the checker will not confuse
8151 	 * a re-allocated indirect block with its old contents.
8152 	 */
8153 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
8154 		indirblk_insert(freework);
8155 	/*
8156 	 * If we are canceling an existing jnewblk pass it to the free
8157 	 * routine, otherwise pass the freeblk which will ultimately
8158 	 * release the freeblks.  If we're not journaling, we can just
8159 	 * free the freeblks immediately.
8160 	 */
8161 	jnewblk = freework->fw_jnewblk;
8162 	if (jnewblk != NULL) {
8163 		cancel_jnewblk(jnewblk, &wkhd);
8164 		needj = 0;
8165 	} else if (needj) {
8166 		freework->fw_state |= DELAYEDFREE;
8167 		freeblks->fb_cgwait++;
8168 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
8169 	}
8170 	FREE_LOCK(ump);
8171 	freeblks_free(ump, freeblks, btodb(bsize));
8172 	CTR4(KTR_SUJ,
8173 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
8174 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
8175 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
8176 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
8177 	ACQUIRE_LOCK(ump);
8178 	/*
8179 	 * The jnewblk will be discarded and the bits in the map never
8180 	 * made it to disk.  We can immediately free the freeblk.
8181 	 */
8182 	if (needj == 0)
8183 		handle_written_freework(freework);
8184 }
8185 
8186 /*
8187  * We enqueue freework items that need processing back on the freeblks and
8188  * add the freeblks to the worklist.  This makes it easier to find all work
8189  * required to flush a truncation in process_truncates().
8190  */
8191 static void
8192 freework_enqueue(freework)
8193 	struct freework *freework;
8194 {
8195 	struct freeblks *freeblks;
8196 
8197 	freeblks = freework->fw_freeblks;
8198 	if ((freework->fw_state & INPROGRESS) == 0)
8199 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
8200 	if ((freeblks->fb_state &
8201 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
8202 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
8203 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8204 }
8205 
8206 /*
8207  * Start, continue, or finish the process of freeing an indirect block tree.
8208  * The free operation may be paused at any point with fw_off containing the
8209  * offset to restart from.  This enables us to implement some flow control
8210  * for large truncates which may fan out and generate a huge number of
8211  * dependencies.
8212  */
8213 static void
8214 handle_workitem_indirblk(freework)
8215 	struct freework *freework;
8216 {
8217 	struct freeblks *freeblks;
8218 	struct ufsmount *ump;
8219 	struct fs *fs;
8220 
8221 	freeblks = freework->fw_freeblks;
8222 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8223 	fs = ump->um_fs;
8224 	if (freework->fw_state & DEPCOMPLETE) {
8225 		handle_written_freework(freework);
8226 		return;
8227 	}
8228 	if (freework->fw_off == NINDIR(fs)) {
8229 		freework_freeblock(freework, SINGLETON_KEY);
8230 		return;
8231 	}
8232 	freework->fw_state |= INPROGRESS;
8233 	FREE_LOCK(ump);
8234 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
8235 	    freework->fw_lbn);
8236 	ACQUIRE_LOCK(ump);
8237 }
8238 
8239 /*
8240  * Called when a freework structure attached to a cg buf is written.  The
8241  * ref on either the parent or the freeblks structure is released and
8242  * the freeblks is added back to the worklist if there is more work to do.
8243  */
8244 static void
8245 handle_written_freework(freework)
8246 	struct freework *freework;
8247 {
8248 	struct freeblks *freeblks;
8249 	struct freework *parent;
8250 
8251 	freeblks = freework->fw_freeblks;
8252 	parent = freework->fw_parent;
8253 	if (freework->fw_state & DELAYEDFREE)
8254 		freeblks->fb_cgwait--;
8255 	freework->fw_state |= COMPLETE;
8256 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
8257 		WORKITEM_FREE(freework, D_FREEWORK);
8258 	if (parent) {
8259 		if (--parent->fw_ref == 0)
8260 			freework_enqueue(parent);
8261 		return;
8262 	}
8263 	if (--freeblks->fb_ref != 0)
8264 		return;
8265 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
8266 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
8267 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8268 }
8269 
8270 /*
8271  * This workitem routine performs the block de-allocation.
8272  * The workitem is added to the pending list after the updated
8273  * inode block has been written to disk.  As mentioned above,
8274  * checks regarding the number of blocks de-allocated (compared
8275  * to the number of blocks allocated for the file) are also
8276  * performed in this function.
8277  */
8278 static int
8279 handle_workitem_freeblocks(freeblks, flags)
8280 	struct freeblks *freeblks;
8281 	int flags;
8282 {
8283 	struct freework *freework;
8284 	struct newblk *newblk;
8285 	struct allocindir *aip;
8286 	struct ufsmount *ump;
8287 	struct worklist *wk;
8288 	u_long key;
8289 
8290 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
8291 	    ("handle_workitem_freeblocks: Journal entries not written."));
8292 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8293 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8294 	ACQUIRE_LOCK(ump);
8295 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
8296 		WORKLIST_REMOVE(wk);
8297 		switch (wk->wk_type) {
8298 		case D_DIRREM:
8299 			wk->wk_state |= COMPLETE;
8300 			add_to_worklist(wk, 0);
8301 			continue;
8302 
8303 		case D_ALLOCDIRECT:
8304 			free_newblk(WK_NEWBLK(wk));
8305 			continue;
8306 
8307 		case D_ALLOCINDIR:
8308 			aip = WK_ALLOCINDIR(wk);
8309 			freework = NULL;
8310 			if (aip->ai_state & DELAYEDFREE) {
8311 				FREE_LOCK(ump);
8312 				freework = newfreework(ump, freeblks, NULL,
8313 				    aip->ai_lbn, aip->ai_newblkno,
8314 				    ump->um_fs->fs_frag, 0, 0);
8315 				ACQUIRE_LOCK(ump);
8316 			}
8317 			newblk = WK_NEWBLK(wk);
8318 			if (newblk->nb_jnewblk) {
8319 				freework->fw_jnewblk = newblk->nb_jnewblk;
8320 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
8321 				newblk->nb_jnewblk = NULL;
8322 			}
8323 			free_newblk(newblk);
8324 			continue;
8325 
8326 		case D_FREEWORK:
8327 			freework = WK_FREEWORK(wk);
8328 			if (freework->fw_lbn <= -UFS_NDADDR)
8329 				handle_workitem_indirblk(freework);
8330 			else
8331 				freework_freeblock(freework, key);
8332 			continue;
8333 		default:
8334 			panic("handle_workitem_freeblocks: Unknown type %s",
8335 			    TYPENAME(wk->wk_type));
8336 		}
8337 	}
8338 	if (freeblks->fb_ref != 0) {
8339 		freeblks->fb_state &= ~INPROGRESS;
8340 		wake_worklist(&freeblks->fb_list);
8341 		freeblks = NULL;
8342 	}
8343 	FREE_LOCK(ump);
8344 	ffs_blkrelease_finish(ump, key);
8345 	if (freeblks)
8346 		return handle_complete_freeblocks(freeblks, flags);
8347 	return (0);
8348 }
8349 
8350 /*
8351  * Handle completion of block free via truncate.  This allows fs_pending
8352  * to track the actual free block count more closely than if we only updated
8353  * it at the end.  We must be careful to handle cases where the block count
8354  * on free was incorrect.
8355  */
8356 static void
8357 freeblks_free(ump, freeblks, blocks)
8358 	struct ufsmount *ump;
8359 	struct freeblks *freeblks;
8360 	int blocks;
8361 {
8362 	struct fs *fs;
8363 	ufs2_daddr_t remain;
8364 
8365 	UFS_LOCK(ump);
8366 	remain = -freeblks->fb_chkcnt;
8367 	freeblks->fb_chkcnt += blocks;
8368 	if (remain > 0) {
8369 		if (remain < blocks)
8370 			blocks = remain;
8371 		fs = ump->um_fs;
8372 		fs->fs_pendingblocks -= blocks;
8373 	}
8374 	UFS_UNLOCK(ump);
8375 }
8376 
8377 /*
8378  * Once all of the freework workitems are complete we can retire the
8379  * freeblocks dependency and any journal work awaiting completion.  This
8380  * can not be called until all other dependencies are stable on disk.
8381  */
8382 static int
8383 handle_complete_freeblocks(freeblks, flags)
8384 	struct freeblks *freeblks;
8385 	int flags;
8386 {
8387 	struct inodedep *inodedep;
8388 	struct inode *ip;
8389 	struct vnode *vp;
8390 	struct fs *fs;
8391 	struct ufsmount *ump;
8392 	ufs2_daddr_t spare;
8393 
8394 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8395 	fs = ump->um_fs;
8396 	flags = LK_EXCLUSIVE | flags;
8397 	spare = freeblks->fb_chkcnt;
8398 
8399 	/*
8400 	 * If we did not release the expected number of blocks we may have
8401 	 * to adjust the inode block count here.  Only do so if it wasn't
8402 	 * a truncation to zero and the modrev still matches.
8403 	 */
8404 	if (spare && freeblks->fb_len != 0) {
8405 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8406 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8407 			return (EBUSY);
8408 		ip = VTOI(vp);
8409 		if (ip->i_mode == 0) {
8410 			vgone(vp);
8411 		} else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8412 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8413 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8414 			/*
8415 			 * We must wait so this happens before the
8416 			 * journal is reclaimed.
8417 			 */
8418 			ffs_update(vp, 1);
8419 		}
8420 		vput(vp);
8421 	}
8422 	if (spare < 0) {
8423 		UFS_LOCK(ump);
8424 		fs->fs_pendingblocks += spare;
8425 		UFS_UNLOCK(ump);
8426 	}
8427 #ifdef QUOTA
8428 	/* Handle spare. */
8429 	if (spare)
8430 		quotaadj(freeblks->fb_quota, ump, -spare);
8431 	quotarele(freeblks->fb_quota);
8432 #endif
8433 	ACQUIRE_LOCK(ump);
8434 	if (freeblks->fb_state & ONDEPLIST) {
8435 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8436 		    0, &inodedep);
8437 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8438 		freeblks->fb_state &= ~ONDEPLIST;
8439 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8440 			free_inodedep(inodedep);
8441 	}
8442 	/*
8443 	 * All of the freeblock deps must be complete prior to this call
8444 	 * so it's now safe to complete earlier outstanding journal entries.
8445 	 */
8446 	handle_jwork(&freeblks->fb_jwork);
8447 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8448 	FREE_LOCK(ump);
8449 	return (0);
8450 }
8451 
8452 /*
8453  * Release blocks associated with the freeblks and stored in the indirect
8454  * block dbn. If level is greater than SINGLE, the block is an indirect block
8455  * and recursive calls to indirtrunc must be used to cleanse other indirect
8456  * blocks.
8457  *
8458  * This handles partial and complete truncation of blocks.  Partial is noted
8459  * with goingaway == 0.  In this case the freework is completed after the
8460  * zero'd indirects are written to disk.  For full truncation the freework
8461  * is completed after the block is freed.
8462  */
8463 static void
8464 indir_trunc(freework, dbn, lbn)
8465 	struct freework *freework;
8466 	ufs2_daddr_t dbn;
8467 	ufs_lbn_t lbn;
8468 {
8469 	struct freework *nfreework;
8470 	struct workhead wkhd;
8471 	struct freeblks *freeblks;
8472 	struct buf *bp;
8473 	struct fs *fs;
8474 	struct indirdep *indirdep;
8475 	struct mount *mp;
8476 	struct ufsmount *ump;
8477 	ufs1_daddr_t *bap1;
8478 	ufs2_daddr_t nb, nnb, *bap2;
8479 	ufs_lbn_t lbnadd, nlbn;
8480 	u_long key;
8481 	int nblocks, ufs1fmt, freedblocks;
8482 	int goingaway, freedeps, needj, level, cnt, i, error;
8483 
8484 	freeblks = freework->fw_freeblks;
8485 	mp = freeblks->fb_list.wk_mp;
8486 	ump = VFSTOUFS(mp);
8487 	fs = ump->um_fs;
8488 	/*
8489 	 * Get buffer of block pointers to be freed.  There are three cases:
8490 	 *
8491 	 * 1) Partial truncate caches the indirdep pointer in the freework
8492 	 *    which provides us a back copy to the save bp which holds the
8493 	 *    pointers we want to clear.  When this completes the zero
8494 	 *    pointers are written to the real copy.
8495 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8496 	 *    eliminated the real copy and placed the indirdep on the saved
8497 	 *    copy.  The indirdep and buf are discarded when this completes.
8498 	 * 3) The indirect was not in memory, we read a copy off of the disk
8499 	 *    using the devvp and drop and invalidate the buffer when we're
8500 	 *    done.
8501 	 */
8502 	goingaway = 1;
8503 	indirdep = NULL;
8504 	if (freework->fw_indir != NULL) {
8505 		goingaway = 0;
8506 		indirdep = freework->fw_indir;
8507 		bp = indirdep->ir_savebp;
8508 		if (bp == NULL || bp->b_blkno != dbn)
8509 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8510 			    bp, (intmax_t)dbn);
8511 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8512 		/*
8513 		 * The lock prevents the buf dep list from changing and
8514 	 	 * indirects on devvp should only ever have one dependency.
8515 		 */
8516 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8517 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8518 			panic("indir_trunc: Bad indirdep %p from buf %p",
8519 			    indirdep, bp);
8520 	} else {
8521 		error = ffs_breadz(ump, freeblks->fb_devvp, dbn, dbn,
8522 		    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
8523 		if (error)
8524 			return;
8525 	}
8526 	ACQUIRE_LOCK(ump);
8527 	/* Protects against a race with complete_trunc_indir(). */
8528 	freework->fw_state &= ~INPROGRESS;
8529 	/*
8530 	 * If we have an indirdep we need to enforce the truncation order
8531 	 * and discard it when it is complete.
8532 	 */
8533 	if (indirdep) {
8534 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8535 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8536 			/*
8537 			 * Add the complete truncate to the list on the
8538 			 * indirdep to enforce in-order processing.
8539 			 */
8540 			if (freework->fw_indir == NULL)
8541 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8542 				    freework, fw_next);
8543 			FREE_LOCK(ump);
8544 			return;
8545 		}
8546 		/*
8547 		 * If we're goingaway, free the indirdep.  Otherwise it will
8548 		 * linger until the write completes.
8549 		 */
8550 		if (goingaway) {
8551 			KASSERT(indirdep->ir_savebp == bp,
8552 			    ("indir_trunc: losing ir_savebp %p",
8553 			    indirdep->ir_savebp));
8554 			indirdep->ir_savebp = NULL;
8555 			free_indirdep(indirdep);
8556 		}
8557 	}
8558 	FREE_LOCK(ump);
8559 	/* Initialize pointers depending on block size. */
8560 	if (ump->um_fstype == UFS1) {
8561 		bap1 = (ufs1_daddr_t *)bp->b_data;
8562 		nb = bap1[freework->fw_off];
8563 		ufs1fmt = 1;
8564 		bap2 = NULL;
8565 	} else {
8566 		bap2 = (ufs2_daddr_t *)bp->b_data;
8567 		nb = bap2[freework->fw_off];
8568 		ufs1fmt = 0;
8569 		bap1 = NULL;
8570 	}
8571 	level = lbn_level(lbn);
8572 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8573 	lbnadd = lbn_offset(fs, level);
8574 	nblocks = btodb(fs->fs_bsize);
8575 	nfreework = freework;
8576 	freedeps = 0;
8577 	cnt = 0;
8578 	/*
8579 	 * Reclaim blocks.  Traverses into nested indirect levels and
8580 	 * arranges for the current level to be freed when subordinates
8581 	 * are free when journaling.
8582 	 */
8583 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8584 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8585 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8586 		    fs->fs_bsize) != 0)
8587 			nb = 0;
8588 		if (i != NINDIR(fs) - 1) {
8589 			if (ufs1fmt)
8590 				nnb = bap1[i+1];
8591 			else
8592 				nnb = bap2[i+1];
8593 		} else
8594 			nnb = 0;
8595 		if (nb == 0)
8596 			continue;
8597 		cnt++;
8598 		if (level != 0) {
8599 			nlbn = (lbn + 1) - (i * lbnadd);
8600 			if (needj != 0) {
8601 				nfreework = newfreework(ump, freeblks, freework,
8602 				    nlbn, nb, fs->fs_frag, 0, 0);
8603 				freedeps++;
8604 			}
8605 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8606 		} else {
8607 			struct freedep *freedep;
8608 
8609 			/*
8610 			 * Attempt to aggregate freedep dependencies for
8611 			 * all blocks being released to the same CG.
8612 			 */
8613 			LIST_INIT(&wkhd);
8614 			if (needj != 0 &&
8615 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8616 				freedep = newfreedep(freework);
8617 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8618 				    &freedep->fd_list);
8619 				freedeps++;
8620 			}
8621 			CTR3(KTR_SUJ,
8622 			    "indir_trunc: ino %jd blkno %jd size %d",
8623 			    freeblks->fb_inum, nb, fs->fs_bsize);
8624 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8625 			    fs->fs_bsize, freeblks->fb_inum,
8626 			    freeblks->fb_vtype, &wkhd, key);
8627 		}
8628 	}
8629 	ffs_blkrelease_finish(ump, key);
8630 	if (goingaway) {
8631 		bp->b_flags |= B_INVAL | B_NOCACHE;
8632 		brelse(bp);
8633 	}
8634 	freedblocks = 0;
8635 	if (level == 0)
8636 		freedblocks = (nblocks * cnt);
8637 	if (needj == 0)
8638 		freedblocks += nblocks;
8639 	freeblks_free(ump, freeblks, freedblocks);
8640 	/*
8641 	 * If we are journaling set up the ref counts and offset so this
8642 	 * indirect can be completed when its children are free.
8643 	 */
8644 	if (needj) {
8645 		ACQUIRE_LOCK(ump);
8646 		freework->fw_off = i;
8647 		freework->fw_ref += freedeps;
8648 		freework->fw_ref -= NINDIR(fs) + 1;
8649 		if (level == 0)
8650 			freeblks->fb_cgwait += freedeps;
8651 		if (freework->fw_ref == 0)
8652 			freework_freeblock(freework, SINGLETON_KEY);
8653 		FREE_LOCK(ump);
8654 		return;
8655 	}
8656 	/*
8657 	 * If we're not journaling we can free the indirect now.
8658 	 */
8659 	dbn = dbtofsb(fs, dbn);
8660 	CTR3(KTR_SUJ,
8661 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8662 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8663 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8664 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8665 	/* Non SUJ softdep does single-threaded truncations. */
8666 	if (freework->fw_blkno == dbn) {
8667 		freework->fw_state |= ALLCOMPLETE;
8668 		ACQUIRE_LOCK(ump);
8669 		handle_written_freework(freework);
8670 		FREE_LOCK(ump);
8671 	}
8672 	return;
8673 }
8674 
8675 /*
8676  * Cancel an allocindir when it is removed via truncation.  When bp is not
8677  * NULL the indirect never appeared on disk and is scheduled to be freed
8678  * independently of the indir so we can more easily track journal work.
8679  */
8680 static void
8681 cancel_allocindir(aip, bp, freeblks, trunc)
8682 	struct allocindir *aip;
8683 	struct buf *bp;
8684 	struct freeblks *freeblks;
8685 	int trunc;
8686 {
8687 	struct indirdep *indirdep;
8688 	struct freefrag *freefrag;
8689 	struct newblk *newblk;
8690 
8691 	newblk = (struct newblk *)aip;
8692 	LIST_REMOVE(aip, ai_next);
8693 	/*
8694 	 * We must eliminate the pointer in bp if it must be freed on its
8695 	 * own due to partial truncate or pending journal work.
8696 	 */
8697 	if (bp && (trunc || newblk->nb_jnewblk)) {
8698 		/*
8699 		 * Clear the pointer and mark the aip to be freed
8700 		 * directly if it never existed on disk.
8701 		 */
8702 		aip->ai_state |= DELAYEDFREE;
8703 		indirdep = aip->ai_indirdep;
8704 		if (indirdep->ir_state & UFS1FMT)
8705 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8706 		else
8707 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8708 	}
8709 	/*
8710 	 * When truncating the previous pointer will be freed via
8711 	 * savedbp.  Eliminate the freefrag which would dup free.
8712 	 */
8713 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8714 		newblk->nb_freefrag = NULL;
8715 		if (freefrag->ff_jdep)
8716 			cancel_jfreefrag(
8717 			    WK_JFREEFRAG(freefrag->ff_jdep));
8718 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8719 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8720 	}
8721 	/*
8722 	 * If the journal hasn't been written the jnewblk must be passed
8723 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8724 	 * this by leaving the journal dependency on the newblk to be freed
8725 	 * when a freework is created in handle_workitem_freeblocks().
8726 	 */
8727 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8728 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8729 }
8730 
8731 /*
8732  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8733  * in to a newdirblk so any subsequent additions are tracked properly.  The
8734  * caller is responsible for adding the mkdir1 dependency to the journal
8735  * and updating id_mkdiradd.  This function returns with the per-filesystem
8736  * lock held.
8737  */
8738 static struct mkdir *
8739 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8740 	struct diradd *dap;
8741 	ino_t newinum;
8742 	ino_t dinum;
8743 	struct buf *newdirbp;
8744 	struct mkdir **mkdirp;
8745 {
8746 	struct newblk *newblk;
8747 	struct pagedep *pagedep;
8748 	struct inodedep *inodedep;
8749 	struct newdirblk *newdirblk;
8750 	struct mkdir *mkdir1, *mkdir2;
8751 	struct worklist *wk;
8752 	struct jaddref *jaddref;
8753 	struct ufsmount *ump;
8754 	struct mount *mp;
8755 
8756 	mp = dap->da_list.wk_mp;
8757 	ump = VFSTOUFS(mp);
8758 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8759 	    M_SOFTDEP_FLAGS);
8760 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8761 	LIST_INIT(&newdirblk->db_mkdir);
8762 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8763 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8764 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8765 	mkdir1->md_diradd = dap;
8766 	mkdir1->md_jaddref = NULL;
8767 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8768 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8769 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8770 	mkdir2->md_diradd = dap;
8771 	mkdir2->md_jaddref = NULL;
8772 	if (MOUNTEDSUJ(mp) == 0) {
8773 		mkdir1->md_state |= DEPCOMPLETE;
8774 		mkdir2->md_state |= DEPCOMPLETE;
8775 	}
8776 	/*
8777 	 * Dependency on "." and ".." being written to disk.
8778 	 */
8779 	mkdir1->md_buf = newdirbp;
8780 	ACQUIRE_LOCK(VFSTOUFS(mp));
8781 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8782 	/*
8783 	 * We must link the pagedep, allocdirect, and newdirblk for
8784 	 * the initial file page so the pointer to the new directory
8785 	 * is not written until the directory contents are live and
8786 	 * any subsequent additions are not marked live until the
8787 	 * block is reachable via the inode.
8788 	 */
8789 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8790 		panic("setup_newdir: lost pagedep");
8791 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8792 		if (wk->wk_type == D_ALLOCDIRECT)
8793 			break;
8794 	if (wk == NULL)
8795 		panic("setup_newdir: lost allocdirect");
8796 	if (pagedep->pd_state & NEWBLOCK)
8797 		panic("setup_newdir: NEWBLOCK already set");
8798 	newblk = WK_NEWBLK(wk);
8799 	pagedep->pd_state |= NEWBLOCK;
8800 	pagedep->pd_newdirblk = newdirblk;
8801 	newdirblk->db_pagedep = pagedep;
8802 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8803 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8804 	/*
8805 	 * Look up the inodedep for the parent directory so that we
8806 	 * can link mkdir2 into the pending dotdot jaddref or
8807 	 * the inode write if there is none.  If the inode is
8808 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8809 	 * been satisfied and mkdir2 can be freed.
8810 	 */
8811 	inodedep_lookup(mp, dinum, 0, &inodedep);
8812 	if (MOUNTEDSUJ(mp)) {
8813 		if (inodedep == NULL)
8814 			panic("setup_newdir: Lost parent.");
8815 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8816 		    inoreflst);
8817 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8818 		    (jaddref->ja_state & MKDIR_PARENT),
8819 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8820 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8821 		mkdir2->md_jaddref = jaddref;
8822 		jaddref->ja_mkdir = mkdir2;
8823 	} else if (inodedep == NULL ||
8824 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8825 		dap->da_state &= ~MKDIR_PARENT;
8826 		WORKITEM_FREE(mkdir2, D_MKDIR);
8827 		mkdir2 = NULL;
8828 	} else {
8829 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8830 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8831 	}
8832 	*mkdirp = mkdir2;
8833 
8834 	return (mkdir1);
8835 }
8836 
8837 /*
8838  * Directory entry addition dependencies.
8839  *
8840  * When adding a new directory entry, the inode (with its incremented link
8841  * count) must be written to disk before the directory entry's pointer to it.
8842  * Also, if the inode is newly allocated, the corresponding freemap must be
8843  * updated (on disk) before the directory entry's pointer. These requirements
8844  * are met via undo/redo on the directory entry's pointer, which consists
8845  * simply of the inode number.
8846  *
8847  * As directory entries are added and deleted, the free space within a
8848  * directory block can become fragmented.  The ufs filesystem will compact
8849  * a fragmented directory block to make space for a new entry. When this
8850  * occurs, the offsets of previously added entries change. Any "diradd"
8851  * dependency structures corresponding to these entries must be updated with
8852  * the new offsets.
8853  */
8854 
8855 /*
8856  * This routine is called after the in-memory inode's link
8857  * count has been incremented, but before the directory entry's
8858  * pointer to the inode has been set.
8859  */
8860 int
8861 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8862 	struct buf *bp;		/* buffer containing directory block */
8863 	struct inode *dp;	/* inode for directory */
8864 	off_t diroffset;	/* offset of new entry in directory */
8865 	ino_t newinum;		/* inode referenced by new directory entry */
8866 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8867 	int isnewblk;		/* entry is in a newly allocated block */
8868 {
8869 	int offset;		/* offset of new entry within directory block */
8870 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8871 	struct fs *fs;
8872 	struct diradd *dap;
8873 	struct newblk *newblk;
8874 	struct pagedep *pagedep;
8875 	struct inodedep *inodedep;
8876 	struct newdirblk *newdirblk;
8877 	struct mkdir *mkdir1, *mkdir2;
8878 	struct jaddref *jaddref;
8879 	struct ufsmount *ump;
8880 	struct mount *mp;
8881 	int isindir;
8882 
8883 	mp = ITOVFS(dp);
8884 	ump = VFSTOUFS(mp);
8885 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8886 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8887 	/*
8888 	 * Whiteouts have no dependencies.
8889 	 */
8890 	if (newinum == UFS_WINO) {
8891 		if (newdirbp != NULL)
8892 			bdwrite(newdirbp);
8893 		return (0);
8894 	}
8895 	jaddref = NULL;
8896 	mkdir1 = mkdir2 = NULL;
8897 	fs = ump->um_fs;
8898 	lbn = lblkno(fs, diroffset);
8899 	offset = blkoff(fs, diroffset);
8900 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8901 		M_SOFTDEP_FLAGS|M_ZERO);
8902 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8903 	dap->da_offset = offset;
8904 	dap->da_newinum = newinum;
8905 	dap->da_state = ATTACHED;
8906 	LIST_INIT(&dap->da_jwork);
8907 	isindir = bp->b_lblkno >= UFS_NDADDR;
8908 	newdirblk = NULL;
8909 	if (isnewblk &&
8910 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8911 		newdirblk = malloc(sizeof(struct newdirblk),
8912 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8913 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8914 		LIST_INIT(&newdirblk->db_mkdir);
8915 	}
8916 	/*
8917 	 * If we're creating a new directory setup the dependencies and set
8918 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8919 	 * we can move on.
8920 	 */
8921 	if (newdirbp == NULL) {
8922 		dap->da_state |= DEPCOMPLETE;
8923 		ACQUIRE_LOCK(ump);
8924 	} else {
8925 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8926 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8927 		    &mkdir2);
8928 	}
8929 	/*
8930 	 * Link into parent directory pagedep to await its being written.
8931 	 */
8932 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8933 #ifdef INVARIANTS
8934 	if (diradd_lookup(pagedep, offset) != NULL)
8935 		panic("softdep_setup_directory_add: %p already at off %d\n",
8936 		    diradd_lookup(pagedep, offset), offset);
8937 #endif
8938 	dap->da_pagedep = pagedep;
8939 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8940 	    da_pdlist);
8941 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8942 	/*
8943 	 * If we're journaling, link the diradd into the jaddref so it
8944 	 * may be completed after the journal entry is written.  Otherwise,
8945 	 * link the diradd into its inodedep.  If the inode is not yet
8946 	 * written place it on the bufwait list, otherwise do the post-inode
8947 	 * write processing to put it on the id_pendinghd list.
8948 	 */
8949 	if (MOUNTEDSUJ(mp)) {
8950 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8951 		    inoreflst);
8952 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8953 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8954 		jaddref->ja_diroff = diroffset;
8955 		jaddref->ja_diradd = dap;
8956 		add_to_journal(&jaddref->ja_list);
8957 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8958 		diradd_inode_written(dap, inodedep);
8959 	else
8960 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8961 	/*
8962 	 * Add the journal entries for . and .. links now that the primary
8963 	 * link is written.
8964 	 */
8965 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8966 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8967 		    inoreflst, if_deps);
8968 		KASSERT(jaddref != NULL &&
8969 		    jaddref->ja_ino == jaddref->ja_parent &&
8970 		    (jaddref->ja_state & MKDIR_BODY),
8971 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8972 		    jaddref));
8973 		mkdir1->md_jaddref = jaddref;
8974 		jaddref->ja_mkdir = mkdir1;
8975 		/*
8976 		 * It is important that the dotdot journal entry
8977 		 * is added prior to the dot entry since dot writes
8978 		 * both the dot and dotdot links.  These both must
8979 		 * be added after the primary link for the journal
8980 		 * to remain consistent.
8981 		 */
8982 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8983 		add_to_journal(&jaddref->ja_list);
8984 	}
8985 	/*
8986 	 * If we are adding a new directory remember this diradd so that if
8987 	 * we rename it we can keep the dot and dotdot dependencies.  If
8988 	 * we are adding a new name for an inode that has a mkdiradd we
8989 	 * must be in rename and we have to move the dot and dotdot
8990 	 * dependencies to this new name.  The old name is being orphaned
8991 	 * soon.
8992 	 */
8993 	if (mkdir1 != NULL) {
8994 		if (inodedep->id_mkdiradd != NULL)
8995 			panic("softdep_setup_directory_add: Existing mkdir");
8996 		inodedep->id_mkdiradd = dap;
8997 	} else if (inodedep->id_mkdiradd)
8998 		merge_diradd(inodedep, dap);
8999 	if (newdirblk != NULL) {
9000 		/*
9001 		 * There is nothing to do if we are already tracking
9002 		 * this block.
9003 		 */
9004 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
9005 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
9006 			FREE_LOCK(ump);
9007 			return (0);
9008 		}
9009 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
9010 		    == 0)
9011 			panic("softdep_setup_directory_add: lost entry");
9012 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
9013 		pagedep->pd_state |= NEWBLOCK;
9014 		pagedep->pd_newdirblk = newdirblk;
9015 		newdirblk->db_pagedep = pagedep;
9016 		FREE_LOCK(ump);
9017 		/*
9018 		 * If we extended into an indirect signal direnter to sync.
9019 		 */
9020 		if (isindir)
9021 			return (1);
9022 		return (0);
9023 	}
9024 	FREE_LOCK(ump);
9025 	return (0);
9026 }
9027 
9028 /*
9029  * This procedure is called to change the offset of a directory
9030  * entry when compacting a directory block which must be owned
9031  * exclusively by the caller. Note that the actual entry movement
9032  * must be done in this procedure to ensure that no I/O completions
9033  * occur while the move is in progress.
9034  */
9035 void
9036 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
9037 	struct buf *bp;		/* Buffer holding directory block. */
9038 	struct inode *dp;	/* inode for directory */
9039 	caddr_t base;		/* address of dp->i_offset */
9040 	caddr_t oldloc;		/* address of old directory location */
9041 	caddr_t newloc;		/* address of new directory location */
9042 	int entrysize;		/* size of directory entry */
9043 {
9044 	int offset, oldoffset, newoffset;
9045 	struct pagedep *pagedep;
9046 	struct jmvref *jmvref;
9047 	struct diradd *dap;
9048 	struct direct *de;
9049 	struct mount *mp;
9050 	struct ufsmount *ump;
9051 	ufs_lbn_t lbn;
9052 	int flags;
9053 
9054 	mp = ITOVFS(dp);
9055 	ump = VFSTOUFS(mp);
9056 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9057 	    ("softdep_change_directoryentry_offset called on "
9058 	     "non-softdep filesystem"));
9059 	de = (struct direct *)oldloc;
9060 	jmvref = NULL;
9061 	flags = 0;
9062 	/*
9063 	 * Moves are always journaled as it would be too complex to
9064 	 * determine if any affected adds or removes are present in the
9065 	 * journal.
9066 	 */
9067 	if (MOUNTEDSUJ(mp)) {
9068 		flags = DEPALLOC;
9069 		jmvref = newjmvref(dp, de->d_ino,
9070 		    I_OFFSET(dp) + (oldloc - base),
9071 		    I_OFFSET(dp) + (newloc - base));
9072 	}
9073 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9074 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9075 	oldoffset = offset + (oldloc - base);
9076 	newoffset = offset + (newloc - base);
9077 	ACQUIRE_LOCK(ump);
9078 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
9079 		goto done;
9080 	dap = diradd_lookup(pagedep, oldoffset);
9081 	if (dap) {
9082 		dap->da_offset = newoffset;
9083 		newoffset = DIRADDHASH(newoffset);
9084 		oldoffset = DIRADDHASH(oldoffset);
9085 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
9086 		    newoffset != oldoffset) {
9087 			LIST_REMOVE(dap, da_pdlist);
9088 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
9089 			    dap, da_pdlist);
9090 		}
9091 	}
9092 done:
9093 	if (jmvref) {
9094 		jmvref->jm_pagedep = pagedep;
9095 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
9096 		add_to_journal(&jmvref->jm_list);
9097 	}
9098 	bcopy(oldloc, newloc, entrysize);
9099 	FREE_LOCK(ump);
9100 }
9101 
9102 /*
9103  * Move the mkdir dependencies and journal work from one diradd to another
9104  * when renaming a directory.  The new name must depend on the mkdir deps
9105  * completing as the old name did.  Directories can only have one valid link
9106  * at a time so one must be canonical.
9107  */
9108 static void
9109 merge_diradd(inodedep, newdap)
9110 	struct inodedep *inodedep;
9111 	struct diradd *newdap;
9112 {
9113 	struct diradd *olddap;
9114 	struct mkdir *mkdir, *nextmd;
9115 	struct ufsmount *ump;
9116 	short state;
9117 
9118 	olddap = inodedep->id_mkdiradd;
9119 	inodedep->id_mkdiradd = newdap;
9120 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9121 		newdap->da_state &= ~DEPCOMPLETE;
9122 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
9123 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9124 		     mkdir = nextmd) {
9125 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9126 			if (mkdir->md_diradd != olddap)
9127 				continue;
9128 			mkdir->md_diradd = newdap;
9129 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
9130 			newdap->da_state |= state;
9131 			olddap->da_state &= ~state;
9132 			if ((olddap->da_state &
9133 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
9134 				break;
9135 		}
9136 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9137 			panic("merge_diradd: unfound ref");
9138 	}
9139 	/*
9140 	 * Any mkdir related journal items are not safe to be freed until
9141 	 * the new name is stable.
9142 	 */
9143 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
9144 	olddap->da_state |= DEPCOMPLETE;
9145 	complete_diradd(olddap);
9146 }
9147 
9148 /*
9149  * Move the diradd to the pending list when all diradd dependencies are
9150  * complete.
9151  */
9152 static void
9153 complete_diradd(dap)
9154 	struct diradd *dap;
9155 {
9156 	struct pagedep *pagedep;
9157 
9158 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
9159 		if (dap->da_state & DIRCHG)
9160 			pagedep = dap->da_previous->dm_pagedep;
9161 		else
9162 			pagedep = dap->da_pagedep;
9163 		LIST_REMOVE(dap, da_pdlist);
9164 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9165 	}
9166 }
9167 
9168 /*
9169  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
9170  * add entries and conditonally journal the remove.
9171  */
9172 static void
9173 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
9174 	struct diradd *dap;
9175 	struct dirrem *dirrem;
9176 	struct jremref *jremref;
9177 	struct jremref *dotremref;
9178 	struct jremref *dotdotremref;
9179 {
9180 	struct inodedep *inodedep;
9181 	struct jaddref *jaddref;
9182 	struct inoref *inoref;
9183 	struct ufsmount *ump;
9184 	struct mkdir *mkdir;
9185 
9186 	/*
9187 	 * If no remove references were allocated we're on a non-journaled
9188 	 * filesystem and can skip the cancel step.
9189 	 */
9190 	if (jremref == NULL) {
9191 		free_diradd(dap, NULL);
9192 		return;
9193 	}
9194 	/*
9195 	 * Cancel the primary name an free it if it does not require
9196 	 * journaling.
9197 	 */
9198 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
9199 	    0, &inodedep) != 0) {
9200 		/* Abort the addref that reference this diradd.  */
9201 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
9202 			if (inoref->if_list.wk_type != D_JADDREF)
9203 				continue;
9204 			jaddref = (struct jaddref *)inoref;
9205 			if (jaddref->ja_diradd != dap)
9206 				continue;
9207 			if (cancel_jaddref(jaddref, inodedep,
9208 			    &dirrem->dm_jwork) == 0) {
9209 				free_jremref(jremref);
9210 				jremref = NULL;
9211 			}
9212 			break;
9213 		}
9214 	}
9215 	/*
9216 	 * Cancel subordinate names and free them if they do not require
9217 	 * journaling.
9218 	 */
9219 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9220 		ump = VFSTOUFS(dap->da_list.wk_mp);
9221 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
9222 			if (mkdir->md_diradd != dap)
9223 				continue;
9224 			if ((jaddref = mkdir->md_jaddref) == NULL)
9225 				continue;
9226 			mkdir->md_jaddref = NULL;
9227 			if (mkdir->md_state & MKDIR_PARENT) {
9228 				if (cancel_jaddref(jaddref, NULL,
9229 				    &dirrem->dm_jwork) == 0) {
9230 					free_jremref(dotdotremref);
9231 					dotdotremref = NULL;
9232 				}
9233 			} else {
9234 				if (cancel_jaddref(jaddref, inodedep,
9235 				    &dirrem->dm_jwork) == 0) {
9236 					free_jremref(dotremref);
9237 					dotremref = NULL;
9238 				}
9239 			}
9240 		}
9241 	}
9242 
9243 	if (jremref)
9244 		journal_jremref(dirrem, jremref, inodedep);
9245 	if (dotremref)
9246 		journal_jremref(dirrem, dotremref, inodedep);
9247 	if (dotdotremref)
9248 		journal_jremref(dirrem, dotdotremref, NULL);
9249 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
9250 	free_diradd(dap, &dirrem->dm_jwork);
9251 }
9252 
9253 /*
9254  * Free a diradd dependency structure.
9255  */
9256 static void
9257 free_diradd(dap, wkhd)
9258 	struct diradd *dap;
9259 	struct workhead *wkhd;
9260 {
9261 	struct dirrem *dirrem;
9262 	struct pagedep *pagedep;
9263 	struct inodedep *inodedep;
9264 	struct mkdir *mkdir, *nextmd;
9265 	struct ufsmount *ump;
9266 
9267 	ump = VFSTOUFS(dap->da_list.wk_mp);
9268 	LOCK_OWNED(ump);
9269 	LIST_REMOVE(dap, da_pdlist);
9270 	if (dap->da_state & ONWORKLIST)
9271 		WORKLIST_REMOVE(&dap->da_list);
9272 	if ((dap->da_state & DIRCHG) == 0) {
9273 		pagedep = dap->da_pagedep;
9274 	} else {
9275 		dirrem = dap->da_previous;
9276 		pagedep = dirrem->dm_pagedep;
9277 		dirrem->dm_dirinum = pagedep->pd_ino;
9278 		dirrem->dm_state |= COMPLETE;
9279 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9280 			add_to_worklist(&dirrem->dm_list, 0);
9281 	}
9282 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
9283 	    0, &inodedep) != 0)
9284 		if (inodedep->id_mkdiradd == dap)
9285 			inodedep->id_mkdiradd = NULL;
9286 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9287 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9288 		     mkdir = nextmd) {
9289 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9290 			if (mkdir->md_diradd != dap)
9291 				continue;
9292 			dap->da_state &=
9293 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
9294 			LIST_REMOVE(mkdir, md_mkdirs);
9295 			if (mkdir->md_state & ONWORKLIST)
9296 				WORKLIST_REMOVE(&mkdir->md_list);
9297 			if (mkdir->md_jaddref != NULL)
9298 				panic("free_diradd: Unexpected jaddref");
9299 			WORKITEM_FREE(mkdir, D_MKDIR);
9300 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
9301 				break;
9302 		}
9303 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9304 			panic("free_diradd: unfound ref");
9305 	}
9306 	if (inodedep)
9307 		free_inodedep(inodedep);
9308 	/*
9309 	 * Free any journal segments waiting for the directory write.
9310 	 */
9311 	handle_jwork(&dap->da_jwork);
9312 	WORKITEM_FREE(dap, D_DIRADD);
9313 }
9314 
9315 /*
9316  * Directory entry removal dependencies.
9317  *
9318  * When removing a directory entry, the entry's inode pointer must be
9319  * zero'ed on disk before the corresponding inode's link count is decremented
9320  * (possibly freeing the inode for re-use). This dependency is handled by
9321  * updating the directory entry but delaying the inode count reduction until
9322  * after the directory block has been written to disk. After this point, the
9323  * inode count can be decremented whenever it is convenient.
9324  */
9325 
9326 /*
9327  * This routine should be called immediately after removing
9328  * a directory entry.  The inode's link count should not be
9329  * decremented by the calling procedure -- the soft updates
9330  * code will do this task when it is safe.
9331  */
9332 void
9333 softdep_setup_remove(bp, dp, ip, isrmdir)
9334 	struct buf *bp;		/* buffer containing directory block */
9335 	struct inode *dp;	/* inode for the directory being modified */
9336 	struct inode *ip;	/* inode for directory entry being removed */
9337 	int isrmdir;		/* indicates if doing RMDIR */
9338 {
9339 	struct dirrem *dirrem, *prevdirrem;
9340 	struct inodedep *inodedep;
9341 	struct ufsmount *ump;
9342 	int direct;
9343 
9344 	ump = ITOUMP(ip);
9345 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9346 	    ("softdep_setup_remove called on non-softdep filesystem"));
9347 	/*
9348 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9349 	 * newdirrem() to setup the full directory remove which requires
9350 	 * isrmdir > 1.
9351 	 */
9352 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9353 	/*
9354 	 * Add the dirrem to the inodedep's pending remove list for quick
9355 	 * discovery later.
9356 	 */
9357 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9358 		panic("softdep_setup_remove: Lost inodedep.");
9359 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9360 	dirrem->dm_state |= ONDEPLIST;
9361 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9362 
9363 	/*
9364 	 * If the COMPLETE flag is clear, then there were no active
9365 	 * entries and we want to roll back to a zeroed entry until
9366 	 * the new inode is committed to disk. If the COMPLETE flag is
9367 	 * set then we have deleted an entry that never made it to
9368 	 * disk. If the entry we deleted resulted from a name change,
9369 	 * then the old name still resides on disk. We cannot delete
9370 	 * its inode (returned to us in prevdirrem) until the zeroed
9371 	 * directory entry gets to disk. The new inode has never been
9372 	 * referenced on the disk, so can be deleted immediately.
9373 	 */
9374 	if ((dirrem->dm_state & COMPLETE) == 0) {
9375 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9376 		    dm_next);
9377 		FREE_LOCK(ump);
9378 	} else {
9379 		if (prevdirrem != NULL)
9380 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9381 			    prevdirrem, dm_next);
9382 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9383 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9384 		FREE_LOCK(ump);
9385 		if (direct)
9386 			handle_workitem_remove(dirrem, 0);
9387 	}
9388 }
9389 
9390 /*
9391  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9392  * pd_pendinghd list of a pagedep.
9393  */
9394 static struct diradd *
9395 diradd_lookup(pagedep, offset)
9396 	struct pagedep *pagedep;
9397 	int offset;
9398 {
9399 	struct diradd *dap;
9400 
9401 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9402 		if (dap->da_offset == offset)
9403 			return (dap);
9404 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9405 		if (dap->da_offset == offset)
9406 			return (dap);
9407 	return (NULL);
9408 }
9409 
9410 /*
9411  * Search for a .. diradd dependency in a directory that is being removed.
9412  * If the directory was renamed to a new parent we have a diradd rather
9413  * than a mkdir for the .. entry.  We need to cancel it now before
9414  * it is found in truncate().
9415  */
9416 static struct jremref *
9417 cancel_diradd_dotdot(ip, dirrem, jremref)
9418 	struct inode *ip;
9419 	struct dirrem *dirrem;
9420 	struct jremref *jremref;
9421 {
9422 	struct pagedep *pagedep;
9423 	struct diradd *dap;
9424 	struct worklist *wk;
9425 
9426 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9427 		return (jremref);
9428 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9429 	if (dap == NULL)
9430 		return (jremref);
9431 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9432 	/*
9433 	 * Mark any journal work as belonging to the parent so it is freed
9434 	 * with the .. reference.
9435 	 */
9436 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9437 		wk->wk_state |= MKDIR_PARENT;
9438 	return (NULL);
9439 }
9440 
9441 /*
9442  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9443  * replace it with a dirrem/diradd pair as a result of re-parenting a
9444  * directory.  This ensures that we don't simultaneously have a mkdir and
9445  * a diradd for the same .. entry.
9446  */
9447 static struct jremref *
9448 cancel_mkdir_dotdot(ip, dirrem, jremref)
9449 	struct inode *ip;
9450 	struct dirrem *dirrem;
9451 	struct jremref *jremref;
9452 {
9453 	struct inodedep *inodedep;
9454 	struct jaddref *jaddref;
9455 	struct ufsmount *ump;
9456 	struct mkdir *mkdir;
9457 	struct diradd *dap;
9458 	struct mount *mp;
9459 
9460 	mp = ITOVFS(ip);
9461 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9462 		return (jremref);
9463 	dap = inodedep->id_mkdiradd;
9464 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9465 		return (jremref);
9466 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9467 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9468 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9469 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9470 			break;
9471 	if (mkdir == NULL)
9472 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9473 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9474 		mkdir->md_jaddref = NULL;
9475 		jaddref->ja_state &= ~MKDIR_PARENT;
9476 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9477 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9478 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9479 			journal_jremref(dirrem, jremref, inodedep);
9480 			jremref = NULL;
9481 		}
9482 	}
9483 	if (mkdir->md_state & ONWORKLIST)
9484 		WORKLIST_REMOVE(&mkdir->md_list);
9485 	mkdir->md_state |= ALLCOMPLETE;
9486 	complete_mkdir(mkdir);
9487 	return (jremref);
9488 }
9489 
9490 static void
9491 journal_jremref(dirrem, jremref, inodedep)
9492 	struct dirrem *dirrem;
9493 	struct jremref *jremref;
9494 	struct inodedep *inodedep;
9495 {
9496 
9497 	if (inodedep == NULL)
9498 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9499 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9500 			panic("journal_jremref: Lost inodedep");
9501 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9502 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9503 	add_to_journal(&jremref->jr_list);
9504 }
9505 
9506 static void
9507 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9508 	struct dirrem *dirrem;
9509 	struct jremref *jremref;
9510 	struct jremref *dotremref;
9511 	struct jremref *dotdotremref;
9512 {
9513 	struct inodedep *inodedep;
9514 
9515 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9516 	    &inodedep) == 0)
9517 		panic("dirrem_journal: Lost inodedep");
9518 	journal_jremref(dirrem, jremref, inodedep);
9519 	if (dotremref)
9520 		journal_jremref(dirrem, dotremref, inodedep);
9521 	if (dotdotremref)
9522 		journal_jremref(dirrem, dotdotremref, NULL);
9523 }
9524 
9525 /*
9526  * Allocate a new dirrem if appropriate and return it along with
9527  * its associated pagedep. Called without a lock, returns with lock.
9528  */
9529 static struct dirrem *
9530 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9531 	struct buf *bp;		/* buffer containing directory block */
9532 	struct inode *dp;	/* inode for the directory being modified */
9533 	struct inode *ip;	/* inode for directory entry being removed */
9534 	int isrmdir;		/* indicates if doing RMDIR */
9535 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9536 {
9537 	int offset;
9538 	ufs_lbn_t lbn;
9539 	struct diradd *dap;
9540 	struct dirrem *dirrem;
9541 	struct pagedep *pagedep;
9542 	struct jremref *jremref;
9543 	struct jremref *dotremref;
9544 	struct jremref *dotdotremref;
9545 	struct vnode *dvp;
9546 	struct ufsmount *ump;
9547 
9548 	/*
9549 	 * Whiteouts have no deletion dependencies.
9550 	 */
9551 	if (ip == NULL)
9552 		panic("newdirrem: whiteout");
9553 	dvp = ITOV(dp);
9554 	ump = ITOUMP(dp);
9555 
9556 	/*
9557 	 * If the system is over its limit and our filesystem is
9558 	 * responsible for more than our share of that usage and
9559 	 * we are not a snapshot, request some inodedep cleanup.
9560 	 * Limiting the number of dirrem structures will also limit
9561 	 * the number of freefile and freeblks structures.
9562 	 */
9563 	ACQUIRE_LOCK(ump);
9564 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9565 		schedule_cleanup(UFSTOVFS(ump));
9566 	else
9567 		FREE_LOCK(ump);
9568 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9569 	    M_ZERO);
9570 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9571 	LIST_INIT(&dirrem->dm_jremrefhd);
9572 	LIST_INIT(&dirrem->dm_jwork);
9573 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9574 	dirrem->dm_oldinum = ip->i_number;
9575 	*prevdirremp = NULL;
9576 	/*
9577 	 * Allocate remove reference structures to track journal write
9578 	 * dependencies.  We will always have one for the link and
9579 	 * when doing directories we will always have one more for dot.
9580 	 * When renaming a directory we skip the dotdot link change so
9581 	 * this is not needed.
9582 	 */
9583 	jremref = dotremref = dotdotremref = NULL;
9584 	if (DOINGSUJ(dvp)) {
9585 		if (isrmdir) {
9586 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9587 			    ip->i_effnlink + 2);
9588 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9589 			    ip->i_effnlink + 1);
9590 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9591 			    dp->i_effnlink + 1);
9592 			dotdotremref->jr_state |= MKDIR_PARENT;
9593 		} else
9594 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9595 			    ip->i_effnlink + 1);
9596 	}
9597 	ACQUIRE_LOCK(ump);
9598 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9599 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9600 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9601 	    &pagedep);
9602 	dirrem->dm_pagedep = pagedep;
9603 	dirrem->dm_offset = offset;
9604 	/*
9605 	 * If we're renaming a .. link to a new directory, cancel any
9606 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9607 	 * the jremref is preserved for any potential diradd in this
9608 	 * location.  This can not coincide with a rmdir.
9609 	 */
9610 	if (I_OFFSET(dp) == DOTDOT_OFFSET) {
9611 		if (isrmdir)
9612 			panic("newdirrem: .. directory change during remove?");
9613 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9614 	}
9615 	/*
9616 	 * If we're removing a directory search for the .. dependency now and
9617 	 * cancel it.  Any pending journal work will be added to the dirrem
9618 	 * to be completed when the workitem remove completes.
9619 	 */
9620 	if (isrmdir)
9621 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9622 	/*
9623 	 * Check for a diradd dependency for the same directory entry.
9624 	 * If present, then both dependencies become obsolete and can
9625 	 * be de-allocated.
9626 	 */
9627 	dap = diradd_lookup(pagedep, offset);
9628 	if (dap == NULL) {
9629 		/*
9630 		 * Link the jremref structures into the dirrem so they are
9631 		 * written prior to the pagedep.
9632 		 */
9633 		if (jremref)
9634 			dirrem_journal(dirrem, jremref, dotremref,
9635 			    dotdotremref);
9636 		return (dirrem);
9637 	}
9638 	/*
9639 	 * Must be ATTACHED at this point.
9640 	 */
9641 	if ((dap->da_state & ATTACHED) == 0)
9642 		panic("newdirrem: not ATTACHED");
9643 	if (dap->da_newinum != ip->i_number)
9644 		panic("newdirrem: inum %ju should be %ju",
9645 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9646 	/*
9647 	 * If we are deleting a changed name that never made it to disk,
9648 	 * then return the dirrem describing the previous inode (which
9649 	 * represents the inode currently referenced from this entry on disk).
9650 	 */
9651 	if ((dap->da_state & DIRCHG) != 0) {
9652 		*prevdirremp = dap->da_previous;
9653 		dap->da_state &= ~DIRCHG;
9654 		dap->da_pagedep = pagedep;
9655 	}
9656 	/*
9657 	 * We are deleting an entry that never made it to disk.
9658 	 * Mark it COMPLETE so we can delete its inode immediately.
9659 	 */
9660 	dirrem->dm_state |= COMPLETE;
9661 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9662 #ifdef INVARIANTS
9663 	if (isrmdir == 0) {
9664 		struct worklist *wk;
9665 
9666 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9667 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9668 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9669 	}
9670 #endif
9671 
9672 	return (dirrem);
9673 }
9674 
9675 /*
9676  * Directory entry change dependencies.
9677  *
9678  * Changing an existing directory entry requires that an add operation
9679  * be completed first followed by a deletion. The semantics for the addition
9680  * are identical to the description of adding a new entry above except
9681  * that the rollback is to the old inode number rather than zero. Once
9682  * the addition dependency is completed, the removal is done as described
9683  * in the removal routine above.
9684  */
9685 
9686 /*
9687  * This routine should be called immediately after changing
9688  * a directory entry.  The inode's link count should not be
9689  * decremented by the calling procedure -- the soft updates
9690  * code will perform this task when it is safe.
9691  */
9692 void
9693 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9694 	struct buf *bp;		/* buffer containing directory block */
9695 	struct inode *dp;	/* inode for the directory being modified */
9696 	struct inode *ip;	/* inode for directory entry being removed */
9697 	ino_t newinum;		/* new inode number for changed entry */
9698 	int isrmdir;		/* indicates if doing RMDIR */
9699 {
9700 	int offset;
9701 	struct diradd *dap = NULL;
9702 	struct dirrem *dirrem, *prevdirrem;
9703 	struct pagedep *pagedep;
9704 	struct inodedep *inodedep;
9705 	struct jaddref *jaddref;
9706 	struct mount *mp;
9707 	struct ufsmount *ump;
9708 
9709 	mp = ITOVFS(dp);
9710 	ump = VFSTOUFS(mp);
9711 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9712 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9713 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9714 
9715 	/*
9716 	 * Whiteouts do not need diradd dependencies.
9717 	 */
9718 	if (newinum != UFS_WINO) {
9719 		dap = malloc(sizeof(struct diradd),
9720 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9721 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9722 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9723 		dap->da_offset = offset;
9724 		dap->da_newinum = newinum;
9725 		LIST_INIT(&dap->da_jwork);
9726 	}
9727 
9728 	/*
9729 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9730 	 */
9731 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9732 	pagedep = dirrem->dm_pagedep;
9733 	/*
9734 	 * The possible values for isrmdir:
9735 	 *	0 - non-directory file rename
9736 	 *	1 - directory rename within same directory
9737 	 *   inum - directory rename to new directory of given inode number
9738 	 * When renaming to a new directory, we are both deleting and
9739 	 * creating a new directory entry, so the link count on the new
9740 	 * directory should not change. Thus we do not need the followup
9741 	 * dirrem which is usually done in handle_workitem_remove. We set
9742 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9743 	 * followup dirrem.
9744 	 */
9745 	if (isrmdir > 1)
9746 		dirrem->dm_state |= DIRCHG;
9747 
9748 	/*
9749 	 * Whiteouts have no additional dependencies,
9750 	 * so just put the dirrem on the correct list.
9751 	 */
9752 	if (newinum == UFS_WINO) {
9753 		if ((dirrem->dm_state & COMPLETE) == 0) {
9754 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9755 			    dm_next);
9756 		} else {
9757 			dirrem->dm_dirinum = pagedep->pd_ino;
9758 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9759 				add_to_worklist(&dirrem->dm_list, 0);
9760 		}
9761 		FREE_LOCK(ump);
9762 		return;
9763 	}
9764 	/*
9765 	 * Add the dirrem to the inodedep's pending remove list for quick
9766 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9767 	 * will not fail.
9768 	 */
9769 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9770 		panic("softdep_setup_directory_change: Lost inodedep.");
9771 	dirrem->dm_state |= ONDEPLIST;
9772 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9773 
9774 	/*
9775 	 * If the COMPLETE flag is clear, then there were no active
9776 	 * entries and we want to roll back to the previous inode until
9777 	 * the new inode is committed to disk. If the COMPLETE flag is
9778 	 * set, then we have deleted an entry that never made it to disk.
9779 	 * If the entry we deleted resulted from a name change, then the old
9780 	 * inode reference still resides on disk. Any rollback that we do
9781 	 * needs to be to that old inode (returned to us in prevdirrem). If
9782 	 * the entry we deleted resulted from a create, then there is
9783 	 * no entry on the disk, so we want to roll back to zero rather
9784 	 * than the uncommitted inode. In either of the COMPLETE cases we
9785 	 * want to immediately free the unwritten and unreferenced inode.
9786 	 */
9787 	if ((dirrem->dm_state & COMPLETE) == 0) {
9788 		dap->da_previous = dirrem;
9789 	} else {
9790 		if (prevdirrem != NULL) {
9791 			dap->da_previous = prevdirrem;
9792 		} else {
9793 			dap->da_state &= ~DIRCHG;
9794 			dap->da_pagedep = pagedep;
9795 		}
9796 		dirrem->dm_dirinum = pagedep->pd_ino;
9797 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9798 			add_to_worklist(&dirrem->dm_list, 0);
9799 	}
9800 	/*
9801 	 * Lookup the jaddref for this journal entry.  We must finish
9802 	 * initializing it and make the diradd write dependent on it.
9803 	 * If we're not journaling, put it on the id_bufwait list if the
9804 	 * inode is not yet written. If it is written, do the post-inode
9805 	 * write processing to put it on the id_pendinghd list.
9806 	 */
9807 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9808 	if (MOUNTEDSUJ(mp)) {
9809 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9810 		    inoreflst);
9811 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9812 		    ("softdep_setup_directory_change: bad jaddref %p",
9813 		    jaddref));
9814 		jaddref->ja_diroff = I_OFFSET(dp);
9815 		jaddref->ja_diradd = dap;
9816 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9817 		    dap, da_pdlist);
9818 		add_to_journal(&jaddref->ja_list);
9819 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9820 		dap->da_state |= COMPLETE;
9821 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9822 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9823 	} else {
9824 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9825 		    dap, da_pdlist);
9826 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9827 	}
9828 	/*
9829 	 * If we're making a new name for a directory that has not been
9830 	 * committed when need to move the dot and dotdot references to
9831 	 * this new name.
9832 	 */
9833 	if (inodedep->id_mkdiradd && I_OFFSET(dp) != DOTDOT_OFFSET)
9834 		merge_diradd(inodedep, dap);
9835 	FREE_LOCK(ump);
9836 }
9837 
9838 /*
9839  * Called whenever the link count on an inode is changed.
9840  * It creates an inode dependency so that the new reference(s)
9841  * to the inode cannot be committed to disk until the updated
9842  * inode has been written.
9843  */
9844 void
9845 softdep_change_linkcnt(ip)
9846 	struct inode *ip;	/* the inode with the increased link count */
9847 {
9848 	struct inodedep *inodedep;
9849 	struct ufsmount *ump;
9850 
9851 	ump = ITOUMP(ip);
9852 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9853 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9854 	ACQUIRE_LOCK(ump);
9855 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9856 	if (ip->i_nlink < ip->i_effnlink)
9857 		panic("softdep_change_linkcnt: bad delta");
9858 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9859 	FREE_LOCK(ump);
9860 }
9861 
9862 /*
9863  * Attach a sbdep dependency to the superblock buf so that we can keep
9864  * track of the head of the linked list of referenced but unlinked inodes.
9865  */
9866 void
9867 softdep_setup_sbupdate(ump, fs, bp)
9868 	struct ufsmount *ump;
9869 	struct fs *fs;
9870 	struct buf *bp;
9871 {
9872 	struct sbdep *sbdep;
9873 	struct worklist *wk;
9874 
9875 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9876 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9877 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9878 		if (wk->wk_type == D_SBDEP)
9879 			break;
9880 	if (wk != NULL)
9881 		return;
9882 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9883 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9884 	sbdep->sb_fs = fs;
9885 	sbdep->sb_ump = ump;
9886 	ACQUIRE_LOCK(ump);
9887 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9888 	FREE_LOCK(ump);
9889 }
9890 
9891 /*
9892  * Return the first unlinked inodedep which is ready to be the head of the
9893  * list.  The inodedep and all those after it must have valid next pointers.
9894  */
9895 static struct inodedep *
9896 first_unlinked_inodedep(ump)
9897 	struct ufsmount *ump;
9898 {
9899 	struct inodedep *inodedep;
9900 	struct inodedep *idp;
9901 
9902 	LOCK_OWNED(ump);
9903 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9904 	    inodedep; inodedep = idp) {
9905 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9906 			return (NULL);
9907 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9908 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9909 			break;
9910 		if ((inodedep->id_state & UNLINKPREV) == 0)
9911 			break;
9912 	}
9913 	return (inodedep);
9914 }
9915 
9916 /*
9917  * Set the sujfree unlinked head pointer prior to writing a superblock.
9918  */
9919 static void
9920 initiate_write_sbdep(sbdep)
9921 	struct sbdep *sbdep;
9922 {
9923 	struct inodedep *inodedep;
9924 	struct fs *bpfs;
9925 	struct fs *fs;
9926 
9927 	bpfs = sbdep->sb_fs;
9928 	fs = sbdep->sb_ump->um_fs;
9929 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9930 	if (inodedep) {
9931 		fs->fs_sujfree = inodedep->id_ino;
9932 		inodedep->id_state |= UNLINKPREV;
9933 	} else
9934 		fs->fs_sujfree = 0;
9935 	bpfs->fs_sujfree = fs->fs_sujfree;
9936 	/*
9937 	 * Because we have made changes to the superblock, we need to
9938 	 * recompute its check-hash.
9939 	 */
9940 	bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9941 }
9942 
9943 /*
9944  * After a superblock is written determine whether it must be written again
9945  * due to a changing unlinked list head.
9946  */
9947 static int
9948 handle_written_sbdep(sbdep, bp)
9949 	struct sbdep *sbdep;
9950 	struct buf *bp;
9951 {
9952 	struct inodedep *inodedep;
9953 	struct fs *fs;
9954 
9955 	LOCK_OWNED(sbdep->sb_ump);
9956 	fs = sbdep->sb_fs;
9957 	/*
9958 	 * If the superblock doesn't match the in-memory list start over.
9959 	 */
9960 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9961 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9962 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9963 		bdirty(bp);
9964 		return (1);
9965 	}
9966 	WORKITEM_FREE(sbdep, D_SBDEP);
9967 	if (fs->fs_sujfree == 0)
9968 		return (0);
9969 	/*
9970 	 * Now that we have a record of this inode in stable store allow it
9971 	 * to be written to free up pending work.  Inodes may see a lot of
9972 	 * write activity after they are unlinked which we must not hold up.
9973 	 */
9974 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9975 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9976 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9977 			    inodedep, inodedep->id_state);
9978 		if (inodedep->id_state & UNLINKONLIST)
9979 			break;
9980 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9981 	}
9982 
9983 	return (0);
9984 }
9985 
9986 /*
9987  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9988  */
9989 static void
9990 unlinked_inodedep(mp, inodedep)
9991 	struct mount *mp;
9992 	struct inodedep *inodedep;
9993 {
9994 	struct ufsmount *ump;
9995 
9996 	ump = VFSTOUFS(mp);
9997 	LOCK_OWNED(ump);
9998 	if (MOUNTEDSUJ(mp) == 0)
9999 		return;
10000 	ump->um_fs->fs_fmod = 1;
10001 	if (inodedep->id_state & UNLINKED)
10002 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
10003 	inodedep->id_state |= UNLINKED;
10004 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
10005 }
10006 
10007 /*
10008  * Remove an inodedep from the unlinked inodedep list.  This may require
10009  * disk writes if the inode has made it that far.
10010  */
10011 static void
10012 clear_unlinked_inodedep(inodedep)
10013 	struct inodedep *inodedep;
10014 {
10015 	struct ufs2_dinode *dip;
10016 	struct ufsmount *ump;
10017 	struct inodedep *idp;
10018 	struct inodedep *idn;
10019 	struct fs *fs, *bpfs;
10020 	struct buf *bp;
10021 	daddr_t dbn;
10022 	ino_t ino;
10023 	ino_t nino;
10024 	ino_t pino;
10025 	int error;
10026 
10027 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10028 	fs = ump->um_fs;
10029 	ino = inodedep->id_ino;
10030 	error = 0;
10031 	for (;;) {
10032 		LOCK_OWNED(ump);
10033 		KASSERT((inodedep->id_state & UNLINKED) != 0,
10034 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
10035 		    inodedep));
10036 		/*
10037 		 * If nothing has yet been written simply remove us from
10038 		 * the in memory list and return.  This is the most common
10039 		 * case where handle_workitem_remove() loses the final
10040 		 * reference.
10041 		 */
10042 		if ((inodedep->id_state & UNLINKLINKS) == 0)
10043 			break;
10044 		/*
10045 		 * If we have a NEXT pointer and no PREV pointer we can simply
10046 		 * clear NEXT's PREV and remove ourselves from the list.  Be
10047 		 * careful not to clear PREV if the superblock points at
10048 		 * next as well.
10049 		 */
10050 		idn = TAILQ_NEXT(inodedep, id_unlinked);
10051 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
10052 			if (idn && fs->fs_sujfree != idn->id_ino)
10053 				idn->id_state &= ~UNLINKPREV;
10054 			break;
10055 		}
10056 		/*
10057 		 * Here we have an inodedep which is actually linked into
10058 		 * the list.  We must remove it by forcing a write to the
10059 		 * link before us, whether it be the superblock or an inode.
10060 		 * Unfortunately the list may change while we're waiting
10061 		 * on the buf lock for either resource so we must loop until
10062 		 * we lock the right one.  If both the superblock and an
10063 		 * inode point to this inode we must clear the inode first
10064 		 * followed by the superblock.
10065 		 */
10066 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
10067 		pino = 0;
10068 		if (idp && (idp->id_state & UNLINKNEXT))
10069 			pino = idp->id_ino;
10070 		FREE_LOCK(ump);
10071 		if (pino == 0) {
10072 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
10073 			    (int)fs->fs_sbsize, 0, 0, 0);
10074 		} else {
10075 			dbn = fsbtodb(fs, ino_to_fsba(fs, pino));
10076 			error = ffs_breadz(ump, ump->um_devvp, dbn, dbn,
10077 			    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL,
10078 			    &bp);
10079 		}
10080 		ACQUIRE_LOCK(ump);
10081 		if (error)
10082 			break;
10083 		/* If the list has changed restart the loop. */
10084 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
10085 		nino = 0;
10086 		if (idp && (idp->id_state & UNLINKNEXT))
10087 			nino = idp->id_ino;
10088 		if (nino != pino ||
10089 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
10090 			FREE_LOCK(ump);
10091 			brelse(bp);
10092 			ACQUIRE_LOCK(ump);
10093 			continue;
10094 		}
10095 		nino = 0;
10096 		idn = TAILQ_NEXT(inodedep, id_unlinked);
10097 		if (idn)
10098 			nino = idn->id_ino;
10099 		/*
10100 		 * Remove us from the in memory list.  After this we cannot
10101 		 * access the inodedep.
10102 		 */
10103 		KASSERT((inodedep->id_state & UNLINKED) != 0,
10104 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
10105 		    inodedep));
10106 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
10107 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
10108 		FREE_LOCK(ump);
10109 		/*
10110 		 * The predecessor's next pointer is manually updated here
10111 		 * so that the NEXT flag is never cleared for an element
10112 		 * that is in the list.
10113 		 */
10114 		if (pino == 0) {
10115 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
10116 			bpfs = (struct fs *)bp->b_data;
10117 			ffs_oldfscompat_write(bpfs, ump);
10118 			softdep_setup_sbupdate(ump, bpfs, bp);
10119 			/*
10120 			 * Because we may have made changes to the superblock,
10121 			 * we need to recompute its check-hash.
10122 			 */
10123 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
10124 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
10125 			((struct ufs1_dinode *)bp->b_data +
10126 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
10127 		} else {
10128 			dip = (struct ufs2_dinode *)bp->b_data +
10129 			    ino_to_fsbo(fs, pino);
10130 			dip->di_freelink = nino;
10131 			ffs_update_dinode_ckhash(fs, dip);
10132 		}
10133 		/*
10134 		 * If the bwrite fails we have no recourse to recover.  The
10135 		 * filesystem is corrupted already.
10136 		 */
10137 		bwrite(bp);
10138 		ACQUIRE_LOCK(ump);
10139 		/*
10140 		 * If the superblock pointer still needs to be cleared force
10141 		 * a write here.
10142 		 */
10143 		if (fs->fs_sujfree == ino) {
10144 			FREE_LOCK(ump);
10145 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
10146 			    (int)fs->fs_sbsize, 0, 0, 0);
10147 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
10148 			bpfs = (struct fs *)bp->b_data;
10149 			ffs_oldfscompat_write(bpfs, ump);
10150 			softdep_setup_sbupdate(ump, bpfs, bp);
10151 			/*
10152 			 * Because we may have made changes to the superblock,
10153 			 * we need to recompute its check-hash.
10154 			 */
10155 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
10156 			bwrite(bp);
10157 			ACQUIRE_LOCK(ump);
10158 		}
10159 
10160 		if (fs->fs_sujfree != ino)
10161 			return;
10162 		panic("clear_unlinked_inodedep: Failed to clear free head");
10163 	}
10164 	if (inodedep->id_ino == fs->fs_sujfree)
10165 		panic("clear_unlinked_inodedep: Freeing head of free list");
10166 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
10167 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
10168 	return;
10169 }
10170 
10171 /*
10172  * This workitem decrements the inode's link count.
10173  * If the link count reaches zero, the file is removed.
10174  */
10175 static int
10176 handle_workitem_remove(dirrem, flags)
10177 	struct dirrem *dirrem;
10178 	int flags;
10179 {
10180 	struct inodedep *inodedep;
10181 	struct workhead dotdotwk;
10182 	struct worklist *wk;
10183 	struct ufsmount *ump;
10184 	struct mount *mp;
10185 	struct vnode *vp;
10186 	struct inode *ip;
10187 	ino_t oldinum;
10188 
10189 	if (dirrem->dm_state & ONWORKLIST)
10190 		panic("handle_workitem_remove: dirrem %p still on worklist",
10191 		    dirrem);
10192 	oldinum = dirrem->dm_oldinum;
10193 	mp = dirrem->dm_list.wk_mp;
10194 	ump = VFSTOUFS(mp);
10195 	flags |= LK_EXCLUSIVE;
10196 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
10197 		return (EBUSY);
10198 	ip = VTOI(vp);
10199 	MPASS(ip->i_mode != 0);
10200 	ACQUIRE_LOCK(ump);
10201 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
10202 		panic("handle_workitem_remove: lost inodedep");
10203 	if (dirrem->dm_state & ONDEPLIST)
10204 		LIST_REMOVE(dirrem, dm_inonext);
10205 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
10206 	    ("handle_workitem_remove:  Journal entries not written."));
10207 
10208 	/*
10209 	 * Move all dependencies waiting on the remove to complete
10210 	 * from the dirrem to the inode inowait list to be completed
10211 	 * after the inode has been updated and written to disk.
10212 	 *
10213 	 * Any marked MKDIR_PARENT are saved to be completed when the
10214 	 * dotdot ref is removed unless DIRCHG is specified.  For
10215 	 * directory change operations there will be no further
10216 	 * directory writes and the jsegdeps need to be moved along
10217 	 * with the rest to be completed when the inode is free or
10218 	 * stable in the inode free list.
10219 	 */
10220 	LIST_INIT(&dotdotwk);
10221 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
10222 		WORKLIST_REMOVE(wk);
10223 		if ((dirrem->dm_state & DIRCHG) == 0 &&
10224 		    wk->wk_state & MKDIR_PARENT) {
10225 			wk->wk_state &= ~MKDIR_PARENT;
10226 			WORKLIST_INSERT(&dotdotwk, wk);
10227 			continue;
10228 		}
10229 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
10230 	}
10231 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
10232 	/*
10233 	 * Normal file deletion.
10234 	 */
10235 	if ((dirrem->dm_state & RMDIR) == 0) {
10236 		ip->i_nlink--;
10237 		KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
10238 		    "%ju negative i_nlink %d", (intmax_t)ip->i_number,
10239 		    ip->i_nlink));
10240 		DIP_SET(ip, i_nlink, ip->i_nlink);
10241 		UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10242 		if (ip->i_nlink < ip->i_effnlink)
10243 			panic("handle_workitem_remove: bad file delta");
10244 		if (ip->i_nlink == 0)
10245 			unlinked_inodedep(mp, inodedep);
10246 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10247 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10248 		    ("handle_workitem_remove: worklist not empty. %s",
10249 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
10250 		WORKITEM_FREE(dirrem, D_DIRREM);
10251 		FREE_LOCK(ump);
10252 		goto out;
10253 	}
10254 	/*
10255 	 * Directory deletion. Decrement reference count for both the
10256 	 * just deleted parent directory entry and the reference for ".".
10257 	 * Arrange to have the reference count on the parent decremented
10258 	 * to account for the loss of "..".
10259 	 */
10260 	ip->i_nlink -= 2;
10261 	KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
10262 	    "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
10263 	DIP_SET(ip, i_nlink, ip->i_nlink);
10264 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10265 	if (ip->i_nlink < ip->i_effnlink)
10266 		panic("handle_workitem_remove: bad dir delta");
10267 	if (ip->i_nlink == 0)
10268 		unlinked_inodedep(mp, inodedep);
10269 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10270 	/*
10271 	 * Rename a directory to a new parent. Since, we are both deleting
10272 	 * and creating a new directory entry, the link count on the new
10273 	 * directory should not change. Thus we skip the followup dirrem.
10274 	 */
10275 	if (dirrem->dm_state & DIRCHG) {
10276 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10277 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
10278 		WORKITEM_FREE(dirrem, D_DIRREM);
10279 		FREE_LOCK(ump);
10280 		goto out;
10281 	}
10282 	dirrem->dm_state = ONDEPLIST;
10283 	dirrem->dm_oldinum = dirrem->dm_dirinum;
10284 	/*
10285 	 * Place the dirrem on the parent's diremhd list.
10286 	 */
10287 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
10288 		panic("handle_workitem_remove: lost dir inodedep");
10289 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
10290 	/*
10291 	 * If the allocated inode has never been written to disk, then
10292 	 * the on-disk inode is zero'ed and we can remove the file
10293 	 * immediately.  When journaling if the inode has been marked
10294 	 * unlinked and not DEPCOMPLETE we know it can never be written.
10295 	 */
10296 	inodedep_lookup(mp, oldinum, 0, &inodedep);
10297 	if (inodedep == NULL ||
10298 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
10299 	    check_inode_unwritten(inodedep)) {
10300 		FREE_LOCK(ump);
10301 		vput(vp);
10302 		return handle_workitem_remove(dirrem, flags);
10303 	}
10304 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
10305 	FREE_LOCK(ump);
10306 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10307 out:
10308 	ffs_update(vp, 0);
10309 	vput(vp);
10310 	return (0);
10311 }
10312 
10313 /*
10314  * Inode de-allocation dependencies.
10315  *
10316  * When an inode's link count is reduced to zero, it can be de-allocated. We
10317  * found it convenient to postpone de-allocation until after the inode is
10318  * written to disk with its new link count (zero).  At this point, all of the
10319  * on-disk inode's block pointers are nullified and, with careful dependency
10320  * list ordering, all dependencies related to the inode will be satisfied and
10321  * the corresponding dependency structures de-allocated.  So, if/when the
10322  * inode is reused, there will be no mixing of old dependencies with new
10323  * ones.  This artificial dependency is set up by the block de-allocation
10324  * procedure above (softdep_setup_freeblocks) and completed by the
10325  * following procedure.
10326  */
10327 static void
10328 handle_workitem_freefile(freefile)
10329 	struct freefile *freefile;
10330 {
10331 	struct workhead wkhd;
10332 	struct fs *fs;
10333 	struct ufsmount *ump;
10334 	int error;
10335 #ifdef INVARIANTS
10336 	struct inodedep *idp;
10337 #endif
10338 
10339 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
10340 	fs = ump->um_fs;
10341 #ifdef INVARIANTS
10342 	ACQUIRE_LOCK(ump);
10343 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10344 	FREE_LOCK(ump);
10345 	if (error)
10346 		panic("handle_workitem_freefile: inodedep %p survived", idp);
10347 #endif
10348 	UFS_LOCK(ump);
10349 	fs->fs_pendinginodes -= 1;
10350 	UFS_UNLOCK(ump);
10351 	LIST_INIT(&wkhd);
10352 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10353 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10354 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10355 		softdep_error("handle_workitem_freefile", error);
10356 	ACQUIRE_LOCK(ump);
10357 	WORKITEM_FREE(freefile, D_FREEFILE);
10358 	FREE_LOCK(ump);
10359 }
10360 
10361 /*
10362  * Helper function which unlinks marker element from work list and returns
10363  * the next element on the list.
10364  */
10365 static __inline struct worklist *
10366 markernext(struct worklist *marker)
10367 {
10368 	struct worklist *next;
10369 
10370 	next = LIST_NEXT(marker, wk_list);
10371 	LIST_REMOVE(marker, wk_list);
10372 	return next;
10373 }
10374 
10375 /*
10376  * Disk writes.
10377  *
10378  * The dependency structures constructed above are most actively used when file
10379  * system blocks are written to disk.  No constraints are placed on when a
10380  * block can be written, but unsatisfied update dependencies are made safe by
10381  * modifying (or replacing) the source memory for the duration of the disk
10382  * write.  When the disk write completes, the memory block is again brought
10383  * up-to-date.
10384  *
10385  * In-core inode structure reclamation.
10386  *
10387  * Because there are a finite number of "in-core" inode structures, they are
10388  * reused regularly.  By transferring all inode-related dependencies to the
10389  * in-memory inode block and indexing them separately (via "inodedep"s), we
10390  * can allow "in-core" inode structures to be reused at any time and avoid
10391  * any increase in contention.
10392  *
10393  * Called just before entering the device driver to initiate a new disk I/O.
10394  * The buffer must be locked, thus, no I/O completion operations can occur
10395  * while we are manipulating its associated dependencies.
10396  */
10397 static void
10398 softdep_disk_io_initiation(bp)
10399 	struct buf *bp;		/* structure describing disk write to occur */
10400 {
10401 	struct worklist *wk;
10402 	struct worklist marker;
10403 	struct inodedep *inodedep;
10404 	struct freeblks *freeblks;
10405 	struct jblkdep *jblkdep;
10406 	struct newblk *newblk;
10407 	struct ufsmount *ump;
10408 
10409 	/*
10410 	 * We only care about write operations. There should never
10411 	 * be dependencies for reads.
10412 	 */
10413 	if (bp->b_iocmd != BIO_WRITE)
10414 		panic("softdep_disk_io_initiation: not write");
10415 
10416 	if (bp->b_vflags & BV_BKGRDINPROG)
10417 		panic("softdep_disk_io_initiation: Writing buffer with "
10418 		    "background write in progress: %p", bp);
10419 
10420 	ump = softdep_bp_to_mp(bp);
10421 	if (ump == NULL)
10422 		return;
10423 
10424 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10425 	PHOLD(curproc);			/* Don't swap out kernel stack */
10426 	ACQUIRE_LOCK(ump);
10427 	/*
10428 	 * Do any necessary pre-I/O processing.
10429 	 */
10430 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10431 	     wk = markernext(&marker)) {
10432 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10433 		switch (wk->wk_type) {
10434 		case D_PAGEDEP:
10435 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10436 			continue;
10437 
10438 		case D_INODEDEP:
10439 			inodedep = WK_INODEDEP(wk);
10440 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10441 				initiate_write_inodeblock_ufs1(inodedep, bp);
10442 			else
10443 				initiate_write_inodeblock_ufs2(inodedep, bp);
10444 			continue;
10445 
10446 		case D_INDIRDEP:
10447 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10448 			continue;
10449 
10450 		case D_BMSAFEMAP:
10451 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10452 			continue;
10453 
10454 		case D_JSEG:
10455 			WK_JSEG(wk)->js_buf = NULL;
10456 			continue;
10457 
10458 		case D_FREEBLKS:
10459 			freeblks = WK_FREEBLKS(wk);
10460 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10461 			/*
10462 			 * We have to wait for the freeblks to be journaled
10463 			 * before we can write an inodeblock with updated
10464 			 * pointers.  Be careful to arrange the marker so
10465 			 * we revisit the freeblks if it's not removed by
10466 			 * the first jwait().
10467 			 */
10468 			if (jblkdep != NULL) {
10469 				LIST_REMOVE(&marker, wk_list);
10470 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10471 				jwait(&jblkdep->jb_list, MNT_WAIT);
10472 			}
10473 			continue;
10474 		case D_ALLOCDIRECT:
10475 		case D_ALLOCINDIR:
10476 			/*
10477 			 * We have to wait for the jnewblk to be journaled
10478 			 * before we can write to a block if the contents
10479 			 * may be confused with an earlier file's indirect
10480 			 * at recovery time.  Handle the marker as described
10481 			 * above.
10482 			 */
10483 			newblk = WK_NEWBLK(wk);
10484 			if (newblk->nb_jnewblk != NULL &&
10485 			    indirblk_lookup(newblk->nb_list.wk_mp,
10486 			    newblk->nb_newblkno)) {
10487 				LIST_REMOVE(&marker, wk_list);
10488 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10489 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10490 			}
10491 			continue;
10492 
10493 		case D_SBDEP:
10494 			initiate_write_sbdep(WK_SBDEP(wk));
10495 			continue;
10496 
10497 		case D_MKDIR:
10498 		case D_FREEWORK:
10499 		case D_FREEDEP:
10500 		case D_JSEGDEP:
10501 			continue;
10502 
10503 		default:
10504 			panic("handle_disk_io_initiation: Unexpected type %s",
10505 			    TYPENAME(wk->wk_type));
10506 			/* NOTREACHED */
10507 		}
10508 	}
10509 	FREE_LOCK(ump);
10510 	PRELE(curproc);			/* Allow swapout of kernel stack */
10511 }
10512 
10513 /*
10514  * Called from within the procedure above to deal with unsatisfied
10515  * allocation dependencies in a directory. The buffer must be locked,
10516  * thus, no I/O completion operations can occur while we are
10517  * manipulating its associated dependencies.
10518  */
10519 static void
10520 initiate_write_filepage(pagedep, bp)
10521 	struct pagedep *pagedep;
10522 	struct buf *bp;
10523 {
10524 	struct jremref *jremref;
10525 	struct jmvref *jmvref;
10526 	struct dirrem *dirrem;
10527 	struct diradd *dap;
10528 	struct direct *ep;
10529 	int i;
10530 
10531 	if (pagedep->pd_state & IOSTARTED) {
10532 		/*
10533 		 * This can only happen if there is a driver that does not
10534 		 * understand chaining. Here biodone will reissue the call
10535 		 * to strategy for the incomplete buffers.
10536 		 */
10537 		printf("initiate_write_filepage: already started\n");
10538 		return;
10539 	}
10540 	pagedep->pd_state |= IOSTARTED;
10541 	/*
10542 	 * Wait for all journal remove dependencies to hit the disk.
10543 	 * We can not allow any potentially conflicting directory adds
10544 	 * to be visible before removes and rollback is too difficult.
10545 	 * The per-filesystem lock may be dropped and re-acquired, however
10546 	 * we hold the buf locked so the dependency can not go away.
10547 	 */
10548 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10549 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10550 			jwait(&jremref->jr_list, MNT_WAIT);
10551 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10552 		jwait(&jmvref->jm_list, MNT_WAIT);
10553 	for (i = 0; i < DAHASHSZ; i++) {
10554 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10555 			ep = (struct direct *)
10556 			    ((char *)bp->b_data + dap->da_offset);
10557 			if (ep->d_ino != dap->da_newinum)
10558 				panic("%s: dir inum %ju != new %ju",
10559 				    "initiate_write_filepage",
10560 				    (uintmax_t)ep->d_ino,
10561 				    (uintmax_t)dap->da_newinum);
10562 			if (dap->da_state & DIRCHG)
10563 				ep->d_ino = dap->da_previous->dm_oldinum;
10564 			else
10565 				ep->d_ino = 0;
10566 			dap->da_state &= ~ATTACHED;
10567 			dap->da_state |= UNDONE;
10568 		}
10569 	}
10570 }
10571 
10572 /*
10573  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10574  * Note that any bug fixes made to this routine must be done in the
10575  * version found below.
10576  *
10577  * Called from within the procedure above to deal with unsatisfied
10578  * allocation dependencies in an inodeblock. The buffer must be
10579  * locked, thus, no I/O completion operations can occur while we
10580  * are manipulating its associated dependencies.
10581  */
10582 static void
10583 initiate_write_inodeblock_ufs1(inodedep, bp)
10584 	struct inodedep *inodedep;
10585 	struct buf *bp;			/* The inode block */
10586 {
10587 	struct allocdirect *adp, *lastadp;
10588 	struct ufs1_dinode *dp;
10589 	struct ufs1_dinode *sip;
10590 	struct inoref *inoref;
10591 	struct ufsmount *ump;
10592 	struct fs *fs;
10593 	ufs_lbn_t i;
10594 #ifdef INVARIANTS
10595 	ufs_lbn_t prevlbn = 0;
10596 #endif
10597 	int deplist;
10598 
10599 	if (inodedep->id_state & IOSTARTED)
10600 		panic("initiate_write_inodeblock_ufs1: already started");
10601 	inodedep->id_state |= IOSTARTED;
10602 	fs = inodedep->id_fs;
10603 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10604 	LOCK_OWNED(ump);
10605 	dp = (struct ufs1_dinode *)bp->b_data +
10606 	    ino_to_fsbo(fs, inodedep->id_ino);
10607 
10608 	/*
10609 	 * If we're on the unlinked list but have not yet written our
10610 	 * next pointer initialize it here.
10611 	 */
10612 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10613 		struct inodedep *inon;
10614 
10615 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10616 		dp->di_freelink = inon ? inon->id_ino : 0;
10617 	}
10618 	/*
10619 	 * If the bitmap is not yet written, then the allocated
10620 	 * inode cannot be written to disk.
10621 	 */
10622 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10623 		if (inodedep->id_savedino1 != NULL)
10624 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10625 		FREE_LOCK(ump);
10626 		sip = malloc(sizeof(struct ufs1_dinode),
10627 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10628 		ACQUIRE_LOCK(ump);
10629 		inodedep->id_savedino1 = sip;
10630 		*inodedep->id_savedino1 = *dp;
10631 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10632 		dp->di_gen = inodedep->id_savedino1->di_gen;
10633 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10634 		return;
10635 	}
10636 	/*
10637 	 * If no dependencies, then there is nothing to roll back.
10638 	 */
10639 	inodedep->id_savedsize = dp->di_size;
10640 	inodedep->id_savedextsize = 0;
10641 	inodedep->id_savednlink = dp->di_nlink;
10642 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10643 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10644 		return;
10645 	/*
10646 	 * Revert the link count to that of the first unwritten journal entry.
10647 	 */
10648 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10649 	if (inoref)
10650 		dp->di_nlink = inoref->if_nlink;
10651 	/*
10652 	 * Set the dependencies to busy.
10653 	 */
10654 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10655 	     adp = TAILQ_NEXT(adp, ad_next)) {
10656 #ifdef INVARIANTS
10657 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10658 			panic("softdep_write_inodeblock: lbn order");
10659 		prevlbn = adp->ad_offset;
10660 		if (adp->ad_offset < UFS_NDADDR &&
10661 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10662 			panic("initiate_write_inodeblock_ufs1: "
10663 			    "direct pointer #%jd mismatch %d != %jd",
10664 			    (intmax_t)adp->ad_offset,
10665 			    dp->di_db[adp->ad_offset],
10666 			    (intmax_t)adp->ad_newblkno);
10667 		if (adp->ad_offset >= UFS_NDADDR &&
10668 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10669 			panic("initiate_write_inodeblock_ufs1: "
10670 			    "indirect pointer #%jd mismatch %d != %jd",
10671 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10672 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10673 			    (intmax_t)adp->ad_newblkno);
10674 		deplist |= 1 << adp->ad_offset;
10675 		if ((adp->ad_state & ATTACHED) == 0)
10676 			panic("initiate_write_inodeblock_ufs1: "
10677 			    "Unknown state 0x%x", adp->ad_state);
10678 #endif /* INVARIANTS */
10679 		adp->ad_state &= ~ATTACHED;
10680 		adp->ad_state |= UNDONE;
10681 	}
10682 	/*
10683 	 * The on-disk inode cannot claim to be any larger than the last
10684 	 * fragment that has been written. Otherwise, the on-disk inode
10685 	 * might have fragments that were not the last block in the file
10686 	 * which would corrupt the filesystem.
10687 	 */
10688 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10689 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10690 		if (adp->ad_offset >= UFS_NDADDR)
10691 			break;
10692 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10693 		/* keep going until hitting a rollback to a frag */
10694 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10695 			continue;
10696 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10697 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10698 #ifdef INVARIANTS
10699 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10700 				panic("initiate_write_inodeblock_ufs1: "
10701 				    "lost dep1");
10702 #endif /* INVARIANTS */
10703 			dp->di_db[i] = 0;
10704 		}
10705 		for (i = 0; i < UFS_NIADDR; i++) {
10706 #ifdef INVARIANTS
10707 			if (dp->di_ib[i] != 0 &&
10708 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10709 				panic("initiate_write_inodeblock_ufs1: "
10710 				    "lost dep2");
10711 #endif /* INVARIANTS */
10712 			dp->di_ib[i] = 0;
10713 		}
10714 		return;
10715 	}
10716 	/*
10717 	 * If we have zero'ed out the last allocated block of the file,
10718 	 * roll back the size to the last currently allocated block.
10719 	 * We know that this last allocated block is a full-sized as
10720 	 * we already checked for fragments in the loop above.
10721 	 */
10722 	if (lastadp != NULL &&
10723 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10724 		for (i = lastadp->ad_offset; i >= 0; i--)
10725 			if (dp->di_db[i] != 0)
10726 				break;
10727 		dp->di_size = (i + 1) * fs->fs_bsize;
10728 	}
10729 	/*
10730 	 * The only dependencies are for indirect blocks.
10731 	 *
10732 	 * The file size for indirect block additions is not guaranteed.
10733 	 * Such a guarantee would be non-trivial to achieve. The conventional
10734 	 * synchronous write implementation also does not make this guarantee.
10735 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10736 	 * can be over-estimated without destroying integrity when the file
10737 	 * moves into the indirect blocks (i.e., is large). If we want to
10738 	 * postpone fsck, we are stuck with this argument.
10739 	 */
10740 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10741 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10742 }
10743 
10744 /*
10745  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10746  * Note that any bug fixes made to this routine must be done in the
10747  * version found above.
10748  *
10749  * Called from within the procedure above to deal with unsatisfied
10750  * allocation dependencies in an inodeblock. The buffer must be
10751  * locked, thus, no I/O completion operations can occur while we
10752  * are manipulating its associated dependencies.
10753  */
10754 static void
10755 initiate_write_inodeblock_ufs2(inodedep, bp)
10756 	struct inodedep *inodedep;
10757 	struct buf *bp;			/* The inode block */
10758 {
10759 	struct allocdirect *adp, *lastadp;
10760 	struct ufs2_dinode *dp;
10761 	struct ufs2_dinode *sip;
10762 	struct inoref *inoref;
10763 	struct ufsmount *ump;
10764 	struct fs *fs;
10765 	ufs_lbn_t i;
10766 #ifdef INVARIANTS
10767 	ufs_lbn_t prevlbn = 0;
10768 #endif
10769 	int deplist;
10770 
10771 	if (inodedep->id_state & IOSTARTED)
10772 		panic("initiate_write_inodeblock_ufs2: already started");
10773 	inodedep->id_state |= IOSTARTED;
10774 	fs = inodedep->id_fs;
10775 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10776 	LOCK_OWNED(ump);
10777 	dp = (struct ufs2_dinode *)bp->b_data +
10778 	    ino_to_fsbo(fs, inodedep->id_ino);
10779 
10780 	/*
10781 	 * If we're on the unlinked list but have not yet written our
10782 	 * next pointer initialize it here.
10783 	 */
10784 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10785 		struct inodedep *inon;
10786 
10787 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10788 		dp->di_freelink = inon ? inon->id_ino : 0;
10789 		ffs_update_dinode_ckhash(fs, dp);
10790 	}
10791 	/*
10792 	 * If the bitmap is not yet written, then the allocated
10793 	 * inode cannot be written to disk.
10794 	 */
10795 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10796 		if (inodedep->id_savedino2 != NULL)
10797 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10798 		FREE_LOCK(ump);
10799 		sip = malloc(sizeof(struct ufs2_dinode),
10800 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10801 		ACQUIRE_LOCK(ump);
10802 		inodedep->id_savedino2 = sip;
10803 		*inodedep->id_savedino2 = *dp;
10804 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10805 		dp->di_gen = inodedep->id_savedino2->di_gen;
10806 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10807 		return;
10808 	}
10809 	/*
10810 	 * If no dependencies, then there is nothing to roll back.
10811 	 */
10812 	inodedep->id_savedsize = dp->di_size;
10813 	inodedep->id_savedextsize = dp->di_extsize;
10814 	inodedep->id_savednlink = dp->di_nlink;
10815 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10816 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10817 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10818 		return;
10819 	/*
10820 	 * Revert the link count to that of the first unwritten journal entry.
10821 	 */
10822 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10823 	if (inoref)
10824 		dp->di_nlink = inoref->if_nlink;
10825 
10826 	/*
10827 	 * Set the ext data dependencies to busy.
10828 	 */
10829 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10830 	     adp = TAILQ_NEXT(adp, ad_next)) {
10831 #ifdef INVARIANTS
10832 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10833 			panic("initiate_write_inodeblock_ufs2: lbn order");
10834 		prevlbn = adp->ad_offset;
10835 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10836 			panic("initiate_write_inodeblock_ufs2: "
10837 			    "ext pointer #%jd mismatch %jd != %jd",
10838 			    (intmax_t)adp->ad_offset,
10839 			    (intmax_t)dp->di_extb[adp->ad_offset],
10840 			    (intmax_t)adp->ad_newblkno);
10841 		deplist |= 1 << adp->ad_offset;
10842 		if ((adp->ad_state & ATTACHED) == 0)
10843 			panic("initiate_write_inodeblock_ufs2: Unknown "
10844 			    "state 0x%x", adp->ad_state);
10845 #endif /* INVARIANTS */
10846 		adp->ad_state &= ~ATTACHED;
10847 		adp->ad_state |= UNDONE;
10848 	}
10849 	/*
10850 	 * The on-disk inode cannot claim to be any larger than the last
10851 	 * fragment that has been written. Otherwise, the on-disk inode
10852 	 * might have fragments that were not the last block in the ext
10853 	 * data which would corrupt the filesystem.
10854 	 */
10855 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10856 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10857 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10858 		/* keep going until hitting a rollback to a frag */
10859 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10860 			continue;
10861 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10862 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10863 #ifdef INVARIANTS
10864 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10865 				panic("initiate_write_inodeblock_ufs2: "
10866 				    "lost dep1");
10867 #endif /* INVARIANTS */
10868 			dp->di_extb[i] = 0;
10869 		}
10870 		lastadp = NULL;
10871 		break;
10872 	}
10873 	/*
10874 	 * If we have zero'ed out the last allocated block of the ext
10875 	 * data, roll back the size to the last currently allocated block.
10876 	 * We know that this last allocated block is a full-sized as
10877 	 * we already checked for fragments in the loop above.
10878 	 */
10879 	if (lastadp != NULL &&
10880 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10881 		for (i = lastadp->ad_offset; i >= 0; i--)
10882 			if (dp->di_extb[i] != 0)
10883 				break;
10884 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10885 	}
10886 	/*
10887 	 * Set the file data dependencies to busy.
10888 	 */
10889 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10890 	     adp = TAILQ_NEXT(adp, ad_next)) {
10891 #ifdef INVARIANTS
10892 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10893 			panic("softdep_write_inodeblock: lbn order");
10894 		if ((adp->ad_state & ATTACHED) == 0)
10895 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10896 		prevlbn = adp->ad_offset;
10897 		if (!ffs_fsfail_cleanup(ump, 0) &&
10898 		    adp->ad_offset < UFS_NDADDR &&
10899 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10900 			panic("initiate_write_inodeblock_ufs2: "
10901 			    "direct pointer #%jd mismatch %jd != %jd",
10902 			    (intmax_t)adp->ad_offset,
10903 			    (intmax_t)dp->di_db[adp->ad_offset],
10904 			    (intmax_t)adp->ad_newblkno);
10905 		if (!ffs_fsfail_cleanup(ump, 0) &&
10906 		    adp->ad_offset >= UFS_NDADDR &&
10907 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10908 			panic("initiate_write_inodeblock_ufs2: "
10909 			    "indirect pointer #%jd mismatch %jd != %jd",
10910 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10911 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10912 			    (intmax_t)adp->ad_newblkno);
10913 		deplist |= 1 << adp->ad_offset;
10914 		if ((adp->ad_state & ATTACHED) == 0)
10915 			panic("initiate_write_inodeblock_ufs2: Unknown "
10916 			     "state 0x%x", adp->ad_state);
10917 #endif /* INVARIANTS */
10918 		adp->ad_state &= ~ATTACHED;
10919 		adp->ad_state |= UNDONE;
10920 	}
10921 	/*
10922 	 * The on-disk inode cannot claim to be any larger than the last
10923 	 * fragment that has been written. Otherwise, the on-disk inode
10924 	 * might have fragments that were not the last block in the file
10925 	 * which would corrupt the filesystem.
10926 	 */
10927 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10928 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10929 		if (adp->ad_offset >= UFS_NDADDR)
10930 			break;
10931 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10932 		/* keep going until hitting a rollback to a frag */
10933 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10934 			continue;
10935 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10936 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10937 #ifdef INVARIANTS
10938 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10939 				panic("initiate_write_inodeblock_ufs2: "
10940 				    "lost dep2");
10941 #endif /* INVARIANTS */
10942 			dp->di_db[i] = 0;
10943 		}
10944 		for (i = 0; i < UFS_NIADDR; i++) {
10945 #ifdef INVARIANTS
10946 			if (dp->di_ib[i] != 0 &&
10947 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10948 				panic("initiate_write_inodeblock_ufs2: "
10949 				    "lost dep3");
10950 #endif /* INVARIANTS */
10951 			dp->di_ib[i] = 0;
10952 		}
10953 		ffs_update_dinode_ckhash(fs, dp);
10954 		return;
10955 	}
10956 	/*
10957 	 * If we have zero'ed out the last allocated block of the file,
10958 	 * roll back the size to the last currently allocated block.
10959 	 * We know that this last allocated block is a full-sized as
10960 	 * we already checked for fragments in the loop above.
10961 	 */
10962 	if (lastadp != NULL &&
10963 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10964 		for (i = lastadp->ad_offset; i >= 0; i--)
10965 			if (dp->di_db[i] != 0)
10966 				break;
10967 		dp->di_size = (i + 1) * fs->fs_bsize;
10968 	}
10969 	/*
10970 	 * The only dependencies are for indirect blocks.
10971 	 *
10972 	 * The file size for indirect block additions is not guaranteed.
10973 	 * Such a guarantee would be non-trivial to achieve. The conventional
10974 	 * synchronous write implementation also does not make this guarantee.
10975 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10976 	 * can be over-estimated without destroying integrity when the file
10977 	 * moves into the indirect blocks (i.e., is large). If we want to
10978 	 * postpone fsck, we are stuck with this argument.
10979 	 */
10980 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10981 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10982 	ffs_update_dinode_ckhash(fs, dp);
10983 }
10984 
10985 /*
10986  * Cancel an indirdep as a result of truncation.  Release all of the
10987  * children allocindirs and place their journal work on the appropriate
10988  * list.
10989  */
10990 static void
10991 cancel_indirdep(indirdep, bp, freeblks)
10992 	struct indirdep *indirdep;
10993 	struct buf *bp;
10994 	struct freeblks *freeblks;
10995 {
10996 	struct allocindir *aip;
10997 
10998 	/*
10999 	 * None of the indirect pointers will ever be visible,
11000 	 * so they can simply be tossed. GOINGAWAY ensures
11001 	 * that allocated pointers will be saved in the buffer
11002 	 * cache until they are freed. Note that they will
11003 	 * only be able to be found by their physical address
11004 	 * since the inode mapping the logical address will
11005 	 * be gone. The save buffer used for the safe copy
11006 	 * was allocated in setup_allocindir_phase2 using
11007 	 * the physical address so it could be used for this
11008 	 * purpose. Hence we swap the safe copy with the real
11009 	 * copy, allowing the safe copy to be freed and holding
11010 	 * on to the real copy for later use in indir_trunc.
11011 	 */
11012 	if (indirdep->ir_state & GOINGAWAY)
11013 		panic("cancel_indirdep: already gone");
11014 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11015 		indirdep->ir_state |= DEPCOMPLETE;
11016 		LIST_REMOVE(indirdep, ir_next);
11017 	}
11018 	indirdep->ir_state |= GOINGAWAY;
11019 	/*
11020 	 * Pass in bp for blocks still have journal writes
11021 	 * pending so we can cancel them on their own.
11022 	 */
11023 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
11024 		cancel_allocindir(aip, bp, freeblks, 0);
11025 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
11026 		cancel_allocindir(aip, NULL, freeblks, 0);
11027 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
11028 		cancel_allocindir(aip, NULL, freeblks, 0);
11029 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
11030 		cancel_allocindir(aip, NULL, freeblks, 0);
11031 	/*
11032 	 * If there are pending partial truncations we need to keep the
11033 	 * old block copy around until they complete.  This is because
11034 	 * the current b_data is not a perfect superset of the available
11035 	 * blocks.
11036 	 */
11037 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
11038 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
11039 	else
11040 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
11041 	WORKLIST_REMOVE(&indirdep->ir_list);
11042 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
11043 	indirdep->ir_bp = NULL;
11044 	indirdep->ir_freeblks = freeblks;
11045 }
11046 
11047 /*
11048  * Free an indirdep once it no longer has new pointers to track.
11049  */
11050 static void
11051 free_indirdep(indirdep)
11052 	struct indirdep *indirdep;
11053 {
11054 
11055 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
11056 	    ("free_indirdep: Indir trunc list not empty."));
11057 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
11058 	    ("free_indirdep: Complete head not empty."));
11059 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
11060 	    ("free_indirdep: write head not empty."));
11061 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
11062 	    ("free_indirdep: done head not empty."));
11063 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
11064 	    ("free_indirdep: deplist head not empty."));
11065 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
11066 	    ("free_indirdep: %p still on newblk list.", indirdep));
11067 	KASSERT(indirdep->ir_saveddata == NULL,
11068 	    ("free_indirdep: %p still has saved data.", indirdep));
11069 	KASSERT(indirdep->ir_savebp == NULL,
11070 	    ("free_indirdep: %p still has savebp buffer.", indirdep));
11071 	if (indirdep->ir_state & ONWORKLIST)
11072 		WORKLIST_REMOVE(&indirdep->ir_list);
11073 	WORKITEM_FREE(indirdep, D_INDIRDEP);
11074 }
11075 
11076 /*
11077  * Called before a write to an indirdep.  This routine is responsible for
11078  * rolling back pointers to a safe state which includes only those
11079  * allocindirs which have been completed.
11080  */
11081 static void
11082 initiate_write_indirdep(indirdep, bp)
11083 	struct indirdep *indirdep;
11084 	struct buf *bp;
11085 {
11086 	struct ufsmount *ump;
11087 
11088 	indirdep->ir_state |= IOSTARTED;
11089 	if (indirdep->ir_state & GOINGAWAY)
11090 		panic("disk_io_initiation: indirdep gone");
11091 	/*
11092 	 * If there are no remaining dependencies, this will be writing
11093 	 * the real pointers.
11094 	 */
11095 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
11096 	    TAILQ_EMPTY(&indirdep->ir_trunc))
11097 		return;
11098 	/*
11099 	 * Replace up-to-date version with safe version.
11100 	 */
11101 	if (indirdep->ir_saveddata == NULL) {
11102 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
11103 		LOCK_OWNED(ump);
11104 		FREE_LOCK(ump);
11105 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
11106 		    M_SOFTDEP_FLAGS);
11107 		ACQUIRE_LOCK(ump);
11108 	}
11109 	indirdep->ir_state &= ~ATTACHED;
11110 	indirdep->ir_state |= UNDONE;
11111 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
11112 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
11113 	    bp->b_bcount);
11114 }
11115 
11116 /*
11117  * Called when an inode has been cleared in a cg bitmap.  This finally
11118  * eliminates any canceled jaddrefs
11119  */
11120 void
11121 softdep_setup_inofree(mp, bp, ino, wkhd)
11122 	struct mount *mp;
11123 	struct buf *bp;
11124 	ino_t ino;
11125 	struct workhead *wkhd;
11126 {
11127 	struct worklist *wk, *wkn;
11128 	struct inodedep *inodedep;
11129 	struct ufsmount *ump;
11130 	uint8_t *inosused;
11131 	struct cg *cgp;
11132 	struct fs *fs;
11133 
11134 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
11135 	    ("softdep_setup_inofree called on non-softdep filesystem"));
11136 	ump = VFSTOUFS(mp);
11137 	ACQUIRE_LOCK(ump);
11138 	if (!ffs_fsfail_cleanup(ump, 0)) {
11139 		fs = ump->um_fs;
11140 		cgp = (struct cg *)bp->b_data;
11141 		inosused = cg_inosused(cgp);
11142 		if (isset(inosused, ino % fs->fs_ipg))
11143 			panic("softdep_setup_inofree: inode %ju not freed.",
11144 			    (uintmax_t)ino);
11145 	}
11146 	if (inodedep_lookup(mp, ino, 0, &inodedep))
11147 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
11148 		    (uintmax_t)ino, inodedep);
11149 	if (wkhd) {
11150 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
11151 			if (wk->wk_type != D_JADDREF)
11152 				continue;
11153 			WORKLIST_REMOVE(wk);
11154 			/*
11155 			 * We can free immediately even if the jaddref
11156 			 * isn't attached in a background write as now
11157 			 * the bitmaps are reconciled.
11158 			 */
11159 			wk->wk_state |= COMPLETE | ATTACHED;
11160 			free_jaddref(WK_JADDREF(wk));
11161 		}
11162 		jwork_move(&bp->b_dep, wkhd);
11163 	}
11164 	FREE_LOCK(ump);
11165 }
11166 
11167 /*
11168  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
11169  * map.  Any dependencies waiting for the write to clear are added to the
11170  * buf's list and any jnewblks that are being canceled are discarded
11171  * immediately.
11172  */
11173 void
11174 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
11175 	struct mount *mp;
11176 	struct buf *bp;
11177 	ufs2_daddr_t blkno;
11178 	int frags;
11179 	struct workhead *wkhd;
11180 {
11181 	struct bmsafemap *bmsafemap;
11182 	struct jnewblk *jnewblk;
11183 	struct ufsmount *ump;
11184 	struct worklist *wk;
11185 	struct fs *fs;
11186 #ifdef INVARIANTS
11187 	uint8_t *blksfree;
11188 	struct cg *cgp;
11189 	ufs2_daddr_t jstart;
11190 	ufs2_daddr_t jend;
11191 	ufs2_daddr_t end;
11192 	long bno;
11193 	int i;
11194 #endif
11195 
11196 	CTR3(KTR_SUJ,
11197 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
11198 	    blkno, frags, wkhd);
11199 
11200 	ump = VFSTOUFS(mp);
11201 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
11202 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
11203 	ACQUIRE_LOCK(ump);
11204 	/* Lookup the bmsafemap so we track when it is dirty. */
11205 	fs = ump->um_fs;
11206 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11207 	/*
11208 	 * Detach any jnewblks which have been canceled.  They must linger
11209 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
11210 	 * an unjournaled allocation from hitting the disk.
11211 	 */
11212 	if (wkhd) {
11213 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
11214 			CTR2(KTR_SUJ,
11215 			    "softdep_setup_blkfree: blkno %jd wk type %d",
11216 			    blkno, wk->wk_type);
11217 			WORKLIST_REMOVE(wk);
11218 			if (wk->wk_type != D_JNEWBLK) {
11219 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
11220 				continue;
11221 			}
11222 			jnewblk = WK_JNEWBLK(wk);
11223 			KASSERT(jnewblk->jn_state & GOINGAWAY,
11224 			    ("softdep_setup_blkfree: jnewblk not canceled."));
11225 #ifdef INVARIANTS
11226 			/*
11227 			 * Assert that this block is free in the bitmap
11228 			 * before we discard the jnewblk.
11229 			 */
11230 			cgp = (struct cg *)bp->b_data;
11231 			blksfree = cg_blksfree(cgp);
11232 			bno = dtogd(fs, jnewblk->jn_blkno);
11233 			for (i = jnewblk->jn_oldfrags;
11234 			    i < jnewblk->jn_frags; i++) {
11235 				if (isset(blksfree, bno + i))
11236 					continue;
11237 				panic("softdep_setup_blkfree: not free");
11238 			}
11239 #endif
11240 			/*
11241 			 * Even if it's not attached we can free immediately
11242 			 * as the new bitmap is correct.
11243 			 */
11244 			wk->wk_state |= COMPLETE | ATTACHED;
11245 			free_jnewblk(jnewblk);
11246 		}
11247 	}
11248 
11249 #ifdef INVARIANTS
11250 	/*
11251 	 * Assert that we are not freeing a block which has an outstanding
11252 	 * allocation dependency.
11253 	 */
11254 	fs = VFSTOUFS(mp)->um_fs;
11255 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11256 	end = blkno + frags;
11257 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11258 		/*
11259 		 * Don't match against blocks that will be freed when the
11260 		 * background write is done.
11261 		 */
11262 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
11263 		    (COMPLETE | DEPCOMPLETE))
11264 			continue;
11265 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
11266 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
11267 		if ((blkno >= jstart && blkno < jend) ||
11268 		    (end > jstart && end <= jend)) {
11269 			printf("state 0x%X %jd - %d %d dep %p\n",
11270 			    jnewblk->jn_state, jnewblk->jn_blkno,
11271 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
11272 			    jnewblk->jn_dep);
11273 			panic("softdep_setup_blkfree: "
11274 			    "%jd-%jd(%d) overlaps with %jd-%jd",
11275 			    blkno, end, frags, jstart, jend);
11276 		}
11277 	}
11278 #endif
11279 	FREE_LOCK(ump);
11280 }
11281 
11282 /*
11283  * Revert a block allocation when the journal record that describes it
11284  * is not yet written.
11285  */
11286 static int
11287 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
11288 	struct jnewblk *jnewblk;
11289 	struct fs *fs;
11290 	struct cg *cgp;
11291 	uint8_t *blksfree;
11292 {
11293 	ufs1_daddr_t fragno;
11294 	long cgbno, bbase;
11295 	int frags, blk;
11296 	int i;
11297 
11298 	frags = 0;
11299 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11300 	/*
11301 	 * We have to test which frags need to be rolled back.  We may
11302 	 * be operating on a stale copy when doing background writes.
11303 	 */
11304 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
11305 		if (isclr(blksfree, cgbno + i))
11306 			frags++;
11307 	if (frags == 0)
11308 		return (0);
11309 	/*
11310 	 * This is mostly ffs_blkfree() sans some validation and
11311 	 * superblock updates.
11312 	 */
11313 	if (frags == fs->fs_frag) {
11314 		fragno = fragstoblks(fs, cgbno);
11315 		ffs_setblock(fs, blksfree, fragno);
11316 		ffs_clusteracct(fs, cgp, fragno, 1);
11317 		cgp->cg_cs.cs_nbfree++;
11318 	} else {
11319 		cgbno += jnewblk->jn_oldfrags;
11320 		bbase = cgbno - fragnum(fs, cgbno);
11321 		/* Decrement the old frags.  */
11322 		blk = blkmap(fs, blksfree, bbase);
11323 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11324 		/* Deallocate the fragment */
11325 		for (i = 0; i < frags; i++)
11326 			setbit(blksfree, cgbno + i);
11327 		cgp->cg_cs.cs_nffree += frags;
11328 		/* Add back in counts associated with the new frags */
11329 		blk = blkmap(fs, blksfree, bbase);
11330 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11331 		/* If a complete block has been reassembled, account for it. */
11332 		fragno = fragstoblks(fs, bbase);
11333 		if (ffs_isblock(fs, blksfree, fragno)) {
11334 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
11335 			ffs_clusteracct(fs, cgp, fragno, 1);
11336 			cgp->cg_cs.cs_nbfree++;
11337 		}
11338 	}
11339 	stat_jnewblk++;
11340 	jnewblk->jn_state &= ~ATTACHED;
11341 	jnewblk->jn_state |= UNDONE;
11342 
11343 	return (frags);
11344 }
11345 
11346 static void
11347 initiate_write_bmsafemap(bmsafemap, bp)
11348 	struct bmsafemap *bmsafemap;
11349 	struct buf *bp;			/* The cg block. */
11350 {
11351 	struct jaddref *jaddref;
11352 	struct jnewblk *jnewblk;
11353 	uint8_t *inosused;
11354 	uint8_t *blksfree;
11355 	struct cg *cgp;
11356 	struct fs *fs;
11357 	ino_t ino;
11358 
11359 	/*
11360 	 * If this is a background write, we did this at the time that
11361 	 * the copy was made, so do not need to do it again.
11362 	 */
11363 	if (bmsafemap->sm_state & IOSTARTED)
11364 		return;
11365 	bmsafemap->sm_state |= IOSTARTED;
11366 	/*
11367 	 * Clear any inode allocations which are pending journal writes.
11368 	 */
11369 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11370 		cgp = (struct cg *)bp->b_data;
11371 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11372 		inosused = cg_inosused(cgp);
11373 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11374 			ino = jaddref->ja_ino % fs->fs_ipg;
11375 			if (isset(inosused, ino)) {
11376 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11377 					cgp->cg_cs.cs_ndir--;
11378 				cgp->cg_cs.cs_nifree++;
11379 				clrbit(inosused, ino);
11380 				jaddref->ja_state &= ~ATTACHED;
11381 				jaddref->ja_state |= UNDONE;
11382 				stat_jaddref++;
11383 			} else
11384 				panic("initiate_write_bmsafemap: inode %ju "
11385 				    "marked free", (uintmax_t)jaddref->ja_ino);
11386 		}
11387 	}
11388 	/*
11389 	 * Clear any block allocations which are pending journal writes.
11390 	 */
11391 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11392 		cgp = (struct cg *)bp->b_data;
11393 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11394 		blksfree = cg_blksfree(cgp);
11395 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11396 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11397 				continue;
11398 			panic("initiate_write_bmsafemap: block %jd "
11399 			    "marked free", jnewblk->jn_blkno);
11400 		}
11401 	}
11402 	/*
11403 	 * Move allocation lists to the written lists so they can be
11404 	 * cleared once the block write is complete.
11405 	 */
11406 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11407 	    inodedep, id_deps);
11408 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11409 	    newblk, nb_deps);
11410 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11411 	    wk_list);
11412 }
11413 
11414 void
11415 softdep_handle_error(struct buf *bp)
11416 {
11417 	struct ufsmount *ump;
11418 
11419 	ump = softdep_bp_to_mp(bp);
11420 	if (ump == NULL)
11421 		return;
11422 
11423 	if (ffs_fsfail_cleanup(ump, bp->b_error)) {
11424 		/*
11425 		 * No future writes will succeed, so the on-disk image is safe.
11426 		 * Pretend that this write succeeded so that the softdep state
11427 		 * will be cleaned up naturally.
11428 		 */
11429 		bp->b_ioflags &= ~BIO_ERROR;
11430 		bp->b_error = 0;
11431 	}
11432 }
11433 
11434 /*
11435  * This routine is called during the completion interrupt
11436  * service routine for a disk write (from the procedure called
11437  * by the device driver to inform the filesystem caches of
11438  * a request completion).  It should be called early in this
11439  * procedure, before the block is made available to other
11440  * processes or other routines are called.
11441  *
11442  */
11443 static void
11444 softdep_disk_write_complete(bp)
11445 	struct buf *bp;		/* describes the completed disk write */
11446 {
11447 	struct worklist *wk;
11448 	struct worklist *owk;
11449 	struct ufsmount *ump;
11450 	struct workhead reattach;
11451 	struct freeblks *freeblks;
11452 	struct buf *sbp;
11453 
11454 	ump = softdep_bp_to_mp(bp);
11455 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11456 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11457 	     "with outstanding dependencies for buffer %p", bp));
11458 	if (ump == NULL)
11459 		return;
11460 	if ((bp->b_ioflags & BIO_ERROR) != 0)
11461 		softdep_handle_error(bp);
11462 	/*
11463 	 * If an error occurred while doing the write, then the data
11464 	 * has not hit the disk and the dependencies cannot be processed.
11465 	 * But we do have to go through and roll forward any dependencies
11466 	 * that were rolled back before the disk write.
11467 	 */
11468 	sbp = NULL;
11469 	ACQUIRE_LOCK(ump);
11470 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11471 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11472 			switch (wk->wk_type) {
11473 			case D_PAGEDEP:
11474 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11475 				continue;
11476 
11477 			case D_INODEDEP:
11478 				handle_written_inodeblock(WK_INODEDEP(wk),
11479 				    bp, 0);
11480 				continue;
11481 
11482 			case D_BMSAFEMAP:
11483 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11484 				    bp, 0);
11485 				continue;
11486 
11487 			case D_INDIRDEP:
11488 				handle_written_indirdep(WK_INDIRDEP(wk),
11489 				    bp, &sbp, 0);
11490 				continue;
11491 			default:
11492 				/* nothing to roll forward */
11493 				continue;
11494 			}
11495 		}
11496 		FREE_LOCK(ump);
11497 		if (sbp)
11498 			brelse(sbp);
11499 		return;
11500 	}
11501 	LIST_INIT(&reattach);
11502 
11503 	/*
11504 	 * Ump SU lock must not be released anywhere in this code segment.
11505 	 */
11506 	owk = NULL;
11507 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11508 		WORKLIST_REMOVE(wk);
11509 		atomic_add_long(&dep_write[wk->wk_type], 1);
11510 		if (wk == owk)
11511 			panic("duplicate worklist: %p\n", wk);
11512 		owk = wk;
11513 		switch (wk->wk_type) {
11514 		case D_PAGEDEP:
11515 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11516 			    WRITESUCCEEDED))
11517 				WORKLIST_INSERT(&reattach, wk);
11518 			continue;
11519 
11520 		case D_INODEDEP:
11521 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11522 			    WRITESUCCEEDED))
11523 				WORKLIST_INSERT(&reattach, wk);
11524 			continue;
11525 
11526 		case D_BMSAFEMAP:
11527 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11528 			    WRITESUCCEEDED))
11529 				WORKLIST_INSERT(&reattach, wk);
11530 			continue;
11531 
11532 		case D_MKDIR:
11533 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11534 			continue;
11535 
11536 		case D_ALLOCDIRECT:
11537 			wk->wk_state |= COMPLETE;
11538 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11539 			continue;
11540 
11541 		case D_ALLOCINDIR:
11542 			wk->wk_state |= COMPLETE;
11543 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11544 			continue;
11545 
11546 		case D_INDIRDEP:
11547 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11548 			    WRITESUCCEEDED))
11549 				WORKLIST_INSERT(&reattach, wk);
11550 			continue;
11551 
11552 		case D_FREEBLKS:
11553 			wk->wk_state |= COMPLETE;
11554 			freeblks = WK_FREEBLKS(wk);
11555 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11556 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11557 				add_to_worklist(wk, WK_NODELAY);
11558 			continue;
11559 
11560 		case D_FREEWORK:
11561 			handle_written_freework(WK_FREEWORK(wk));
11562 			break;
11563 
11564 		case D_JSEGDEP:
11565 			free_jsegdep(WK_JSEGDEP(wk));
11566 			continue;
11567 
11568 		case D_JSEG:
11569 			handle_written_jseg(WK_JSEG(wk), bp);
11570 			continue;
11571 
11572 		case D_SBDEP:
11573 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11574 				WORKLIST_INSERT(&reattach, wk);
11575 			continue;
11576 
11577 		case D_FREEDEP:
11578 			free_freedep(WK_FREEDEP(wk));
11579 			continue;
11580 
11581 		default:
11582 			panic("handle_disk_write_complete: Unknown type %s",
11583 			    TYPENAME(wk->wk_type));
11584 			/* NOTREACHED */
11585 		}
11586 	}
11587 	/*
11588 	 * Reattach any requests that must be redone.
11589 	 */
11590 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11591 		WORKLIST_REMOVE(wk);
11592 		WORKLIST_INSERT(&bp->b_dep, wk);
11593 	}
11594 	FREE_LOCK(ump);
11595 	if (sbp)
11596 		brelse(sbp);
11597 }
11598 
11599 /*
11600  * Called from within softdep_disk_write_complete above.
11601  */
11602 static void
11603 handle_allocdirect_partdone(adp, wkhd)
11604 	struct allocdirect *adp;	/* the completed allocdirect */
11605 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11606 {
11607 	struct allocdirectlst *listhead;
11608 	struct allocdirect *listadp;
11609 	struct inodedep *inodedep;
11610 	long bsize;
11611 
11612 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11613 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11614 		return;
11615 	/*
11616 	 * The on-disk inode cannot claim to be any larger than the last
11617 	 * fragment that has been written. Otherwise, the on-disk inode
11618 	 * might have fragments that were not the last block in the file
11619 	 * which would corrupt the filesystem. Thus, we cannot free any
11620 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11621 	 * these blocks must be rolled back to zero before writing the inode.
11622 	 * We check the currently active set of allocdirects in id_inoupdt
11623 	 * or id_extupdt as appropriate.
11624 	 */
11625 	inodedep = adp->ad_inodedep;
11626 	bsize = inodedep->id_fs->fs_bsize;
11627 	if (adp->ad_state & EXTDATA)
11628 		listhead = &inodedep->id_extupdt;
11629 	else
11630 		listhead = &inodedep->id_inoupdt;
11631 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11632 		/* found our block */
11633 		if (listadp == adp)
11634 			break;
11635 		/* continue if ad_oldlbn is not a fragment */
11636 		if (listadp->ad_oldsize == 0 ||
11637 		    listadp->ad_oldsize == bsize)
11638 			continue;
11639 		/* hit a fragment */
11640 		return;
11641 	}
11642 	/*
11643 	 * If we have reached the end of the current list without
11644 	 * finding the just finished dependency, then it must be
11645 	 * on the future dependency list. Future dependencies cannot
11646 	 * be freed until they are moved to the current list.
11647 	 */
11648 	if (listadp == NULL) {
11649 #ifdef INVARIANTS
11650 		if (adp->ad_state & EXTDATA)
11651 			listhead = &inodedep->id_newextupdt;
11652 		else
11653 			listhead = &inodedep->id_newinoupdt;
11654 		TAILQ_FOREACH(listadp, listhead, ad_next)
11655 			/* found our block */
11656 			if (listadp == adp)
11657 				break;
11658 		if (listadp == NULL)
11659 			panic("handle_allocdirect_partdone: lost dep");
11660 #endif /* INVARIANTS */
11661 		return;
11662 	}
11663 	/*
11664 	 * If we have found the just finished dependency, then queue
11665 	 * it along with anything that follows it that is complete.
11666 	 * Since the pointer has not yet been written in the inode
11667 	 * as the dependency prevents it, place the allocdirect on the
11668 	 * bufwait list where it will be freed once the pointer is
11669 	 * valid.
11670 	 */
11671 	if (wkhd == NULL)
11672 		wkhd = &inodedep->id_bufwait;
11673 	for (; adp; adp = listadp) {
11674 		listadp = TAILQ_NEXT(adp, ad_next);
11675 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11676 			return;
11677 		TAILQ_REMOVE(listhead, adp, ad_next);
11678 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11679 	}
11680 }
11681 
11682 /*
11683  * Called from within softdep_disk_write_complete above.  This routine
11684  * completes successfully written allocindirs.
11685  */
11686 static void
11687 handle_allocindir_partdone(aip)
11688 	struct allocindir *aip;		/* the completed allocindir */
11689 {
11690 	struct indirdep *indirdep;
11691 
11692 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11693 		return;
11694 	indirdep = aip->ai_indirdep;
11695 	LIST_REMOVE(aip, ai_next);
11696 	/*
11697 	 * Don't set a pointer while the buffer is undergoing IO or while
11698 	 * we have active truncations.
11699 	 */
11700 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11701 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11702 		return;
11703 	}
11704 	if (indirdep->ir_state & UFS1FMT)
11705 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11706 		    aip->ai_newblkno;
11707 	else
11708 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11709 		    aip->ai_newblkno;
11710 	/*
11711 	 * Await the pointer write before freeing the allocindir.
11712 	 */
11713 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11714 }
11715 
11716 /*
11717  * Release segments held on a jwork list.
11718  */
11719 static void
11720 handle_jwork(wkhd)
11721 	struct workhead *wkhd;
11722 {
11723 	struct worklist *wk;
11724 
11725 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11726 		WORKLIST_REMOVE(wk);
11727 		switch (wk->wk_type) {
11728 		case D_JSEGDEP:
11729 			free_jsegdep(WK_JSEGDEP(wk));
11730 			continue;
11731 		case D_FREEDEP:
11732 			free_freedep(WK_FREEDEP(wk));
11733 			continue;
11734 		case D_FREEFRAG:
11735 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11736 			WORKITEM_FREE(wk, D_FREEFRAG);
11737 			continue;
11738 		case D_FREEWORK:
11739 			handle_written_freework(WK_FREEWORK(wk));
11740 			continue;
11741 		default:
11742 			panic("handle_jwork: Unknown type %s\n",
11743 			    TYPENAME(wk->wk_type));
11744 		}
11745 	}
11746 }
11747 
11748 /*
11749  * Handle the bufwait list on an inode when it is safe to release items
11750  * held there.  This normally happens after an inode block is written but
11751  * may be delayed and handled later if there are pending journal items that
11752  * are not yet safe to be released.
11753  */
11754 static struct freefile *
11755 handle_bufwait(inodedep, refhd)
11756 	struct inodedep *inodedep;
11757 	struct workhead *refhd;
11758 {
11759 	struct jaddref *jaddref;
11760 	struct freefile *freefile;
11761 	struct worklist *wk;
11762 
11763 	freefile = NULL;
11764 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11765 		WORKLIST_REMOVE(wk);
11766 		switch (wk->wk_type) {
11767 		case D_FREEFILE:
11768 			/*
11769 			 * We defer adding freefile to the worklist
11770 			 * until all other additions have been made to
11771 			 * ensure that it will be done after all the
11772 			 * old blocks have been freed.
11773 			 */
11774 			if (freefile != NULL)
11775 				panic("handle_bufwait: freefile");
11776 			freefile = WK_FREEFILE(wk);
11777 			continue;
11778 
11779 		case D_MKDIR:
11780 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11781 			continue;
11782 
11783 		case D_DIRADD:
11784 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11785 			continue;
11786 
11787 		case D_FREEFRAG:
11788 			wk->wk_state |= COMPLETE;
11789 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11790 				add_to_worklist(wk, 0);
11791 			continue;
11792 
11793 		case D_DIRREM:
11794 			wk->wk_state |= COMPLETE;
11795 			add_to_worklist(wk, 0);
11796 			continue;
11797 
11798 		case D_ALLOCDIRECT:
11799 		case D_ALLOCINDIR:
11800 			free_newblk(WK_NEWBLK(wk));
11801 			continue;
11802 
11803 		case D_JNEWBLK:
11804 			wk->wk_state |= COMPLETE;
11805 			free_jnewblk(WK_JNEWBLK(wk));
11806 			continue;
11807 
11808 		/*
11809 		 * Save freed journal segments and add references on
11810 		 * the supplied list which will delay their release
11811 		 * until the cg bitmap is cleared on disk.
11812 		 */
11813 		case D_JSEGDEP:
11814 			if (refhd == NULL)
11815 				free_jsegdep(WK_JSEGDEP(wk));
11816 			else
11817 				WORKLIST_INSERT(refhd, wk);
11818 			continue;
11819 
11820 		case D_JADDREF:
11821 			jaddref = WK_JADDREF(wk);
11822 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11823 			    if_deps);
11824 			/*
11825 			 * Transfer any jaddrefs to the list to be freed with
11826 			 * the bitmap if we're handling a removed file.
11827 			 */
11828 			if (refhd == NULL) {
11829 				wk->wk_state |= COMPLETE;
11830 				free_jaddref(jaddref);
11831 			} else
11832 				WORKLIST_INSERT(refhd, wk);
11833 			continue;
11834 
11835 		default:
11836 			panic("handle_bufwait: Unknown type %p(%s)",
11837 			    wk, TYPENAME(wk->wk_type));
11838 			/* NOTREACHED */
11839 		}
11840 	}
11841 	return (freefile);
11842 }
11843 /*
11844  * Called from within softdep_disk_write_complete above to restore
11845  * in-memory inode block contents to their most up-to-date state. Note
11846  * that this routine is always called from interrupt level with further
11847  * interrupts from this device blocked.
11848  *
11849  * If the write did not succeed, we will do all the roll-forward
11850  * operations, but we will not take the actions that will allow its
11851  * dependencies to be processed.
11852  */
11853 static int
11854 handle_written_inodeblock(inodedep, bp, flags)
11855 	struct inodedep *inodedep;
11856 	struct buf *bp;		/* buffer containing the inode block */
11857 	int flags;
11858 {
11859 	struct freefile *freefile;
11860 	struct allocdirect *adp, *nextadp;
11861 	struct ufs1_dinode *dp1 = NULL;
11862 	struct ufs2_dinode *dp2 = NULL;
11863 	struct workhead wkhd;
11864 	int hadchanges, fstype;
11865 	ino_t freelink;
11866 
11867 	LIST_INIT(&wkhd);
11868 	hadchanges = 0;
11869 	freefile = NULL;
11870 	if ((inodedep->id_state & IOSTARTED) == 0)
11871 		panic("handle_written_inodeblock: not started");
11872 	inodedep->id_state &= ~IOSTARTED;
11873 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11874 		fstype = UFS1;
11875 		dp1 = (struct ufs1_dinode *)bp->b_data +
11876 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11877 		freelink = dp1->di_freelink;
11878 	} else {
11879 		fstype = UFS2;
11880 		dp2 = (struct ufs2_dinode *)bp->b_data +
11881 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11882 		freelink = dp2->di_freelink;
11883 	}
11884 	/*
11885 	 * Leave this inodeblock dirty until it's in the list.
11886 	 */
11887 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11888 	    (flags & WRITESUCCEEDED)) {
11889 		struct inodedep *inon;
11890 
11891 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11892 		if ((inon == NULL && freelink == 0) ||
11893 		    (inon && inon->id_ino == freelink)) {
11894 			if (inon)
11895 				inon->id_state |= UNLINKPREV;
11896 			inodedep->id_state |= UNLINKNEXT;
11897 		}
11898 		hadchanges = 1;
11899 	}
11900 	/*
11901 	 * If we had to rollback the inode allocation because of
11902 	 * bitmaps being incomplete, then simply restore it.
11903 	 * Keep the block dirty so that it will not be reclaimed until
11904 	 * all associated dependencies have been cleared and the
11905 	 * corresponding updates written to disk.
11906 	 */
11907 	if (inodedep->id_savedino1 != NULL) {
11908 		hadchanges = 1;
11909 		if (fstype == UFS1)
11910 			*dp1 = *inodedep->id_savedino1;
11911 		else
11912 			*dp2 = *inodedep->id_savedino2;
11913 		free(inodedep->id_savedino1, M_SAVEDINO);
11914 		inodedep->id_savedino1 = NULL;
11915 		if ((bp->b_flags & B_DELWRI) == 0)
11916 			stat_inode_bitmap++;
11917 		bdirty(bp);
11918 		/*
11919 		 * If the inode is clear here and GOINGAWAY it will never
11920 		 * be written.  Process the bufwait and clear any pending
11921 		 * work which may include the freefile.
11922 		 */
11923 		if (inodedep->id_state & GOINGAWAY)
11924 			goto bufwait;
11925 		return (1);
11926 	}
11927 	if (flags & WRITESUCCEEDED)
11928 		inodedep->id_state |= COMPLETE;
11929 	/*
11930 	 * Roll forward anything that had to be rolled back before
11931 	 * the inode could be updated.
11932 	 */
11933 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11934 		nextadp = TAILQ_NEXT(adp, ad_next);
11935 		if (adp->ad_state & ATTACHED)
11936 			panic("handle_written_inodeblock: new entry");
11937 		if (fstype == UFS1) {
11938 			if (adp->ad_offset < UFS_NDADDR) {
11939 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11940 					panic("%s %s #%jd mismatch %d != %jd",
11941 					    "handle_written_inodeblock:",
11942 					    "direct pointer",
11943 					    (intmax_t)adp->ad_offset,
11944 					    dp1->di_db[adp->ad_offset],
11945 					    (intmax_t)adp->ad_oldblkno);
11946 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11947 			} else {
11948 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11949 				    0)
11950 					panic("%s: %s #%jd allocated as %d",
11951 					    "handle_written_inodeblock",
11952 					    "indirect pointer",
11953 					    (intmax_t)adp->ad_offset -
11954 					    UFS_NDADDR,
11955 					    dp1->di_ib[adp->ad_offset -
11956 					    UFS_NDADDR]);
11957 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11958 				    adp->ad_newblkno;
11959 			}
11960 		} else {
11961 			if (adp->ad_offset < UFS_NDADDR) {
11962 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11963 					panic("%s: %s #%jd %s %jd != %jd",
11964 					    "handle_written_inodeblock",
11965 					    "direct pointer",
11966 					    (intmax_t)adp->ad_offset, "mismatch",
11967 					    (intmax_t)dp2->di_db[adp->ad_offset],
11968 					    (intmax_t)adp->ad_oldblkno);
11969 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11970 			} else {
11971 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11972 				    0)
11973 					panic("%s: %s #%jd allocated as %jd",
11974 					    "handle_written_inodeblock",
11975 					    "indirect pointer",
11976 					    (intmax_t)adp->ad_offset -
11977 					    UFS_NDADDR,
11978 					    (intmax_t)
11979 					    dp2->di_ib[adp->ad_offset -
11980 					    UFS_NDADDR]);
11981 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11982 				    adp->ad_newblkno;
11983 			}
11984 		}
11985 		adp->ad_state &= ~UNDONE;
11986 		adp->ad_state |= ATTACHED;
11987 		hadchanges = 1;
11988 	}
11989 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11990 		nextadp = TAILQ_NEXT(adp, ad_next);
11991 		if (adp->ad_state & ATTACHED)
11992 			panic("handle_written_inodeblock: new entry");
11993 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11994 			panic("%s: direct pointers #%jd %s %jd != %jd",
11995 			    "handle_written_inodeblock",
11996 			    (intmax_t)adp->ad_offset, "mismatch",
11997 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11998 			    (intmax_t)adp->ad_oldblkno);
11999 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
12000 		adp->ad_state &= ~UNDONE;
12001 		adp->ad_state |= ATTACHED;
12002 		hadchanges = 1;
12003 	}
12004 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
12005 		stat_direct_blk_ptrs++;
12006 	/*
12007 	 * Reset the file size to its most up-to-date value.
12008 	 */
12009 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
12010 		panic("handle_written_inodeblock: bad size");
12011 	if (inodedep->id_savednlink > UFS_LINK_MAX)
12012 		panic("handle_written_inodeblock: Invalid link count "
12013 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
12014 		    inodedep);
12015 	if (fstype == UFS1) {
12016 		if (dp1->di_nlink != inodedep->id_savednlink) {
12017 			dp1->di_nlink = inodedep->id_savednlink;
12018 			hadchanges = 1;
12019 		}
12020 		if (dp1->di_size != inodedep->id_savedsize) {
12021 			dp1->di_size = inodedep->id_savedsize;
12022 			hadchanges = 1;
12023 		}
12024 	} else {
12025 		if (dp2->di_nlink != inodedep->id_savednlink) {
12026 			dp2->di_nlink = inodedep->id_savednlink;
12027 			hadchanges = 1;
12028 		}
12029 		if (dp2->di_size != inodedep->id_savedsize) {
12030 			dp2->di_size = inodedep->id_savedsize;
12031 			hadchanges = 1;
12032 		}
12033 		if (dp2->di_extsize != inodedep->id_savedextsize) {
12034 			dp2->di_extsize = inodedep->id_savedextsize;
12035 			hadchanges = 1;
12036 		}
12037 	}
12038 	inodedep->id_savedsize = -1;
12039 	inodedep->id_savedextsize = -1;
12040 	inodedep->id_savednlink = -1;
12041 	/*
12042 	 * If there were any rollbacks in the inode block, then it must be
12043 	 * marked dirty so that its will eventually get written back in
12044 	 * its correct form.
12045 	 */
12046 	if (hadchanges) {
12047 		if (fstype == UFS2)
12048 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
12049 		bdirty(bp);
12050 	}
12051 bufwait:
12052 	/*
12053 	 * If the write did not succeed, we have done all the roll-forward
12054 	 * operations, but we cannot take the actions that will allow its
12055 	 * dependencies to be processed.
12056 	 */
12057 	if ((flags & WRITESUCCEEDED) == 0)
12058 		return (hadchanges);
12059 	/*
12060 	 * Process any allocdirects that completed during the update.
12061 	 */
12062 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
12063 		handle_allocdirect_partdone(adp, &wkhd);
12064 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
12065 		handle_allocdirect_partdone(adp, &wkhd);
12066 	/*
12067 	 * Process deallocations that were held pending until the
12068 	 * inode had been written to disk. Freeing of the inode
12069 	 * is delayed until after all blocks have been freed to
12070 	 * avoid creation of new <vfsid, inum, lbn> triples
12071 	 * before the old ones have been deleted.  Completely
12072 	 * unlinked inodes are not processed until the unlinked
12073 	 * inode list is written or the last reference is removed.
12074 	 */
12075 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
12076 		freefile = handle_bufwait(inodedep, NULL);
12077 		if (freefile && !LIST_EMPTY(&wkhd)) {
12078 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
12079 			freefile = NULL;
12080 		}
12081 	}
12082 	/*
12083 	 * Move rolled forward dependency completions to the bufwait list
12084 	 * now that those that were already written have been processed.
12085 	 */
12086 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
12087 		panic("handle_written_inodeblock: bufwait but no changes");
12088 	jwork_move(&inodedep->id_bufwait, &wkhd);
12089 
12090 	if (freefile != NULL) {
12091 		/*
12092 		 * If the inode is goingaway it was never written.  Fake up
12093 		 * the state here so free_inodedep() can succeed.
12094 		 */
12095 		if (inodedep->id_state & GOINGAWAY)
12096 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
12097 		if (free_inodedep(inodedep) == 0)
12098 			panic("handle_written_inodeblock: live inodedep %p",
12099 			    inodedep);
12100 		add_to_worklist(&freefile->fx_list, 0);
12101 		return (0);
12102 	}
12103 
12104 	/*
12105 	 * If no outstanding dependencies, free it.
12106 	 */
12107 	if (free_inodedep(inodedep) ||
12108 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
12109 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
12110 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
12111 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
12112 		return (0);
12113 	return (hadchanges);
12114 }
12115 
12116 /*
12117  * Perform needed roll-forwards and kick off any dependencies that
12118  * can now be processed.
12119  *
12120  * If the write did not succeed, we will do all the roll-forward
12121  * operations, but we will not take the actions that will allow its
12122  * dependencies to be processed.
12123  */
12124 static int
12125 handle_written_indirdep(indirdep, bp, bpp, flags)
12126 	struct indirdep *indirdep;
12127 	struct buf *bp;
12128 	struct buf **bpp;
12129 	int flags;
12130 {
12131 	struct allocindir *aip;
12132 	struct buf *sbp;
12133 	int chgs;
12134 
12135 	if (indirdep->ir_state & GOINGAWAY)
12136 		panic("handle_written_indirdep: indirdep gone");
12137 	if ((indirdep->ir_state & IOSTARTED) == 0)
12138 		panic("handle_written_indirdep: IO not started");
12139 	chgs = 0;
12140 	/*
12141 	 * If there were rollbacks revert them here.
12142 	 */
12143 	if (indirdep->ir_saveddata) {
12144 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
12145 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
12146 			free(indirdep->ir_saveddata, M_INDIRDEP);
12147 			indirdep->ir_saveddata = NULL;
12148 		}
12149 		chgs = 1;
12150 	}
12151 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
12152 	indirdep->ir_state |= ATTACHED;
12153 	/*
12154 	 * If the write did not succeed, we have done all the roll-forward
12155 	 * operations, but we cannot take the actions that will allow its
12156 	 * dependencies to be processed.
12157 	 */
12158 	if ((flags & WRITESUCCEEDED) == 0) {
12159 		stat_indir_blk_ptrs++;
12160 		bdirty(bp);
12161 		return (1);
12162 	}
12163 	/*
12164 	 * Move allocindirs with written pointers to the completehd if
12165 	 * the indirdep's pointer is not yet written.  Otherwise
12166 	 * free them here.
12167 	 */
12168 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
12169 		LIST_REMOVE(aip, ai_next);
12170 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
12171 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
12172 			    ai_next);
12173 			newblk_freefrag(&aip->ai_block);
12174 			continue;
12175 		}
12176 		free_newblk(&aip->ai_block);
12177 	}
12178 	/*
12179 	 * Move allocindirs that have finished dependency processing from
12180 	 * the done list to the write list after updating the pointers.
12181 	 */
12182 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
12183 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
12184 			handle_allocindir_partdone(aip);
12185 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
12186 				panic("disk_write_complete: not gone");
12187 			chgs = 1;
12188 		}
12189 	}
12190 	/*
12191 	 * Preserve the indirdep if there were any changes or if it is not
12192 	 * yet valid on disk.
12193 	 */
12194 	if (chgs) {
12195 		stat_indir_blk_ptrs++;
12196 		bdirty(bp);
12197 		return (1);
12198 	}
12199 	/*
12200 	 * If there were no changes we can discard the savedbp and detach
12201 	 * ourselves from the buf.  We are only carrying completed pointers
12202 	 * in this case.
12203 	 */
12204 	sbp = indirdep->ir_savebp;
12205 	sbp->b_flags |= B_INVAL | B_NOCACHE;
12206 	indirdep->ir_savebp = NULL;
12207 	indirdep->ir_bp = NULL;
12208 	if (*bpp != NULL)
12209 		panic("handle_written_indirdep: bp already exists.");
12210 	*bpp = sbp;
12211 	/*
12212 	 * The indirdep may not be freed until its parent points at it.
12213 	 */
12214 	if (indirdep->ir_state & DEPCOMPLETE)
12215 		free_indirdep(indirdep);
12216 
12217 	return (0);
12218 }
12219 
12220 /*
12221  * Process a diradd entry after its dependent inode has been written.
12222  */
12223 static void
12224 diradd_inode_written(dap, inodedep)
12225 	struct diradd *dap;
12226 	struct inodedep *inodedep;
12227 {
12228 
12229 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
12230 	dap->da_state |= COMPLETE;
12231 	complete_diradd(dap);
12232 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
12233 }
12234 
12235 /*
12236  * Returns true if the bmsafemap will have rollbacks when written.  Must only
12237  * be called with the per-filesystem lock and the buf lock on the cg held.
12238  */
12239 static int
12240 bmsafemap_backgroundwrite(bmsafemap, bp)
12241 	struct bmsafemap *bmsafemap;
12242 	struct buf *bp;
12243 {
12244 	int dirty;
12245 
12246 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
12247 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
12248 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
12249 	/*
12250 	 * If we're initiating a background write we need to process the
12251 	 * rollbacks as they exist now, not as they exist when IO starts.
12252 	 * No other consumers will look at the contents of the shadowed
12253 	 * buf so this is safe to do here.
12254 	 */
12255 	if (bp->b_xflags & BX_BKGRDMARKER)
12256 		initiate_write_bmsafemap(bmsafemap, bp);
12257 
12258 	return (dirty);
12259 }
12260 
12261 /*
12262  * Re-apply an allocation when a cg write is complete.
12263  */
12264 static int
12265 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
12266 	struct jnewblk *jnewblk;
12267 	struct fs *fs;
12268 	struct cg *cgp;
12269 	uint8_t *blksfree;
12270 {
12271 	ufs1_daddr_t fragno;
12272 	ufs2_daddr_t blkno;
12273 	long cgbno, bbase;
12274 	int frags, blk;
12275 	int i;
12276 
12277 	frags = 0;
12278 	cgbno = dtogd(fs, jnewblk->jn_blkno);
12279 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
12280 		if (isclr(blksfree, cgbno + i))
12281 			panic("jnewblk_rollforward: re-allocated fragment");
12282 		frags++;
12283 	}
12284 	if (frags == fs->fs_frag) {
12285 		blkno = fragstoblks(fs, cgbno);
12286 		ffs_clrblock(fs, blksfree, (long)blkno);
12287 		ffs_clusteracct(fs, cgp, blkno, -1);
12288 		cgp->cg_cs.cs_nbfree--;
12289 	} else {
12290 		bbase = cgbno - fragnum(fs, cgbno);
12291 		cgbno += jnewblk->jn_oldfrags;
12292                 /* If a complete block had been reassembled, account for it. */
12293 		fragno = fragstoblks(fs, bbase);
12294 		if (ffs_isblock(fs, blksfree, fragno)) {
12295 			cgp->cg_cs.cs_nffree += fs->fs_frag;
12296 			ffs_clusteracct(fs, cgp, fragno, -1);
12297 			cgp->cg_cs.cs_nbfree--;
12298 		}
12299 		/* Decrement the old frags.  */
12300 		blk = blkmap(fs, blksfree, bbase);
12301 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
12302 		/* Allocate the fragment */
12303 		for (i = 0; i < frags; i++)
12304 			clrbit(blksfree, cgbno + i);
12305 		cgp->cg_cs.cs_nffree -= frags;
12306 		/* Add back in counts associated with the new frags */
12307 		blk = blkmap(fs, blksfree, bbase);
12308 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
12309 	}
12310 	return (frags);
12311 }
12312 
12313 /*
12314  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
12315  * changes if it's not a background write.  Set all written dependencies
12316  * to DEPCOMPLETE and free the structure if possible.
12317  *
12318  * If the write did not succeed, we will do all the roll-forward
12319  * operations, but we will not take the actions that will allow its
12320  * dependencies to be processed.
12321  */
12322 static int
12323 handle_written_bmsafemap(bmsafemap, bp, flags)
12324 	struct bmsafemap *bmsafemap;
12325 	struct buf *bp;
12326 	int flags;
12327 {
12328 	struct newblk *newblk;
12329 	struct inodedep *inodedep;
12330 	struct jaddref *jaddref, *jatmp;
12331 	struct jnewblk *jnewblk, *jntmp;
12332 	struct ufsmount *ump;
12333 	uint8_t *inosused;
12334 	uint8_t *blksfree;
12335 	struct cg *cgp;
12336 	struct fs *fs;
12337 	ino_t ino;
12338 	int foreground;
12339 	int chgs;
12340 
12341 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
12342 		panic("handle_written_bmsafemap: Not started\n");
12343 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
12344 	chgs = 0;
12345 	bmsafemap->sm_state &= ~IOSTARTED;
12346 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
12347 	/*
12348 	 * If write was successful, release journal work that was waiting
12349 	 * on the write. Otherwise move the work back.
12350 	 */
12351 	if (flags & WRITESUCCEEDED)
12352 		handle_jwork(&bmsafemap->sm_freewr);
12353 	else
12354 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12355 		    worklist, wk_list);
12356 
12357 	/*
12358 	 * Restore unwritten inode allocation pending jaddref writes.
12359 	 */
12360 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
12361 		cgp = (struct cg *)bp->b_data;
12362 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12363 		inosused = cg_inosused(cgp);
12364 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
12365 		    ja_bmdeps, jatmp) {
12366 			if ((jaddref->ja_state & UNDONE) == 0)
12367 				continue;
12368 			ino = jaddref->ja_ino % fs->fs_ipg;
12369 			if (isset(inosused, ino))
12370 				panic("handle_written_bmsafemap: "
12371 				    "re-allocated inode");
12372 			/* Do the roll-forward only if it's a real copy. */
12373 			if (foreground) {
12374 				if ((jaddref->ja_mode & IFMT) == IFDIR)
12375 					cgp->cg_cs.cs_ndir++;
12376 				cgp->cg_cs.cs_nifree--;
12377 				setbit(inosused, ino);
12378 				chgs = 1;
12379 			}
12380 			jaddref->ja_state &= ~UNDONE;
12381 			jaddref->ja_state |= ATTACHED;
12382 			free_jaddref(jaddref);
12383 		}
12384 	}
12385 	/*
12386 	 * Restore any block allocations which are pending journal writes.
12387 	 */
12388 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12389 		cgp = (struct cg *)bp->b_data;
12390 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12391 		blksfree = cg_blksfree(cgp);
12392 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12393 		    jntmp) {
12394 			if ((jnewblk->jn_state & UNDONE) == 0)
12395 				continue;
12396 			/* Do the roll-forward only if it's a real copy. */
12397 			if (foreground &&
12398 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12399 				chgs = 1;
12400 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12401 			jnewblk->jn_state |= ATTACHED;
12402 			free_jnewblk(jnewblk);
12403 		}
12404 	}
12405 	/*
12406 	 * If the write did not succeed, we have done all the roll-forward
12407 	 * operations, but we cannot take the actions that will allow its
12408 	 * dependencies to be processed.
12409 	 */
12410 	if ((flags & WRITESUCCEEDED) == 0) {
12411 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12412 		    newblk, nb_deps);
12413 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12414 		    worklist, wk_list);
12415 		if (foreground)
12416 			bdirty(bp);
12417 		return (1);
12418 	}
12419 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12420 		newblk->nb_state |= DEPCOMPLETE;
12421 		newblk->nb_state &= ~ONDEPLIST;
12422 		newblk->nb_bmsafemap = NULL;
12423 		LIST_REMOVE(newblk, nb_deps);
12424 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12425 			handle_allocdirect_partdone(
12426 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12427 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12428 			handle_allocindir_partdone(
12429 			    WK_ALLOCINDIR(&newblk->nb_list));
12430 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12431 			panic("handle_written_bmsafemap: Unexpected type: %s",
12432 			    TYPENAME(newblk->nb_list.wk_type));
12433 	}
12434 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12435 		inodedep->id_state |= DEPCOMPLETE;
12436 		inodedep->id_state &= ~ONDEPLIST;
12437 		LIST_REMOVE(inodedep, id_deps);
12438 		inodedep->id_bmsafemap = NULL;
12439 	}
12440 	LIST_REMOVE(bmsafemap, sm_next);
12441 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12442 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12443 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12444 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12445 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12446 		LIST_REMOVE(bmsafemap, sm_hash);
12447 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12448 		return (0);
12449 	}
12450 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12451 	if (foreground)
12452 		bdirty(bp);
12453 	return (1);
12454 }
12455 
12456 /*
12457  * Try to free a mkdir dependency.
12458  */
12459 static void
12460 complete_mkdir(mkdir)
12461 	struct mkdir *mkdir;
12462 {
12463 	struct diradd *dap;
12464 
12465 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12466 		return;
12467 	LIST_REMOVE(mkdir, md_mkdirs);
12468 	dap = mkdir->md_diradd;
12469 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12470 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12471 		dap->da_state |= DEPCOMPLETE;
12472 		complete_diradd(dap);
12473 	}
12474 	WORKITEM_FREE(mkdir, D_MKDIR);
12475 }
12476 
12477 /*
12478  * Handle the completion of a mkdir dependency.
12479  */
12480 static void
12481 handle_written_mkdir(mkdir, type)
12482 	struct mkdir *mkdir;
12483 	int type;
12484 {
12485 
12486 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12487 		panic("handle_written_mkdir: bad type");
12488 	mkdir->md_state |= COMPLETE;
12489 	complete_mkdir(mkdir);
12490 }
12491 
12492 static int
12493 free_pagedep(pagedep)
12494 	struct pagedep *pagedep;
12495 {
12496 	int i;
12497 
12498 	if (pagedep->pd_state & NEWBLOCK)
12499 		return (0);
12500 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12501 		return (0);
12502 	for (i = 0; i < DAHASHSZ; i++)
12503 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12504 			return (0);
12505 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12506 		return (0);
12507 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12508 		return (0);
12509 	if (pagedep->pd_state & ONWORKLIST)
12510 		WORKLIST_REMOVE(&pagedep->pd_list);
12511 	LIST_REMOVE(pagedep, pd_hash);
12512 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12513 
12514 	return (1);
12515 }
12516 
12517 /*
12518  * Called from within softdep_disk_write_complete above.
12519  * A write operation was just completed. Removed inodes can
12520  * now be freed and associated block pointers may be committed.
12521  * Note that this routine is always called from interrupt level
12522  * with further interrupts from this device blocked.
12523  *
12524  * If the write did not succeed, we will do all the roll-forward
12525  * operations, but we will not take the actions that will allow its
12526  * dependencies to be processed.
12527  */
12528 static int
12529 handle_written_filepage(pagedep, bp, flags)
12530 	struct pagedep *pagedep;
12531 	struct buf *bp;		/* buffer containing the written page */
12532 	int flags;
12533 {
12534 	struct dirrem *dirrem;
12535 	struct diradd *dap, *nextdap;
12536 	struct direct *ep;
12537 	int i, chgs;
12538 
12539 	if ((pagedep->pd_state & IOSTARTED) == 0)
12540 		panic("handle_written_filepage: not started");
12541 	pagedep->pd_state &= ~IOSTARTED;
12542 	if ((flags & WRITESUCCEEDED) == 0)
12543 		goto rollforward;
12544 	/*
12545 	 * Process any directory removals that have been committed.
12546 	 */
12547 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12548 		LIST_REMOVE(dirrem, dm_next);
12549 		dirrem->dm_state |= COMPLETE;
12550 		dirrem->dm_dirinum = pagedep->pd_ino;
12551 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12552 		    ("handle_written_filepage: Journal entries not written."));
12553 		add_to_worklist(&dirrem->dm_list, 0);
12554 	}
12555 	/*
12556 	 * Free any directory additions that have been committed.
12557 	 * If it is a newly allocated block, we have to wait until
12558 	 * the on-disk directory inode claims the new block.
12559 	 */
12560 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12561 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12562 			free_diradd(dap, NULL);
12563 rollforward:
12564 	/*
12565 	 * Uncommitted directory entries must be restored.
12566 	 */
12567 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12568 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12569 		     dap = nextdap) {
12570 			nextdap = LIST_NEXT(dap, da_pdlist);
12571 			if (dap->da_state & ATTACHED)
12572 				panic("handle_written_filepage: attached");
12573 			ep = (struct direct *)
12574 			    ((char *)bp->b_data + dap->da_offset);
12575 			ep->d_ino = dap->da_newinum;
12576 			dap->da_state &= ~UNDONE;
12577 			dap->da_state |= ATTACHED;
12578 			chgs = 1;
12579 			/*
12580 			 * If the inode referenced by the directory has
12581 			 * been written out, then the dependency can be
12582 			 * moved to the pending list.
12583 			 */
12584 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12585 				LIST_REMOVE(dap, da_pdlist);
12586 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12587 				    da_pdlist);
12588 			}
12589 		}
12590 	}
12591 	/*
12592 	 * If there were any rollbacks in the directory, then it must be
12593 	 * marked dirty so that its will eventually get written back in
12594 	 * its correct form.
12595 	 */
12596 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12597 		if ((bp->b_flags & B_DELWRI) == 0)
12598 			stat_dir_entry++;
12599 		bdirty(bp);
12600 		return (1);
12601 	}
12602 	/*
12603 	 * If we are not waiting for a new directory block to be
12604 	 * claimed by its inode, then the pagedep will be freed.
12605 	 * Otherwise it will remain to track any new entries on
12606 	 * the page in case they are fsync'ed.
12607 	 */
12608 	free_pagedep(pagedep);
12609 	return (0);
12610 }
12611 
12612 /*
12613  * Writing back in-core inode structures.
12614  *
12615  * The filesystem only accesses an inode's contents when it occupies an
12616  * "in-core" inode structure.  These "in-core" structures are separate from
12617  * the page frames used to cache inode blocks.  Only the latter are
12618  * transferred to/from the disk.  So, when the updated contents of the
12619  * "in-core" inode structure are copied to the corresponding in-memory inode
12620  * block, the dependencies are also transferred.  The following procedure is
12621  * called when copying a dirty "in-core" inode to a cached inode block.
12622  */
12623 
12624 /*
12625  * Called when an inode is loaded from disk. If the effective link count
12626  * differed from the actual link count when it was last flushed, then we
12627  * need to ensure that the correct effective link count is put back.
12628  */
12629 void
12630 softdep_load_inodeblock(ip)
12631 	struct inode *ip;	/* the "in_core" copy of the inode */
12632 {
12633 	struct inodedep *inodedep;
12634 	struct ufsmount *ump;
12635 
12636 	ump = ITOUMP(ip);
12637 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12638 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12639 	/*
12640 	 * Check for alternate nlink count.
12641 	 */
12642 	ip->i_effnlink = ip->i_nlink;
12643 	ACQUIRE_LOCK(ump);
12644 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12645 		FREE_LOCK(ump);
12646 		return;
12647 	}
12648 	if (ip->i_nlink != inodedep->id_nlinkwrote &&
12649 	    inodedep->id_nlinkwrote != -1) {
12650 		KASSERT(ip->i_nlink == 0 &&
12651 		    (ump->um_flags & UM_FSFAIL_CLEANUP) != 0,
12652 		    ("read bad i_nlink value"));
12653 		ip->i_effnlink = ip->i_nlink = inodedep->id_nlinkwrote;
12654 	}
12655 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12656 	KASSERT(ip->i_effnlink >= 0,
12657 	    ("softdep_load_inodeblock: negative i_effnlink"));
12658 	FREE_LOCK(ump);
12659 }
12660 
12661 /*
12662  * This routine is called just before the "in-core" inode
12663  * information is to be copied to the in-memory inode block.
12664  * Recall that an inode block contains several inodes. If
12665  * the force flag is set, then the dependencies will be
12666  * cleared so that the update can always be made. Note that
12667  * the buffer is locked when this routine is called, so we
12668  * will never be in the middle of writing the inode block
12669  * to disk.
12670  */
12671 void
12672 softdep_update_inodeblock(ip, bp, waitfor)
12673 	struct inode *ip;	/* the "in_core" copy of the inode */
12674 	struct buf *bp;		/* the buffer containing the inode block */
12675 	int waitfor;		/* nonzero => update must be allowed */
12676 {
12677 	struct inodedep *inodedep;
12678 	struct inoref *inoref;
12679 	struct ufsmount *ump;
12680 	struct worklist *wk;
12681 	struct mount *mp;
12682 	struct buf *ibp;
12683 	struct fs *fs;
12684 	int error;
12685 
12686 	ump = ITOUMP(ip);
12687 	mp = UFSTOVFS(ump);
12688 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12689 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12690 	fs = ump->um_fs;
12691 	/*
12692 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12693 	 * does not have access to the in-core ip so must write directly into
12694 	 * the inode block buffer when setting freelink.
12695 	 */
12696 	if (fs->fs_magic == FS_UFS1_MAGIC)
12697 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12698 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12699 	else
12700 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12701 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12702 	/*
12703 	 * If the effective link count is not equal to the actual link
12704 	 * count, then we must track the difference in an inodedep while
12705 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12706 	 * if there is no existing inodedep, then there are no dependencies
12707 	 * to track.
12708 	 */
12709 	ACQUIRE_LOCK(ump);
12710 again:
12711 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12712 		FREE_LOCK(ump);
12713 		if (ip->i_effnlink != ip->i_nlink)
12714 			panic("softdep_update_inodeblock: bad link count");
12715 		return;
12716 	}
12717 	KASSERT(ip->i_nlink >= inodedep->id_nlinkdelta,
12718 	    ("softdep_update_inodeblock inconsistent ip %p i_nlink %d "
12719 	    "inodedep %p id_nlinkdelta %jd",
12720 	    ip, ip->i_nlink, inodedep, (intmax_t)inodedep->id_nlinkdelta));
12721 	inodedep->id_nlinkwrote = ip->i_nlink;
12722 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12723 		panic("softdep_update_inodeblock: bad delta");
12724 	/*
12725 	 * If we're flushing all dependencies we must also move any waiting
12726 	 * for journal writes onto the bufwait list prior to I/O.
12727 	 */
12728 	if (waitfor) {
12729 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12730 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12731 			    == DEPCOMPLETE) {
12732 				jwait(&inoref->if_list, MNT_WAIT);
12733 				goto again;
12734 			}
12735 		}
12736 	}
12737 	/*
12738 	 * Changes have been initiated. Anything depending on these
12739 	 * changes cannot occur until this inode has been written.
12740 	 */
12741 	inodedep->id_state &= ~COMPLETE;
12742 	if ((inodedep->id_state & ONWORKLIST) == 0)
12743 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12744 	/*
12745 	 * Any new dependencies associated with the incore inode must
12746 	 * now be moved to the list associated with the buffer holding
12747 	 * the in-memory copy of the inode. Once merged process any
12748 	 * allocdirects that are completed by the merger.
12749 	 */
12750 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12751 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12752 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12753 		    NULL);
12754 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12755 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12756 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12757 		    NULL);
12758 	/*
12759 	 * Now that the inode has been pushed into the buffer, the
12760 	 * operations dependent on the inode being written to disk
12761 	 * can be moved to the id_bufwait so that they will be
12762 	 * processed when the buffer I/O completes.
12763 	 */
12764 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12765 		WORKLIST_REMOVE(wk);
12766 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12767 	}
12768 	/*
12769 	 * Newly allocated inodes cannot be written until the bitmap
12770 	 * that allocates them have been written (indicated by
12771 	 * DEPCOMPLETE being set in id_state). If we are doing a
12772 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12773 	 * to be written so that the update can be done.
12774 	 */
12775 	if (waitfor == 0) {
12776 		FREE_LOCK(ump);
12777 		return;
12778 	}
12779 retry:
12780 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12781 		FREE_LOCK(ump);
12782 		return;
12783 	}
12784 	ibp = inodedep->id_bmsafemap->sm_buf;
12785 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12786 	if (ibp == NULL) {
12787 		/*
12788 		 * If ibp came back as NULL, the dependency could have been
12789 		 * freed while we slept.  Look it up again, and check to see
12790 		 * that it has completed.
12791 		 */
12792 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12793 			goto retry;
12794 		FREE_LOCK(ump);
12795 		return;
12796 	}
12797 	FREE_LOCK(ump);
12798 	if ((error = bwrite(ibp)) != 0)
12799 		softdep_error("softdep_update_inodeblock: bwrite", error);
12800 }
12801 
12802 /*
12803  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12804  * old inode dependency list (such as id_inoupdt).
12805  */
12806 static void
12807 merge_inode_lists(newlisthead, oldlisthead)
12808 	struct allocdirectlst *newlisthead;
12809 	struct allocdirectlst *oldlisthead;
12810 {
12811 	struct allocdirect *listadp, *newadp;
12812 
12813 	newadp = TAILQ_FIRST(newlisthead);
12814 	if (newadp != NULL)
12815 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12816 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12817 		if (listadp->ad_offset < newadp->ad_offset) {
12818 			listadp = TAILQ_NEXT(listadp, ad_next);
12819 			continue;
12820 		}
12821 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12822 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12823 		if (listadp->ad_offset == newadp->ad_offset) {
12824 			allocdirect_merge(oldlisthead, newadp,
12825 			    listadp);
12826 			listadp = newadp;
12827 		}
12828 		newadp = TAILQ_FIRST(newlisthead);
12829 	}
12830 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12831 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12832 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12833 	}
12834 }
12835 
12836 /*
12837  * If we are doing an fsync, then we must ensure that any directory
12838  * entries for the inode have been written after the inode gets to disk.
12839  */
12840 int
12841 softdep_fsync(vp)
12842 	struct vnode *vp;	/* the "in_core" copy of the inode */
12843 {
12844 	struct inodedep *inodedep;
12845 	struct pagedep *pagedep;
12846 	struct inoref *inoref;
12847 	struct ufsmount *ump;
12848 	struct worklist *wk;
12849 	struct diradd *dap;
12850 	struct mount *mp;
12851 	struct vnode *pvp;
12852 	struct inode *ip;
12853 	struct buf *bp;
12854 	struct fs *fs;
12855 	struct thread *td = curthread;
12856 	int error, flushparent, pagedep_new_block;
12857 	ino_t parentino;
12858 	ufs_lbn_t lbn;
12859 
12860 	ip = VTOI(vp);
12861 	mp = vp->v_mount;
12862 	ump = VFSTOUFS(mp);
12863 	fs = ump->um_fs;
12864 	if (MOUNTEDSOFTDEP(mp) == 0)
12865 		return (0);
12866 	ACQUIRE_LOCK(ump);
12867 restart:
12868 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12869 		FREE_LOCK(ump);
12870 		return (0);
12871 	}
12872 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12873 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12874 		    == DEPCOMPLETE) {
12875 			jwait(&inoref->if_list, MNT_WAIT);
12876 			goto restart;
12877 		}
12878 	}
12879 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12880 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12881 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12882 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12883 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12884 		panic("softdep_fsync: pending ops %p", inodedep);
12885 	for (error = 0, flushparent = 0; ; ) {
12886 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12887 			break;
12888 		if (wk->wk_type != D_DIRADD)
12889 			panic("softdep_fsync: Unexpected type %s",
12890 			    TYPENAME(wk->wk_type));
12891 		dap = WK_DIRADD(wk);
12892 		/*
12893 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12894 		 * dependency or is contained in a newly allocated block.
12895 		 */
12896 		if (dap->da_state & DIRCHG)
12897 			pagedep = dap->da_previous->dm_pagedep;
12898 		else
12899 			pagedep = dap->da_pagedep;
12900 		parentino = pagedep->pd_ino;
12901 		lbn = pagedep->pd_lbn;
12902 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12903 			panic("softdep_fsync: dirty");
12904 		if ((dap->da_state & MKDIR_PARENT) ||
12905 		    (pagedep->pd_state & NEWBLOCK))
12906 			flushparent = 1;
12907 		else
12908 			flushparent = 0;
12909 		/*
12910 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12911 		 * then we will not be able to release and recover the
12912 		 * vnode below, so we just have to give up on writing its
12913 		 * directory entry out. It will eventually be written, just
12914 		 * not now, but then the user was not asking to have it
12915 		 * written, so we are not breaking any promises.
12916 		 */
12917 		if (VN_IS_DOOMED(vp))
12918 			break;
12919 		/*
12920 		 * We prevent deadlock by always fetching inodes from the
12921 		 * root, moving down the directory tree. Thus, when fetching
12922 		 * our parent directory, we first try to get the lock. If
12923 		 * that fails, we must unlock ourselves before requesting
12924 		 * the lock on our parent. See the comment in ufs_lookup
12925 		 * for details on possible races.
12926 		 */
12927 		FREE_LOCK(ump);
12928 		error = get_parent_vp(vp, mp, parentino, NULL, NULL, NULL,
12929 		    &pvp);
12930 		if (error == ERELOOKUP)
12931 			error = 0;
12932 		if (error != 0)
12933 			return (error);
12934 		/*
12935 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12936 		 * that are contained in direct blocks will be resolved by
12937 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12938 		 * may require a complete sync'ing of the directory. So, we
12939 		 * try the cheap and fast ffs_update first, and if that fails,
12940 		 * then we do the slower ffs_syncvnode of the directory.
12941 		 */
12942 		if (flushparent) {
12943 			int locked;
12944 
12945 			if ((error = ffs_update(pvp, 1)) != 0) {
12946 				vput(pvp);
12947 				return (error);
12948 			}
12949 			ACQUIRE_LOCK(ump);
12950 			locked = 1;
12951 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12952 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12953 					if (wk->wk_type != D_DIRADD)
12954 						panic("softdep_fsync: Unexpected type %s",
12955 						      TYPENAME(wk->wk_type));
12956 					dap = WK_DIRADD(wk);
12957 					if (dap->da_state & DIRCHG)
12958 						pagedep = dap->da_previous->dm_pagedep;
12959 					else
12960 						pagedep = dap->da_pagedep;
12961 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12962 					FREE_LOCK(ump);
12963 					locked = 0;
12964 					if (pagedep_new_block && (error =
12965 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12966 						vput(pvp);
12967 						return (error);
12968 					}
12969 				}
12970 			}
12971 			if (locked)
12972 				FREE_LOCK(ump);
12973 		}
12974 		/*
12975 		 * Flush directory page containing the inode's name.
12976 		 */
12977 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12978 		    &bp);
12979 		if (error == 0)
12980 			error = bwrite(bp);
12981 		else
12982 			brelse(bp);
12983 		vput(pvp);
12984 		if (!ffs_fsfail_cleanup(ump, error))
12985 			return (error);
12986 		ACQUIRE_LOCK(ump);
12987 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12988 			break;
12989 	}
12990 	FREE_LOCK(ump);
12991 	return (0);
12992 }
12993 
12994 /*
12995  * Flush all the dirty bitmaps associated with the block device
12996  * before flushing the rest of the dirty blocks so as to reduce
12997  * the number of dependencies that will have to be rolled back.
12998  *
12999  * XXX Unused?
13000  */
13001 void
13002 softdep_fsync_mountdev(vp)
13003 	struct vnode *vp;
13004 {
13005 	struct buf *bp, *nbp;
13006 	struct worklist *wk;
13007 	struct bufobj *bo;
13008 
13009 	if (!vn_isdisk(vp))
13010 		panic("softdep_fsync_mountdev: vnode not a disk");
13011 	bo = &vp->v_bufobj;
13012 restart:
13013 	BO_LOCK(bo);
13014 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
13015 		/*
13016 		 * If it is already scheduled, skip to the next buffer.
13017 		 */
13018 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
13019 			continue;
13020 
13021 		if ((bp->b_flags & B_DELWRI) == 0)
13022 			panic("softdep_fsync_mountdev: not dirty");
13023 		/*
13024 		 * We are only interested in bitmaps with outstanding
13025 		 * dependencies.
13026 		 */
13027 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
13028 		    wk->wk_type != D_BMSAFEMAP ||
13029 		    (bp->b_vflags & BV_BKGRDINPROG)) {
13030 			BUF_UNLOCK(bp);
13031 			continue;
13032 		}
13033 		BO_UNLOCK(bo);
13034 		bremfree(bp);
13035 		(void) bawrite(bp);
13036 		goto restart;
13037 	}
13038 	drain_output(vp);
13039 	BO_UNLOCK(bo);
13040 }
13041 
13042 /*
13043  * Sync all cylinder groups that were dirty at the time this function is
13044  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
13045  * is used to flush freedep activity that may be holding up writes to a
13046  * indirect block.
13047  */
13048 static int
13049 sync_cgs(mp, waitfor)
13050 	struct mount *mp;
13051 	int waitfor;
13052 {
13053 	struct bmsafemap *bmsafemap;
13054 	struct bmsafemap *sentinel;
13055 	struct ufsmount *ump;
13056 	struct buf *bp;
13057 	int error;
13058 
13059 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
13060 	sentinel->sm_cg = -1;
13061 	ump = VFSTOUFS(mp);
13062 	error = 0;
13063 	ACQUIRE_LOCK(ump);
13064 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
13065 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
13066 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
13067 		/* Skip sentinels and cgs with no work to release. */
13068 		if (bmsafemap->sm_cg == -1 ||
13069 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
13070 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
13071 			LIST_REMOVE(sentinel, sm_next);
13072 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
13073 			continue;
13074 		}
13075 		/*
13076 		 * If we don't get the lock and we're waiting try again, if
13077 		 * not move on to the next buf and try to sync it.
13078 		 */
13079 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
13080 		if (bp == NULL && waitfor == MNT_WAIT)
13081 			continue;
13082 		LIST_REMOVE(sentinel, sm_next);
13083 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
13084 		if (bp == NULL)
13085 			continue;
13086 		FREE_LOCK(ump);
13087 		if (waitfor == MNT_NOWAIT)
13088 			bawrite(bp);
13089 		else
13090 			error = bwrite(bp);
13091 		ACQUIRE_LOCK(ump);
13092 		if (error)
13093 			break;
13094 	}
13095 	LIST_REMOVE(sentinel, sm_next);
13096 	FREE_LOCK(ump);
13097 	free(sentinel, M_BMSAFEMAP);
13098 	return (error);
13099 }
13100 
13101 /*
13102  * This routine is called when we are trying to synchronously flush a
13103  * file. This routine must eliminate any filesystem metadata dependencies
13104  * so that the syncing routine can succeed.
13105  */
13106 int
13107 softdep_sync_metadata(struct vnode *vp)
13108 {
13109 	struct inode *ip;
13110 	int error;
13111 
13112 	ip = VTOI(vp);
13113 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13114 	    ("softdep_sync_metadata called on non-softdep filesystem"));
13115 	/*
13116 	 * Ensure that any direct block dependencies have been cleared,
13117 	 * truncations are started, and inode references are journaled.
13118 	 */
13119 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
13120 	/*
13121 	 * Write all journal records to prevent rollbacks on devvp.
13122 	 */
13123 	if (vp->v_type == VCHR)
13124 		softdep_flushjournal(vp->v_mount);
13125 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
13126 	/*
13127 	 * Ensure that all truncates are written so we won't find deps on
13128 	 * indirect blocks.
13129 	 */
13130 	process_truncates(vp);
13131 	FREE_LOCK(VFSTOUFS(vp->v_mount));
13132 
13133 	return (error);
13134 }
13135 
13136 /*
13137  * This routine is called when we are attempting to sync a buf with
13138  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
13139  * other IO it can but returns EBUSY if the buffer is not yet able to
13140  * be written.  Dependencies which will not cause rollbacks will always
13141  * return 0.
13142  */
13143 int
13144 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
13145 {
13146 	struct indirdep *indirdep;
13147 	struct pagedep *pagedep;
13148 	struct allocindir *aip;
13149 	struct newblk *newblk;
13150 	struct ufsmount *ump;
13151 	struct buf *nbp;
13152 	struct worklist *wk;
13153 	int i, error;
13154 
13155 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13156 	    ("softdep_sync_buf called on non-softdep filesystem"));
13157 	/*
13158 	 * For VCHR we just don't want to force flush any dependencies that
13159 	 * will cause rollbacks.
13160 	 */
13161 	if (vp->v_type == VCHR) {
13162 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
13163 			return (EBUSY);
13164 		return (0);
13165 	}
13166 	ump = VFSTOUFS(vp->v_mount);
13167 	ACQUIRE_LOCK(ump);
13168 	/*
13169 	 * As we hold the buffer locked, none of its dependencies
13170 	 * will disappear.
13171 	 */
13172 	error = 0;
13173 top:
13174 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13175 		switch (wk->wk_type) {
13176 		case D_ALLOCDIRECT:
13177 		case D_ALLOCINDIR:
13178 			newblk = WK_NEWBLK(wk);
13179 			if (newblk->nb_jnewblk != NULL) {
13180 				if (waitfor == MNT_NOWAIT) {
13181 					error = EBUSY;
13182 					goto out_unlock;
13183 				}
13184 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
13185 				goto top;
13186 			}
13187 			if (newblk->nb_state & DEPCOMPLETE ||
13188 			    waitfor == MNT_NOWAIT)
13189 				continue;
13190 			nbp = newblk->nb_bmsafemap->sm_buf;
13191 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13192 			if (nbp == NULL)
13193 				goto top;
13194 			FREE_LOCK(ump);
13195 			if ((error = bwrite(nbp)) != 0)
13196 				goto out;
13197 			ACQUIRE_LOCK(ump);
13198 			continue;
13199 
13200 		case D_INDIRDEP:
13201 			indirdep = WK_INDIRDEP(wk);
13202 			if (waitfor == MNT_NOWAIT) {
13203 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
13204 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
13205 					error = EBUSY;
13206 					goto out_unlock;
13207 				}
13208 			}
13209 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
13210 				panic("softdep_sync_buf: truncation pending.");
13211 		restart:
13212 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13213 				newblk = (struct newblk *)aip;
13214 				if (newblk->nb_jnewblk != NULL) {
13215 					jwait(&newblk->nb_jnewblk->jn_list,
13216 					    waitfor);
13217 					goto restart;
13218 				}
13219 				if (newblk->nb_state & DEPCOMPLETE)
13220 					continue;
13221 				nbp = newblk->nb_bmsafemap->sm_buf;
13222 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13223 				if (nbp == NULL)
13224 					goto restart;
13225 				FREE_LOCK(ump);
13226 				if ((error = bwrite(nbp)) != 0)
13227 					goto out;
13228 				ACQUIRE_LOCK(ump);
13229 				goto restart;
13230 			}
13231 			continue;
13232 
13233 		case D_PAGEDEP:
13234 			/*
13235 			 * Only flush directory entries in synchronous passes.
13236 			 */
13237 			if (waitfor != MNT_WAIT) {
13238 				error = EBUSY;
13239 				goto out_unlock;
13240 			}
13241 			/*
13242 			 * While syncing snapshots, we must allow recursive
13243 			 * lookups.
13244 			 */
13245 			BUF_AREC(bp);
13246 			/*
13247 			 * We are trying to sync a directory that may
13248 			 * have dependencies on both its own metadata
13249 			 * and/or dependencies on the inodes of any
13250 			 * recently allocated files. We walk its diradd
13251 			 * lists pushing out the associated inode.
13252 			 */
13253 			pagedep = WK_PAGEDEP(wk);
13254 			for (i = 0; i < DAHASHSZ; i++) {
13255 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
13256 					continue;
13257 				error = flush_pagedep_deps(vp, wk->wk_mp,
13258 				    &pagedep->pd_diraddhd[i], bp);
13259 				if (error != 0) {
13260 					if (error != ERELOOKUP)
13261 						BUF_NOREC(bp);
13262 					goto out_unlock;
13263 				}
13264 			}
13265 			BUF_NOREC(bp);
13266 			continue;
13267 
13268 		case D_FREEWORK:
13269 		case D_FREEDEP:
13270 		case D_JSEGDEP:
13271 		case D_JNEWBLK:
13272 			continue;
13273 
13274 		default:
13275 			panic("softdep_sync_buf: Unknown type %s",
13276 			    TYPENAME(wk->wk_type));
13277 			/* NOTREACHED */
13278 		}
13279 	}
13280 out_unlock:
13281 	FREE_LOCK(ump);
13282 out:
13283 	return (error);
13284 }
13285 
13286 /*
13287  * Flush the dependencies associated with an inodedep.
13288  */
13289 static int
13290 flush_inodedep_deps(vp, mp, ino)
13291 	struct vnode *vp;
13292 	struct mount *mp;
13293 	ino_t ino;
13294 {
13295 	struct inodedep *inodedep;
13296 	struct inoref *inoref;
13297 	struct ufsmount *ump;
13298 	int error, waitfor;
13299 
13300 	/*
13301 	 * This work is done in two passes. The first pass grabs most
13302 	 * of the buffers and begins asynchronously writing them. The
13303 	 * only way to wait for these asynchronous writes is to sleep
13304 	 * on the filesystem vnode which may stay busy for a long time
13305 	 * if the filesystem is active. So, instead, we make a second
13306 	 * pass over the dependencies blocking on each write. In the
13307 	 * usual case we will be blocking against a write that we
13308 	 * initiated, so when it is done the dependency will have been
13309 	 * resolved. Thus the second pass is expected to end quickly.
13310 	 * We give a brief window at the top of the loop to allow
13311 	 * any pending I/O to complete.
13312 	 */
13313 	ump = VFSTOUFS(mp);
13314 	LOCK_OWNED(ump);
13315 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
13316 		if (error)
13317 			return (error);
13318 		FREE_LOCK(ump);
13319 		ACQUIRE_LOCK(ump);
13320 restart:
13321 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13322 			return (0);
13323 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13324 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13325 			    == DEPCOMPLETE) {
13326 				jwait(&inoref->if_list, MNT_WAIT);
13327 				goto restart;
13328 			}
13329 		}
13330 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
13331 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
13332 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
13333 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
13334 			continue;
13335 		/*
13336 		 * If pass2, we are done, otherwise do pass 2.
13337 		 */
13338 		if (waitfor == MNT_WAIT)
13339 			break;
13340 		waitfor = MNT_WAIT;
13341 	}
13342 	/*
13343 	 * Try freeing inodedep in case all dependencies have been removed.
13344 	 */
13345 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
13346 		(void) free_inodedep(inodedep);
13347 	return (0);
13348 }
13349 
13350 /*
13351  * Flush an inode dependency list.
13352  */
13353 static int
13354 flush_deplist(listhead, waitfor, errorp)
13355 	struct allocdirectlst *listhead;
13356 	int waitfor;
13357 	int *errorp;
13358 {
13359 	struct allocdirect *adp;
13360 	struct newblk *newblk;
13361 	struct ufsmount *ump;
13362 	struct buf *bp;
13363 
13364 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
13365 		return (0);
13366 	ump = VFSTOUFS(adp->ad_list.wk_mp);
13367 	LOCK_OWNED(ump);
13368 	TAILQ_FOREACH(adp, listhead, ad_next) {
13369 		newblk = (struct newblk *)adp;
13370 		if (newblk->nb_jnewblk != NULL) {
13371 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13372 			return (1);
13373 		}
13374 		if (newblk->nb_state & DEPCOMPLETE)
13375 			continue;
13376 		bp = newblk->nb_bmsafemap->sm_buf;
13377 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13378 		if (bp == NULL) {
13379 			if (waitfor == MNT_NOWAIT)
13380 				continue;
13381 			return (1);
13382 		}
13383 		FREE_LOCK(ump);
13384 		if (waitfor == MNT_NOWAIT)
13385 			bawrite(bp);
13386 		else
13387 			*errorp = bwrite(bp);
13388 		ACQUIRE_LOCK(ump);
13389 		return (1);
13390 	}
13391 	return (0);
13392 }
13393 
13394 /*
13395  * Flush dependencies associated with an allocdirect block.
13396  */
13397 static int
13398 flush_newblk_dep(vp, mp, lbn)
13399 	struct vnode *vp;
13400 	struct mount *mp;
13401 	ufs_lbn_t lbn;
13402 {
13403 	struct newblk *newblk;
13404 	struct ufsmount *ump;
13405 	struct bufobj *bo;
13406 	struct inode *ip;
13407 	struct buf *bp;
13408 	ufs2_daddr_t blkno;
13409 	int error;
13410 
13411 	error = 0;
13412 	bo = &vp->v_bufobj;
13413 	ip = VTOI(vp);
13414 	blkno = DIP(ip, i_db[lbn]);
13415 	if (blkno == 0)
13416 		panic("flush_newblk_dep: Missing block");
13417 	ump = VFSTOUFS(mp);
13418 	ACQUIRE_LOCK(ump);
13419 	/*
13420 	 * Loop until all dependencies related to this block are satisfied.
13421 	 * We must be careful to restart after each sleep in case a write
13422 	 * completes some part of this process for us.
13423 	 */
13424 	for (;;) {
13425 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13426 			FREE_LOCK(ump);
13427 			break;
13428 		}
13429 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13430 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13431 		/*
13432 		 * Flush the journal.
13433 		 */
13434 		if (newblk->nb_jnewblk != NULL) {
13435 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13436 			continue;
13437 		}
13438 		/*
13439 		 * Write the bitmap dependency.
13440 		 */
13441 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13442 			bp = newblk->nb_bmsafemap->sm_buf;
13443 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13444 			if (bp == NULL)
13445 				continue;
13446 			FREE_LOCK(ump);
13447 			error = bwrite(bp);
13448 			if (error)
13449 				break;
13450 			ACQUIRE_LOCK(ump);
13451 			continue;
13452 		}
13453 		/*
13454 		 * Write the buffer.
13455 		 */
13456 		FREE_LOCK(ump);
13457 		BO_LOCK(bo);
13458 		bp = gbincore(bo, lbn);
13459 		if (bp != NULL) {
13460 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13461 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13462 			if (error == ENOLCK) {
13463 				ACQUIRE_LOCK(ump);
13464 				error = 0;
13465 				continue; /* Slept, retry */
13466 			}
13467 			if (error != 0)
13468 				break;	/* Failed */
13469 			if (bp->b_flags & B_DELWRI) {
13470 				bremfree(bp);
13471 				error = bwrite(bp);
13472 				if (error)
13473 					break;
13474 			} else
13475 				BUF_UNLOCK(bp);
13476 		} else
13477 			BO_UNLOCK(bo);
13478 		/*
13479 		 * We have to wait for the direct pointers to
13480 		 * point at the newdirblk before the dependency
13481 		 * will go away.
13482 		 */
13483 		error = ffs_update(vp, 1);
13484 		if (error)
13485 			break;
13486 		ACQUIRE_LOCK(ump);
13487 	}
13488 	return (error);
13489 }
13490 
13491 /*
13492  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13493  */
13494 static int
13495 flush_pagedep_deps(pvp, mp, diraddhdp, locked_bp)
13496 	struct vnode *pvp;
13497 	struct mount *mp;
13498 	struct diraddhd *diraddhdp;
13499 	struct buf *locked_bp;
13500 {
13501 	struct inodedep *inodedep;
13502 	struct inoref *inoref;
13503 	struct ufsmount *ump;
13504 	struct diradd *dap;
13505 	struct vnode *vp;
13506 	int error = 0;
13507 	struct buf *bp;
13508 	ino_t inum;
13509 	struct diraddhd unfinished;
13510 
13511 	LIST_INIT(&unfinished);
13512 	ump = VFSTOUFS(mp);
13513 	LOCK_OWNED(ump);
13514 restart:
13515 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13516 		/*
13517 		 * Flush ourselves if this directory entry
13518 		 * has a MKDIR_PARENT dependency.
13519 		 */
13520 		if (dap->da_state & MKDIR_PARENT) {
13521 			FREE_LOCK(ump);
13522 			if ((error = ffs_update(pvp, 1)) != 0)
13523 				break;
13524 			ACQUIRE_LOCK(ump);
13525 			/*
13526 			 * If that cleared dependencies, go on to next.
13527 			 */
13528 			if (dap != LIST_FIRST(diraddhdp))
13529 				continue;
13530 			/*
13531 			 * All MKDIR_PARENT dependencies and all the
13532 			 * NEWBLOCK pagedeps that are contained in direct
13533 			 * blocks were resolved by doing above ffs_update.
13534 			 * Pagedeps contained in indirect blocks may
13535 			 * require a complete sync'ing of the directory.
13536 			 * We are in the midst of doing a complete sync,
13537 			 * so if they are not resolved in this pass we
13538 			 * defer them for now as they will be sync'ed by
13539 			 * our caller shortly.
13540 			 */
13541 			LIST_REMOVE(dap, da_pdlist);
13542 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13543 			continue;
13544 		}
13545 		/*
13546 		 * A newly allocated directory must have its "." and
13547 		 * ".." entries written out before its name can be
13548 		 * committed in its parent.
13549 		 */
13550 		inum = dap->da_newinum;
13551 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13552 			panic("flush_pagedep_deps: lost inode1");
13553 		/*
13554 		 * Wait for any pending journal adds to complete so we don't
13555 		 * cause rollbacks while syncing.
13556 		 */
13557 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13558 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13559 			    == DEPCOMPLETE) {
13560 				jwait(&inoref->if_list, MNT_WAIT);
13561 				goto restart;
13562 			}
13563 		}
13564 		if (dap->da_state & MKDIR_BODY) {
13565 			FREE_LOCK(ump);
13566 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13567 			    diraddhdp, &unfinished, &vp);
13568 			if (error != 0)
13569 				break;
13570 			error = flush_newblk_dep(vp, mp, 0);
13571 			/*
13572 			 * If we still have the dependency we might need to
13573 			 * update the vnode to sync the new link count to
13574 			 * disk.
13575 			 */
13576 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13577 				error = ffs_update(vp, 1);
13578 			vput(vp);
13579 			if (error != 0)
13580 				break;
13581 			ACQUIRE_LOCK(ump);
13582 			/*
13583 			 * If that cleared dependencies, go on to next.
13584 			 */
13585 			if (dap != LIST_FIRST(diraddhdp))
13586 				continue;
13587 			if (dap->da_state & MKDIR_BODY) {
13588 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13589 				    &inodedep);
13590 				panic("flush_pagedep_deps: MKDIR_BODY "
13591 				    "inodedep %p dap %p vp %p",
13592 				    inodedep, dap, vp);
13593 			}
13594 		}
13595 		/*
13596 		 * Flush the inode on which the directory entry depends.
13597 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13598 		 * the only remaining dependency is that the updated inode
13599 		 * count must get pushed to disk. The inode has already
13600 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13601 		 * the time of the reference count change. So we need only
13602 		 * locate that buffer, ensure that there will be no rollback
13603 		 * caused by a bitmap dependency, then write the inode buffer.
13604 		 */
13605 retry:
13606 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13607 			panic("flush_pagedep_deps: lost inode");
13608 		/*
13609 		 * If the inode still has bitmap dependencies,
13610 		 * push them to disk.
13611 		 */
13612 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13613 			bp = inodedep->id_bmsafemap->sm_buf;
13614 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13615 			if (bp == NULL)
13616 				goto retry;
13617 			FREE_LOCK(ump);
13618 			if ((error = bwrite(bp)) != 0)
13619 				break;
13620 			ACQUIRE_LOCK(ump);
13621 			if (dap != LIST_FIRST(diraddhdp))
13622 				continue;
13623 		}
13624 		/*
13625 		 * If the inode is still sitting in a buffer waiting
13626 		 * to be written or waiting for the link count to be
13627 		 * adjusted update it here to flush it to disk.
13628 		 */
13629 		if (dap == LIST_FIRST(diraddhdp)) {
13630 			FREE_LOCK(ump);
13631 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13632 			    diraddhdp, &unfinished, &vp);
13633 			if (error != 0)
13634 				break;
13635 			error = ffs_update(vp, 1);
13636 			vput(vp);
13637 			if (error)
13638 				break;
13639 			ACQUIRE_LOCK(ump);
13640 		}
13641 		/*
13642 		 * If we have failed to get rid of all the dependencies
13643 		 * then something is seriously wrong.
13644 		 */
13645 		if (dap == LIST_FIRST(diraddhdp)) {
13646 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13647 			panic("flush_pagedep_deps: failed to flush "
13648 			    "inodedep %p ino %ju dap %p",
13649 			    inodedep, (uintmax_t)inum, dap);
13650 		}
13651 	}
13652 	if (error)
13653 		ACQUIRE_LOCK(ump);
13654 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13655 		LIST_REMOVE(dap, da_pdlist);
13656 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13657 	}
13658 	return (error);
13659 }
13660 
13661 /*
13662  * A large burst of file addition or deletion activity can drive the
13663  * memory load excessively high. First attempt to slow things down
13664  * using the techniques below. If that fails, this routine requests
13665  * the offending operations to fall back to running synchronously
13666  * until the memory load returns to a reasonable level.
13667  */
13668 int
13669 softdep_slowdown(vp)
13670 	struct vnode *vp;
13671 {
13672 	struct ufsmount *ump;
13673 	int jlow;
13674 	int max_softdeps_hard;
13675 
13676 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13677 	    ("softdep_slowdown called on non-softdep filesystem"));
13678 	ump = VFSTOUFS(vp->v_mount);
13679 	ACQUIRE_LOCK(ump);
13680 	jlow = 0;
13681 	/*
13682 	 * Check for journal space if needed.
13683 	 */
13684 	if (DOINGSUJ(vp)) {
13685 		if (journal_space(ump, 0) == 0)
13686 			jlow = 1;
13687 	}
13688 	/*
13689 	 * If the system is under its limits and our filesystem is
13690 	 * not responsible for more than our share of the usage and
13691 	 * we are not low on journal space, then no need to slow down.
13692 	 */
13693 	max_softdeps_hard = max_softdeps * 11 / 10;
13694 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13695 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13696 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13697 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13698 	    ump->softdep_curdeps[D_DIRREM] <
13699 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13700 	    ump->softdep_curdeps[D_INODEDEP] <
13701 	    max_softdeps_hard / stat_flush_threads &&
13702 	    ump->softdep_curdeps[D_INDIRDEP] <
13703 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13704 	    ump->softdep_curdeps[D_FREEBLKS] <
13705 	    max_softdeps_hard / stat_flush_threads) {
13706 		FREE_LOCK(ump);
13707   		return (0);
13708 	}
13709 	/*
13710 	 * If the journal is low or our filesystem is over its limit
13711 	 * then speedup the cleanup.
13712 	 */
13713 	if (ump->softdep_curdeps[D_INDIRDEP] <
13714 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13715 		softdep_speedup(ump);
13716 	stat_sync_limit_hit += 1;
13717 	FREE_LOCK(ump);
13718 	/*
13719 	 * We only slow down the rate at which new dependencies are
13720 	 * generated if we are not using journaling. With journaling,
13721 	 * the cleanup should always be sufficient to keep things
13722 	 * under control.
13723 	 */
13724 	if (DOINGSUJ(vp))
13725 		return (0);
13726 	return (1);
13727 }
13728 
13729 /*
13730  * Called by the allocation routines when they are about to fail
13731  * in the hope that we can free up the requested resource (inodes
13732  * or disk space).
13733  *
13734  * First check to see if the work list has anything on it. If it has,
13735  * clean up entries until we successfully free the requested resource.
13736  * Because this process holds inodes locked, we cannot handle any remove
13737  * requests that might block on a locked inode as that could lead to
13738  * deadlock. If the worklist yields none of the requested resource,
13739  * start syncing out vnodes to free up the needed space.
13740  */
13741 int
13742 softdep_request_cleanup(fs, vp, cred, resource)
13743 	struct fs *fs;
13744 	struct vnode *vp;
13745 	struct ucred *cred;
13746 	int resource;
13747 {
13748 	struct ufsmount *ump;
13749 	struct mount *mp;
13750 	long starttime;
13751 	ufs2_daddr_t needed;
13752 	int error, failed_vnode;
13753 
13754 	/*
13755 	 * If we are being called because of a process doing a
13756 	 * copy-on-write, then it is not safe to process any
13757 	 * worklist items as we will recurse into the copyonwrite
13758 	 * routine.  This will result in an incoherent snapshot.
13759 	 * If the vnode that we hold is a snapshot, we must avoid
13760 	 * handling other resources that could cause deadlock.
13761 	 */
13762 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13763 		return (0);
13764 
13765 	if (resource == FLUSH_BLOCKS_WAIT)
13766 		stat_cleanup_blkrequests += 1;
13767 	else
13768 		stat_cleanup_inorequests += 1;
13769 
13770 	mp = vp->v_mount;
13771 	ump = VFSTOUFS(mp);
13772 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13773 	UFS_UNLOCK(ump);
13774 	error = ffs_update(vp, 1);
13775 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13776 		UFS_LOCK(ump);
13777 		return (0);
13778 	}
13779 	/*
13780 	 * If we are in need of resources, start by cleaning up
13781 	 * any block removals associated with our inode.
13782 	 */
13783 	ACQUIRE_LOCK(ump);
13784 	process_removes(vp);
13785 	process_truncates(vp);
13786 	FREE_LOCK(ump);
13787 	/*
13788 	 * Now clean up at least as many resources as we will need.
13789 	 *
13790 	 * When requested to clean up inodes, the number that are needed
13791 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13792 	 * plus a bit of slop (2) in case some more writers show up while
13793 	 * we are cleaning.
13794 	 *
13795 	 * When requested to free up space, the amount of space that
13796 	 * we need is enough blocks to allocate a full-sized segment
13797 	 * (fs_contigsumsize). The number of such segments that will
13798 	 * be needed is set by the number of simultaneous writers
13799 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13800 	 * writers show up while we are cleaning.
13801 	 *
13802 	 * Additionally, if we are unpriviledged and allocating space,
13803 	 * we need to ensure that we clean up enough blocks to get the
13804 	 * needed number of blocks over the threshold of the minimum
13805 	 * number of blocks required to be kept free by the filesystem
13806 	 * (fs_minfree).
13807 	 */
13808 	if (resource == FLUSH_INODES_WAIT) {
13809 		needed = vfs_mount_fetch_counter(vp->v_mount,
13810 		    MNT_COUNT_WRITEOPCOUNT) + 2;
13811 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13812 		needed = (vfs_mount_fetch_counter(vp->v_mount,
13813 		    MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13814 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13815 			needed += fragstoblks(fs,
13816 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13817 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13818 	} else {
13819 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13820 		    resource);
13821 		UFS_LOCK(ump);
13822 		return (0);
13823 	}
13824 	starttime = time_second;
13825 retry:
13826 	if (resource == FLUSH_BLOCKS_WAIT &&
13827 	    fs->fs_cstotal.cs_nbfree <= needed)
13828 		softdep_send_speedup(ump, needed * fs->fs_bsize,
13829 		    BIO_SPEEDUP_TRIM);
13830 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13831 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13832 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13833 	    fs->fs_cstotal.cs_nifree <= needed)) {
13834 		ACQUIRE_LOCK(ump);
13835 		if (ump->softdep_on_worklist > 0 &&
13836 		    process_worklist_item(UFSTOVFS(ump),
13837 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13838 			stat_worklist_push += 1;
13839 		FREE_LOCK(ump);
13840 	}
13841 	/*
13842 	 * If we still need resources and there are no more worklist
13843 	 * entries to process to obtain them, we have to start flushing
13844 	 * the dirty vnodes to force the release of additional requests
13845 	 * to the worklist that we can then process to reap addition
13846 	 * resources. We walk the vnodes associated with the mount point
13847 	 * until we get the needed worklist requests that we can reap.
13848 	 *
13849 	 * If there are several threads all needing to clean the same
13850 	 * mount point, only one is allowed to walk the mount list.
13851 	 * When several threads all try to walk the same mount list,
13852 	 * they end up competing with each other and often end up in
13853 	 * livelock. This approach ensures that forward progress is
13854 	 * made at the cost of occational ENOSPC errors being returned
13855 	 * that might otherwise have been avoided.
13856 	 */
13857 	error = 1;
13858 	if ((resource == FLUSH_BLOCKS_WAIT &&
13859 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13860 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13861 	     fs->fs_cstotal.cs_nifree <= needed)) {
13862 		ACQUIRE_LOCK(ump);
13863 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13864 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13865 			FREE_LOCK(ump);
13866 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13867 			ACQUIRE_LOCK(ump);
13868 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13869 			FREE_LOCK(ump);
13870 			if (ump->softdep_on_worklist > 0) {
13871 				stat_cleanup_retries += 1;
13872 				if (!failed_vnode)
13873 					goto retry;
13874 			}
13875 		} else {
13876 			FREE_LOCK(ump);
13877 			error = 0;
13878 		}
13879 		stat_cleanup_failures += 1;
13880 	}
13881 	if (time_second - starttime > stat_cleanup_high_delay)
13882 		stat_cleanup_high_delay = time_second - starttime;
13883 	UFS_LOCK(ump);
13884 	return (error);
13885 }
13886 
13887 /*
13888  * Scan the vnodes for the specified mount point flushing out any
13889  * vnodes that can be locked without waiting. Finally, try to flush
13890  * the device associated with the mount point if it can be locked
13891  * without waiting.
13892  *
13893  * We return 0 if we were able to lock every vnode in our scan.
13894  * If we had to skip one or more vnodes, we return 1.
13895  */
13896 static int
13897 softdep_request_cleanup_flush(mp, ump)
13898 	struct mount *mp;
13899 	struct ufsmount *ump;
13900 {
13901 	struct thread *td;
13902 	struct vnode *lvp, *mvp;
13903 	int failed_vnode;
13904 
13905 	failed_vnode = 0;
13906 	td = curthread;
13907 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13908 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13909 			VI_UNLOCK(lvp);
13910 			continue;
13911 		}
13912 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT) != 0) {
13913 			failed_vnode = 1;
13914 			continue;
13915 		}
13916 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13917 			vput(lvp);
13918 			continue;
13919 		}
13920 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13921 		vput(lvp);
13922 	}
13923 	lvp = ump->um_devvp;
13924 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13925 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13926 		VOP_UNLOCK(lvp);
13927 	}
13928 	return (failed_vnode);
13929 }
13930 
13931 static bool
13932 softdep_excess_items(struct ufsmount *ump, int item)
13933 {
13934 
13935 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13936 	return (dep_current[item] > max_softdeps &&
13937 	    ump->softdep_curdeps[item] > max_softdeps /
13938 	    stat_flush_threads);
13939 }
13940 
13941 static void
13942 schedule_cleanup(struct mount *mp)
13943 {
13944 	struct ufsmount *ump;
13945 	struct thread *td;
13946 
13947 	ump = VFSTOUFS(mp);
13948 	LOCK_OWNED(ump);
13949 	FREE_LOCK(ump);
13950 	td = curthread;
13951 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13952 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13953 		/*
13954 		 * No ast is delivered to kernel threads, so nobody
13955 		 * would deref the mp.  Some kernel threads
13956 		 * explicitely check for AST, e.g. NFS daemon does
13957 		 * this in the serving loop.
13958 		 */
13959 		return;
13960 	}
13961 	if (td->td_su != NULL)
13962 		vfs_rel(td->td_su);
13963 	vfs_ref(mp);
13964 	td->td_su = mp;
13965 	thread_lock(td);
13966 	td->td_flags |= TDF_ASTPENDING;
13967 	thread_unlock(td);
13968 }
13969 
13970 static void
13971 softdep_ast_cleanup_proc(struct thread *td)
13972 {
13973 	struct mount *mp;
13974 	struct ufsmount *ump;
13975 	int error;
13976 	bool req;
13977 
13978 	while ((mp = td->td_su) != NULL) {
13979 		td->td_su = NULL;
13980 		error = vfs_busy(mp, MBF_NOWAIT);
13981 		vfs_rel(mp);
13982 		if (error != 0)
13983 			return;
13984 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13985 			ump = VFSTOUFS(mp);
13986 			for (;;) {
13987 				req = false;
13988 				ACQUIRE_LOCK(ump);
13989 				if (softdep_excess_items(ump, D_INODEDEP)) {
13990 					req = true;
13991 					request_cleanup(mp, FLUSH_INODES);
13992 				}
13993 				if (softdep_excess_items(ump, D_DIRREM)) {
13994 					req = true;
13995 					request_cleanup(mp, FLUSH_BLOCKS);
13996 				}
13997 				FREE_LOCK(ump);
13998 				if (softdep_excess_items(ump, D_NEWBLK) ||
13999 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
14000 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
14001 					error = vn_start_write(NULL, &mp,
14002 					    V_WAIT);
14003 					if (error == 0) {
14004 						req = true;
14005 						VFS_SYNC(mp, MNT_WAIT);
14006 						vn_finished_write(mp);
14007 					}
14008 				}
14009 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
14010 					break;
14011 			}
14012 		}
14013 		vfs_unbusy(mp);
14014 	}
14015 	if ((mp = td->td_su) != NULL) {
14016 		td->td_su = NULL;
14017 		vfs_rel(mp);
14018 	}
14019 }
14020 
14021 /*
14022  * If memory utilization has gotten too high, deliberately slow things
14023  * down and speed up the I/O processing.
14024  */
14025 static int
14026 request_cleanup(mp, resource)
14027 	struct mount *mp;
14028 	int resource;
14029 {
14030 	struct thread *td = curthread;
14031 	struct ufsmount *ump;
14032 
14033 	ump = VFSTOUFS(mp);
14034 	LOCK_OWNED(ump);
14035 	/*
14036 	 * We never hold up the filesystem syncer or buf daemon.
14037 	 */
14038 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
14039 		return (0);
14040 	/*
14041 	 * First check to see if the work list has gotten backlogged.
14042 	 * If it has, co-opt this process to help clean up two entries.
14043 	 * Because this process may hold inodes locked, we cannot
14044 	 * handle any remove requests that might block on a locked
14045 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
14046 	 * to avoid recursively processing the worklist.
14047 	 */
14048 	if (ump->softdep_on_worklist > max_softdeps / 10) {
14049 		td->td_pflags |= TDP_SOFTDEP;
14050 		process_worklist_item(mp, 2, LK_NOWAIT);
14051 		td->td_pflags &= ~TDP_SOFTDEP;
14052 		stat_worklist_push += 2;
14053 		return(1);
14054 	}
14055 	/*
14056 	 * Next, we attempt to speed up the syncer process. If that
14057 	 * is successful, then we allow the process to continue.
14058 	 */
14059 	if (softdep_speedup(ump) &&
14060 	    resource != FLUSH_BLOCKS_WAIT &&
14061 	    resource != FLUSH_INODES_WAIT)
14062 		return(0);
14063 	/*
14064 	 * If we are resource constrained on inode dependencies, try
14065 	 * flushing some dirty inodes. Otherwise, we are constrained
14066 	 * by file deletions, so try accelerating flushes of directories
14067 	 * with removal dependencies. We would like to do the cleanup
14068 	 * here, but we probably hold an inode locked at this point and
14069 	 * that might deadlock against one that we try to clean. So,
14070 	 * the best that we can do is request the syncer daemon to do
14071 	 * the cleanup for us.
14072 	 */
14073 	switch (resource) {
14074 	case FLUSH_INODES:
14075 	case FLUSH_INODES_WAIT:
14076 		ACQUIRE_GBLLOCK(&lk);
14077 		stat_ino_limit_push += 1;
14078 		req_clear_inodedeps += 1;
14079 		FREE_GBLLOCK(&lk);
14080 		stat_countp = &stat_ino_limit_hit;
14081 		break;
14082 
14083 	case FLUSH_BLOCKS:
14084 	case FLUSH_BLOCKS_WAIT:
14085 		ACQUIRE_GBLLOCK(&lk);
14086 		stat_blk_limit_push += 1;
14087 		req_clear_remove += 1;
14088 		FREE_GBLLOCK(&lk);
14089 		stat_countp = &stat_blk_limit_hit;
14090 		break;
14091 
14092 	default:
14093 		panic("request_cleanup: unknown type");
14094 	}
14095 	/*
14096 	 * Hopefully the syncer daemon will catch up and awaken us.
14097 	 * We wait at most tickdelay before proceeding in any case.
14098 	 */
14099 	ACQUIRE_GBLLOCK(&lk);
14100 	FREE_LOCK(ump);
14101 	proc_waiting += 1;
14102 	if (callout_pending(&softdep_callout) == FALSE)
14103 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
14104 		    pause_timer, 0);
14105 
14106 	if ((td->td_pflags & TDP_KTHREAD) == 0)
14107 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
14108 	proc_waiting -= 1;
14109 	FREE_GBLLOCK(&lk);
14110 	ACQUIRE_LOCK(ump);
14111 	return (1);
14112 }
14113 
14114 /*
14115  * Awaken processes pausing in request_cleanup and clear proc_waiting
14116  * to indicate that there is no longer a timer running. Pause_timer
14117  * will be called with the global softdep mutex (&lk) locked.
14118  */
14119 static void
14120 pause_timer(arg)
14121 	void *arg;
14122 {
14123 
14124 	GBLLOCK_OWNED(&lk);
14125 	/*
14126 	 * The callout_ API has acquired mtx and will hold it around this
14127 	 * function call.
14128 	 */
14129 	*stat_countp += proc_waiting;
14130 	wakeup(&proc_waiting);
14131 }
14132 
14133 /*
14134  * If requested, try removing inode or removal dependencies.
14135  */
14136 static void
14137 check_clear_deps(mp)
14138 	struct mount *mp;
14139 {
14140 	struct ufsmount *ump;
14141 	bool suj_susp;
14142 
14143 	/*
14144 	 * Tell the lower layers that any TRIM or WRITE transactions that have
14145 	 * been delayed for performance reasons should proceed to help alleviate
14146 	 * the shortage faster. The race between checking req_* and the softdep
14147 	 * mutex (lk) is fine since this is an advisory operation that at most
14148 	 * causes deferred work to be done sooner.
14149 	 */
14150 	ump = VFSTOUFS(mp);
14151 	suj_susp = MOUNTEDSUJ(mp) && ump->softdep_jblocks->jb_suspended;
14152 	if (req_clear_remove || req_clear_inodedeps || suj_susp) {
14153 		FREE_LOCK(ump);
14154 		softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
14155 		ACQUIRE_LOCK(ump);
14156 	}
14157 
14158 	/*
14159 	 * If we are suspended, it may be because of our using
14160 	 * too many inodedeps, so help clear them out.
14161 	 */
14162 	if (suj_susp)
14163 		clear_inodedeps(mp);
14164 
14165 	/*
14166 	 * General requests for cleanup of backed up dependencies
14167 	 */
14168 	ACQUIRE_GBLLOCK(&lk);
14169 	if (req_clear_inodedeps) {
14170 		req_clear_inodedeps -= 1;
14171 		FREE_GBLLOCK(&lk);
14172 		clear_inodedeps(mp);
14173 		ACQUIRE_GBLLOCK(&lk);
14174 		wakeup(&proc_waiting);
14175 	}
14176 	if (req_clear_remove) {
14177 		req_clear_remove -= 1;
14178 		FREE_GBLLOCK(&lk);
14179 		clear_remove(mp);
14180 		ACQUIRE_GBLLOCK(&lk);
14181 		wakeup(&proc_waiting);
14182 	}
14183 	FREE_GBLLOCK(&lk);
14184 }
14185 
14186 /*
14187  * Flush out a directory with at least one removal dependency in an effort to
14188  * reduce the number of dirrem, freefile, and freeblks dependency structures.
14189  */
14190 static void
14191 clear_remove(mp)
14192 	struct mount *mp;
14193 {
14194 	struct pagedep_hashhead *pagedephd;
14195 	struct pagedep *pagedep;
14196 	struct ufsmount *ump;
14197 	struct vnode *vp;
14198 	struct bufobj *bo;
14199 	int error, cnt;
14200 	ino_t ino;
14201 
14202 	ump = VFSTOUFS(mp);
14203 	LOCK_OWNED(ump);
14204 
14205 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
14206 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
14207 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
14208 			ump->pagedep_nextclean = 0;
14209 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
14210 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
14211 				continue;
14212 			ino = pagedep->pd_ino;
14213 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14214 				continue;
14215 			FREE_LOCK(ump);
14216 
14217 			/*
14218 			 * Let unmount clear deps
14219 			 */
14220 			error = vfs_busy(mp, MBF_NOWAIT);
14221 			if (error != 0)
14222 				goto finish_write;
14223 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14224 			     FFSV_FORCEINSMQ);
14225 			vfs_unbusy(mp);
14226 			if (error != 0) {
14227 				softdep_error("clear_remove: vget", error);
14228 				goto finish_write;
14229 			}
14230 			MPASS(VTOI(vp)->i_mode != 0);
14231 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14232 				softdep_error("clear_remove: fsync", error);
14233 			bo = &vp->v_bufobj;
14234 			BO_LOCK(bo);
14235 			drain_output(vp);
14236 			BO_UNLOCK(bo);
14237 			vput(vp);
14238 		finish_write:
14239 			vn_finished_write(mp);
14240 			ACQUIRE_LOCK(ump);
14241 			return;
14242 		}
14243 	}
14244 }
14245 
14246 /*
14247  * Clear out a block of dirty inodes in an effort to reduce
14248  * the number of inodedep dependency structures.
14249  */
14250 static void
14251 clear_inodedeps(mp)
14252 	struct mount *mp;
14253 {
14254 	struct inodedep_hashhead *inodedephd;
14255 	struct inodedep *inodedep;
14256 	struct ufsmount *ump;
14257 	struct vnode *vp;
14258 	struct fs *fs;
14259 	int error, cnt;
14260 	ino_t firstino, lastino, ino;
14261 
14262 	ump = VFSTOUFS(mp);
14263 	fs = ump->um_fs;
14264 	LOCK_OWNED(ump);
14265 	/*
14266 	 * Pick a random inode dependency to be cleared.
14267 	 * We will then gather up all the inodes in its block
14268 	 * that have dependencies and flush them out.
14269 	 */
14270 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
14271 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
14272 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
14273 			ump->inodedep_nextclean = 0;
14274 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
14275 			break;
14276 	}
14277 	if (inodedep == NULL)
14278 		return;
14279 	/*
14280 	 * Find the last inode in the block with dependencies.
14281 	 */
14282 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
14283 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
14284 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
14285 			break;
14286 	/*
14287 	 * Asynchronously push all but the last inode with dependencies.
14288 	 * Synchronously push the last inode with dependencies to ensure
14289 	 * that the inode block gets written to free up the inodedeps.
14290 	 */
14291 	for (ino = firstino; ino <= lastino; ino++) {
14292 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
14293 			continue;
14294 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14295 			continue;
14296 		FREE_LOCK(ump);
14297 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
14298 		if (error != 0) {
14299 			vn_finished_write(mp);
14300 			ACQUIRE_LOCK(ump);
14301 			return;
14302 		}
14303 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14304 		    FFSV_FORCEINSMQ)) != 0) {
14305 			softdep_error("clear_inodedeps: vget", error);
14306 			vfs_unbusy(mp);
14307 			vn_finished_write(mp);
14308 			ACQUIRE_LOCK(ump);
14309 			return;
14310 		}
14311 		vfs_unbusy(mp);
14312 		if (VTOI(vp)->i_mode == 0) {
14313 			vgone(vp);
14314 		} else if (ino == lastino) {
14315 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
14316 				softdep_error("clear_inodedeps: fsync1", error);
14317 		} else {
14318 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14319 				softdep_error("clear_inodedeps: fsync2", error);
14320 			BO_LOCK(&vp->v_bufobj);
14321 			drain_output(vp);
14322 			BO_UNLOCK(&vp->v_bufobj);
14323 		}
14324 		vput(vp);
14325 		vn_finished_write(mp);
14326 		ACQUIRE_LOCK(ump);
14327 	}
14328 }
14329 
14330 void
14331 softdep_buf_append(bp, wkhd)
14332 	struct buf *bp;
14333 	struct workhead *wkhd;
14334 {
14335 	struct worklist *wk;
14336 	struct ufsmount *ump;
14337 
14338 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14339 		return;
14340 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14341 	    ("softdep_buf_append called on non-softdep filesystem"));
14342 	ump = VFSTOUFS(wk->wk_mp);
14343 	ACQUIRE_LOCK(ump);
14344 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
14345 		WORKLIST_REMOVE(wk);
14346 		WORKLIST_INSERT(&bp->b_dep, wk);
14347 	}
14348 	FREE_LOCK(ump);
14349 
14350 }
14351 
14352 void
14353 softdep_inode_append(ip, cred, wkhd)
14354 	struct inode *ip;
14355 	struct ucred *cred;
14356 	struct workhead *wkhd;
14357 {
14358 	struct buf *bp;
14359 	struct fs *fs;
14360 	struct ufsmount *ump;
14361 	int error;
14362 
14363 	ump = ITOUMP(ip);
14364 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
14365 	    ("softdep_inode_append called on non-softdep filesystem"));
14366 	fs = ump->um_fs;
14367 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14368 	    (int)fs->fs_bsize, cred, &bp);
14369 	if (error) {
14370 		bqrelse(bp);
14371 		softdep_freework(wkhd);
14372 		return;
14373 	}
14374 	softdep_buf_append(bp, wkhd);
14375 	bqrelse(bp);
14376 }
14377 
14378 void
14379 softdep_freework(wkhd)
14380 	struct workhead *wkhd;
14381 {
14382 	struct worklist *wk;
14383 	struct ufsmount *ump;
14384 
14385 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14386 		return;
14387 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14388 	    ("softdep_freework called on non-softdep filesystem"));
14389 	ump = VFSTOUFS(wk->wk_mp);
14390 	ACQUIRE_LOCK(ump);
14391 	handle_jwork(wkhd);
14392 	FREE_LOCK(ump);
14393 }
14394 
14395 static struct ufsmount *
14396 softdep_bp_to_mp(bp)
14397 	struct buf *bp;
14398 {
14399 	struct mount *mp;
14400 	struct vnode *vp;
14401 
14402 	if (LIST_EMPTY(&bp->b_dep))
14403 		return (NULL);
14404 	vp = bp->b_vp;
14405 	KASSERT(vp != NULL,
14406 	    ("%s, buffer with dependencies lacks vnode", __func__));
14407 
14408 	/*
14409 	 * The ump mount point is stable after we get a correct
14410 	 * pointer, since bp is locked and this prevents unmount from
14411 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
14412 	 * head wk_mp, because we do not yet own SU ump lock and
14413 	 * workitem might be freed while dereferenced.
14414 	 */
14415 retry:
14416 	switch (vp->v_type) {
14417 	case VCHR:
14418 		VI_LOCK(vp);
14419 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14420 		VI_UNLOCK(vp);
14421 		if (mp == NULL)
14422 			goto retry;
14423 		break;
14424 	case VREG:
14425 	case VDIR:
14426 	case VLNK:
14427 	case VFIFO:
14428 	case VSOCK:
14429 		mp = vp->v_mount;
14430 		break;
14431 	case VBLK:
14432 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14433 		/* FALLTHROUGH */
14434 	case VNON:
14435 	case VBAD:
14436 	case VMARKER:
14437 		mp = NULL;
14438 		break;
14439 	default:
14440 		vn_printf(vp, "unknown vnode type");
14441 		mp = NULL;
14442 		break;
14443 	}
14444 	return (VFSTOUFS(mp));
14445 }
14446 
14447 /*
14448  * Function to determine if the buffer has outstanding dependencies
14449  * that will cause a roll-back if the buffer is written. If wantcount
14450  * is set, return number of dependencies, otherwise just yes or no.
14451  */
14452 static int
14453 softdep_count_dependencies(bp, wantcount)
14454 	struct buf *bp;
14455 	int wantcount;
14456 {
14457 	struct worklist *wk;
14458 	struct ufsmount *ump;
14459 	struct bmsafemap *bmsafemap;
14460 	struct freework *freework;
14461 	struct inodedep *inodedep;
14462 	struct indirdep *indirdep;
14463 	struct freeblks *freeblks;
14464 	struct allocindir *aip;
14465 	struct pagedep *pagedep;
14466 	struct dirrem *dirrem;
14467 	struct newblk *newblk;
14468 	struct mkdir *mkdir;
14469 	struct diradd *dap;
14470 	int i, retval;
14471 
14472 	ump = softdep_bp_to_mp(bp);
14473 	if (ump == NULL)
14474 		return (0);
14475 	retval = 0;
14476 	ACQUIRE_LOCK(ump);
14477 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14478 		switch (wk->wk_type) {
14479 		case D_INODEDEP:
14480 			inodedep = WK_INODEDEP(wk);
14481 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14482 				/* bitmap allocation dependency */
14483 				retval += 1;
14484 				if (!wantcount)
14485 					goto out;
14486 			}
14487 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14488 				/* direct block pointer dependency */
14489 				retval += 1;
14490 				if (!wantcount)
14491 					goto out;
14492 			}
14493 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14494 				/* direct block pointer dependency */
14495 				retval += 1;
14496 				if (!wantcount)
14497 					goto out;
14498 			}
14499 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14500 				/* Add reference dependency. */
14501 				retval += 1;
14502 				if (!wantcount)
14503 					goto out;
14504 			}
14505 			continue;
14506 
14507 		case D_INDIRDEP:
14508 			indirdep = WK_INDIRDEP(wk);
14509 
14510 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14511 				/* indirect truncation dependency */
14512 				retval += 1;
14513 				if (!wantcount)
14514 					goto out;
14515 			}
14516 
14517 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14518 				/* indirect block pointer dependency */
14519 				retval += 1;
14520 				if (!wantcount)
14521 					goto out;
14522 			}
14523 			continue;
14524 
14525 		case D_PAGEDEP:
14526 			pagedep = WK_PAGEDEP(wk);
14527 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14528 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14529 					/* Journal remove ref dependency. */
14530 					retval += 1;
14531 					if (!wantcount)
14532 						goto out;
14533 				}
14534 			}
14535 			for (i = 0; i < DAHASHSZ; i++) {
14536 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14537 					/* directory entry dependency */
14538 					retval += 1;
14539 					if (!wantcount)
14540 						goto out;
14541 				}
14542 			}
14543 			continue;
14544 
14545 		case D_BMSAFEMAP:
14546 			bmsafemap = WK_BMSAFEMAP(wk);
14547 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14548 				/* Add reference dependency. */
14549 				retval += 1;
14550 				if (!wantcount)
14551 					goto out;
14552 			}
14553 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14554 				/* Allocate block dependency. */
14555 				retval += 1;
14556 				if (!wantcount)
14557 					goto out;
14558 			}
14559 			continue;
14560 
14561 		case D_FREEBLKS:
14562 			freeblks = WK_FREEBLKS(wk);
14563 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14564 				/* Freeblk journal dependency. */
14565 				retval += 1;
14566 				if (!wantcount)
14567 					goto out;
14568 			}
14569 			continue;
14570 
14571 		case D_ALLOCDIRECT:
14572 		case D_ALLOCINDIR:
14573 			newblk = WK_NEWBLK(wk);
14574 			if (newblk->nb_jnewblk) {
14575 				/* Journal allocate dependency. */
14576 				retval += 1;
14577 				if (!wantcount)
14578 					goto out;
14579 			}
14580 			continue;
14581 
14582 		case D_MKDIR:
14583 			mkdir = WK_MKDIR(wk);
14584 			if (mkdir->md_jaddref) {
14585 				/* Journal reference dependency. */
14586 				retval += 1;
14587 				if (!wantcount)
14588 					goto out;
14589 			}
14590 			continue;
14591 
14592 		case D_FREEWORK:
14593 		case D_FREEDEP:
14594 		case D_JSEGDEP:
14595 		case D_JSEG:
14596 		case D_SBDEP:
14597 			/* never a dependency on these blocks */
14598 			continue;
14599 
14600 		default:
14601 			panic("softdep_count_dependencies: Unexpected type %s",
14602 			    TYPENAME(wk->wk_type));
14603 			/* NOTREACHED */
14604 		}
14605 	}
14606 out:
14607 	FREE_LOCK(ump);
14608 	return (retval);
14609 }
14610 
14611 /*
14612  * Acquire exclusive access to a buffer.
14613  * Must be called with a locked mtx parameter.
14614  * Return acquired buffer or NULL on failure.
14615  */
14616 static struct buf *
14617 getdirtybuf(bp, lock, waitfor)
14618 	struct buf *bp;
14619 	struct rwlock *lock;
14620 	int waitfor;
14621 {
14622 	int error;
14623 
14624 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14625 		if (waitfor != MNT_WAIT)
14626 			return (NULL);
14627 		error = BUF_LOCK(bp,
14628 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14629 		/*
14630 		 * Even if we successfully acquire bp here, we have dropped
14631 		 * lock, which may violates our guarantee.
14632 		 */
14633 		if (error == 0)
14634 			BUF_UNLOCK(bp);
14635 		else if (error != ENOLCK)
14636 			panic("getdirtybuf: inconsistent lock: %d", error);
14637 		rw_wlock(lock);
14638 		return (NULL);
14639 	}
14640 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14641 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14642 			rw_wunlock(lock);
14643 			BO_LOCK(bp->b_bufobj);
14644 			BUF_UNLOCK(bp);
14645 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14646 				bp->b_vflags |= BV_BKGRDWAIT;
14647 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14648 				       PRIBIO | PDROP, "getbuf", 0);
14649 			} else
14650 				BO_UNLOCK(bp->b_bufobj);
14651 			rw_wlock(lock);
14652 			return (NULL);
14653 		}
14654 		BUF_UNLOCK(bp);
14655 		if (waitfor != MNT_WAIT)
14656 			return (NULL);
14657 #ifdef DEBUG_VFS_LOCKS
14658 		if (bp->b_vp->v_type != VCHR)
14659 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14660 #endif
14661 		bp->b_vflags |= BV_BKGRDWAIT;
14662 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14663 		return (NULL);
14664 	}
14665 	if ((bp->b_flags & B_DELWRI) == 0) {
14666 		BUF_UNLOCK(bp);
14667 		return (NULL);
14668 	}
14669 	bremfree(bp);
14670 	return (bp);
14671 }
14672 
14673 /*
14674  * Check if it is safe to suspend the file system now.  On entry,
14675  * the vnode interlock for devvp should be held.  Return 0 with
14676  * the mount interlock held if the file system can be suspended now,
14677  * otherwise return EAGAIN with the mount interlock held.
14678  */
14679 int
14680 softdep_check_suspend(struct mount *mp,
14681 		      struct vnode *devvp,
14682 		      int softdep_depcnt,
14683 		      int softdep_accdepcnt,
14684 		      int secondary_writes,
14685 		      int secondary_accwrites)
14686 {
14687 	struct bufobj *bo;
14688 	struct ufsmount *ump;
14689 	struct inodedep *inodedep;
14690 	int error, unlinked;
14691 
14692 	bo = &devvp->v_bufobj;
14693 	ASSERT_BO_WLOCKED(bo);
14694 
14695 	/*
14696 	 * If we are not running with soft updates, then we need only
14697 	 * deal with secondary writes as we try to suspend.
14698 	 */
14699 	if (MOUNTEDSOFTDEP(mp) == 0) {
14700 		MNT_ILOCK(mp);
14701 		while (mp->mnt_secondary_writes != 0) {
14702 			BO_UNLOCK(bo);
14703 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14704 			    (PUSER - 1) | PDROP, "secwr", 0);
14705 			BO_LOCK(bo);
14706 			MNT_ILOCK(mp);
14707 		}
14708 
14709 		/*
14710 		 * Reasons for needing more work before suspend:
14711 		 * - Dirty buffers on devvp.
14712 		 * - Secondary writes occurred after start of vnode sync loop
14713 		 */
14714 		error = 0;
14715 		if (bo->bo_numoutput > 0 ||
14716 		    bo->bo_dirty.bv_cnt > 0 ||
14717 		    secondary_writes != 0 ||
14718 		    mp->mnt_secondary_writes != 0 ||
14719 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14720 			error = EAGAIN;
14721 		BO_UNLOCK(bo);
14722 		return (error);
14723 	}
14724 
14725 	/*
14726 	 * If we are running with soft updates, then we need to coordinate
14727 	 * with them as we try to suspend.
14728 	 */
14729 	ump = VFSTOUFS(mp);
14730 	for (;;) {
14731 		if (!TRY_ACQUIRE_LOCK(ump)) {
14732 			BO_UNLOCK(bo);
14733 			ACQUIRE_LOCK(ump);
14734 			FREE_LOCK(ump);
14735 			BO_LOCK(bo);
14736 			continue;
14737 		}
14738 		MNT_ILOCK(mp);
14739 		if (mp->mnt_secondary_writes != 0) {
14740 			FREE_LOCK(ump);
14741 			BO_UNLOCK(bo);
14742 			msleep(&mp->mnt_secondary_writes,
14743 			       MNT_MTX(mp),
14744 			       (PUSER - 1) | PDROP, "secwr", 0);
14745 			BO_LOCK(bo);
14746 			continue;
14747 		}
14748 		break;
14749 	}
14750 
14751 	unlinked = 0;
14752 	if (MOUNTEDSUJ(mp)) {
14753 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14754 		    inodedep != NULL;
14755 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14756 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14757 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14758 			    UNLINKONLIST) ||
14759 			    !check_inodedep_free(inodedep))
14760 				continue;
14761 			unlinked++;
14762 		}
14763 	}
14764 
14765 	/*
14766 	 * Reasons for needing more work before suspend:
14767 	 * - Dirty buffers on devvp.
14768 	 * - Softdep activity occurred after start of vnode sync loop
14769 	 * - Secondary writes occurred after start of vnode sync loop
14770 	 */
14771 	error = 0;
14772 	if (bo->bo_numoutput > 0 ||
14773 	    bo->bo_dirty.bv_cnt > 0 ||
14774 	    softdep_depcnt != unlinked ||
14775 	    ump->softdep_deps != unlinked ||
14776 	    softdep_accdepcnt != ump->softdep_accdeps ||
14777 	    secondary_writes != 0 ||
14778 	    mp->mnt_secondary_writes != 0 ||
14779 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14780 		error = EAGAIN;
14781 	FREE_LOCK(ump);
14782 	BO_UNLOCK(bo);
14783 	return (error);
14784 }
14785 
14786 /*
14787  * Get the number of dependency structures for the file system, both
14788  * the current number and the total number allocated.  These will
14789  * later be used to detect that softdep processing has occurred.
14790  */
14791 void
14792 softdep_get_depcounts(struct mount *mp,
14793 		      int *softdep_depsp,
14794 		      int *softdep_accdepsp)
14795 {
14796 	struct ufsmount *ump;
14797 
14798 	if (MOUNTEDSOFTDEP(mp) == 0) {
14799 		*softdep_depsp = 0;
14800 		*softdep_accdepsp = 0;
14801 		return;
14802 	}
14803 	ump = VFSTOUFS(mp);
14804 	ACQUIRE_LOCK(ump);
14805 	*softdep_depsp = ump->softdep_deps;
14806 	*softdep_accdepsp = ump->softdep_accdeps;
14807 	FREE_LOCK(ump);
14808 }
14809 
14810 /*
14811  * Wait for pending output on a vnode to complete.
14812  */
14813 static void
14814 drain_output(vp)
14815 	struct vnode *vp;
14816 {
14817 
14818 	ASSERT_VOP_LOCKED(vp, "drain_output");
14819 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14820 }
14821 
14822 /*
14823  * Called whenever a buffer that is being invalidated or reallocated
14824  * contains dependencies. This should only happen if an I/O error has
14825  * occurred. The routine is called with the buffer locked.
14826  */
14827 static void
14828 softdep_deallocate_dependencies(bp)
14829 	struct buf *bp;
14830 {
14831 
14832 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14833 		panic("softdep_deallocate_dependencies: dangling deps");
14834 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14835 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14836 	else
14837 		printf("softdep_deallocate_dependencies: "
14838 		    "got error %d while accessing filesystem\n", bp->b_error);
14839 	if (bp->b_error != ENXIO)
14840 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14841 }
14842 
14843 /*
14844  * Function to handle asynchronous write errors in the filesystem.
14845  */
14846 static void
14847 softdep_error(func, error)
14848 	char *func;
14849 	int error;
14850 {
14851 
14852 	/* XXX should do something better! */
14853 	printf("%s: got error %d while accessing filesystem\n", func, error);
14854 }
14855 
14856 #ifdef DDB
14857 
14858 /* exported to ffs_vfsops.c */
14859 extern void db_print_ffs(struct ufsmount *ump);
14860 void
14861 db_print_ffs(struct ufsmount *ump)
14862 {
14863 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14864 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14865 	db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14866 	    ump->um_fs, ump->softdep_on_worklist,
14867 	    ump->softdep_deps, ump->softdep_req);
14868 }
14869 
14870 static void
14871 worklist_print(struct worklist *wk, int verbose)
14872 {
14873 
14874 	if (!verbose) {
14875 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14876 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14877 		return;
14878 	}
14879 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14880 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14881 	    LIST_NEXT(wk, wk_list));
14882 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14883 }
14884 
14885 static void
14886 inodedep_print(struct inodedep *inodedep, int verbose)
14887 {
14888 
14889 	worklist_print(&inodedep->id_list, 0);
14890 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14891 	    inodedep->id_fs,
14892 	    (intmax_t)inodedep->id_ino,
14893 	    (intmax_t)fsbtodb(inodedep->id_fs,
14894 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14895 	    (intmax_t)inodedep->id_nlinkdelta,
14896 	    (intmax_t)inodedep->id_savednlink);
14897 
14898 	if (verbose == 0)
14899 		return;
14900 
14901 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14902 	    inodedep->id_bmsafemap,
14903 	    inodedep->id_mkdiradd,
14904 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14905 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14906 	    LIST_FIRST(&inodedep->id_dirremhd),
14907 	    LIST_FIRST(&inodedep->id_pendinghd),
14908 	    LIST_FIRST(&inodedep->id_bufwait));
14909 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14910 	    LIST_FIRST(&inodedep->id_inowait),
14911 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14912 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14913 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14914 	    TAILQ_FIRST(&inodedep->id_extupdt),
14915 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14916 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14917 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14918 	    inodedep->id_savedino1,
14919 	    (intmax_t)inodedep->id_savedsize,
14920 	    (intmax_t)inodedep->id_savedextsize);
14921 }
14922 
14923 static void
14924 newblk_print(struct newblk *nbp)
14925 {
14926 
14927 	worklist_print(&nbp->nb_list, 0);
14928 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14929 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14930 	    &nbp->nb_jnewblk,
14931 	    &nbp->nb_bmsafemap,
14932 	    &nbp->nb_freefrag);
14933 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14934 	    LIST_FIRST(&nbp->nb_indirdeps),
14935 	    LIST_FIRST(&nbp->nb_newdirblk),
14936 	    LIST_FIRST(&nbp->nb_jwork));
14937 }
14938 
14939 static void
14940 allocdirect_print(struct allocdirect *adp)
14941 {
14942 
14943 	newblk_print(&adp->ad_block);
14944 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14945 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14946 	db_printf("    offset %d, inodedep %p\n",
14947 	    adp->ad_offset, adp->ad_inodedep);
14948 }
14949 
14950 static void
14951 allocindir_print(struct allocindir *aip)
14952 {
14953 
14954 	newblk_print(&aip->ai_block);
14955 	db_printf("    oldblkno %jd, lbn %jd\n",
14956 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14957 	db_printf("    offset %d, indirdep %p\n",
14958 	    aip->ai_offset, aip->ai_indirdep);
14959 }
14960 
14961 static void
14962 mkdir_print(struct mkdir *mkdir)
14963 {
14964 
14965 	worklist_print(&mkdir->md_list, 0);
14966 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14967 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14968 }
14969 
14970 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14971 {
14972 
14973 	if (have_addr == 0) {
14974 		db_printf("inodedep address required\n");
14975 		return;
14976 	}
14977 	inodedep_print((struct inodedep*)addr, 1);
14978 }
14979 
14980 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14981 {
14982 	struct inodedep_hashhead *inodedephd;
14983 	struct inodedep *inodedep;
14984 	struct ufsmount *ump;
14985 	int cnt;
14986 
14987 	if (have_addr == 0) {
14988 		db_printf("ufsmount address required\n");
14989 		return;
14990 	}
14991 	ump = (struct ufsmount *)addr;
14992 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14993 		inodedephd = &ump->inodedep_hashtbl[cnt];
14994 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14995 			inodedep_print(inodedep, 0);
14996 		}
14997 	}
14998 }
14999 
15000 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
15001 {
15002 
15003 	if (have_addr == 0) {
15004 		db_printf("worklist address required\n");
15005 		return;
15006 	}
15007 	worklist_print((struct worklist *)addr, 1);
15008 }
15009 
15010 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
15011 {
15012 	struct worklist *wk;
15013 	struct workhead *wkhd;
15014 
15015 	if (have_addr == 0) {
15016 		db_printf("worklist address required "
15017 		    "(for example value in bp->b_dep)\n");
15018 		return;
15019 	}
15020 	/*
15021 	 * We often do not have the address of the worklist head but
15022 	 * instead a pointer to its first entry (e.g., we have the
15023 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
15024 	 * pointer of bp->b_dep will point at the head of the list, so
15025 	 * we cheat and use that instead. If we are in the middle of
15026 	 * a list we will still get the same result, so nothing
15027 	 * unexpected will result.
15028 	 */
15029 	wk = (struct worklist *)addr;
15030 	if (wk == NULL)
15031 		return;
15032 	wkhd = (struct workhead *)wk->wk_list.le_prev;
15033 	LIST_FOREACH(wk, wkhd, wk_list) {
15034 		switch(wk->wk_type) {
15035 		case D_INODEDEP:
15036 			inodedep_print(WK_INODEDEP(wk), 0);
15037 			continue;
15038 		case D_ALLOCDIRECT:
15039 			allocdirect_print(WK_ALLOCDIRECT(wk));
15040 			continue;
15041 		case D_ALLOCINDIR:
15042 			allocindir_print(WK_ALLOCINDIR(wk));
15043 			continue;
15044 		case D_MKDIR:
15045 			mkdir_print(WK_MKDIR(wk));
15046 			continue;
15047 		default:
15048 			worklist_print(wk, 0);
15049 			continue;
15050 		}
15051 	}
15052 }
15053 
15054 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
15055 {
15056 	if (have_addr == 0) {
15057 		db_printf("mkdir address required\n");
15058 		return;
15059 	}
15060 	mkdir_print((struct mkdir *)addr);
15061 }
15062 
15063 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
15064 {
15065 	struct mkdirlist *mkdirlisthd;
15066 	struct mkdir *mkdir;
15067 
15068 	if (have_addr == 0) {
15069 		db_printf("mkdir listhead address required\n");
15070 		return;
15071 	}
15072 	mkdirlisthd = (struct mkdirlist *)addr;
15073 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
15074 		mkdir_print(mkdir);
15075 		if (mkdir->md_diradd != NULL) {
15076 			db_printf("    ");
15077 			worklist_print(&mkdir->md_diradd->da_list, 0);
15078 		}
15079 		if (mkdir->md_jaddref != NULL) {
15080 			db_printf("    ");
15081 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
15082 		}
15083 	}
15084 }
15085 
15086 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
15087 {
15088 	if (have_addr == 0) {
15089 		db_printf("allocdirect address required\n");
15090 		return;
15091 	}
15092 	allocdirect_print((struct allocdirect *)addr);
15093 }
15094 
15095 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
15096 {
15097 	if (have_addr == 0) {
15098 		db_printf("allocindir address required\n");
15099 		return;
15100 	}
15101 	allocindir_print((struct allocindir *)addr);
15102 }
15103 
15104 #endif /* DDB */
15105 
15106 #endif /* SOFTUPDATES */
15107