xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 53071ed1c96db7f89defc99c95b0ad1031d48f45)
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 #else
613 
614 FEATURE(softupdates, "FFS soft-updates support");
615 
616 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
617     "soft updates stats");
618 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
619     "total dependencies allocated");
620 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
621     "high use dependencies allocated");
622 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
623     "current dependencies allocated");
624 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
625     "current dependencies written");
626 
627 unsigned long dep_current[D_LAST + 1];
628 unsigned long dep_highuse[D_LAST + 1];
629 unsigned long dep_total[D_LAST + 1];
630 unsigned long dep_write[D_LAST + 1];
631 
632 #define	SOFTDEP_TYPE(type, str, long)					\
633     static MALLOC_DEFINE(M_ ## type, #str, long);			\
634     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
635 	&dep_total[D_ ## type], 0, "");					\
636     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
637 	&dep_current[D_ ## type], 0, "");				\
638     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
639 	&dep_highuse[D_ ## type], 0, "");				\
640     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
641 	&dep_write[D_ ## type], 0, "");
642 
643 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
644 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
645 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
646     "Block or frag allocated from cyl group map");
647 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
648 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
649 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
650 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
651 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
652 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
653 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
654 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
655 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
656 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
657 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
658 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
659 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
660 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
661 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
662 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
663 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
664 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
665 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
666 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
667 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
668 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
669 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
670 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
671 
672 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
673 
674 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
675 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
676 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
677 
678 #define M_SOFTDEP_FLAGS	(M_WAITOK)
679 
680 /*
681  * translate from workitem type to memory type
682  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
683  */
684 static struct malloc_type *memtype[] = {
685 	NULL,
686 	M_PAGEDEP,
687 	M_INODEDEP,
688 	M_BMSAFEMAP,
689 	M_NEWBLK,
690 	M_ALLOCDIRECT,
691 	M_INDIRDEP,
692 	M_ALLOCINDIR,
693 	M_FREEFRAG,
694 	M_FREEBLKS,
695 	M_FREEFILE,
696 	M_DIRADD,
697 	M_MKDIR,
698 	M_DIRREM,
699 	M_NEWDIRBLK,
700 	M_FREEWORK,
701 	M_FREEDEP,
702 	M_JADDREF,
703 	M_JREMREF,
704 	M_JMVREF,
705 	M_JNEWBLK,
706 	M_JFREEBLK,
707 	M_JFREEFRAG,
708 	M_JSEG,
709 	M_JSEGDEP,
710 	M_SBDEP,
711 	M_JTRUNC,
712 	M_JFSYNC,
713 	M_SENTINEL
714 };
715 
716 #define DtoM(type) (memtype[type])
717 
718 /*
719  * Names of malloc types.
720  */
721 #define TYPENAME(type)  \
722 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
723 	memtype[type]->ks_shortdesc : "???")
724 /*
725  * End system adaptation definitions.
726  */
727 
728 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
729 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
730 
731 /*
732  * Internal function prototypes.
733  */
734 static	void check_clear_deps(struct mount *);
735 static	void softdep_error(char *, int);
736 static	int softdep_process_worklist(struct mount *, int);
737 static	int softdep_waitidle(struct mount *, int);
738 static	void drain_output(struct vnode *);
739 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
740 static	int check_inodedep_free(struct inodedep *);
741 static	void clear_remove(struct mount *);
742 static	void clear_inodedeps(struct mount *);
743 static	void unlinked_inodedep(struct mount *, struct inodedep *);
744 static	void clear_unlinked_inodedep(struct inodedep *);
745 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
746 static	int flush_pagedep_deps(struct vnode *, struct mount *,
747 	    struct diraddhd *);
748 static	int free_pagedep(struct pagedep *);
749 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
750 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
751 static	int flush_deplist(struct allocdirectlst *, int, int *);
752 static	int sync_cgs(struct mount *, int);
753 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
754 static	int handle_written_sbdep(struct sbdep *, struct buf *);
755 static	void initiate_write_sbdep(struct sbdep *);
756 static	void diradd_inode_written(struct diradd *, struct inodedep *);
757 static	int handle_written_indirdep(struct indirdep *, struct buf *,
758 	    struct buf**, int);
759 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
760 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
761 	    uint8_t *);
762 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
763 static	void handle_written_jaddref(struct jaddref *);
764 static	void handle_written_jremref(struct jremref *);
765 static	void handle_written_jseg(struct jseg *, struct buf *);
766 static	void handle_written_jnewblk(struct jnewblk *);
767 static	void handle_written_jblkdep(struct jblkdep *);
768 static	void handle_written_jfreefrag(struct jfreefrag *);
769 static	void complete_jseg(struct jseg *);
770 static	void complete_jsegs(struct jseg *);
771 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
772 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
773 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
774 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
775 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
776 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
777 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
778 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
779 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
780 static	inline void inoref_write(struct inoref *, struct jseg *,
781 	    struct jrefrec *);
782 static	void handle_allocdirect_partdone(struct allocdirect *,
783 	    struct workhead *);
784 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
785 	    struct workhead *);
786 static	void indirdep_complete(struct indirdep *);
787 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
788 static	void indirblk_insert(struct freework *);
789 static	void indirblk_remove(struct freework *);
790 static	void handle_allocindir_partdone(struct allocindir *);
791 static	void initiate_write_filepage(struct pagedep *, struct buf *);
792 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
793 static	void handle_written_mkdir(struct mkdir *, int);
794 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
795 	    uint8_t *);
796 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
797 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
798 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
799 static	void handle_workitem_freefile(struct freefile *);
800 static	int handle_workitem_remove(struct dirrem *, int);
801 static	struct dirrem *newdirrem(struct buf *, struct inode *,
802 	    struct inode *, int, struct dirrem **);
803 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
804 	    struct buf *);
805 static	void cancel_indirdep(struct indirdep *, struct buf *,
806 	    struct freeblks *);
807 static	void free_indirdep(struct indirdep *);
808 static	void free_diradd(struct diradd *, struct workhead *);
809 static	void merge_diradd(struct inodedep *, struct diradd *);
810 static	void complete_diradd(struct diradd *);
811 static	struct diradd *diradd_lookup(struct pagedep *, int);
812 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
813 	    struct jremref *);
814 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
815 	    struct jremref *);
816 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
817 	    struct jremref *, struct jremref *);
818 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
819 	    struct jremref *);
820 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
821 	    struct freeblks *, int);
822 static	int setup_trunc_indir(struct freeblks *, struct inode *,
823 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
824 static	void complete_trunc_indir(struct freework *);
825 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
826 	    int);
827 static	void complete_mkdir(struct mkdir *);
828 static	void free_newdirblk(struct newdirblk *);
829 static	void free_jremref(struct jremref *);
830 static	void free_jaddref(struct jaddref *);
831 static	void free_jsegdep(struct jsegdep *);
832 static	void free_jsegs(struct jblocks *);
833 static	void rele_jseg(struct jseg *);
834 static	void free_jseg(struct jseg *, struct jblocks *);
835 static	void free_jnewblk(struct jnewblk *);
836 static	void free_jblkdep(struct jblkdep *);
837 static	void free_jfreefrag(struct jfreefrag *);
838 static	void free_freedep(struct freedep *);
839 static	void journal_jremref(struct dirrem *, struct jremref *,
840 	    struct inodedep *);
841 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
842 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
843 	    struct workhead *);
844 static	void cancel_jfreefrag(struct jfreefrag *);
845 static	inline void setup_freedirect(struct freeblks *, struct inode *,
846 	    int, int);
847 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
848 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
849 	    ufs_lbn_t, int);
850 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
851 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
852 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
853 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
854 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
855 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
856 	    int, int);
857 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
858 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
859 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
860 static	void newblk_freefrag(struct newblk*);
861 static	void free_newblk(struct newblk *);
862 static	void cancel_allocdirect(struct allocdirectlst *,
863 	    struct allocdirect *, struct freeblks *);
864 static	int check_inode_unwritten(struct inodedep *);
865 static	int free_inodedep(struct inodedep *);
866 static	void freework_freeblock(struct freework *, u_long);
867 static	void freework_enqueue(struct freework *);
868 static	int handle_workitem_freeblocks(struct freeblks *, int);
869 static	int handle_complete_freeblocks(struct freeblks *, int);
870 static	void handle_workitem_indirblk(struct freework *);
871 static	void handle_written_freework(struct freework *);
872 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
873 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
874 	    struct workhead *);
875 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
876 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
877 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
878 	    ufs2_daddr_t, ufs_lbn_t);
879 static	void handle_workitem_freefrag(struct freefrag *);
880 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
881 	    ufs_lbn_t, u_long);
882 static	void allocdirect_merge(struct allocdirectlst *,
883 	    struct allocdirect *, struct allocdirect *);
884 static	struct freefrag *allocindir_merge(struct allocindir *,
885 	    struct allocindir *);
886 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
887 	    struct bmsafemap **);
888 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
889 	    int cg, struct bmsafemap *);
890 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
891 	    struct newblk **);
892 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
893 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
894 	    struct inodedep **);
895 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
896 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
897 	    int, struct pagedep **);
898 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
899 	    struct pagedep **);
900 static	void pause_timer(void *);
901 static	int request_cleanup(struct mount *, int);
902 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
903 static	void schedule_cleanup(struct mount *);
904 static void softdep_ast_cleanup_proc(struct thread *);
905 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
906 static	int process_worklist_item(struct mount *, int, int);
907 static	void process_removes(struct vnode *);
908 static	void process_truncates(struct vnode *);
909 static	void jwork_move(struct workhead *, struct workhead *);
910 static	void jwork_insert(struct workhead *, struct jsegdep *);
911 static	void add_to_worklist(struct worklist *, int);
912 static	void wake_worklist(struct worklist *);
913 static	void wait_worklist(struct worklist *, char *);
914 static	void remove_from_worklist(struct worklist *);
915 static	void softdep_flush(void *);
916 static	void softdep_flushjournal(struct mount *);
917 static	int softdep_speedup(struct ufsmount *);
918 static	void worklist_speedup(struct mount *);
919 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
920 static	void journal_unmount(struct ufsmount *);
921 static	int journal_space(struct ufsmount *, int);
922 static	void journal_suspend(struct ufsmount *);
923 static	int journal_unsuspend(struct ufsmount *ump);
924 static	void softdep_prelink(struct vnode *, struct vnode *);
925 static	void add_to_journal(struct worklist *);
926 static	void remove_from_journal(struct worklist *);
927 static	bool softdep_excess_items(struct ufsmount *, int);
928 static	void softdep_process_journal(struct mount *, struct worklist *, int);
929 static	struct jremref *newjremref(struct dirrem *, struct inode *,
930 	    struct inode *ip, off_t, nlink_t);
931 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
932 	    uint16_t);
933 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
934 	    uint16_t);
935 static	inline struct jsegdep *inoref_jseg(struct inoref *);
936 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
937 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
938 	    ufs2_daddr_t, int);
939 static	void adjust_newfreework(struct freeblks *, int);
940 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
941 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
942 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
943 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
944 	    ufs2_daddr_t, long, ufs_lbn_t);
945 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
946 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
947 static	int jwait(struct worklist *, int);
948 static	struct inodedep *inodedep_lookup_ip(struct inode *);
949 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
950 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
951 static	void handle_jwork(struct workhead *);
952 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
953 	    struct mkdir **);
954 static	struct jblocks *jblocks_create(void);
955 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
956 static	void jblocks_free(struct jblocks *, struct mount *, int);
957 static	void jblocks_destroy(struct jblocks *);
958 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
959 
960 /*
961  * Exported softdep operations.
962  */
963 static	void softdep_disk_io_initiation(struct buf *);
964 static	void softdep_disk_write_complete(struct buf *);
965 static	void softdep_deallocate_dependencies(struct buf *);
966 static	int softdep_count_dependencies(struct buf *bp, int);
967 
968 /*
969  * Global lock over all of soft updates.
970  */
971 static struct mtx lk;
972 MTX_SYSINIT(softdep_lock, &lk, "global softdep", MTX_DEF);
973 
974 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
975 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
976 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
977 
978 /*
979  * Per-filesystem soft-updates locking.
980  */
981 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
982 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
983 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
984 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
985 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
986 				    RA_WLOCKED)
987 
988 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
989 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
990 
991 /*
992  * Worklist queue management.
993  * These routines require that the lock be held.
994  */
995 #ifndef /* NOT */ INVARIANTS
996 #define WORKLIST_INSERT(head, item) do {	\
997 	(item)->wk_state |= ONWORKLIST;		\
998 	LIST_INSERT_HEAD(head, item, wk_list);	\
999 } while (0)
1000 #define WORKLIST_REMOVE(item) do {		\
1001 	(item)->wk_state &= ~ONWORKLIST;	\
1002 	LIST_REMOVE(item, wk_list);		\
1003 } while (0)
1004 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1005 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1006 
1007 #else /* INVARIANTS */
1008 static	void worklist_insert(struct workhead *, struct worklist *, int,
1009 	const char *, int);
1010 static	void worklist_remove(struct worklist *, int, const char *, int);
1011 
1012 #define WORKLIST_INSERT(head, item) \
1013 	worklist_insert(head, item, 1, __func__, __LINE__)
1014 #define WORKLIST_INSERT_UNLOCKED(head, item)\
1015 	worklist_insert(head, item, 0, __func__, __LINE__)
1016 #define WORKLIST_REMOVE(item)\
1017 	worklist_remove(item, 1, __func__, __LINE__)
1018 #define WORKLIST_REMOVE_UNLOCKED(item)\
1019 	worklist_remove(item, 0, __func__, __LINE__)
1020 
1021 static void
1022 worklist_insert(head, item, locked, func, line)
1023 	struct workhead *head;
1024 	struct worklist *item;
1025 	int locked;
1026 	const char *func;
1027 	int line;
1028 {
1029 
1030 	if (locked)
1031 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1032 	if (item->wk_state & ONWORKLIST)
1033 		panic("worklist_insert: %p %s(0x%X) already on list, "
1034 		    "added in function %s at line %d",
1035 		    item, TYPENAME(item->wk_type), item->wk_state,
1036 		    item->wk_func, item->wk_line);
1037 	item->wk_state |= ONWORKLIST;
1038 	item->wk_func = func;
1039 	item->wk_line = line;
1040 	LIST_INSERT_HEAD(head, item, wk_list);
1041 }
1042 
1043 static void
1044 worklist_remove(item, locked, func, line)
1045 	struct worklist *item;
1046 	int locked;
1047 	const char *func;
1048 	int line;
1049 {
1050 
1051 	if (locked)
1052 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1053 	if ((item->wk_state & ONWORKLIST) == 0)
1054 		panic("worklist_remove: %p %s(0x%X) not on list, "
1055 		    "removed in function %s at line %d",
1056 		    item, TYPENAME(item->wk_type), item->wk_state,
1057 		    item->wk_func, item->wk_line);
1058 	item->wk_state &= ~ONWORKLIST;
1059 	item->wk_func = func;
1060 	item->wk_line = line;
1061 	LIST_REMOVE(item, wk_list);
1062 }
1063 #endif /* INVARIANTS */
1064 
1065 /*
1066  * Merge two jsegdeps keeping only the oldest one as newer references
1067  * can't be discarded until after older references.
1068  */
1069 static inline struct jsegdep *
1070 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1071 {
1072 	struct jsegdep *swp;
1073 
1074 	if (two == NULL)
1075 		return (one);
1076 
1077 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1078 		swp = one;
1079 		one = two;
1080 		two = swp;
1081 	}
1082 	WORKLIST_REMOVE(&two->jd_list);
1083 	free_jsegdep(two);
1084 
1085 	return (one);
1086 }
1087 
1088 /*
1089  * If two freedeps are compatible free one to reduce list size.
1090  */
1091 static inline struct freedep *
1092 freedep_merge(struct freedep *one, struct freedep *two)
1093 {
1094 	if (two == NULL)
1095 		return (one);
1096 
1097 	if (one->fd_freework == two->fd_freework) {
1098 		WORKLIST_REMOVE(&two->fd_list);
1099 		free_freedep(two);
1100 	}
1101 	return (one);
1102 }
1103 
1104 /*
1105  * Move journal work from one list to another.  Duplicate freedeps and
1106  * jsegdeps are coalesced to keep the lists as small as possible.
1107  */
1108 static void
1109 jwork_move(dst, src)
1110 	struct workhead *dst;
1111 	struct workhead *src;
1112 {
1113 	struct freedep *freedep;
1114 	struct jsegdep *jsegdep;
1115 	struct worklist *wkn;
1116 	struct worklist *wk;
1117 
1118 	KASSERT(dst != src,
1119 	    ("jwork_move: dst == src"));
1120 	freedep = NULL;
1121 	jsegdep = NULL;
1122 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1123 		if (wk->wk_type == D_JSEGDEP)
1124 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1125 		else if (wk->wk_type == D_FREEDEP)
1126 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1127 	}
1128 
1129 	while ((wk = LIST_FIRST(src)) != NULL) {
1130 		WORKLIST_REMOVE(wk);
1131 		WORKLIST_INSERT(dst, wk);
1132 		if (wk->wk_type == D_JSEGDEP) {
1133 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1134 			continue;
1135 		}
1136 		if (wk->wk_type == D_FREEDEP)
1137 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1138 	}
1139 }
1140 
1141 static void
1142 jwork_insert(dst, jsegdep)
1143 	struct workhead *dst;
1144 	struct jsegdep *jsegdep;
1145 {
1146 	struct jsegdep *jsegdepn;
1147 	struct worklist *wk;
1148 
1149 	LIST_FOREACH(wk, dst, wk_list)
1150 		if (wk->wk_type == D_JSEGDEP)
1151 			break;
1152 	if (wk == NULL) {
1153 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1154 		return;
1155 	}
1156 	jsegdepn = WK_JSEGDEP(wk);
1157 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1158 		WORKLIST_REMOVE(wk);
1159 		free_jsegdep(jsegdepn);
1160 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1161 	} else
1162 		free_jsegdep(jsegdep);
1163 }
1164 
1165 /*
1166  * Routines for tracking and managing workitems.
1167  */
1168 static	void workitem_free(struct worklist *, int);
1169 static	void workitem_alloc(struct worklist *, int, struct mount *);
1170 static	void workitem_reassign(struct worklist *, int);
1171 
1172 #define	WORKITEM_FREE(item, type) \
1173 	workitem_free((struct worklist *)(item), (type))
1174 #define	WORKITEM_REASSIGN(item, type) \
1175 	workitem_reassign((struct worklist *)(item), (type))
1176 
1177 static void
1178 workitem_free(item, type)
1179 	struct worklist *item;
1180 	int type;
1181 {
1182 	struct ufsmount *ump;
1183 
1184 #ifdef INVARIANTS
1185 	if (item->wk_state & ONWORKLIST)
1186 		panic("workitem_free: %s(0x%X) still on list, "
1187 		    "added in function %s at line %d",
1188 		    TYPENAME(item->wk_type), item->wk_state,
1189 		    item->wk_func, item->wk_line);
1190 	if (item->wk_type != type && type != D_NEWBLK)
1191 		panic("workitem_free: type mismatch %s != %s",
1192 		    TYPENAME(item->wk_type), TYPENAME(type));
1193 #endif
1194 	if (item->wk_state & IOWAITING)
1195 		wakeup(item);
1196 	ump = VFSTOUFS(item->wk_mp);
1197 	LOCK_OWNED(ump);
1198 	KASSERT(ump->softdep_deps > 0,
1199 	    ("workitem_free: %s: softdep_deps going negative",
1200 	    ump->um_fs->fs_fsmnt));
1201 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1202 		wakeup(&ump->softdep_deps);
1203 	KASSERT(dep_current[item->wk_type] > 0,
1204 	    ("workitem_free: %s: dep_current[%s] going negative",
1205 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1206 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1207 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1208 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1209 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1210 	ump->softdep_curdeps[item->wk_type] -= 1;
1211 #ifdef INVARIANTS
1212 	LIST_REMOVE(item, wk_all);
1213 #endif
1214 	free(item, DtoM(type));
1215 }
1216 
1217 static void
1218 workitem_alloc(item, type, mp)
1219 	struct worklist *item;
1220 	int type;
1221 	struct mount *mp;
1222 {
1223 	struct ufsmount *ump;
1224 
1225 	item->wk_type = type;
1226 	item->wk_mp = mp;
1227 	item->wk_state = 0;
1228 
1229 	ump = VFSTOUFS(mp);
1230 	ACQUIRE_GBLLOCK(&lk);
1231 	dep_current[type]++;
1232 	if (dep_current[type] > dep_highuse[type])
1233 		dep_highuse[type] = dep_current[type];
1234 	dep_total[type]++;
1235 	FREE_GBLLOCK(&lk);
1236 	ACQUIRE_LOCK(ump);
1237 	ump->softdep_curdeps[type] += 1;
1238 	ump->softdep_deps++;
1239 	ump->softdep_accdeps++;
1240 #ifdef INVARIANTS
1241 	LIST_INSERT_HEAD(&ump->softdep_alldeps[type], item, wk_all);
1242 #endif
1243 	FREE_LOCK(ump);
1244 }
1245 
1246 static void
1247 workitem_reassign(item, newtype)
1248 	struct worklist *item;
1249 	int newtype;
1250 {
1251 	struct ufsmount *ump;
1252 
1253 	ump = VFSTOUFS(item->wk_mp);
1254 	LOCK_OWNED(ump);
1255 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1256 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1257 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1258 	ump->softdep_curdeps[item->wk_type] -= 1;
1259 	ump->softdep_curdeps[newtype] += 1;
1260 	KASSERT(dep_current[item->wk_type] > 0,
1261 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1262 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1263 	ACQUIRE_GBLLOCK(&lk);
1264 	dep_current[newtype]++;
1265 	dep_current[item->wk_type]--;
1266 	if (dep_current[newtype] > dep_highuse[newtype])
1267 		dep_highuse[newtype] = dep_current[newtype];
1268 	dep_total[newtype]++;
1269 	FREE_GBLLOCK(&lk);
1270 	item->wk_type = newtype;
1271 }
1272 
1273 /*
1274  * Workitem queue management
1275  */
1276 static int max_softdeps;	/* maximum number of structs before slowdown */
1277 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1278 static int proc_waiting;	/* tracks whether we have a timeout posted */
1279 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1280 static struct callout softdep_callout;
1281 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1282 static int req_clear_remove;	/* syncer process flush some freeblks */
1283 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1284 
1285 /*
1286  * runtime statistics
1287  */
1288 static int stat_flush_threads;	/* number of softdep flushing threads */
1289 static int stat_worklist_push;	/* number of worklist cleanups */
1290 static int stat_blk_limit_push;	/* number of times block limit neared */
1291 static int stat_ino_limit_push;	/* number of times inode limit neared */
1292 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1293 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1294 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1295 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1296 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1297 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1298 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1299 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1300 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1301 static int stat_journal_min;	/* Times hit journal min threshold */
1302 static int stat_journal_low;	/* Times hit journal low threshold */
1303 static int stat_journal_wait;	/* Times blocked in jwait(). */
1304 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1305 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1306 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1307 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1308 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1309 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1310 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1311 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1312 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1313 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1314 
1315 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1316     &max_softdeps, 0, "");
1317 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1318     &tickdelay, 0, "");
1319 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1320     &stat_flush_threads, 0, "");
1321 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1322     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1323 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1324     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1325 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1326     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1328     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1329 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1330     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1331 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1332     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1333 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1334     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1335 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1336     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1337 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1338     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1340     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1341 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1342     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1343 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1344     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1345 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1346     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1347 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1348     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1349 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1350     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1351 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1352     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1353 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1354     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1355 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1356     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1357 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1358     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1359 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1360     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1361 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1362     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1363 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1364     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1365 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1366     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1367 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1368     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1369 
1370 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1371     &softdep_flushcache, 0, "");
1372 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1373     &stat_emptyjblocks, 0, "");
1374 
1375 SYSCTL_DECL(_vfs_ffs);
1376 
1377 /* Whether to recompute the summary at mount time */
1378 static int compute_summary_at_mount = 0;
1379 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1380 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1381 static int print_threads = 0;
1382 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1383     &print_threads, 0, "Notify flusher thread start/stop");
1384 
1385 /* List of all filesystems mounted with soft updates */
1386 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1387 
1388 /*
1389  * This function cleans the worklist for a filesystem.
1390  * Each filesystem running with soft dependencies gets its own
1391  * thread to run in this function. The thread is started up in
1392  * softdep_mount and shutdown in softdep_unmount. They show up
1393  * as part of the kernel "bufdaemon" process whose process
1394  * entry is available in bufdaemonproc.
1395  */
1396 static int searchfailed;
1397 extern struct proc *bufdaemonproc;
1398 static void
1399 softdep_flush(addr)
1400 	void *addr;
1401 {
1402 	struct mount *mp;
1403 	struct thread *td;
1404 	struct ufsmount *ump;
1405 
1406 	td = curthread;
1407 	td->td_pflags |= TDP_NORUNNINGBUF;
1408 	mp = (struct mount *)addr;
1409 	ump = VFSTOUFS(mp);
1410 	atomic_add_int(&stat_flush_threads, 1);
1411 	ACQUIRE_LOCK(ump);
1412 	ump->softdep_flags &= ~FLUSH_STARTING;
1413 	wakeup(&ump->softdep_flushtd);
1414 	FREE_LOCK(ump);
1415 	if (print_threads) {
1416 		if (stat_flush_threads == 1)
1417 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1418 			    bufdaemonproc->p_pid);
1419 		printf("Start thread %s\n", td->td_name);
1420 	}
1421 	for (;;) {
1422 		while (softdep_process_worklist(mp, 0) > 0 ||
1423 		    (MOUNTEDSUJ(mp) &&
1424 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1425 			kthread_suspend_check();
1426 		ACQUIRE_LOCK(ump);
1427 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1428 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1429 			    "sdflush", hz / 2);
1430 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1431 		/*
1432 		 * Check to see if we are done and need to exit.
1433 		 */
1434 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1435 			FREE_LOCK(ump);
1436 			continue;
1437 		}
1438 		ump->softdep_flags &= ~FLUSH_EXIT;
1439 		FREE_LOCK(ump);
1440 		wakeup(&ump->softdep_flags);
1441 		if (print_threads)
1442 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1443 		atomic_subtract_int(&stat_flush_threads, 1);
1444 		kthread_exit();
1445 		panic("kthread_exit failed\n");
1446 	}
1447 }
1448 
1449 static void
1450 worklist_speedup(mp)
1451 	struct mount *mp;
1452 {
1453 	struct ufsmount *ump;
1454 
1455 	ump = VFSTOUFS(mp);
1456 	LOCK_OWNED(ump);
1457 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1458 		ump->softdep_flags |= FLUSH_CLEANUP;
1459 	wakeup(&ump->softdep_flushtd);
1460 }
1461 
1462 static void
1463 softdep_send_speedup(struct ufsmount *ump, size_t shortage, u_int flags)
1464 {
1465 	struct buf *bp;
1466 
1467 	bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
1468 	bp->b_iocmd = BIO_SPEEDUP;
1469 	bp->b_ioflags = flags;
1470 	bp->b_bcount = shortage;
1471 	g_vfs_strategy(ump->um_bo, bp);
1472 	bufwait(bp);
1473 	free(bp, M_TRIM);
1474 }
1475 
1476 static int
1477 softdep_speedup(ump)
1478 	struct ufsmount *ump;
1479 {
1480 	struct ufsmount *altump;
1481 	struct mount_softdeps *sdp;
1482 
1483 	LOCK_OWNED(ump);
1484 	worklist_speedup(ump->um_mountp);
1485 	bd_speedup();
1486 	/*
1487 	 * If we have global shortages, then we need other
1488 	 * filesystems to help with the cleanup. Here we wakeup a
1489 	 * flusher thread for a filesystem that is over its fair
1490 	 * share of resources.
1491 	 */
1492 	if (req_clear_inodedeps || req_clear_remove) {
1493 		ACQUIRE_GBLLOCK(&lk);
1494 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1495 			if ((altump = sdp->sd_ump) == ump)
1496 				continue;
1497 			if (((req_clear_inodedeps &&
1498 			    altump->softdep_curdeps[D_INODEDEP] >
1499 			    max_softdeps / stat_flush_threads) ||
1500 			    (req_clear_remove &&
1501 			    altump->softdep_curdeps[D_DIRREM] >
1502 			    (max_softdeps / 2) / stat_flush_threads)) &&
1503 			    TRY_ACQUIRE_LOCK(altump))
1504 				break;
1505 		}
1506 		if (sdp == NULL) {
1507 			searchfailed++;
1508 			FREE_GBLLOCK(&lk);
1509 		} else {
1510 			/*
1511 			 * Move to the end of the list so we pick a
1512 			 * different one on out next try.
1513 			 */
1514 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1515 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1516 			FREE_GBLLOCK(&lk);
1517 			if ((altump->softdep_flags &
1518 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1519 				altump->softdep_flags |= FLUSH_CLEANUP;
1520 			altump->um_softdep->sd_cleanups++;
1521 			wakeup(&altump->softdep_flushtd);
1522 			FREE_LOCK(altump);
1523 		}
1524 	}
1525 	return (speedup_syncer());
1526 }
1527 
1528 /*
1529  * Add an item to the end of the work queue.
1530  * This routine requires that the lock be held.
1531  * This is the only routine that adds items to the list.
1532  * The following routine is the only one that removes items
1533  * and does so in order from first to last.
1534  */
1535 
1536 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1537 #define	WK_NODELAY	0x0002	/* Process immediately. */
1538 
1539 static void
1540 add_to_worklist(wk, flags)
1541 	struct worklist *wk;
1542 	int flags;
1543 {
1544 	struct ufsmount *ump;
1545 
1546 	ump = VFSTOUFS(wk->wk_mp);
1547 	LOCK_OWNED(ump);
1548 	if (wk->wk_state & ONWORKLIST)
1549 		panic("add_to_worklist: %s(0x%X) already on list",
1550 		    TYPENAME(wk->wk_type), wk->wk_state);
1551 	wk->wk_state |= ONWORKLIST;
1552 	if (ump->softdep_on_worklist == 0) {
1553 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1554 		ump->softdep_worklist_tail = wk;
1555 	} else if (flags & WK_HEAD) {
1556 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1557 	} else {
1558 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1559 		ump->softdep_worklist_tail = wk;
1560 	}
1561 	ump->softdep_on_worklist += 1;
1562 	if (flags & WK_NODELAY)
1563 		worklist_speedup(wk->wk_mp);
1564 }
1565 
1566 /*
1567  * Remove the item to be processed. If we are removing the last
1568  * item on the list, we need to recalculate the tail pointer.
1569  */
1570 static void
1571 remove_from_worklist(wk)
1572 	struct worklist *wk;
1573 {
1574 	struct ufsmount *ump;
1575 
1576 	ump = VFSTOUFS(wk->wk_mp);
1577 	if (ump->softdep_worklist_tail == wk)
1578 		ump->softdep_worklist_tail =
1579 		    (struct worklist *)wk->wk_list.le_prev;
1580 	WORKLIST_REMOVE(wk);
1581 	ump->softdep_on_worklist -= 1;
1582 }
1583 
1584 static void
1585 wake_worklist(wk)
1586 	struct worklist *wk;
1587 {
1588 	if (wk->wk_state & IOWAITING) {
1589 		wk->wk_state &= ~IOWAITING;
1590 		wakeup(wk);
1591 	}
1592 }
1593 
1594 static void
1595 wait_worklist(wk, wmesg)
1596 	struct worklist *wk;
1597 	char *wmesg;
1598 {
1599 	struct ufsmount *ump;
1600 
1601 	ump = VFSTOUFS(wk->wk_mp);
1602 	wk->wk_state |= IOWAITING;
1603 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1604 }
1605 
1606 /*
1607  * Process that runs once per second to handle items in the background queue.
1608  *
1609  * Note that we ensure that everything is done in the order in which they
1610  * appear in the queue. The code below depends on this property to ensure
1611  * that blocks of a file are freed before the inode itself is freed. This
1612  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1613  * until all the old ones have been purged from the dependency lists.
1614  */
1615 static int
1616 softdep_process_worklist(mp, full)
1617 	struct mount *mp;
1618 	int full;
1619 {
1620 	int cnt, matchcnt;
1621 	struct ufsmount *ump;
1622 	long starttime;
1623 
1624 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1625 	if (MOUNTEDSOFTDEP(mp) == 0)
1626 		return (0);
1627 	matchcnt = 0;
1628 	ump = VFSTOUFS(mp);
1629 	ACQUIRE_LOCK(ump);
1630 	starttime = time_second;
1631 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1632 	check_clear_deps(mp);
1633 	while (ump->softdep_on_worklist > 0) {
1634 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1635 			break;
1636 		else
1637 			matchcnt += cnt;
1638 		check_clear_deps(mp);
1639 		/*
1640 		 * We do not generally want to stop for buffer space, but if
1641 		 * we are really being a buffer hog, we will stop and wait.
1642 		 */
1643 		if (should_yield()) {
1644 			FREE_LOCK(ump);
1645 			kern_yield(PRI_USER);
1646 			bwillwrite();
1647 			ACQUIRE_LOCK(ump);
1648 		}
1649 		/*
1650 		 * Never allow processing to run for more than one
1651 		 * second. This gives the syncer thread the opportunity
1652 		 * to pause if appropriate.
1653 		 */
1654 		if (!full && starttime != time_second)
1655 			break;
1656 	}
1657 	if (full == 0)
1658 		journal_unsuspend(ump);
1659 	FREE_LOCK(ump);
1660 	return (matchcnt);
1661 }
1662 
1663 /*
1664  * Process all removes associated with a vnode if we are running out of
1665  * journal space.  Any other process which attempts to flush these will
1666  * be unable as we have the vnodes locked.
1667  */
1668 static void
1669 process_removes(vp)
1670 	struct vnode *vp;
1671 {
1672 	struct inodedep *inodedep;
1673 	struct dirrem *dirrem;
1674 	struct ufsmount *ump;
1675 	struct mount *mp;
1676 	ino_t inum;
1677 
1678 	mp = vp->v_mount;
1679 	ump = VFSTOUFS(mp);
1680 	LOCK_OWNED(ump);
1681 	inum = VTOI(vp)->i_number;
1682 	for (;;) {
1683 top:
1684 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1685 			return;
1686 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1687 			/*
1688 			 * If another thread is trying to lock this vnode
1689 			 * it will fail but we must wait for it to do so
1690 			 * before we can proceed.
1691 			 */
1692 			if (dirrem->dm_state & INPROGRESS) {
1693 				wait_worklist(&dirrem->dm_list, "pwrwait");
1694 				goto top;
1695 			}
1696 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1697 			    (COMPLETE | ONWORKLIST))
1698 				break;
1699 		}
1700 		if (dirrem == NULL)
1701 			return;
1702 		remove_from_worklist(&dirrem->dm_list);
1703 		FREE_LOCK(ump);
1704 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1705 			panic("process_removes: suspended filesystem");
1706 		handle_workitem_remove(dirrem, 0);
1707 		vn_finished_secondary_write(mp);
1708 		ACQUIRE_LOCK(ump);
1709 	}
1710 }
1711 
1712 /*
1713  * Process all truncations associated with a vnode if we are running out
1714  * of journal space.  This is called when the vnode lock is already held
1715  * and no other process can clear the truncation.  This function returns
1716  * a value greater than zero if it did any work.
1717  */
1718 static void
1719 process_truncates(vp)
1720 	struct vnode *vp;
1721 {
1722 	struct inodedep *inodedep;
1723 	struct freeblks *freeblks;
1724 	struct ufsmount *ump;
1725 	struct mount *mp;
1726 	ino_t inum;
1727 	int cgwait;
1728 
1729 	mp = vp->v_mount;
1730 	ump = VFSTOUFS(mp);
1731 	LOCK_OWNED(ump);
1732 	inum = VTOI(vp)->i_number;
1733 	for (;;) {
1734 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1735 			return;
1736 		cgwait = 0;
1737 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1738 			/* Journal entries not yet written.  */
1739 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1740 				jwait(&LIST_FIRST(
1741 				    &freeblks->fb_jblkdephd)->jb_list,
1742 				    MNT_WAIT);
1743 				break;
1744 			}
1745 			/* Another thread is executing this item. */
1746 			if (freeblks->fb_state & INPROGRESS) {
1747 				wait_worklist(&freeblks->fb_list, "ptrwait");
1748 				break;
1749 			}
1750 			/* Freeblks is waiting on a inode write. */
1751 			if ((freeblks->fb_state & COMPLETE) == 0) {
1752 				FREE_LOCK(ump);
1753 				ffs_update(vp, 1);
1754 				ACQUIRE_LOCK(ump);
1755 				break;
1756 			}
1757 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1758 			    (ALLCOMPLETE | ONWORKLIST)) {
1759 				remove_from_worklist(&freeblks->fb_list);
1760 				freeblks->fb_state |= INPROGRESS;
1761 				FREE_LOCK(ump);
1762 				if (vn_start_secondary_write(NULL, &mp,
1763 				    V_NOWAIT))
1764 					panic("process_truncates: "
1765 					    "suspended filesystem");
1766 				handle_workitem_freeblocks(freeblks, 0);
1767 				vn_finished_secondary_write(mp);
1768 				ACQUIRE_LOCK(ump);
1769 				break;
1770 			}
1771 			if (freeblks->fb_cgwait)
1772 				cgwait++;
1773 		}
1774 		if (cgwait) {
1775 			FREE_LOCK(ump);
1776 			sync_cgs(mp, MNT_WAIT);
1777 			ffs_sync_snap(mp, MNT_WAIT);
1778 			ACQUIRE_LOCK(ump);
1779 			continue;
1780 		}
1781 		if (freeblks == NULL)
1782 			break;
1783 	}
1784 	return;
1785 }
1786 
1787 /*
1788  * Process one item on the worklist.
1789  */
1790 static int
1791 process_worklist_item(mp, target, flags)
1792 	struct mount *mp;
1793 	int target;
1794 	int flags;
1795 {
1796 	struct worklist sentinel;
1797 	struct worklist *wk;
1798 	struct ufsmount *ump;
1799 	int matchcnt;
1800 	int error;
1801 
1802 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1803 	/*
1804 	 * If we are being called because of a process doing a
1805 	 * copy-on-write, then it is not safe to write as we may
1806 	 * recurse into the copy-on-write routine.
1807 	 */
1808 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1809 		return (-1);
1810 	PHOLD(curproc);	/* Don't let the stack go away. */
1811 	ump = VFSTOUFS(mp);
1812 	LOCK_OWNED(ump);
1813 	matchcnt = 0;
1814 	sentinel.wk_mp = NULL;
1815 	sentinel.wk_type = D_SENTINEL;
1816 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1817 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1818 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1819 		if (wk->wk_type == D_SENTINEL) {
1820 			LIST_REMOVE(&sentinel, wk_list);
1821 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1822 			continue;
1823 		}
1824 		if (wk->wk_state & INPROGRESS)
1825 			panic("process_worklist_item: %p already in progress.",
1826 			    wk);
1827 		wk->wk_state |= INPROGRESS;
1828 		remove_from_worklist(wk);
1829 		FREE_LOCK(ump);
1830 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1831 			panic("process_worklist_item: suspended filesystem");
1832 		switch (wk->wk_type) {
1833 		case D_DIRREM:
1834 			/* removal of a directory entry */
1835 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1836 			break;
1837 
1838 		case D_FREEBLKS:
1839 			/* releasing blocks and/or fragments from a file */
1840 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1841 			    flags);
1842 			break;
1843 
1844 		case D_FREEFRAG:
1845 			/* releasing a fragment when replaced as a file grows */
1846 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1847 			error = 0;
1848 			break;
1849 
1850 		case D_FREEFILE:
1851 			/* releasing an inode when its link count drops to 0 */
1852 			handle_workitem_freefile(WK_FREEFILE(wk));
1853 			error = 0;
1854 			break;
1855 
1856 		default:
1857 			panic("%s_process_worklist: Unknown type %s",
1858 			    "softdep", TYPENAME(wk->wk_type));
1859 			/* NOTREACHED */
1860 		}
1861 		vn_finished_secondary_write(mp);
1862 		ACQUIRE_LOCK(ump);
1863 		if (error == 0) {
1864 			if (++matchcnt == target)
1865 				break;
1866 			continue;
1867 		}
1868 		/*
1869 		 * We have to retry the worklist item later.  Wake up any
1870 		 * waiters who may be able to complete it immediately and
1871 		 * add the item back to the head so we don't try to execute
1872 		 * it again.
1873 		 */
1874 		wk->wk_state &= ~INPROGRESS;
1875 		wake_worklist(wk);
1876 		add_to_worklist(wk, WK_HEAD);
1877 	}
1878 	/* Sentinal could've become the tail from remove_from_worklist. */
1879 	if (ump->softdep_worklist_tail == &sentinel)
1880 		ump->softdep_worklist_tail =
1881 		    (struct worklist *)sentinel.wk_list.le_prev;
1882 	LIST_REMOVE(&sentinel, wk_list);
1883 	PRELE(curproc);
1884 	return (matchcnt);
1885 }
1886 
1887 /*
1888  * Move dependencies from one buffer to another.
1889  */
1890 int
1891 softdep_move_dependencies(oldbp, newbp)
1892 	struct buf *oldbp;
1893 	struct buf *newbp;
1894 {
1895 	struct worklist *wk, *wktail;
1896 	struct ufsmount *ump;
1897 	int dirty;
1898 
1899 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1900 		return (0);
1901 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1902 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1903 	dirty = 0;
1904 	wktail = NULL;
1905 	ump = VFSTOUFS(wk->wk_mp);
1906 	ACQUIRE_LOCK(ump);
1907 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1908 		LIST_REMOVE(wk, wk_list);
1909 		if (wk->wk_type == D_BMSAFEMAP &&
1910 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1911 			dirty = 1;
1912 		if (wktail == NULL)
1913 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1914 		else
1915 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1916 		wktail = wk;
1917 	}
1918 	FREE_LOCK(ump);
1919 
1920 	return (dirty);
1921 }
1922 
1923 /*
1924  * Purge the work list of all items associated with a particular mount point.
1925  */
1926 int
1927 softdep_flushworklist(oldmnt, countp, td)
1928 	struct mount *oldmnt;
1929 	int *countp;
1930 	struct thread *td;
1931 {
1932 	struct vnode *devvp;
1933 	struct ufsmount *ump;
1934 	int count, error;
1935 
1936 	/*
1937 	 * Alternately flush the block device associated with the mount
1938 	 * point and process any dependencies that the flushing
1939 	 * creates. We continue until no more worklist dependencies
1940 	 * are found.
1941 	 */
1942 	*countp = 0;
1943 	error = 0;
1944 	ump = VFSTOUFS(oldmnt);
1945 	devvp = ump->um_devvp;
1946 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1947 		*countp += count;
1948 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1949 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1950 		VOP_UNLOCK(devvp);
1951 		if (error != 0)
1952 			break;
1953 	}
1954 	return (error);
1955 }
1956 
1957 #define	SU_WAITIDLE_RETRIES	20
1958 static int
1959 softdep_waitidle(struct mount *mp, int flags __unused)
1960 {
1961 	struct ufsmount *ump;
1962 	struct vnode *devvp;
1963 	struct thread *td;
1964 	int error, i;
1965 
1966 	ump = VFSTOUFS(mp);
1967 	devvp = ump->um_devvp;
1968 	td = curthread;
1969 	error = 0;
1970 	ACQUIRE_LOCK(ump);
1971 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1972 		ump->softdep_req = 1;
1973 		KASSERT((flags & FORCECLOSE) == 0 ||
1974 		    ump->softdep_on_worklist == 0,
1975 		    ("softdep_waitidle: work added after flush"));
1976 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1977 		    "softdeps", 10 * hz);
1978 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1979 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1980 		VOP_UNLOCK(devvp);
1981 		ACQUIRE_LOCK(ump);
1982 		if (error != 0)
1983 			break;
1984 	}
1985 	ump->softdep_req = 0;
1986 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1987 		error = EBUSY;
1988 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1989 		    mp);
1990 	}
1991 	FREE_LOCK(ump);
1992 	return (error);
1993 }
1994 
1995 /*
1996  * Flush all vnodes and worklist items associated with a specified mount point.
1997  */
1998 int
1999 softdep_flushfiles(oldmnt, flags, td)
2000 	struct mount *oldmnt;
2001 	int flags;
2002 	struct thread *td;
2003 {
2004 #ifdef QUOTA
2005 	struct ufsmount *ump;
2006 	int i;
2007 #endif
2008 	int error, early, depcount, loopcnt, retry_flush_count, retry;
2009 	int morework;
2010 
2011 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
2012 	    ("softdep_flushfiles called on non-softdep filesystem"));
2013 	loopcnt = 10;
2014 	retry_flush_count = 3;
2015 retry_flush:
2016 	error = 0;
2017 
2018 	/*
2019 	 * Alternately flush the vnodes associated with the mount
2020 	 * point and process any dependencies that the flushing
2021 	 * creates. In theory, this loop can happen at most twice,
2022 	 * but we give it a few extra just to be sure.
2023 	 */
2024 	for (; loopcnt > 0; loopcnt--) {
2025 		/*
2026 		 * Do another flush in case any vnodes were brought in
2027 		 * as part of the cleanup operations.
2028 		 */
2029 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2030 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2031 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2032 			break;
2033 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2034 		    depcount == 0)
2035 			break;
2036 	}
2037 	/*
2038 	 * If we are unmounting then it is an error to fail. If we
2039 	 * are simply trying to downgrade to read-only, then filesystem
2040 	 * activity can keep us busy forever, so we just fail with EBUSY.
2041 	 */
2042 	if (loopcnt == 0) {
2043 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2044 			panic("softdep_flushfiles: looping");
2045 		error = EBUSY;
2046 	}
2047 	if (!error)
2048 		error = softdep_waitidle(oldmnt, flags);
2049 	if (!error) {
2050 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2051 			retry = 0;
2052 			MNT_ILOCK(oldmnt);
2053 			morework = oldmnt->mnt_nvnodelistsize > 0;
2054 #ifdef QUOTA
2055 			ump = VFSTOUFS(oldmnt);
2056 			UFS_LOCK(ump);
2057 			for (i = 0; i < MAXQUOTAS; i++) {
2058 				if (ump->um_quotas[i] != NULLVP)
2059 					morework = 1;
2060 			}
2061 			UFS_UNLOCK(ump);
2062 #endif
2063 			if (morework) {
2064 				if (--retry_flush_count > 0) {
2065 					retry = 1;
2066 					loopcnt = 3;
2067 				} else
2068 					error = EBUSY;
2069 			}
2070 			MNT_IUNLOCK(oldmnt);
2071 			if (retry)
2072 				goto retry_flush;
2073 		}
2074 	}
2075 	return (error);
2076 }
2077 
2078 /*
2079  * Structure hashing.
2080  *
2081  * There are four types of structures that can be looked up:
2082  *	1) pagedep structures identified by mount point, inode number,
2083  *	   and logical block.
2084  *	2) inodedep structures identified by mount point and inode number.
2085  *	3) newblk structures identified by mount point and
2086  *	   physical block number.
2087  *	4) bmsafemap structures identified by mount point and
2088  *	   cylinder group number.
2089  *
2090  * The "pagedep" and "inodedep" dependency structures are hashed
2091  * separately from the file blocks and inodes to which they correspond.
2092  * This separation helps when the in-memory copy of an inode or
2093  * file block must be replaced. It also obviates the need to access
2094  * an inode or file page when simply updating (or de-allocating)
2095  * dependency structures. Lookup of newblk structures is needed to
2096  * find newly allocated blocks when trying to associate them with
2097  * their allocdirect or allocindir structure.
2098  *
2099  * The lookup routines optionally create and hash a new instance when
2100  * an existing entry is not found. The bmsafemap lookup routine always
2101  * allocates a new structure if an existing one is not found.
2102  */
2103 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2104 
2105 /*
2106  * Structures and routines associated with pagedep caching.
2107  */
2108 #define	PAGEDEP_HASH(ump, inum, lbn) \
2109 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2110 
2111 static int
2112 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2113 	struct pagedep_hashhead *pagedephd;
2114 	ino_t ino;
2115 	ufs_lbn_t lbn;
2116 	struct pagedep **pagedeppp;
2117 {
2118 	struct pagedep *pagedep;
2119 
2120 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2121 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2122 			*pagedeppp = pagedep;
2123 			return (1);
2124 		}
2125 	}
2126 	*pagedeppp = NULL;
2127 	return (0);
2128 }
2129 /*
2130  * Look up a pagedep. Return 1 if found, 0 otherwise.
2131  * If not found, allocate if DEPALLOC flag is passed.
2132  * Found or allocated entry is returned in pagedeppp.
2133  */
2134 static int
2135 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2136 	struct mount *mp;
2137 	struct buf *bp;
2138 	ino_t ino;
2139 	ufs_lbn_t lbn;
2140 	int flags;
2141 	struct pagedep **pagedeppp;
2142 {
2143 	struct pagedep *pagedep;
2144 	struct pagedep_hashhead *pagedephd;
2145 	struct worklist *wk;
2146 	struct ufsmount *ump;
2147 	int ret;
2148 	int i;
2149 
2150 	ump = VFSTOUFS(mp);
2151 	LOCK_OWNED(ump);
2152 	if (bp) {
2153 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2154 			if (wk->wk_type == D_PAGEDEP) {
2155 				*pagedeppp = WK_PAGEDEP(wk);
2156 				return (1);
2157 			}
2158 		}
2159 	}
2160 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2161 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2162 	if (ret) {
2163 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2164 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2165 		return (1);
2166 	}
2167 	if ((flags & DEPALLOC) == 0)
2168 		return (0);
2169 	FREE_LOCK(ump);
2170 	pagedep = malloc(sizeof(struct pagedep),
2171 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2172 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2173 	ACQUIRE_LOCK(ump);
2174 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2175 	if (*pagedeppp) {
2176 		/*
2177 		 * This should never happen since we only create pagedeps
2178 		 * with the vnode lock held.  Could be an assert.
2179 		 */
2180 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2181 		return (ret);
2182 	}
2183 	pagedep->pd_ino = ino;
2184 	pagedep->pd_lbn = lbn;
2185 	LIST_INIT(&pagedep->pd_dirremhd);
2186 	LIST_INIT(&pagedep->pd_pendinghd);
2187 	for (i = 0; i < DAHASHSZ; i++)
2188 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2189 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2190 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2191 	*pagedeppp = pagedep;
2192 	return (0);
2193 }
2194 
2195 /*
2196  * Structures and routines associated with inodedep caching.
2197  */
2198 #define	INODEDEP_HASH(ump, inum) \
2199       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2200 
2201 static int
2202 inodedep_find(inodedephd, inum, inodedeppp)
2203 	struct inodedep_hashhead *inodedephd;
2204 	ino_t inum;
2205 	struct inodedep **inodedeppp;
2206 {
2207 	struct inodedep *inodedep;
2208 
2209 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2210 		if (inum == inodedep->id_ino)
2211 			break;
2212 	if (inodedep) {
2213 		*inodedeppp = inodedep;
2214 		return (1);
2215 	}
2216 	*inodedeppp = NULL;
2217 
2218 	return (0);
2219 }
2220 /*
2221  * Look up an inodedep. Return 1 if found, 0 if not found.
2222  * If not found, allocate if DEPALLOC flag is passed.
2223  * Found or allocated entry is returned in inodedeppp.
2224  */
2225 static int
2226 inodedep_lookup(mp, inum, flags, inodedeppp)
2227 	struct mount *mp;
2228 	ino_t inum;
2229 	int flags;
2230 	struct inodedep **inodedeppp;
2231 {
2232 	struct inodedep *inodedep;
2233 	struct inodedep_hashhead *inodedephd;
2234 	struct ufsmount *ump;
2235 	struct fs *fs;
2236 
2237 	ump = VFSTOUFS(mp);
2238 	LOCK_OWNED(ump);
2239 	fs = ump->um_fs;
2240 	inodedephd = INODEDEP_HASH(ump, inum);
2241 
2242 	if (inodedep_find(inodedephd, inum, inodedeppp))
2243 		return (1);
2244 	if ((flags & DEPALLOC) == 0)
2245 		return (0);
2246 	/*
2247 	 * If the system is over its limit and our filesystem is
2248 	 * responsible for more than our share of that usage and
2249 	 * we are not in a rush, request some inodedep cleanup.
2250 	 */
2251 	if (softdep_excess_items(ump, D_INODEDEP))
2252 		schedule_cleanup(mp);
2253 	else
2254 		FREE_LOCK(ump);
2255 	inodedep = malloc(sizeof(struct inodedep),
2256 		M_INODEDEP, M_SOFTDEP_FLAGS);
2257 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2258 	ACQUIRE_LOCK(ump);
2259 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2260 		WORKITEM_FREE(inodedep, D_INODEDEP);
2261 		return (1);
2262 	}
2263 	inodedep->id_fs = fs;
2264 	inodedep->id_ino = inum;
2265 	inodedep->id_state = ALLCOMPLETE;
2266 	inodedep->id_nlinkdelta = 0;
2267 	inodedep->id_savedino1 = NULL;
2268 	inodedep->id_savedsize = -1;
2269 	inodedep->id_savedextsize = -1;
2270 	inodedep->id_savednlink = -1;
2271 	inodedep->id_bmsafemap = NULL;
2272 	inodedep->id_mkdiradd = NULL;
2273 	LIST_INIT(&inodedep->id_dirremhd);
2274 	LIST_INIT(&inodedep->id_pendinghd);
2275 	LIST_INIT(&inodedep->id_inowait);
2276 	LIST_INIT(&inodedep->id_bufwait);
2277 	TAILQ_INIT(&inodedep->id_inoreflst);
2278 	TAILQ_INIT(&inodedep->id_inoupdt);
2279 	TAILQ_INIT(&inodedep->id_newinoupdt);
2280 	TAILQ_INIT(&inodedep->id_extupdt);
2281 	TAILQ_INIT(&inodedep->id_newextupdt);
2282 	TAILQ_INIT(&inodedep->id_freeblklst);
2283 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2284 	*inodedeppp = inodedep;
2285 	return (0);
2286 }
2287 
2288 /*
2289  * Structures and routines associated with newblk caching.
2290  */
2291 #define	NEWBLK_HASH(ump, inum) \
2292 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2293 
2294 static int
2295 newblk_find(newblkhd, newblkno, flags, newblkpp)
2296 	struct newblk_hashhead *newblkhd;
2297 	ufs2_daddr_t newblkno;
2298 	int flags;
2299 	struct newblk **newblkpp;
2300 {
2301 	struct newblk *newblk;
2302 
2303 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2304 		if (newblkno != newblk->nb_newblkno)
2305 			continue;
2306 		/*
2307 		 * If we're creating a new dependency don't match those that
2308 		 * have already been converted to allocdirects.  This is for
2309 		 * a frag extend.
2310 		 */
2311 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2312 			continue;
2313 		break;
2314 	}
2315 	if (newblk) {
2316 		*newblkpp = newblk;
2317 		return (1);
2318 	}
2319 	*newblkpp = NULL;
2320 	return (0);
2321 }
2322 
2323 /*
2324  * Look up a newblk. Return 1 if found, 0 if not found.
2325  * If not found, allocate if DEPALLOC flag is passed.
2326  * Found or allocated entry is returned in newblkpp.
2327  */
2328 static int
2329 newblk_lookup(mp, newblkno, flags, newblkpp)
2330 	struct mount *mp;
2331 	ufs2_daddr_t newblkno;
2332 	int flags;
2333 	struct newblk **newblkpp;
2334 {
2335 	struct newblk *newblk;
2336 	struct newblk_hashhead *newblkhd;
2337 	struct ufsmount *ump;
2338 
2339 	ump = VFSTOUFS(mp);
2340 	LOCK_OWNED(ump);
2341 	newblkhd = NEWBLK_HASH(ump, newblkno);
2342 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2343 		return (1);
2344 	if ((flags & DEPALLOC) == 0)
2345 		return (0);
2346 	if (softdep_excess_items(ump, D_NEWBLK) ||
2347 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2348 	    softdep_excess_items(ump, D_ALLOCINDIR))
2349 		schedule_cleanup(mp);
2350 	else
2351 		FREE_LOCK(ump);
2352 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2353 	    M_SOFTDEP_FLAGS | M_ZERO);
2354 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2355 	ACQUIRE_LOCK(ump);
2356 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2357 		WORKITEM_FREE(newblk, D_NEWBLK);
2358 		return (1);
2359 	}
2360 	newblk->nb_freefrag = NULL;
2361 	LIST_INIT(&newblk->nb_indirdeps);
2362 	LIST_INIT(&newblk->nb_newdirblk);
2363 	LIST_INIT(&newblk->nb_jwork);
2364 	newblk->nb_state = ATTACHED;
2365 	newblk->nb_newblkno = newblkno;
2366 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2367 	*newblkpp = newblk;
2368 	return (0);
2369 }
2370 
2371 /*
2372  * Structures and routines associated with freed indirect block caching.
2373  */
2374 #define	INDIR_HASH(ump, blkno) \
2375 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2376 
2377 /*
2378  * Lookup an indirect block in the indir hash table.  The freework is
2379  * removed and potentially freed.  The caller must do a blocking journal
2380  * write before writing to the blkno.
2381  */
2382 static int
2383 indirblk_lookup(mp, blkno)
2384 	struct mount *mp;
2385 	ufs2_daddr_t blkno;
2386 {
2387 	struct freework *freework;
2388 	struct indir_hashhead *wkhd;
2389 	struct ufsmount *ump;
2390 
2391 	ump = VFSTOUFS(mp);
2392 	wkhd = INDIR_HASH(ump, blkno);
2393 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2394 		if (freework->fw_blkno != blkno)
2395 			continue;
2396 		indirblk_remove(freework);
2397 		return (1);
2398 	}
2399 	return (0);
2400 }
2401 
2402 /*
2403  * Insert an indirect block represented by freework into the indirblk
2404  * hash table so that it may prevent the block from being re-used prior
2405  * to the journal being written.
2406  */
2407 static void
2408 indirblk_insert(freework)
2409 	struct freework *freework;
2410 {
2411 	struct jblocks *jblocks;
2412 	struct jseg *jseg;
2413 	struct ufsmount *ump;
2414 
2415 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2416 	jblocks = ump->softdep_jblocks;
2417 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2418 	if (jseg == NULL)
2419 		return;
2420 
2421 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2422 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2423 	    fw_next);
2424 	freework->fw_state &= ~DEPCOMPLETE;
2425 }
2426 
2427 static void
2428 indirblk_remove(freework)
2429 	struct freework *freework;
2430 {
2431 	struct ufsmount *ump;
2432 
2433 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2434 	LIST_REMOVE(freework, fw_segs);
2435 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2436 	freework->fw_state |= DEPCOMPLETE;
2437 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2438 		WORKITEM_FREE(freework, D_FREEWORK);
2439 }
2440 
2441 /*
2442  * Executed during filesystem system initialization before
2443  * mounting any filesystems.
2444  */
2445 void
2446 softdep_initialize()
2447 {
2448 
2449 	TAILQ_INIT(&softdepmounts);
2450 #ifdef __LP64__
2451 	max_softdeps = desiredvnodes * 4;
2452 #else
2453 	max_softdeps = desiredvnodes * 2;
2454 #endif
2455 
2456 	/* initialise bioops hack */
2457 	bioops.io_start = softdep_disk_io_initiation;
2458 	bioops.io_complete = softdep_disk_write_complete;
2459 	bioops.io_deallocate = softdep_deallocate_dependencies;
2460 	bioops.io_countdeps = softdep_count_dependencies;
2461 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2462 
2463 	/* Initialize the callout with an mtx. */
2464 	callout_init_mtx(&softdep_callout, &lk, 0);
2465 }
2466 
2467 /*
2468  * Executed after all filesystems have been unmounted during
2469  * filesystem module unload.
2470  */
2471 void
2472 softdep_uninitialize()
2473 {
2474 
2475 	/* clear bioops hack */
2476 	bioops.io_start = NULL;
2477 	bioops.io_complete = NULL;
2478 	bioops.io_deallocate = NULL;
2479 	bioops.io_countdeps = NULL;
2480 	softdep_ast_cleanup = NULL;
2481 
2482 	callout_drain(&softdep_callout);
2483 }
2484 
2485 /*
2486  * Called at mount time to notify the dependency code that a
2487  * filesystem wishes to use it.
2488  */
2489 int
2490 softdep_mount(devvp, mp, fs, cred)
2491 	struct vnode *devvp;
2492 	struct mount *mp;
2493 	struct fs *fs;
2494 	struct ucred *cred;
2495 {
2496 	struct csum_total cstotal;
2497 	struct mount_softdeps *sdp;
2498 	struct ufsmount *ump;
2499 	struct cg *cgp;
2500 	struct buf *bp;
2501 	u_int cyl, i;
2502 	int error;
2503 
2504 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2505 	    M_WAITOK | M_ZERO);
2506 	MNT_ILOCK(mp);
2507 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2508 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2509 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2510 			MNTK_SOFTDEP | MNTK_NOASYNC;
2511 	}
2512 	ump = VFSTOUFS(mp);
2513 	ump->um_softdep = sdp;
2514 	MNT_IUNLOCK(mp);
2515 	rw_init(LOCK_PTR(ump), "per-fs softdep");
2516 	sdp->sd_ump = ump;
2517 	LIST_INIT(&ump->softdep_workitem_pending);
2518 	LIST_INIT(&ump->softdep_journal_pending);
2519 	TAILQ_INIT(&ump->softdep_unlinked);
2520 	LIST_INIT(&ump->softdep_dirtycg);
2521 	ump->softdep_worklist_tail = NULL;
2522 	ump->softdep_on_worklist = 0;
2523 	ump->softdep_deps = 0;
2524 	LIST_INIT(&ump->softdep_mkdirlisthd);
2525 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2526 	    &ump->pagedep_hash_size);
2527 	ump->pagedep_nextclean = 0;
2528 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2529 	    &ump->inodedep_hash_size);
2530 	ump->inodedep_nextclean = 0;
2531 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2532 	    &ump->newblk_hash_size);
2533 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2534 	    &ump->bmsafemap_hash_size);
2535 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2536 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2537 	    M_FREEWORK, M_WAITOK);
2538 	ump->indir_hash_size = i - 1;
2539 	for (i = 0; i <= ump->indir_hash_size; i++)
2540 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2541 #ifdef INVARIANTS
2542 	for (i = 0; i <= D_LAST; i++)
2543 		LIST_INIT(&ump->softdep_alldeps[i]);
2544 #endif
2545 	ACQUIRE_GBLLOCK(&lk);
2546 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2547 	FREE_GBLLOCK(&lk);
2548 	if ((fs->fs_flags & FS_SUJ) &&
2549 	    (error = journal_mount(mp, fs, cred)) != 0) {
2550 		printf("Failed to start journal: %d\n", error);
2551 		softdep_unmount(mp);
2552 		return (error);
2553 	}
2554 	/*
2555 	 * Start our flushing thread in the bufdaemon process.
2556 	 */
2557 	ACQUIRE_LOCK(ump);
2558 	ump->softdep_flags |= FLUSH_STARTING;
2559 	FREE_LOCK(ump);
2560 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2561 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2562 	    mp->mnt_stat.f_mntonname);
2563 	ACQUIRE_LOCK(ump);
2564 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2565 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2566 		    hz / 2);
2567 	}
2568 	FREE_LOCK(ump);
2569 	/*
2570 	 * When doing soft updates, the counters in the
2571 	 * superblock may have gotten out of sync. Recomputation
2572 	 * can take a long time and can be deferred for background
2573 	 * fsck.  However, the old behavior of scanning the cylinder
2574 	 * groups and recalculating them at mount time is available
2575 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2576 	 */
2577 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2578 		return (0);
2579 	bzero(&cstotal, sizeof cstotal);
2580 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2581 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2582 		    fs->fs_cgsize, cred, &bp)) != 0) {
2583 			brelse(bp);
2584 			softdep_unmount(mp);
2585 			return (error);
2586 		}
2587 		cgp = (struct cg *)bp->b_data;
2588 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2589 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2590 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2591 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2592 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2593 		brelse(bp);
2594 	}
2595 #ifdef INVARIANTS
2596 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2597 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2598 #endif
2599 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2600 	return (0);
2601 }
2602 
2603 void
2604 softdep_unmount(mp)
2605 	struct mount *mp;
2606 {
2607 	struct ufsmount *ump;
2608 #ifdef INVARIANTS
2609 	int i;
2610 #endif
2611 
2612 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2613 	    ("softdep_unmount called on non-softdep filesystem"));
2614 	ump = VFSTOUFS(mp);
2615 	MNT_ILOCK(mp);
2616 	mp->mnt_flag &= ~MNT_SOFTDEP;
2617 	if (MOUNTEDSUJ(mp) == 0) {
2618 		MNT_IUNLOCK(mp);
2619 	} else {
2620 		mp->mnt_flag &= ~MNT_SUJ;
2621 		MNT_IUNLOCK(mp);
2622 		journal_unmount(ump);
2623 	}
2624 	/*
2625 	 * Shut down our flushing thread. Check for NULL is if
2626 	 * softdep_mount errors out before the thread has been created.
2627 	 */
2628 	if (ump->softdep_flushtd != NULL) {
2629 		ACQUIRE_LOCK(ump);
2630 		ump->softdep_flags |= FLUSH_EXIT;
2631 		wakeup(&ump->softdep_flushtd);
2632 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2633 		    "sdwait", 0);
2634 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2635 		    ("Thread shutdown failed"));
2636 	}
2637 	/*
2638 	 * Free up our resources.
2639 	 */
2640 	ACQUIRE_GBLLOCK(&lk);
2641 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2642 	FREE_GBLLOCK(&lk);
2643 	rw_destroy(LOCK_PTR(ump));
2644 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2645 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2646 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2647 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2648 	    ump->bmsafemap_hash_size);
2649 	free(ump->indir_hashtbl, M_FREEWORK);
2650 #ifdef INVARIANTS
2651 	for (i = 0; i <= D_LAST; i++) {
2652 		KASSERT(ump->softdep_curdeps[i] == 0,
2653 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2654 		    TYPENAME(i), ump->softdep_curdeps[i]));
2655 		KASSERT(LIST_EMPTY(&ump->softdep_alldeps[i]),
2656 		    ("Unmount %s: Dep type %s not empty (%p)", ump->um_fs->fs_fsmnt,
2657 		    TYPENAME(i), LIST_FIRST(&ump->softdep_alldeps[i])));
2658 	}
2659 #endif
2660 	free(ump->um_softdep, M_MOUNTDATA);
2661 }
2662 
2663 static struct jblocks *
2664 jblocks_create(void)
2665 {
2666 	struct jblocks *jblocks;
2667 
2668 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2669 	TAILQ_INIT(&jblocks->jb_segs);
2670 	jblocks->jb_avail = 10;
2671 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2672 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2673 
2674 	return (jblocks);
2675 }
2676 
2677 static ufs2_daddr_t
2678 jblocks_alloc(jblocks, bytes, actual)
2679 	struct jblocks *jblocks;
2680 	int bytes;
2681 	int *actual;
2682 {
2683 	ufs2_daddr_t daddr;
2684 	struct jextent *jext;
2685 	int freecnt;
2686 	int blocks;
2687 
2688 	blocks = bytes / DEV_BSIZE;
2689 	jext = &jblocks->jb_extent[jblocks->jb_head];
2690 	freecnt = jext->je_blocks - jblocks->jb_off;
2691 	if (freecnt == 0) {
2692 		jblocks->jb_off = 0;
2693 		if (++jblocks->jb_head > jblocks->jb_used)
2694 			jblocks->jb_head = 0;
2695 		jext = &jblocks->jb_extent[jblocks->jb_head];
2696 		freecnt = jext->je_blocks;
2697 	}
2698 	if (freecnt > blocks)
2699 		freecnt = blocks;
2700 	*actual = freecnt * DEV_BSIZE;
2701 	daddr = jext->je_daddr + jblocks->jb_off;
2702 	jblocks->jb_off += freecnt;
2703 	jblocks->jb_free -= freecnt;
2704 
2705 	return (daddr);
2706 }
2707 
2708 static void
2709 jblocks_free(jblocks, mp, bytes)
2710 	struct jblocks *jblocks;
2711 	struct mount *mp;
2712 	int bytes;
2713 {
2714 
2715 	LOCK_OWNED(VFSTOUFS(mp));
2716 	jblocks->jb_free += bytes / DEV_BSIZE;
2717 	if (jblocks->jb_suspended)
2718 		worklist_speedup(mp);
2719 	wakeup(jblocks);
2720 }
2721 
2722 static void
2723 jblocks_destroy(jblocks)
2724 	struct jblocks *jblocks;
2725 {
2726 
2727 	if (jblocks->jb_extent)
2728 		free(jblocks->jb_extent, M_JBLOCKS);
2729 	free(jblocks, M_JBLOCKS);
2730 }
2731 
2732 static void
2733 jblocks_add(jblocks, daddr, blocks)
2734 	struct jblocks *jblocks;
2735 	ufs2_daddr_t daddr;
2736 	int blocks;
2737 {
2738 	struct jextent *jext;
2739 
2740 	jblocks->jb_blocks += blocks;
2741 	jblocks->jb_free += blocks;
2742 	jext = &jblocks->jb_extent[jblocks->jb_used];
2743 	/* Adding the first block. */
2744 	if (jext->je_daddr == 0) {
2745 		jext->je_daddr = daddr;
2746 		jext->je_blocks = blocks;
2747 		return;
2748 	}
2749 	/* Extending the last extent. */
2750 	if (jext->je_daddr + jext->je_blocks == daddr) {
2751 		jext->je_blocks += blocks;
2752 		return;
2753 	}
2754 	/* Adding a new extent. */
2755 	if (++jblocks->jb_used == jblocks->jb_avail) {
2756 		jblocks->jb_avail *= 2;
2757 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2758 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2759 		memcpy(jext, jblocks->jb_extent,
2760 		    sizeof(struct jextent) * jblocks->jb_used);
2761 		free(jblocks->jb_extent, M_JBLOCKS);
2762 		jblocks->jb_extent = jext;
2763 	}
2764 	jext = &jblocks->jb_extent[jblocks->jb_used];
2765 	jext->je_daddr = daddr;
2766 	jext->je_blocks = blocks;
2767 	return;
2768 }
2769 
2770 int
2771 softdep_journal_lookup(mp, vpp)
2772 	struct mount *mp;
2773 	struct vnode **vpp;
2774 {
2775 	struct componentname cnp;
2776 	struct vnode *dvp;
2777 	ino_t sujournal;
2778 	int error;
2779 
2780 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2781 	if (error)
2782 		return (error);
2783 	bzero(&cnp, sizeof(cnp));
2784 	cnp.cn_nameiop = LOOKUP;
2785 	cnp.cn_flags = ISLASTCN;
2786 	cnp.cn_thread = curthread;
2787 	cnp.cn_cred = curthread->td_ucred;
2788 	cnp.cn_pnbuf = SUJ_FILE;
2789 	cnp.cn_nameptr = SUJ_FILE;
2790 	cnp.cn_namelen = strlen(SUJ_FILE);
2791 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2792 	vput(dvp);
2793 	if (error != 0)
2794 		return (error);
2795 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2796 	return (error);
2797 }
2798 
2799 /*
2800  * Open and verify the journal file.
2801  */
2802 static int
2803 journal_mount(mp, fs, cred)
2804 	struct mount *mp;
2805 	struct fs *fs;
2806 	struct ucred *cred;
2807 {
2808 	struct jblocks *jblocks;
2809 	struct ufsmount *ump;
2810 	struct vnode *vp;
2811 	struct inode *ip;
2812 	ufs2_daddr_t blkno;
2813 	int bcount;
2814 	int error;
2815 	int i;
2816 
2817 	ump = VFSTOUFS(mp);
2818 	ump->softdep_journal_tail = NULL;
2819 	ump->softdep_on_journal = 0;
2820 	ump->softdep_accdeps = 0;
2821 	ump->softdep_req = 0;
2822 	ump->softdep_jblocks = NULL;
2823 	error = softdep_journal_lookup(mp, &vp);
2824 	if (error != 0) {
2825 		printf("Failed to find journal.  Use tunefs to create one\n");
2826 		return (error);
2827 	}
2828 	ip = VTOI(vp);
2829 	if (ip->i_size < SUJ_MIN) {
2830 		error = ENOSPC;
2831 		goto out;
2832 	}
2833 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2834 	jblocks = jblocks_create();
2835 	for (i = 0; i < bcount; i++) {
2836 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2837 		if (error)
2838 			break;
2839 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2840 	}
2841 	if (error) {
2842 		jblocks_destroy(jblocks);
2843 		goto out;
2844 	}
2845 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2846 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2847 	ump->softdep_jblocks = jblocks;
2848 out:
2849 	if (error == 0) {
2850 		MNT_ILOCK(mp);
2851 		mp->mnt_flag |= MNT_SUJ;
2852 		mp->mnt_flag &= ~MNT_SOFTDEP;
2853 		MNT_IUNLOCK(mp);
2854 		/*
2855 		 * Only validate the journal contents if the
2856 		 * filesystem is clean, otherwise we write the logs
2857 		 * but they'll never be used.  If the filesystem was
2858 		 * still dirty when we mounted it the journal is
2859 		 * invalid and a new journal can only be valid if it
2860 		 * starts from a clean mount.
2861 		 */
2862 		if (fs->fs_clean) {
2863 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2864 			ip->i_flags |= IN_MODIFIED;
2865 			ffs_update(vp, 1);
2866 		}
2867 	}
2868 	vput(vp);
2869 	return (error);
2870 }
2871 
2872 static void
2873 journal_unmount(ump)
2874 	struct ufsmount *ump;
2875 {
2876 
2877 	if (ump->softdep_jblocks)
2878 		jblocks_destroy(ump->softdep_jblocks);
2879 	ump->softdep_jblocks = NULL;
2880 }
2881 
2882 /*
2883  * Called when a journal record is ready to be written.  Space is allocated
2884  * and the journal entry is created when the journal is flushed to stable
2885  * store.
2886  */
2887 static void
2888 add_to_journal(wk)
2889 	struct worklist *wk;
2890 {
2891 	struct ufsmount *ump;
2892 
2893 	ump = VFSTOUFS(wk->wk_mp);
2894 	LOCK_OWNED(ump);
2895 	if (wk->wk_state & ONWORKLIST)
2896 		panic("add_to_journal: %s(0x%X) already on list",
2897 		    TYPENAME(wk->wk_type), wk->wk_state);
2898 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2899 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2900 		ump->softdep_jblocks->jb_age = ticks;
2901 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2902 	} else
2903 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2904 	ump->softdep_journal_tail = wk;
2905 	ump->softdep_on_journal += 1;
2906 }
2907 
2908 /*
2909  * Remove an arbitrary item for the journal worklist maintain the tail
2910  * pointer.  This happens when a new operation obviates the need to
2911  * journal an old operation.
2912  */
2913 static void
2914 remove_from_journal(wk)
2915 	struct worklist *wk;
2916 {
2917 	struct ufsmount *ump;
2918 
2919 	ump = VFSTOUFS(wk->wk_mp);
2920 	LOCK_OWNED(ump);
2921 #ifdef INVARIANTS
2922 	{
2923 		struct worklist *wkn;
2924 
2925 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2926 			if (wkn == wk)
2927 				break;
2928 		if (wkn == NULL)
2929 			panic("remove_from_journal: %p is not in journal", wk);
2930 	}
2931 #endif
2932 	/*
2933 	 * We emulate a TAILQ to save space in most structures which do not
2934 	 * require TAILQ semantics.  Here we must update the tail position
2935 	 * when removing the tail which is not the final entry. This works
2936 	 * only if the worklist linkage are at the beginning of the structure.
2937 	 */
2938 	if (ump->softdep_journal_tail == wk)
2939 		ump->softdep_journal_tail =
2940 		    (struct worklist *)wk->wk_list.le_prev;
2941 	WORKLIST_REMOVE(wk);
2942 	ump->softdep_on_journal -= 1;
2943 }
2944 
2945 /*
2946  * Check for journal space as well as dependency limits so the prelink
2947  * code can throttle both journaled and non-journaled filesystems.
2948  * Threshold is 0 for low and 1 for min.
2949  */
2950 static int
2951 journal_space(ump, thresh)
2952 	struct ufsmount *ump;
2953 	int thresh;
2954 {
2955 	struct jblocks *jblocks;
2956 	int limit, avail;
2957 
2958 	jblocks = ump->softdep_jblocks;
2959 	if (jblocks == NULL)
2960 		return (1);
2961 	/*
2962 	 * We use a tighter restriction here to prevent request_cleanup()
2963 	 * running in threads from running into locks we currently hold.
2964 	 * We have to be over the limit and our filesystem has to be
2965 	 * responsible for more than our share of that usage.
2966 	 */
2967 	limit = (max_softdeps / 10) * 9;
2968 	if (dep_current[D_INODEDEP] > limit &&
2969 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2970 		return (0);
2971 	if (thresh)
2972 		thresh = jblocks->jb_min;
2973 	else
2974 		thresh = jblocks->jb_low;
2975 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2976 	avail = jblocks->jb_free - avail;
2977 
2978 	return (avail > thresh);
2979 }
2980 
2981 static void
2982 journal_suspend(ump)
2983 	struct ufsmount *ump;
2984 {
2985 	struct jblocks *jblocks;
2986 	struct mount *mp;
2987 	bool set;
2988 
2989 	mp = UFSTOVFS(ump);
2990 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
2991 		return;
2992 
2993 	jblocks = ump->softdep_jblocks;
2994 	vfs_op_enter(mp);
2995 	set = false;
2996 	MNT_ILOCK(mp);
2997 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2998 		stat_journal_min++;
2999 		mp->mnt_kern_flag |= MNTK_SUSPEND;
3000 		mp->mnt_susp_owner = ump->softdep_flushtd;
3001 		set = true;
3002 	}
3003 	jblocks->jb_suspended = 1;
3004 	MNT_IUNLOCK(mp);
3005 	if (!set)
3006 		vfs_op_exit(mp);
3007 }
3008 
3009 static int
3010 journal_unsuspend(struct ufsmount *ump)
3011 {
3012 	struct jblocks *jblocks;
3013 	struct mount *mp;
3014 
3015 	mp = UFSTOVFS(ump);
3016 	jblocks = ump->softdep_jblocks;
3017 
3018 	if (jblocks != NULL && jblocks->jb_suspended &&
3019 	    journal_space(ump, jblocks->jb_min)) {
3020 		jblocks->jb_suspended = 0;
3021 		FREE_LOCK(ump);
3022 		mp->mnt_susp_owner = curthread;
3023 		vfs_write_resume(mp, 0);
3024 		ACQUIRE_LOCK(ump);
3025 		return (1);
3026 	}
3027 	return (0);
3028 }
3029 
3030 /*
3031  * Called before any allocation function to be certain that there is
3032  * sufficient space in the journal prior to creating any new records.
3033  * Since in the case of block allocation we may have multiple locked
3034  * buffers at the time of the actual allocation we can not block
3035  * when the journal records are created.  Doing so would create a deadlock
3036  * if any of these buffers needed to be flushed to reclaim space.  Instead
3037  * we require a sufficiently large amount of available space such that
3038  * each thread in the system could have passed this allocation check and
3039  * still have sufficient free space.  With 20% of a minimum journal size
3040  * of 1MB we have 6553 records available.
3041  */
3042 int
3043 softdep_prealloc(vp, waitok)
3044 	struct vnode *vp;
3045 	int waitok;
3046 {
3047 	struct ufsmount *ump;
3048 
3049 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3050 	    ("softdep_prealloc called on non-softdep filesystem"));
3051 	/*
3052 	 * Nothing to do if we are not running journaled soft updates.
3053 	 * If we currently hold the snapshot lock, we must avoid
3054 	 * handling other resources that could cause deadlock.  Do not
3055 	 * touch quotas vnode since it is typically recursed with
3056 	 * other vnode locks held.
3057 	 */
3058 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3059 	    (vp->v_vflag & VV_SYSTEM) != 0)
3060 		return (0);
3061 	ump = VFSTOUFS(vp->v_mount);
3062 	ACQUIRE_LOCK(ump);
3063 	if (journal_space(ump, 0)) {
3064 		FREE_LOCK(ump);
3065 		return (0);
3066 	}
3067 	stat_journal_low++;
3068 	FREE_LOCK(ump);
3069 	if (waitok == MNT_NOWAIT)
3070 		return (ENOSPC);
3071 	/*
3072 	 * Attempt to sync this vnode once to flush any journal
3073 	 * work attached to it.
3074 	 */
3075 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3076 		ffs_syncvnode(vp, waitok, 0);
3077 	ACQUIRE_LOCK(ump);
3078 	process_removes(vp);
3079 	process_truncates(vp);
3080 	if (journal_space(ump, 0) == 0) {
3081 		softdep_speedup(ump);
3082 		if (journal_space(ump, 1) == 0)
3083 			journal_suspend(ump);
3084 	}
3085 	FREE_LOCK(ump);
3086 
3087 	return (0);
3088 }
3089 
3090 /*
3091  * Before adjusting a link count on a vnode verify that we have sufficient
3092  * journal space.  If not, process operations that depend on the currently
3093  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3094  * and softdep flush threads can not acquire these locks to reclaim space.
3095  */
3096 static void
3097 softdep_prelink(dvp, vp)
3098 	struct vnode *dvp;
3099 	struct vnode *vp;
3100 {
3101 	struct ufsmount *ump;
3102 
3103 	ump = VFSTOUFS(dvp->v_mount);
3104 	LOCK_OWNED(ump);
3105 	/*
3106 	 * Nothing to do if we have sufficient journal space.
3107 	 * If we currently hold the snapshot lock, we must avoid
3108 	 * handling other resources that could cause deadlock.
3109 	 */
3110 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3111 		return;
3112 	stat_journal_low++;
3113 	FREE_LOCK(ump);
3114 	if (vp)
3115 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3116 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3117 	ACQUIRE_LOCK(ump);
3118 	/* Process vp before dvp as it may create .. removes. */
3119 	if (vp) {
3120 		process_removes(vp);
3121 		process_truncates(vp);
3122 	}
3123 	process_removes(dvp);
3124 	process_truncates(dvp);
3125 	softdep_speedup(ump);
3126 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3127 	if (journal_space(ump, 0) == 0) {
3128 		softdep_speedup(ump);
3129 		if (journal_space(ump, 1) == 0)
3130 			journal_suspend(ump);
3131 	}
3132 }
3133 
3134 static void
3135 jseg_write(ump, jseg, data)
3136 	struct ufsmount *ump;
3137 	struct jseg *jseg;
3138 	uint8_t *data;
3139 {
3140 	struct jsegrec *rec;
3141 
3142 	rec = (struct jsegrec *)data;
3143 	rec->jsr_seq = jseg->js_seq;
3144 	rec->jsr_oldest = jseg->js_oldseq;
3145 	rec->jsr_cnt = jseg->js_cnt;
3146 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3147 	rec->jsr_crc = 0;
3148 	rec->jsr_time = ump->um_fs->fs_mtime;
3149 }
3150 
3151 static inline void
3152 inoref_write(inoref, jseg, rec)
3153 	struct inoref *inoref;
3154 	struct jseg *jseg;
3155 	struct jrefrec *rec;
3156 {
3157 
3158 	inoref->if_jsegdep->jd_seg = jseg;
3159 	rec->jr_ino = inoref->if_ino;
3160 	rec->jr_parent = inoref->if_parent;
3161 	rec->jr_nlink = inoref->if_nlink;
3162 	rec->jr_mode = inoref->if_mode;
3163 	rec->jr_diroff = inoref->if_diroff;
3164 }
3165 
3166 static void
3167 jaddref_write(jaddref, jseg, data)
3168 	struct jaddref *jaddref;
3169 	struct jseg *jseg;
3170 	uint8_t *data;
3171 {
3172 	struct jrefrec *rec;
3173 
3174 	rec = (struct jrefrec *)data;
3175 	rec->jr_op = JOP_ADDREF;
3176 	inoref_write(&jaddref->ja_ref, jseg, rec);
3177 }
3178 
3179 static void
3180 jremref_write(jremref, jseg, data)
3181 	struct jremref *jremref;
3182 	struct jseg *jseg;
3183 	uint8_t *data;
3184 {
3185 	struct jrefrec *rec;
3186 
3187 	rec = (struct jrefrec *)data;
3188 	rec->jr_op = JOP_REMREF;
3189 	inoref_write(&jremref->jr_ref, jseg, rec);
3190 }
3191 
3192 static void
3193 jmvref_write(jmvref, jseg, data)
3194 	struct jmvref *jmvref;
3195 	struct jseg *jseg;
3196 	uint8_t *data;
3197 {
3198 	struct jmvrec *rec;
3199 
3200 	rec = (struct jmvrec *)data;
3201 	rec->jm_op = JOP_MVREF;
3202 	rec->jm_ino = jmvref->jm_ino;
3203 	rec->jm_parent = jmvref->jm_parent;
3204 	rec->jm_oldoff = jmvref->jm_oldoff;
3205 	rec->jm_newoff = jmvref->jm_newoff;
3206 }
3207 
3208 static void
3209 jnewblk_write(jnewblk, jseg, data)
3210 	struct jnewblk *jnewblk;
3211 	struct jseg *jseg;
3212 	uint8_t *data;
3213 {
3214 	struct jblkrec *rec;
3215 
3216 	jnewblk->jn_jsegdep->jd_seg = jseg;
3217 	rec = (struct jblkrec *)data;
3218 	rec->jb_op = JOP_NEWBLK;
3219 	rec->jb_ino = jnewblk->jn_ino;
3220 	rec->jb_blkno = jnewblk->jn_blkno;
3221 	rec->jb_lbn = jnewblk->jn_lbn;
3222 	rec->jb_frags = jnewblk->jn_frags;
3223 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3224 }
3225 
3226 static void
3227 jfreeblk_write(jfreeblk, jseg, data)
3228 	struct jfreeblk *jfreeblk;
3229 	struct jseg *jseg;
3230 	uint8_t *data;
3231 {
3232 	struct jblkrec *rec;
3233 
3234 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3235 	rec = (struct jblkrec *)data;
3236 	rec->jb_op = JOP_FREEBLK;
3237 	rec->jb_ino = jfreeblk->jf_ino;
3238 	rec->jb_blkno = jfreeblk->jf_blkno;
3239 	rec->jb_lbn = jfreeblk->jf_lbn;
3240 	rec->jb_frags = jfreeblk->jf_frags;
3241 	rec->jb_oldfrags = 0;
3242 }
3243 
3244 static void
3245 jfreefrag_write(jfreefrag, jseg, data)
3246 	struct jfreefrag *jfreefrag;
3247 	struct jseg *jseg;
3248 	uint8_t *data;
3249 {
3250 	struct jblkrec *rec;
3251 
3252 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3253 	rec = (struct jblkrec *)data;
3254 	rec->jb_op = JOP_FREEBLK;
3255 	rec->jb_ino = jfreefrag->fr_ino;
3256 	rec->jb_blkno = jfreefrag->fr_blkno;
3257 	rec->jb_lbn = jfreefrag->fr_lbn;
3258 	rec->jb_frags = jfreefrag->fr_frags;
3259 	rec->jb_oldfrags = 0;
3260 }
3261 
3262 static void
3263 jtrunc_write(jtrunc, jseg, data)
3264 	struct jtrunc *jtrunc;
3265 	struct jseg *jseg;
3266 	uint8_t *data;
3267 {
3268 	struct jtrncrec *rec;
3269 
3270 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3271 	rec = (struct jtrncrec *)data;
3272 	rec->jt_op = JOP_TRUNC;
3273 	rec->jt_ino = jtrunc->jt_ino;
3274 	rec->jt_size = jtrunc->jt_size;
3275 	rec->jt_extsize = jtrunc->jt_extsize;
3276 }
3277 
3278 static void
3279 jfsync_write(jfsync, jseg, data)
3280 	struct jfsync *jfsync;
3281 	struct jseg *jseg;
3282 	uint8_t *data;
3283 {
3284 	struct jtrncrec *rec;
3285 
3286 	rec = (struct jtrncrec *)data;
3287 	rec->jt_op = JOP_SYNC;
3288 	rec->jt_ino = jfsync->jfs_ino;
3289 	rec->jt_size = jfsync->jfs_size;
3290 	rec->jt_extsize = jfsync->jfs_extsize;
3291 }
3292 
3293 static void
3294 softdep_flushjournal(mp)
3295 	struct mount *mp;
3296 {
3297 	struct jblocks *jblocks;
3298 	struct ufsmount *ump;
3299 
3300 	if (MOUNTEDSUJ(mp) == 0)
3301 		return;
3302 	ump = VFSTOUFS(mp);
3303 	jblocks = ump->softdep_jblocks;
3304 	ACQUIRE_LOCK(ump);
3305 	while (ump->softdep_on_journal) {
3306 		jblocks->jb_needseg = 1;
3307 		softdep_process_journal(mp, NULL, MNT_WAIT);
3308 	}
3309 	FREE_LOCK(ump);
3310 }
3311 
3312 static void softdep_synchronize_completed(struct bio *);
3313 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3314 
3315 static void
3316 softdep_synchronize_completed(bp)
3317         struct bio *bp;
3318 {
3319 	struct jseg *oldest;
3320 	struct jseg *jseg;
3321 	struct ufsmount *ump;
3322 
3323 	/*
3324 	 * caller1 marks the last segment written before we issued the
3325 	 * synchronize cache.
3326 	 */
3327 	jseg = bp->bio_caller1;
3328 	if (jseg == NULL) {
3329 		g_destroy_bio(bp);
3330 		return;
3331 	}
3332 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3333 	ACQUIRE_LOCK(ump);
3334 	oldest = NULL;
3335 	/*
3336 	 * Mark all the journal entries waiting on the synchronize cache
3337 	 * as completed so they may continue on.
3338 	 */
3339 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3340 		jseg->js_state |= COMPLETE;
3341 		oldest = jseg;
3342 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3343 	}
3344 	/*
3345 	 * Restart deferred journal entry processing from the oldest
3346 	 * completed jseg.
3347 	 */
3348 	if (oldest)
3349 		complete_jsegs(oldest);
3350 
3351 	FREE_LOCK(ump);
3352 	g_destroy_bio(bp);
3353 }
3354 
3355 /*
3356  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3357  * barriers.  The journal must be written prior to any blocks that depend
3358  * on it and the journal can not be released until the blocks have be
3359  * written.  This code handles both barriers simultaneously.
3360  */
3361 static void
3362 softdep_synchronize(bp, ump, caller1)
3363 	struct bio *bp;
3364 	struct ufsmount *ump;
3365 	void *caller1;
3366 {
3367 
3368 	bp->bio_cmd = BIO_FLUSH;
3369 	bp->bio_flags |= BIO_ORDERED;
3370 	bp->bio_data = NULL;
3371 	bp->bio_offset = ump->um_cp->provider->mediasize;
3372 	bp->bio_length = 0;
3373 	bp->bio_done = softdep_synchronize_completed;
3374 	bp->bio_caller1 = caller1;
3375 	g_io_request(bp, ump->um_cp);
3376 }
3377 
3378 /*
3379  * Flush some journal records to disk.
3380  */
3381 static void
3382 softdep_process_journal(mp, needwk, flags)
3383 	struct mount *mp;
3384 	struct worklist *needwk;
3385 	int flags;
3386 {
3387 	struct jblocks *jblocks;
3388 	struct ufsmount *ump;
3389 	struct worklist *wk;
3390 	struct jseg *jseg;
3391 	struct buf *bp;
3392 	struct bio *bio;
3393 	uint8_t *data;
3394 	struct fs *fs;
3395 	int shouldflush;
3396 	int segwritten;
3397 	int jrecmin;	/* Minimum records per block. */
3398 	int jrecmax;	/* Maximum records per block. */
3399 	int size;
3400 	int cnt;
3401 	int off;
3402 	int devbsize;
3403 
3404 	if (MOUNTEDSUJ(mp) == 0)
3405 		return;
3406 	shouldflush = softdep_flushcache;
3407 	bio = NULL;
3408 	jseg = NULL;
3409 	ump = VFSTOUFS(mp);
3410 	LOCK_OWNED(ump);
3411 	fs = ump->um_fs;
3412 	jblocks = ump->softdep_jblocks;
3413 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3414 	/*
3415 	 * We write anywhere between a disk block and fs block.  The upper
3416 	 * bound is picked to prevent buffer cache fragmentation and limit
3417 	 * processing time per I/O.
3418 	 */
3419 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3420 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3421 	segwritten = 0;
3422 	for (;;) {
3423 		cnt = ump->softdep_on_journal;
3424 		/*
3425 		 * Criteria for writing a segment:
3426 		 * 1) We have a full block.
3427 		 * 2) We're called from jwait() and haven't found the
3428 		 *    journal item yet.
3429 		 * 3) Always write if needseg is set.
3430 		 * 4) If we are called from process_worklist and have
3431 		 *    not yet written anything we write a partial block
3432 		 *    to enforce a 1 second maximum latency on journal
3433 		 *    entries.
3434 		 */
3435 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3436 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3437 			break;
3438 		cnt++;
3439 		/*
3440 		 * Verify some free journal space.  softdep_prealloc() should
3441 		 * guarantee that we don't run out so this is indicative of
3442 		 * a problem with the flow control.  Try to recover
3443 		 * gracefully in any event.
3444 		 */
3445 		while (jblocks->jb_free == 0) {
3446 			if (flags != MNT_WAIT)
3447 				break;
3448 			printf("softdep: Out of journal space!\n");
3449 			softdep_speedup(ump);
3450 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3451 		}
3452 		FREE_LOCK(ump);
3453 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3454 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3455 		LIST_INIT(&jseg->js_entries);
3456 		LIST_INIT(&jseg->js_indirs);
3457 		jseg->js_state = ATTACHED;
3458 		if (shouldflush == 0)
3459 			jseg->js_state |= COMPLETE;
3460 		else if (bio == NULL)
3461 			bio = g_alloc_bio();
3462 		jseg->js_jblocks = jblocks;
3463 		bp = geteblk(fs->fs_bsize, 0);
3464 		ACQUIRE_LOCK(ump);
3465 		/*
3466 		 * If there was a race while we were allocating the block
3467 		 * and jseg the entry we care about was likely written.
3468 		 * We bail out in both the WAIT and NOWAIT case and assume
3469 		 * the caller will loop if the entry it cares about is
3470 		 * not written.
3471 		 */
3472 		cnt = ump->softdep_on_journal;
3473 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3474 			bp->b_flags |= B_INVAL | B_NOCACHE;
3475 			WORKITEM_FREE(jseg, D_JSEG);
3476 			FREE_LOCK(ump);
3477 			brelse(bp);
3478 			ACQUIRE_LOCK(ump);
3479 			break;
3480 		}
3481 		/*
3482 		 * Calculate the disk block size required for the available
3483 		 * records rounded to the min size.
3484 		 */
3485 		if (cnt == 0)
3486 			size = devbsize;
3487 		else if (cnt < jrecmax)
3488 			size = howmany(cnt, jrecmin) * devbsize;
3489 		else
3490 			size = fs->fs_bsize;
3491 		/*
3492 		 * Allocate a disk block for this journal data and account
3493 		 * for truncation of the requested size if enough contiguous
3494 		 * space was not available.
3495 		 */
3496 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3497 		bp->b_lblkno = bp->b_blkno;
3498 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3499 		bp->b_bcount = size;
3500 		bp->b_flags &= ~B_INVAL;
3501 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3502 		/*
3503 		 * Initialize our jseg with cnt records.  Assign the next
3504 		 * sequence number to it and link it in-order.
3505 		 */
3506 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3507 		jseg->js_buf = bp;
3508 		jseg->js_cnt = cnt;
3509 		jseg->js_refs = cnt + 1;	/* Self ref. */
3510 		jseg->js_size = size;
3511 		jseg->js_seq = jblocks->jb_nextseq++;
3512 		if (jblocks->jb_oldestseg == NULL)
3513 			jblocks->jb_oldestseg = jseg;
3514 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3515 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3516 		if (jblocks->jb_writeseg == NULL)
3517 			jblocks->jb_writeseg = jseg;
3518 		/*
3519 		 * Start filling in records from the pending list.
3520 		 */
3521 		data = bp->b_data;
3522 		off = 0;
3523 
3524 		/*
3525 		 * Always put a header on the first block.
3526 		 * XXX As with below, there might not be a chance to get
3527 		 * into the loop.  Ensure that something valid is written.
3528 		 */
3529 		jseg_write(ump, jseg, data);
3530 		off += JREC_SIZE;
3531 		data = bp->b_data + off;
3532 
3533 		/*
3534 		 * XXX Something is wrong here.  There's no work to do,
3535 		 * but we need to perform and I/O and allow it to complete
3536 		 * anyways.
3537 		 */
3538 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3539 			stat_emptyjblocks++;
3540 
3541 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3542 		    != NULL) {
3543 			if (cnt == 0)
3544 				break;
3545 			/* Place a segment header on every device block. */
3546 			if ((off % devbsize) == 0) {
3547 				jseg_write(ump, jseg, data);
3548 				off += JREC_SIZE;
3549 				data = bp->b_data + off;
3550 			}
3551 			if (wk == needwk)
3552 				needwk = NULL;
3553 			remove_from_journal(wk);
3554 			wk->wk_state |= INPROGRESS;
3555 			WORKLIST_INSERT(&jseg->js_entries, wk);
3556 			switch (wk->wk_type) {
3557 			case D_JADDREF:
3558 				jaddref_write(WK_JADDREF(wk), jseg, data);
3559 				break;
3560 			case D_JREMREF:
3561 				jremref_write(WK_JREMREF(wk), jseg, data);
3562 				break;
3563 			case D_JMVREF:
3564 				jmvref_write(WK_JMVREF(wk), jseg, data);
3565 				break;
3566 			case D_JNEWBLK:
3567 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3568 				break;
3569 			case D_JFREEBLK:
3570 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3571 				break;
3572 			case D_JFREEFRAG:
3573 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3574 				break;
3575 			case D_JTRUNC:
3576 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3577 				break;
3578 			case D_JFSYNC:
3579 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3580 				break;
3581 			default:
3582 				panic("process_journal: Unknown type %s",
3583 				    TYPENAME(wk->wk_type));
3584 				/* NOTREACHED */
3585 			}
3586 			off += JREC_SIZE;
3587 			data = bp->b_data + off;
3588 			cnt--;
3589 		}
3590 
3591 		/* Clear any remaining space so we don't leak kernel data */
3592 		if (size > off)
3593 			bzero(data, size - off);
3594 
3595 		/*
3596 		 * Write this one buffer and continue.
3597 		 */
3598 		segwritten = 1;
3599 		jblocks->jb_needseg = 0;
3600 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3601 		FREE_LOCK(ump);
3602 		pbgetvp(ump->um_devvp, bp);
3603 		/*
3604 		 * We only do the blocking wait once we find the journal
3605 		 * entry we're looking for.
3606 		 */
3607 		if (needwk == NULL && flags == MNT_WAIT)
3608 			bwrite(bp);
3609 		else
3610 			bawrite(bp);
3611 		ACQUIRE_LOCK(ump);
3612 	}
3613 	/*
3614 	 * If we wrote a segment issue a synchronize cache so the journal
3615 	 * is reflected on disk before the data is written.  Since reclaiming
3616 	 * journal space also requires writing a journal record this
3617 	 * process also enforces a barrier before reclamation.
3618 	 */
3619 	if (segwritten && shouldflush) {
3620 		softdep_synchronize(bio, ump,
3621 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3622 	} else if (bio)
3623 		g_destroy_bio(bio);
3624 	/*
3625 	 * If we've suspended the filesystem because we ran out of journal
3626 	 * space either try to sync it here to make some progress or
3627 	 * unsuspend it if we already have.
3628 	 */
3629 	if (flags == 0 && jblocks->jb_suspended) {
3630 		if (journal_unsuspend(ump))
3631 			return;
3632 		FREE_LOCK(ump);
3633 		VFS_SYNC(mp, MNT_NOWAIT);
3634 		ffs_sbupdate(ump, MNT_WAIT, 0);
3635 		ACQUIRE_LOCK(ump);
3636 	}
3637 }
3638 
3639 /*
3640  * Complete a jseg, allowing all dependencies awaiting journal writes
3641  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3642  * structures so that the journal segment can be freed to reclaim space.
3643  */
3644 static void
3645 complete_jseg(jseg)
3646 	struct jseg *jseg;
3647 {
3648 	struct worklist *wk;
3649 	struct jmvref *jmvref;
3650 #ifdef INVARIANTS
3651 	int i = 0;
3652 #endif
3653 
3654 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3655 		WORKLIST_REMOVE(wk);
3656 		wk->wk_state &= ~INPROGRESS;
3657 		wk->wk_state |= COMPLETE;
3658 		KASSERT(i++ < jseg->js_cnt,
3659 		    ("handle_written_jseg: overflow %d >= %d",
3660 		    i - 1, jseg->js_cnt));
3661 		switch (wk->wk_type) {
3662 		case D_JADDREF:
3663 			handle_written_jaddref(WK_JADDREF(wk));
3664 			break;
3665 		case D_JREMREF:
3666 			handle_written_jremref(WK_JREMREF(wk));
3667 			break;
3668 		case D_JMVREF:
3669 			rele_jseg(jseg);	/* No jsegdep. */
3670 			jmvref = WK_JMVREF(wk);
3671 			LIST_REMOVE(jmvref, jm_deps);
3672 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3673 				free_pagedep(jmvref->jm_pagedep);
3674 			WORKITEM_FREE(jmvref, D_JMVREF);
3675 			break;
3676 		case D_JNEWBLK:
3677 			handle_written_jnewblk(WK_JNEWBLK(wk));
3678 			break;
3679 		case D_JFREEBLK:
3680 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3681 			break;
3682 		case D_JTRUNC:
3683 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3684 			break;
3685 		case D_JFSYNC:
3686 			rele_jseg(jseg);	/* No jsegdep. */
3687 			WORKITEM_FREE(wk, D_JFSYNC);
3688 			break;
3689 		case D_JFREEFRAG:
3690 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3691 			break;
3692 		default:
3693 			panic("handle_written_jseg: Unknown type %s",
3694 			    TYPENAME(wk->wk_type));
3695 			/* NOTREACHED */
3696 		}
3697 	}
3698 	/* Release the self reference so the structure may be freed. */
3699 	rele_jseg(jseg);
3700 }
3701 
3702 /*
3703  * Determine which jsegs are ready for completion processing.  Waits for
3704  * synchronize cache to complete as well as forcing in-order completion
3705  * of journal entries.
3706  */
3707 static void
3708 complete_jsegs(jseg)
3709 	struct jseg *jseg;
3710 {
3711 	struct jblocks *jblocks;
3712 	struct jseg *jsegn;
3713 
3714 	jblocks = jseg->js_jblocks;
3715 	/*
3716 	 * Don't allow out of order completions.  If this isn't the first
3717 	 * block wait for it to write before we're done.
3718 	 */
3719 	if (jseg != jblocks->jb_writeseg)
3720 		return;
3721 	/* Iterate through available jsegs processing their entries. */
3722 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3723 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3724 		jsegn = TAILQ_NEXT(jseg, js_next);
3725 		complete_jseg(jseg);
3726 		jseg = jsegn;
3727 	}
3728 	jblocks->jb_writeseg = jseg;
3729 	/*
3730 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3731 	 */
3732 	free_jsegs(jblocks);
3733 }
3734 
3735 /*
3736  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3737  * the final completions.
3738  */
3739 static void
3740 handle_written_jseg(jseg, bp)
3741 	struct jseg *jseg;
3742 	struct buf *bp;
3743 {
3744 
3745 	if (jseg->js_refs == 0)
3746 		panic("handle_written_jseg: No self-reference on %p", jseg);
3747 	jseg->js_state |= DEPCOMPLETE;
3748 	/*
3749 	 * We'll never need this buffer again, set flags so it will be
3750 	 * discarded.
3751 	 */
3752 	bp->b_flags |= B_INVAL | B_NOCACHE;
3753 	pbrelvp(bp);
3754 	complete_jsegs(jseg);
3755 }
3756 
3757 static inline struct jsegdep *
3758 inoref_jseg(inoref)
3759 	struct inoref *inoref;
3760 {
3761 	struct jsegdep *jsegdep;
3762 
3763 	jsegdep = inoref->if_jsegdep;
3764 	inoref->if_jsegdep = NULL;
3765 
3766 	return (jsegdep);
3767 }
3768 
3769 /*
3770  * Called once a jremref has made it to stable store.  The jremref is marked
3771  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3772  * for the jremref to complete will be awoken by free_jremref.
3773  */
3774 static void
3775 handle_written_jremref(jremref)
3776 	struct jremref *jremref;
3777 {
3778 	struct inodedep *inodedep;
3779 	struct jsegdep *jsegdep;
3780 	struct dirrem *dirrem;
3781 
3782 	/* Grab the jsegdep. */
3783 	jsegdep = inoref_jseg(&jremref->jr_ref);
3784 	/*
3785 	 * Remove us from the inoref list.
3786 	 */
3787 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3788 	    0, &inodedep) == 0)
3789 		panic("handle_written_jremref: Lost inodedep");
3790 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3791 	/*
3792 	 * Complete the dirrem.
3793 	 */
3794 	dirrem = jremref->jr_dirrem;
3795 	jremref->jr_dirrem = NULL;
3796 	LIST_REMOVE(jremref, jr_deps);
3797 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3798 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3799 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3800 	    (dirrem->dm_state & COMPLETE) != 0)
3801 		add_to_worklist(&dirrem->dm_list, 0);
3802 	free_jremref(jremref);
3803 }
3804 
3805 /*
3806  * Called once a jaddref has made it to stable store.  The dependency is
3807  * marked complete and any dependent structures are added to the inode
3808  * bufwait list to be completed as soon as it is written.  If a bitmap write
3809  * depends on this entry we move the inode into the inodedephd of the
3810  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3811  */
3812 static void
3813 handle_written_jaddref(jaddref)
3814 	struct jaddref *jaddref;
3815 {
3816 	struct jsegdep *jsegdep;
3817 	struct inodedep *inodedep;
3818 	struct diradd *diradd;
3819 	struct mkdir *mkdir;
3820 
3821 	/* Grab the jsegdep. */
3822 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3823 	mkdir = NULL;
3824 	diradd = NULL;
3825 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3826 	    0, &inodedep) == 0)
3827 		panic("handle_written_jaddref: Lost inodedep.");
3828 	if (jaddref->ja_diradd == NULL)
3829 		panic("handle_written_jaddref: No dependency");
3830 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3831 		diradd = jaddref->ja_diradd;
3832 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3833 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3834 		mkdir = jaddref->ja_mkdir;
3835 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3836 	} else if (jaddref->ja_state & MKDIR_BODY)
3837 		mkdir = jaddref->ja_mkdir;
3838 	else
3839 		panic("handle_written_jaddref: Unknown dependency %p",
3840 		    jaddref->ja_diradd);
3841 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3842 	/*
3843 	 * Remove us from the inode list.
3844 	 */
3845 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3846 	/*
3847 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3848 	 */
3849 	if (mkdir) {
3850 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3851 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3852 		    TYPENAME(mkdir->md_list.wk_type)));
3853 		mkdir->md_jaddref = NULL;
3854 		diradd = mkdir->md_diradd;
3855 		mkdir->md_state |= DEPCOMPLETE;
3856 		complete_mkdir(mkdir);
3857 	}
3858 	jwork_insert(&diradd->da_jwork, jsegdep);
3859 	if (jaddref->ja_state & NEWBLOCK) {
3860 		inodedep->id_state |= ONDEPLIST;
3861 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3862 		    inodedep, id_deps);
3863 	}
3864 	free_jaddref(jaddref);
3865 }
3866 
3867 /*
3868  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3869  * is placed in the bmsafemap to await notification of a written bitmap.  If
3870  * the operation was canceled we add the segdep to the appropriate
3871  * dependency to free the journal space once the canceling operation
3872  * completes.
3873  */
3874 static void
3875 handle_written_jnewblk(jnewblk)
3876 	struct jnewblk *jnewblk;
3877 {
3878 	struct bmsafemap *bmsafemap;
3879 	struct freefrag *freefrag;
3880 	struct freework *freework;
3881 	struct jsegdep *jsegdep;
3882 	struct newblk *newblk;
3883 
3884 	/* Grab the jsegdep. */
3885 	jsegdep = jnewblk->jn_jsegdep;
3886 	jnewblk->jn_jsegdep = NULL;
3887 	if (jnewblk->jn_dep == NULL)
3888 		panic("handle_written_jnewblk: No dependency for the segdep.");
3889 	switch (jnewblk->jn_dep->wk_type) {
3890 	case D_NEWBLK:
3891 	case D_ALLOCDIRECT:
3892 	case D_ALLOCINDIR:
3893 		/*
3894 		 * Add the written block to the bmsafemap so it can
3895 		 * be notified when the bitmap is on disk.
3896 		 */
3897 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3898 		newblk->nb_jnewblk = NULL;
3899 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3900 			bmsafemap = newblk->nb_bmsafemap;
3901 			newblk->nb_state |= ONDEPLIST;
3902 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3903 			    nb_deps);
3904 		}
3905 		jwork_insert(&newblk->nb_jwork, jsegdep);
3906 		break;
3907 	case D_FREEFRAG:
3908 		/*
3909 		 * A newblock being removed by a freefrag when replaced by
3910 		 * frag extension.
3911 		 */
3912 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3913 		freefrag->ff_jdep = NULL;
3914 		jwork_insert(&freefrag->ff_jwork, jsegdep);
3915 		break;
3916 	case D_FREEWORK:
3917 		/*
3918 		 * A direct block was removed by truncate.
3919 		 */
3920 		freework = WK_FREEWORK(jnewblk->jn_dep);
3921 		freework->fw_jnewblk = NULL;
3922 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3923 		break;
3924 	default:
3925 		panic("handle_written_jnewblk: Unknown type %d.",
3926 		    jnewblk->jn_dep->wk_type);
3927 	}
3928 	jnewblk->jn_dep = NULL;
3929 	free_jnewblk(jnewblk);
3930 }
3931 
3932 /*
3933  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3934  * an in-flight allocation that has not yet been committed.  Divorce us
3935  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3936  * to the worklist.
3937  */
3938 static void
3939 cancel_jfreefrag(jfreefrag)
3940 	struct jfreefrag *jfreefrag;
3941 {
3942 	struct freefrag *freefrag;
3943 
3944 	if (jfreefrag->fr_jsegdep) {
3945 		free_jsegdep(jfreefrag->fr_jsegdep);
3946 		jfreefrag->fr_jsegdep = NULL;
3947 	}
3948 	freefrag = jfreefrag->fr_freefrag;
3949 	jfreefrag->fr_freefrag = NULL;
3950 	free_jfreefrag(jfreefrag);
3951 	freefrag->ff_state |= DEPCOMPLETE;
3952 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3953 }
3954 
3955 /*
3956  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3957  */
3958 static void
3959 free_jfreefrag(jfreefrag)
3960 	struct jfreefrag *jfreefrag;
3961 {
3962 
3963 	if (jfreefrag->fr_state & INPROGRESS)
3964 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3965 	else if (jfreefrag->fr_state & ONWORKLIST)
3966 		remove_from_journal(&jfreefrag->fr_list);
3967 	if (jfreefrag->fr_freefrag != NULL)
3968 		panic("free_jfreefrag:  Still attached to a freefrag.");
3969 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3970 }
3971 
3972 /*
3973  * Called when the journal write for a jfreefrag completes.  The parent
3974  * freefrag is added to the worklist if this completes its dependencies.
3975  */
3976 static void
3977 handle_written_jfreefrag(jfreefrag)
3978 	struct jfreefrag *jfreefrag;
3979 {
3980 	struct jsegdep *jsegdep;
3981 	struct freefrag *freefrag;
3982 
3983 	/* Grab the jsegdep. */
3984 	jsegdep = jfreefrag->fr_jsegdep;
3985 	jfreefrag->fr_jsegdep = NULL;
3986 	freefrag = jfreefrag->fr_freefrag;
3987 	if (freefrag == NULL)
3988 		panic("handle_written_jfreefrag: No freefrag.");
3989 	freefrag->ff_state |= DEPCOMPLETE;
3990 	freefrag->ff_jdep = NULL;
3991 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3992 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3993 		add_to_worklist(&freefrag->ff_list, 0);
3994 	jfreefrag->fr_freefrag = NULL;
3995 	free_jfreefrag(jfreefrag);
3996 }
3997 
3998 /*
3999  * Called when the journal write for a jfreeblk completes.  The jfreeblk
4000  * is removed from the freeblks list of pending journal writes and the
4001  * jsegdep is moved to the freeblks jwork to be completed when all blocks
4002  * have been reclaimed.
4003  */
4004 static void
4005 handle_written_jblkdep(jblkdep)
4006 	struct jblkdep *jblkdep;
4007 {
4008 	struct freeblks *freeblks;
4009 	struct jsegdep *jsegdep;
4010 
4011 	/* Grab the jsegdep. */
4012 	jsegdep = jblkdep->jb_jsegdep;
4013 	jblkdep->jb_jsegdep = NULL;
4014 	freeblks = jblkdep->jb_freeblks;
4015 	LIST_REMOVE(jblkdep, jb_deps);
4016 	jwork_insert(&freeblks->fb_jwork, jsegdep);
4017 	/*
4018 	 * If the freeblks is all journaled, we can add it to the worklist.
4019 	 */
4020 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4021 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4022 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4023 
4024 	free_jblkdep(jblkdep);
4025 }
4026 
4027 static struct jsegdep *
4028 newjsegdep(struct worklist *wk)
4029 {
4030 	struct jsegdep *jsegdep;
4031 
4032 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4033 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4034 	jsegdep->jd_seg = NULL;
4035 
4036 	return (jsegdep);
4037 }
4038 
4039 static struct jmvref *
4040 newjmvref(dp, ino, oldoff, newoff)
4041 	struct inode *dp;
4042 	ino_t ino;
4043 	off_t oldoff;
4044 	off_t newoff;
4045 {
4046 	struct jmvref *jmvref;
4047 
4048 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4049 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4050 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4051 	jmvref->jm_parent = dp->i_number;
4052 	jmvref->jm_ino = ino;
4053 	jmvref->jm_oldoff = oldoff;
4054 	jmvref->jm_newoff = newoff;
4055 
4056 	return (jmvref);
4057 }
4058 
4059 /*
4060  * Allocate a new jremref that tracks the removal of ip from dp with the
4061  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4062  * DEPCOMPLETE as we have all the information required for the journal write
4063  * and the directory has already been removed from the buffer.  The caller
4064  * is responsible for linking the jremref into the pagedep and adding it
4065  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4066  * a DOTDOT addition so handle_workitem_remove() can properly assign
4067  * the jsegdep when we're done.
4068  */
4069 static struct jremref *
4070 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4071     off_t diroff, nlink_t nlink)
4072 {
4073 	struct jremref *jremref;
4074 
4075 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4076 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4077 	jremref->jr_state = ATTACHED;
4078 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4079 	   nlink, ip->i_mode);
4080 	jremref->jr_dirrem = dirrem;
4081 
4082 	return (jremref);
4083 }
4084 
4085 static inline void
4086 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4087     nlink_t nlink, uint16_t mode)
4088 {
4089 
4090 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4091 	inoref->if_diroff = diroff;
4092 	inoref->if_ino = ino;
4093 	inoref->if_parent = parent;
4094 	inoref->if_nlink = nlink;
4095 	inoref->if_mode = mode;
4096 }
4097 
4098 /*
4099  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4100  * directory offset may not be known until later.  The caller is responsible
4101  * adding the entry to the journal when this information is available.  nlink
4102  * should be the link count prior to the addition and mode is only required
4103  * to have the correct FMT.
4104  */
4105 static struct jaddref *
4106 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4107     uint16_t mode)
4108 {
4109 	struct jaddref *jaddref;
4110 
4111 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4112 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4113 	jaddref->ja_state = ATTACHED;
4114 	jaddref->ja_mkdir = NULL;
4115 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4116 
4117 	return (jaddref);
4118 }
4119 
4120 /*
4121  * Create a new free dependency for a freework.  The caller is responsible
4122  * for adjusting the reference count when it has the lock held.  The freedep
4123  * will track an outstanding bitmap write that will ultimately clear the
4124  * freework to continue.
4125  */
4126 static struct freedep *
4127 newfreedep(struct freework *freework)
4128 {
4129 	struct freedep *freedep;
4130 
4131 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4132 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4133 	freedep->fd_freework = freework;
4134 
4135 	return (freedep);
4136 }
4137 
4138 /*
4139  * Free a freedep structure once the buffer it is linked to is written.  If
4140  * this is the last reference to the freework schedule it for completion.
4141  */
4142 static void
4143 free_freedep(freedep)
4144 	struct freedep *freedep;
4145 {
4146 	struct freework *freework;
4147 
4148 	freework = freedep->fd_freework;
4149 	freework->fw_freeblks->fb_cgwait--;
4150 	if (--freework->fw_ref == 0)
4151 		freework_enqueue(freework);
4152 	WORKITEM_FREE(freedep, D_FREEDEP);
4153 }
4154 
4155 /*
4156  * Allocate a new freework structure that may be a level in an indirect
4157  * when parent is not NULL or a top level block when it is.  The top level
4158  * freework structures are allocated without the per-filesystem lock held
4159  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4160  */
4161 static struct freework *
4162 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4163 	struct ufsmount *ump;
4164 	struct freeblks *freeblks;
4165 	struct freework *parent;
4166 	ufs_lbn_t lbn;
4167 	ufs2_daddr_t nb;
4168 	int frags;
4169 	int off;
4170 	int journal;
4171 {
4172 	struct freework *freework;
4173 
4174 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4175 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4176 	freework->fw_state = ATTACHED;
4177 	freework->fw_jnewblk = NULL;
4178 	freework->fw_freeblks = freeblks;
4179 	freework->fw_parent = parent;
4180 	freework->fw_lbn = lbn;
4181 	freework->fw_blkno = nb;
4182 	freework->fw_frags = frags;
4183 	freework->fw_indir = NULL;
4184 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4185 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4186 	freework->fw_start = freework->fw_off = off;
4187 	if (journal)
4188 		newjfreeblk(freeblks, lbn, nb, frags);
4189 	if (parent == NULL) {
4190 		ACQUIRE_LOCK(ump);
4191 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4192 		freeblks->fb_ref++;
4193 		FREE_LOCK(ump);
4194 	}
4195 
4196 	return (freework);
4197 }
4198 
4199 /*
4200  * Eliminate a jfreeblk for a block that does not need journaling.
4201  */
4202 static void
4203 cancel_jfreeblk(freeblks, blkno)
4204 	struct freeblks *freeblks;
4205 	ufs2_daddr_t blkno;
4206 {
4207 	struct jfreeblk *jfreeblk;
4208 	struct jblkdep *jblkdep;
4209 
4210 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4211 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4212 			continue;
4213 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4214 		if (jfreeblk->jf_blkno == blkno)
4215 			break;
4216 	}
4217 	if (jblkdep == NULL)
4218 		return;
4219 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4220 	free_jsegdep(jblkdep->jb_jsegdep);
4221 	LIST_REMOVE(jblkdep, jb_deps);
4222 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4223 }
4224 
4225 /*
4226  * Allocate a new jfreeblk to journal top level block pointer when truncating
4227  * a file.  The caller must add this to the worklist when the per-filesystem
4228  * lock is held.
4229  */
4230 static struct jfreeblk *
4231 newjfreeblk(freeblks, lbn, blkno, frags)
4232 	struct freeblks *freeblks;
4233 	ufs_lbn_t lbn;
4234 	ufs2_daddr_t blkno;
4235 	int frags;
4236 {
4237 	struct jfreeblk *jfreeblk;
4238 
4239 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4240 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4241 	    freeblks->fb_list.wk_mp);
4242 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4243 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4244 	jfreeblk->jf_ino = freeblks->fb_inum;
4245 	jfreeblk->jf_lbn = lbn;
4246 	jfreeblk->jf_blkno = blkno;
4247 	jfreeblk->jf_frags = frags;
4248 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4249 
4250 	return (jfreeblk);
4251 }
4252 
4253 /*
4254  * The journal is only prepared to handle full-size block numbers, so we
4255  * have to adjust the record to reflect the change to a full-size block.
4256  * For example, suppose we have a block made up of fragments 8-15 and
4257  * want to free its last two fragments. We are given a request that says:
4258  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4259  * where frags are the number of fragments to free and oldfrags are the
4260  * number of fragments to keep. To block align it, we have to change it to
4261  * have a valid full-size blkno, so it becomes:
4262  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4263  */
4264 static void
4265 adjust_newfreework(freeblks, frag_offset)
4266 	struct freeblks *freeblks;
4267 	int frag_offset;
4268 {
4269 	struct jfreeblk *jfreeblk;
4270 
4271 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4272 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4273 	    ("adjust_newfreework: Missing freeblks dependency"));
4274 
4275 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4276 	jfreeblk->jf_blkno -= frag_offset;
4277 	jfreeblk->jf_frags += frag_offset;
4278 }
4279 
4280 /*
4281  * Allocate a new jtrunc to track a partial truncation.
4282  */
4283 static struct jtrunc *
4284 newjtrunc(freeblks, size, extsize)
4285 	struct freeblks *freeblks;
4286 	off_t size;
4287 	int extsize;
4288 {
4289 	struct jtrunc *jtrunc;
4290 
4291 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4292 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4293 	    freeblks->fb_list.wk_mp);
4294 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4295 	jtrunc->jt_dep.jb_freeblks = freeblks;
4296 	jtrunc->jt_ino = freeblks->fb_inum;
4297 	jtrunc->jt_size = size;
4298 	jtrunc->jt_extsize = extsize;
4299 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4300 
4301 	return (jtrunc);
4302 }
4303 
4304 /*
4305  * If we're canceling a new bitmap we have to search for another ref
4306  * to move into the bmsafemap dep.  This might be better expressed
4307  * with another structure.
4308  */
4309 static void
4310 move_newblock_dep(jaddref, inodedep)
4311 	struct jaddref *jaddref;
4312 	struct inodedep *inodedep;
4313 {
4314 	struct inoref *inoref;
4315 	struct jaddref *jaddrefn;
4316 
4317 	jaddrefn = NULL;
4318 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4319 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4320 		if ((jaddref->ja_state & NEWBLOCK) &&
4321 		    inoref->if_list.wk_type == D_JADDREF) {
4322 			jaddrefn = (struct jaddref *)inoref;
4323 			break;
4324 		}
4325 	}
4326 	if (jaddrefn == NULL)
4327 		return;
4328 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4329 	jaddrefn->ja_state |= jaddref->ja_state &
4330 	    (ATTACHED | UNDONE | NEWBLOCK);
4331 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4332 	jaddref->ja_state |= ATTACHED;
4333 	LIST_REMOVE(jaddref, ja_bmdeps);
4334 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4335 	    ja_bmdeps);
4336 }
4337 
4338 /*
4339  * Cancel a jaddref either before it has been written or while it is being
4340  * written.  This happens when a link is removed before the add reaches
4341  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4342  * and inode to prevent the link count or bitmap from reaching the disk
4343  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4344  * required.
4345  *
4346  * Returns 1 if the canceled addref requires journaling of the remove and
4347  * 0 otherwise.
4348  */
4349 static int
4350 cancel_jaddref(jaddref, inodedep, wkhd)
4351 	struct jaddref *jaddref;
4352 	struct inodedep *inodedep;
4353 	struct workhead *wkhd;
4354 {
4355 	struct inoref *inoref;
4356 	struct jsegdep *jsegdep;
4357 	int needsj;
4358 
4359 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4360 	    ("cancel_jaddref: Canceling complete jaddref"));
4361 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4362 		needsj = 1;
4363 	else
4364 		needsj = 0;
4365 	if (inodedep == NULL)
4366 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4367 		    0, &inodedep) == 0)
4368 			panic("cancel_jaddref: Lost inodedep");
4369 	/*
4370 	 * We must adjust the nlink of any reference operation that follows
4371 	 * us so that it is consistent with the in-memory reference.  This
4372 	 * ensures that inode nlink rollbacks always have the correct link.
4373 	 */
4374 	if (needsj == 0) {
4375 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4376 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4377 			if (inoref->if_state & GOINGAWAY)
4378 				break;
4379 			inoref->if_nlink--;
4380 		}
4381 	}
4382 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4383 	if (jaddref->ja_state & NEWBLOCK)
4384 		move_newblock_dep(jaddref, inodedep);
4385 	wake_worklist(&jaddref->ja_list);
4386 	jaddref->ja_mkdir = NULL;
4387 	if (jaddref->ja_state & INPROGRESS) {
4388 		jaddref->ja_state &= ~INPROGRESS;
4389 		WORKLIST_REMOVE(&jaddref->ja_list);
4390 		jwork_insert(wkhd, jsegdep);
4391 	} else {
4392 		free_jsegdep(jsegdep);
4393 		if (jaddref->ja_state & DEPCOMPLETE)
4394 			remove_from_journal(&jaddref->ja_list);
4395 	}
4396 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4397 	/*
4398 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4399 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4400 	 * no longer need this addref attached to the inoreflst and it
4401 	 * will incorrectly adjust nlink if we leave it.
4402 	 */
4403 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4404 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4405 		    if_deps);
4406 		jaddref->ja_state |= COMPLETE;
4407 		free_jaddref(jaddref);
4408 		return (needsj);
4409 	}
4410 	/*
4411 	 * Leave the head of the list for jsegdeps for fast merging.
4412 	 */
4413 	if (LIST_FIRST(wkhd) != NULL) {
4414 		jaddref->ja_state |= ONWORKLIST;
4415 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4416 	} else
4417 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4418 
4419 	return (needsj);
4420 }
4421 
4422 /*
4423  * Attempt to free a jaddref structure when some work completes.  This
4424  * should only succeed once the entry is written and all dependencies have
4425  * been notified.
4426  */
4427 static void
4428 free_jaddref(jaddref)
4429 	struct jaddref *jaddref;
4430 {
4431 
4432 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4433 		return;
4434 	if (jaddref->ja_ref.if_jsegdep)
4435 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4436 		    jaddref, jaddref->ja_state);
4437 	if (jaddref->ja_state & NEWBLOCK)
4438 		LIST_REMOVE(jaddref, ja_bmdeps);
4439 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4440 		panic("free_jaddref: Bad state %p(0x%X)",
4441 		    jaddref, jaddref->ja_state);
4442 	if (jaddref->ja_mkdir != NULL)
4443 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4444 	WORKITEM_FREE(jaddref, D_JADDREF);
4445 }
4446 
4447 /*
4448  * Free a jremref structure once it has been written or discarded.
4449  */
4450 static void
4451 free_jremref(jremref)
4452 	struct jremref *jremref;
4453 {
4454 
4455 	if (jremref->jr_ref.if_jsegdep)
4456 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4457 	if (jremref->jr_state & INPROGRESS)
4458 		panic("free_jremref: IO still pending");
4459 	WORKITEM_FREE(jremref, D_JREMREF);
4460 }
4461 
4462 /*
4463  * Free a jnewblk structure.
4464  */
4465 static void
4466 free_jnewblk(jnewblk)
4467 	struct jnewblk *jnewblk;
4468 {
4469 
4470 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4471 		return;
4472 	LIST_REMOVE(jnewblk, jn_deps);
4473 	if (jnewblk->jn_dep != NULL)
4474 		panic("free_jnewblk: Dependency still attached.");
4475 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4476 }
4477 
4478 /*
4479  * Cancel a jnewblk which has been been made redundant by frag extension.
4480  */
4481 static void
4482 cancel_jnewblk(jnewblk, wkhd)
4483 	struct jnewblk *jnewblk;
4484 	struct workhead *wkhd;
4485 {
4486 	struct jsegdep *jsegdep;
4487 
4488 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4489 	jsegdep = jnewblk->jn_jsegdep;
4490 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4491 		panic("cancel_jnewblk: Invalid state");
4492 	jnewblk->jn_jsegdep  = NULL;
4493 	jnewblk->jn_dep = NULL;
4494 	jnewblk->jn_state |= GOINGAWAY;
4495 	if (jnewblk->jn_state & INPROGRESS) {
4496 		jnewblk->jn_state &= ~INPROGRESS;
4497 		WORKLIST_REMOVE(&jnewblk->jn_list);
4498 		jwork_insert(wkhd, jsegdep);
4499 	} else {
4500 		free_jsegdep(jsegdep);
4501 		remove_from_journal(&jnewblk->jn_list);
4502 	}
4503 	wake_worklist(&jnewblk->jn_list);
4504 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4505 }
4506 
4507 static void
4508 free_jblkdep(jblkdep)
4509 	struct jblkdep *jblkdep;
4510 {
4511 
4512 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4513 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4514 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4515 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4516 	else
4517 		panic("free_jblkdep: Unexpected type %s",
4518 		    TYPENAME(jblkdep->jb_list.wk_type));
4519 }
4520 
4521 /*
4522  * Free a single jseg once it is no longer referenced in memory or on
4523  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4524  * to disappear.
4525  */
4526 static void
4527 free_jseg(jseg, jblocks)
4528 	struct jseg *jseg;
4529 	struct jblocks *jblocks;
4530 {
4531 	struct freework *freework;
4532 
4533 	/*
4534 	 * Free freework structures that were lingering to indicate freed
4535 	 * indirect blocks that forced journal write ordering on reallocate.
4536 	 */
4537 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4538 		indirblk_remove(freework);
4539 	if (jblocks->jb_oldestseg == jseg)
4540 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4541 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4542 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4543 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4544 	    ("free_jseg: Freed jseg has valid entries."));
4545 	WORKITEM_FREE(jseg, D_JSEG);
4546 }
4547 
4548 /*
4549  * Free all jsegs that meet the criteria for being reclaimed and update
4550  * oldestseg.
4551  */
4552 static void
4553 free_jsegs(jblocks)
4554 	struct jblocks *jblocks;
4555 {
4556 	struct jseg *jseg;
4557 
4558 	/*
4559 	 * Free only those jsegs which have none allocated before them to
4560 	 * preserve the journal space ordering.
4561 	 */
4562 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4563 		/*
4564 		 * Only reclaim space when nothing depends on this journal
4565 		 * set and another set has written that it is no longer
4566 		 * valid.
4567 		 */
4568 		if (jseg->js_refs != 0) {
4569 			jblocks->jb_oldestseg = jseg;
4570 			return;
4571 		}
4572 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4573 			break;
4574 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4575 			break;
4576 		/*
4577 		 * We can free jsegs that didn't write entries when
4578 		 * oldestwrseq == js_seq.
4579 		 */
4580 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4581 		    jseg->js_cnt != 0)
4582 			break;
4583 		free_jseg(jseg, jblocks);
4584 	}
4585 	/*
4586 	 * If we exited the loop above we still must discover the
4587 	 * oldest valid segment.
4588 	 */
4589 	if (jseg)
4590 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4591 		     jseg = TAILQ_NEXT(jseg, js_next))
4592 			if (jseg->js_refs != 0)
4593 				break;
4594 	jblocks->jb_oldestseg = jseg;
4595 	/*
4596 	 * The journal has no valid records but some jsegs may still be
4597 	 * waiting on oldestwrseq to advance.  We force a small record
4598 	 * out to permit these lingering records to be reclaimed.
4599 	 */
4600 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4601 		jblocks->jb_needseg = 1;
4602 }
4603 
4604 /*
4605  * Release one reference to a jseg and free it if the count reaches 0.  This
4606  * should eventually reclaim journal space as well.
4607  */
4608 static void
4609 rele_jseg(jseg)
4610 	struct jseg *jseg;
4611 {
4612 
4613 	KASSERT(jseg->js_refs > 0,
4614 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4615 	if (--jseg->js_refs != 0)
4616 		return;
4617 	free_jsegs(jseg->js_jblocks);
4618 }
4619 
4620 /*
4621  * Release a jsegdep and decrement the jseg count.
4622  */
4623 static void
4624 free_jsegdep(jsegdep)
4625 	struct jsegdep *jsegdep;
4626 {
4627 
4628 	if (jsegdep->jd_seg)
4629 		rele_jseg(jsegdep->jd_seg);
4630 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4631 }
4632 
4633 /*
4634  * Wait for a journal item to make it to disk.  Initiate journal processing
4635  * if required.
4636  */
4637 static int
4638 jwait(wk, waitfor)
4639 	struct worklist *wk;
4640 	int waitfor;
4641 {
4642 
4643 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4644 	/*
4645 	 * Blocking journal waits cause slow synchronous behavior.  Record
4646 	 * stats on the frequency of these blocking operations.
4647 	 */
4648 	if (waitfor == MNT_WAIT) {
4649 		stat_journal_wait++;
4650 		switch (wk->wk_type) {
4651 		case D_JREMREF:
4652 		case D_JMVREF:
4653 			stat_jwait_filepage++;
4654 			break;
4655 		case D_JTRUNC:
4656 		case D_JFREEBLK:
4657 			stat_jwait_freeblks++;
4658 			break;
4659 		case D_JNEWBLK:
4660 			stat_jwait_newblk++;
4661 			break;
4662 		case D_JADDREF:
4663 			stat_jwait_inode++;
4664 			break;
4665 		default:
4666 			break;
4667 		}
4668 	}
4669 	/*
4670 	 * If IO has not started we process the journal.  We can't mark the
4671 	 * worklist item as IOWAITING because we drop the lock while
4672 	 * processing the journal and the worklist entry may be freed after
4673 	 * this point.  The caller may call back in and re-issue the request.
4674 	 */
4675 	if ((wk->wk_state & INPROGRESS) == 0) {
4676 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4677 		if (waitfor != MNT_WAIT)
4678 			return (EBUSY);
4679 		return (0);
4680 	}
4681 	if (waitfor != MNT_WAIT)
4682 		return (EBUSY);
4683 	wait_worklist(wk, "jwait");
4684 	return (0);
4685 }
4686 
4687 /*
4688  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4689  * appropriate.  This is a convenience function to reduce duplicate code
4690  * for the setup and revert functions below.
4691  */
4692 static struct inodedep *
4693 inodedep_lookup_ip(ip)
4694 	struct inode *ip;
4695 {
4696 	struct inodedep *inodedep;
4697 
4698 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4699 	    ("inodedep_lookup_ip: bad delta"));
4700 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4701 	    &inodedep);
4702 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4703 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4704 
4705 	return (inodedep);
4706 }
4707 
4708 /*
4709  * Called prior to creating a new inode and linking it to a directory.  The
4710  * jaddref structure must already be allocated by softdep_setup_inomapdep
4711  * and it is discovered here so we can initialize the mode and update
4712  * nlinkdelta.
4713  */
4714 void
4715 softdep_setup_create(dp, ip)
4716 	struct inode *dp;
4717 	struct inode *ip;
4718 {
4719 	struct inodedep *inodedep;
4720 	struct jaddref *jaddref;
4721 	struct vnode *dvp;
4722 
4723 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4724 	    ("softdep_setup_create called on non-softdep filesystem"));
4725 	KASSERT(ip->i_nlink == 1,
4726 	    ("softdep_setup_create: Invalid link count."));
4727 	dvp = ITOV(dp);
4728 	ACQUIRE_LOCK(ITOUMP(dp));
4729 	inodedep = inodedep_lookup_ip(ip);
4730 	if (DOINGSUJ(dvp)) {
4731 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4732 		    inoreflst);
4733 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4734 		    ("softdep_setup_create: No addref structure present."));
4735 	}
4736 	softdep_prelink(dvp, NULL);
4737 	FREE_LOCK(ITOUMP(dp));
4738 }
4739 
4740 /*
4741  * Create a jaddref structure to track the addition of a DOTDOT link when
4742  * we are reparenting an inode as part of a rename.  This jaddref will be
4743  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4744  * non-journaling softdep.
4745  */
4746 void
4747 softdep_setup_dotdot_link(dp, ip)
4748 	struct inode *dp;
4749 	struct inode *ip;
4750 {
4751 	struct inodedep *inodedep;
4752 	struct jaddref *jaddref;
4753 	struct vnode *dvp;
4754 
4755 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4756 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4757 	dvp = ITOV(dp);
4758 	jaddref = NULL;
4759 	/*
4760 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4761 	 * is used as a normal link would be.
4762 	 */
4763 	if (DOINGSUJ(dvp))
4764 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4765 		    dp->i_effnlink - 1, dp->i_mode);
4766 	ACQUIRE_LOCK(ITOUMP(dp));
4767 	inodedep = inodedep_lookup_ip(dp);
4768 	if (jaddref)
4769 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4770 		    if_deps);
4771 	softdep_prelink(dvp, ITOV(ip));
4772 	FREE_LOCK(ITOUMP(dp));
4773 }
4774 
4775 /*
4776  * Create a jaddref structure to track a new link to an inode.  The directory
4777  * offset is not known until softdep_setup_directory_add or
4778  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4779  * softdep.
4780  */
4781 void
4782 softdep_setup_link(dp, ip)
4783 	struct inode *dp;
4784 	struct inode *ip;
4785 {
4786 	struct inodedep *inodedep;
4787 	struct jaddref *jaddref;
4788 	struct vnode *dvp;
4789 
4790 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4791 	    ("softdep_setup_link called on non-softdep filesystem"));
4792 	dvp = ITOV(dp);
4793 	jaddref = NULL;
4794 	if (DOINGSUJ(dvp))
4795 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4796 		    ip->i_mode);
4797 	ACQUIRE_LOCK(ITOUMP(dp));
4798 	inodedep = inodedep_lookup_ip(ip);
4799 	if (jaddref)
4800 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4801 		    if_deps);
4802 	softdep_prelink(dvp, ITOV(ip));
4803 	FREE_LOCK(ITOUMP(dp));
4804 }
4805 
4806 /*
4807  * Called to create the jaddref structures to track . and .. references as
4808  * well as lookup and further initialize the incomplete jaddref created
4809  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4810  * nlinkdelta for non-journaling softdep.
4811  */
4812 void
4813 softdep_setup_mkdir(dp, ip)
4814 	struct inode *dp;
4815 	struct inode *ip;
4816 {
4817 	struct inodedep *inodedep;
4818 	struct jaddref *dotdotaddref;
4819 	struct jaddref *dotaddref;
4820 	struct jaddref *jaddref;
4821 	struct vnode *dvp;
4822 
4823 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4824 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
4825 	dvp = ITOV(dp);
4826 	dotaddref = dotdotaddref = NULL;
4827 	if (DOINGSUJ(dvp)) {
4828 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4829 		    ip->i_mode);
4830 		dotaddref->ja_state |= MKDIR_BODY;
4831 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4832 		    dp->i_effnlink - 1, dp->i_mode);
4833 		dotdotaddref->ja_state |= MKDIR_PARENT;
4834 	}
4835 	ACQUIRE_LOCK(ITOUMP(dp));
4836 	inodedep = inodedep_lookup_ip(ip);
4837 	if (DOINGSUJ(dvp)) {
4838 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4839 		    inoreflst);
4840 		KASSERT(jaddref != NULL,
4841 		    ("softdep_setup_mkdir: No addref structure present."));
4842 		KASSERT(jaddref->ja_parent == dp->i_number,
4843 		    ("softdep_setup_mkdir: bad parent %ju",
4844 		    (uintmax_t)jaddref->ja_parent));
4845 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4846 		    if_deps);
4847 	}
4848 	inodedep = inodedep_lookup_ip(dp);
4849 	if (DOINGSUJ(dvp))
4850 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4851 		    &dotdotaddref->ja_ref, if_deps);
4852 	softdep_prelink(ITOV(dp), NULL);
4853 	FREE_LOCK(ITOUMP(dp));
4854 }
4855 
4856 /*
4857  * Called to track nlinkdelta of the inode and parent directories prior to
4858  * unlinking a directory.
4859  */
4860 void
4861 softdep_setup_rmdir(dp, ip)
4862 	struct inode *dp;
4863 	struct inode *ip;
4864 {
4865 	struct vnode *dvp;
4866 
4867 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4868 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4869 	dvp = ITOV(dp);
4870 	ACQUIRE_LOCK(ITOUMP(dp));
4871 	(void) inodedep_lookup_ip(ip);
4872 	(void) inodedep_lookup_ip(dp);
4873 	softdep_prelink(dvp, ITOV(ip));
4874 	FREE_LOCK(ITOUMP(dp));
4875 }
4876 
4877 /*
4878  * Called to track nlinkdelta of the inode and parent directories prior to
4879  * unlink.
4880  */
4881 void
4882 softdep_setup_unlink(dp, ip)
4883 	struct inode *dp;
4884 	struct inode *ip;
4885 {
4886 	struct vnode *dvp;
4887 
4888 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4889 	    ("softdep_setup_unlink called on non-softdep filesystem"));
4890 	dvp = ITOV(dp);
4891 	ACQUIRE_LOCK(ITOUMP(dp));
4892 	(void) inodedep_lookup_ip(ip);
4893 	(void) inodedep_lookup_ip(dp);
4894 	softdep_prelink(dvp, ITOV(ip));
4895 	FREE_LOCK(ITOUMP(dp));
4896 }
4897 
4898 /*
4899  * Called to release the journal structures created by a failed non-directory
4900  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4901  */
4902 void
4903 softdep_revert_create(dp, ip)
4904 	struct inode *dp;
4905 	struct inode *ip;
4906 {
4907 	struct inodedep *inodedep;
4908 	struct jaddref *jaddref;
4909 	struct vnode *dvp;
4910 
4911 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4912 	    ("softdep_revert_create called on non-softdep filesystem"));
4913 	dvp = ITOV(dp);
4914 	ACQUIRE_LOCK(ITOUMP(dp));
4915 	inodedep = inodedep_lookup_ip(ip);
4916 	if (DOINGSUJ(dvp)) {
4917 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4918 		    inoreflst);
4919 		KASSERT(jaddref->ja_parent == dp->i_number,
4920 		    ("softdep_revert_create: addref parent mismatch"));
4921 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4922 	}
4923 	FREE_LOCK(ITOUMP(dp));
4924 }
4925 
4926 /*
4927  * Called to release the journal structures created by a failed link
4928  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4929  */
4930 void
4931 softdep_revert_link(dp, ip)
4932 	struct inode *dp;
4933 	struct inode *ip;
4934 {
4935 	struct inodedep *inodedep;
4936 	struct jaddref *jaddref;
4937 	struct vnode *dvp;
4938 
4939 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4940 	    ("softdep_revert_link called on non-softdep filesystem"));
4941 	dvp = ITOV(dp);
4942 	ACQUIRE_LOCK(ITOUMP(dp));
4943 	inodedep = inodedep_lookup_ip(ip);
4944 	if (DOINGSUJ(dvp)) {
4945 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4946 		    inoreflst);
4947 		KASSERT(jaddref->ja_parent == dp->i_number,
4948 		    ("softdep_revert_link: addref parent mismatch"));
4949 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4950 	}
4951 	FREE_LOCK(ITOUMP(dp));
4952 }
4953 
4954 /*
4955  * Called to release the journal structures created by a failed mkdir
4956  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4957  */
4958 void
4959 softdep_revert_mkdir(dp, ip)
4960 	struct inode *dp;
4961 	struct inode *ip;
4962 {
4963 	struct inodedep *inodedep;
4964 	struct jaddref *jaddref;
4965 	struct jaddref *dotaddref;
4966 	struct vnode *dvp;
4967 
4968 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4969 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4970 	dvp = ITOV(dp);
4971 
4972 	ACQUIRE_LOCK(ITOUMP(dp));
4973 	inodedep = inodedep_lookup_ip(dp);
4974 	if (DOINGSUJ(dvp)) {
4975 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4976 		    inoreflst);
4977 		KASSERT(jaddref->ja_parent == ip->i_number,
4978 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4979 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4980 	}
4981 	inodedep = inodedep_lookup_ip(ip);
4982 	if (DOINGSUJ(dvp)) {
4983 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4984 		    inoreflst);
4985 		KASSERT(jaddref->ja_parent == dp->i_number,
4986 		    ("softdep_revert_mkdir: addref parent mismatch"));
4987 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4988 		    inoreflst, if_deps);
4989 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4990 		KASSERT(dotaddref->ja_parent == ip->i_number,
4991 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4992 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4993 	}
4994 	FREE_LOCK(ITOUMP(dp));
4995 }
4996 
4997 /*
4998  * Called to correct nlinkdelta after a failed rmdir.
4999  */
5000 void
5001 softdep_revert_rmdir(dp, ip)
5002 	struct inode *dp;
5003 	struct inode *ip;
5004 {
5005 
5006 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5007 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
5008 	ACQUIRE_LOCK(ITOUMP(dp));
5009 	(void) inodedep_lookup_ip(ip);
5010 	(void) inodedep_lookup_ip(dp);
5011 	FREE_LOCK(ITOUMP(dp));
5012 }
5013 
5014 /*
5015  * Protecting the freemaps (or bitmaps).
5016  *
5017  * To eliminate the need to execute fsck before mounting a filesystem
5018  * after a power failure, one must (conservatively) guarantee that the
5019  * on-disk copy of the bitmaps never indicate that a live inode or block is
5020  * free.  So, when a block or inode is allocated, the bitmap should be
5021  * updated (on disk) before any new pointers.  When a block or inode is
5022  * freed, the bitmap should not be updated until all pointers have been
5023  * reset.  The latter dependency is handled by the delayed de-allocation
5024  * approach described below for block and inode de-allocation.  The former
5025  * dependency is handled by calling the following procedure when a block or
5026  * inode is allocated. When an inode is allocated an "inodedep" is created
5027  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5028  * Each "inodedep" is also inserted into the hash indexing structure so
5029  * that any additional link additions can be made dependent on the inode
5030  * allocation.
5031  *
5032  * The ufs filesystem maintains a number of free block counts (e.g., per
5033  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5034  * in addition to the bitmaps.  These counts are used to improve efficiency
5035  * during allocation and therefore must be consistent with the bitmaps.
5036  * There is no convenient way to guarantee post-crash consistency of these
5037  * counts with simple update ordering, for two main reasons: (1) The counts
5038  * and bitmaps for a single cylinder group block are not in the same disk
5039  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5040  * be written and the other not.  (2) Some of the counts are located in the
5041  * superblock rather than the cylinder group block. So, we focus our soft
5042  * updates implementation on protecting the bitmaps. When mounting a
5043  * filesystem, we recompute the auxiliary counts from the bitmaps.
5044  */
5045 
5046 /*
5047  * Called just after updating the cylinder group block to allocate an inode.
5048  */
5049 void
5050 softdep_setup_inomapdep(bp, ip, newinum, mode)
5051 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5052 	struct inode *ip;	/* inode related to allocation */
5053 	ino_t newinum;		/* new inode number being allocated */
5054 	int mode;
5055 {
5056 	struct inodedep *inodedep;
5057 	struct bmsafemap *bmsafemap;
5058 	struct jaddref *jaddref;
5059 	struct mount *mp;
5060 	struct fs *fs;
5061 
5062 	mp = ITOVFS(ip);
5063 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5064 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5065 	fs = VFSTOUFS(mp)->um_fs;
5066 	jaddref = NULL;
5067 
5068 	/*
5069 	 * Allocate the journal reference add structure so that the bitmap
5070 	 * can be dependent on it.
5071 	 */
5072 	if (MOUNTEDSUJ(mp)) {
5073 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5074 		jaddref->ja_state |= NEWBLOCK;
5075 	}
5076 
5077 	/*
5078 	 * Create a dependency for the newly allocated inode.
5079 	 * Panic if it already exists as something is seriously wrong.
5080 	 * Otherwise add it to the dependency list for the buffer holding
5081 	 * the cylinder group map from which it was allocated.
5082 	 *
5083 	 * We have to preallocate a bmsafemap entry in case it is needed
5084 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5085 	 * have to finish initializing it before we can FREE_LOCK().
5086 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5087 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5088 	 * creating the inodedep as it can be freed during the time
5089 	 * that we FREE_LOCK() while allocating the inodedep. We must
5090 	 * call workitem_alloc() before entering the locked section as
5091 	 * it also acquires the lock and we must avoid trying doing so
5092 	 * recursively.
5093 	 */
5094 	bmsafemap = malloc(sizeof(struct bmsafemap),
5095 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5096 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5097 	ACQUIRE_LOCK(ITOUMP(ip));
5098 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5099 		panic("softdep_setup_inomapdep: dependency %p for new"
5100 		    "inode already exists", inodedep);
5101 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5102 	if (jaddref) {
5103 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5104 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5105 		    if_deps);
5106 	} else {
5107 		inodedep->id_state |= ONDEPLIST;
5108 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5109 	}
5110 	inodedep->id_bmsafemap = bmsafemap;
5111 	inodedep->id_state &= ~DEPCOMPLETE;
5112 	FREE_LOCK(ITOUMP(ip));
5113 }
5114 
5115 /*
5116  * Called just after updating the cylinder group block to
5117  * allocate block or fragment.
5118  */
5119 void
5120 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5121 	struct buf *bp;		/* buffer for cylgroup block with block map */
5122 	struct mount *mp;	/* filesystem doing allocation */
5123 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5124 	int frags;		/* Number of fragments. */
5125 	int oldfrags;		/* Previous number of fragments for extend. */
5126 {
5127 	struct newblk *newblk;
5128 	struct bmsafemap *bmsafemap;
5129 	struct jnewblk *jnewblk;
5130 	struct ufsmount *ump;
5131 	struct fs *fs;
5132 
5133 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5134 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5135 	ump = VFSTOUFS(mp);
5136 	fs = ump->um_fs;
5137 	jnewblk = NULL;
5138 	/*
5139 	 * Create a dependency for the newly allocated block.
5140 	 * Add it to the dependency list for the buffer holding
5141 	 * the cylinder group map from which it was allocated.
5142 	 */
5143 	if (MOUNTEDSUJ(mp)) {
5144 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5145 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5146 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5147 		jnewblk->jn_state = ATTACHED;
5148 		jnewblk->jn_blkno = newblkno;
5149 		jnewblk->jn_frags = frags;
5150 		jnewblk->jn_oldfrags = oldfrags;
5151 #ifdef INVARIANTS
5152 		{
5153 			struct cg *cgp;
5154 			uint8_t *blksfree;
5155 			long bno;
5156 			int i;
5157 
5158 			cgp = (struct cg *)bp->b_data;
5159 			blksfree = cg_blksfree(cgp);
5160 			bno = dtogd(fs, jnewblk->jn_blkno);
5161 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5162 			    i++) {
5163 				if (isset(blksfree, bno + i))
5164 					panic("softdep_setup_blkmapdep: "
5165 					    "free fragment %d from %d-%d "
5166 					    "state 0x%X dep %p", i,
5167 					    jnewblk->jn_oldfrags,
5168 					    jnewblk->jn_frags,
5169 					    jnewblk->jn_state,
5170 					    jnewblk->jn_dep);
5171 			}
5172 		}
5173 #endif
5174 	}
5175 
5176 	CTR3(KTR_SUJ,
5177 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5178 	    newblkno, frags, oldfrags);
5179 	ACQUIRE_LOCK(ump);
5180 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5181 		panic("softdep_setup_blkmapdep: found block");
5182 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5183 	    dtog(fs, newblkno), NULL);
5184 	if (jnewblk) {
5185 		jnewblk->jn_dep = (struct worklist *)newblk;
5186 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5187 	} else {
5188 		newblk->nb_state |= ONDEPLIST;
5189 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5190 	}
5191 	newblk->nb_bmsafemap = bmsafemap;
5192 	newblk->nb_jnewblk = jnewblk;
5193 	FREE_LOCK(ump);
5194 }
5195 
5196 #define	BMSAFEMAP_HASH(ump, cg) \
5197       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5198 
5199 static int
5200 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5201 	struct bmsafemap_hashhead *bmsafemaphd;
5202 	int cg;
5203 	struct bmsafemap **bmsafemapp;
5204 {
5205 	struct bmsafemap *bmsafemap;
5206 
5207 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5208 		if (bmsafemap->sm_cg == cg)
5209 			break;
5210 	if (bmsafemap) {
5211 		*bmsafemapp = bmsafemap;
5212 		return (1);
5213 	}
5214 	*bmsafemapp = NULL;
5215 
5216 	return (0);
5217 }
5218 
5219 /*
5220  * Find the bmsafemap associated with a cylinder group buffer.
5221  * If none exists, create one. The buffer must be locked when
5222  * this routine is called and this routine must be called with
5223  * the softdep lock held. To avoid giving up the lock while
5224  * allocating a new bmsafemap, a preallocated bmsafemap may be
5225  * provided. If it is provided but not needed, it is freed.
5226  */
5227 static struct bmsafemap *
5228 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5229 	struct mount *mp;
5230 	struct buf *bp;
5231 	int cg;
5232 	struct bmsafemap *newbmsafemap;
5233 {
5234 	struct bmsafemap_hashhead *bmsafemaphd;
5235 	struct bmsafemap *bmsafemap, *collision;
5236 	struct worklist *wk;
5237 	struct ufsmount *ump;
5238 
5239 	ump = VFSTOUFS(mp);
5240 	LOCK_OWNED(ump);
5241 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5242 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5243 		if (wk->wk_type == D_BMSAFEMAP) {
5244 			if (newbmsafemap)
5245 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5246 			return (WK_BMSAFEMAP(wk));
5247 		}
5248 	}
5249 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5250 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5251 		if (newbmsafemap)
5252 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5253 		return (bmsafemap);
5254 	}
5255 	if (newbmsafemap) {
5256 		bmsafemap = newbmsafemap;
5257 	} else {
5258 		FREE_LOCK(ump);
5259 		bmsafemap = malloc(sizeof(struct bmsafemap),
5260 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5261 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5262 		ACQUIRE_LOCK(ump);
5263 	}
5264 	bmsafemap->sm_buf = bp;
5265 	LIST_INIT(&bmsafemap->sm_inodedephd);
5266 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5267 	LIST_INIT(&bmsafemap->sm_newblkhd);
5268 	LIST_INIT(&bmsafemap->sm_newblkwr);
5269 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5270 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5271 	LIST_INIT(&bmsafemap->sm_freehd);
5272 	LIST_INIT(&bmsafemap->sm_freewr);
5273 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5274 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5275 		return (collision);
5276 	}
5277 	bmsafemap->sm_cg = cg;
5278 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5279 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5280 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5281 	return (bmsafemap);
5282 }
5283 
5284 /*
5285  * Direct block allocation dependencies.
5286  *
5287  * When a new block is allocated, the corresponding disk locations must be
5288  * initialized (with zeros or new data) before the on-disk inode points to
5289  * them.  Also, the freemap from which the block was allocated must be
5290  * updated (on disk) before the inode's pointer. These two dependencies are
5291  * independent of each other and are needed for all file blocks and indirect
5292  * blocks that are pointed to directly by the inode.  Just before the
5293  * "in-core" version of the inode is updated with a newly allocated block
5294  * number, a procedure (below) is called to setup allocation dependency
5295  * structures.  These structures are removed when the corresponding
5296  * dependencies are satisfied or when the block allocation becomes obsolete
5297  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5298  * fragment that gets upgraded).  All of these cases are handled in
5299  * procedures described later.
5300  *
5301  * When a file extension causes a fragment to be upgraded, either to a larger
5302  * fragment or to a full block, the on-disk location may change (if the
5303  * previous fragment could not simply be extended). In this case, the old
5304  * fragment must be de-allocated, but not until after the inode's pointer has
5305  * been updated. In most cases, this is handled by later procedures, which
5306  * will construct a "freefrag" structure to be added to the workitem queue
5307  * when the inode update is complete (or obsolete).  The main exception to
5308  * this is when an allocation occurs while a pending allocation dependency
5309  * (for the same block pointer) remains.  This case is handled in the main
5310  * allocation dependency setup procedure by immediately freeing the
5311  * unreferenced fragments.
5312  */
5313 void
5314 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5315 	struct inode *ip;	/* inode to which block is being added */
5316 	ufs_lbn_t off;		/* block pointer within inode */
5317 	ufs2_daddr_t newblkno;	/* disk block number being added */
5318 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5319 	long newsize;		/* size of new block */
5320 	long oldsize;		/* size of new block */
5321 	struct buf *bp;		/* bp for allocated block */
5322 {
5323 	struct allocdirect *adp, *oldadp;
5324 	struct allocdirectlst *adphead;
5325 	struct freefrag *freefrag;
5326 	struct inodedep *inodedep;
5327 	struct pagedep *pagedep;
5328 	struct jnewblk *jnewblk;
5329 	struct newblk *newblk;
5330 	struct mount *mp;
5331 	ufs_lbn_t lbn;
5332 
5333 	lbn = bp->b_lblkno;
5334 	mp = ITOVFS(ip);
5335 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5336 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5337 	if (oldblkno && oldblkno != newblkno)
5338 		/*
5339 		 * The usual case is that a smaller fragment that
5340 		 * was just allocated has been replaced with a bigger
5341 		 * fragment or a full-size block. If it is marked as
5342 		 * B_DELWRI, the current contents have not been written
5343 		 * to disk. It is possible that the block was written
5344 		 * earlier, but very uncommon. If the block has never
5345 		 * been written, there is no need to send a BIO_DELETE
5346 		 * for it when it is freed. The gain from avoiding the
5347 		 * TRIMs for the common case of unwritten blocks far
5348 		 * exceeds the cost of the write amplification for the
5349 		 * uncommon case of failing to send a TRIM for a block
5350 		 * that had been written.
5351 		 */
5352 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5353 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5354 	else
5355 		freefrag = NULL;
5356 
5357 	CTR6(KTR_SUJ,
5358 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5359 	    "off %jd newsize %ld oldsize %d",
5360 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5361 	ACQUIRE_LOCK(ITOUMP(ip));
5362 	if (off >= UFS_NDADDR) {
5363 		if (lbn > 0)
5364 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5365 			    lbn, off);
5366 		/* allocating an indirect block */
5367 		if (oldblkno != 0)
5368 			panic("softdep_setup_allocdirect: non-zero indir");
5369 	} else {
5370 		if (off != lbn)
5371 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5372 			    lbn, off);
5373 		/*
5374 		 * Allocating a direct block.
5375 		 *
5376 		 * If we are allocating a directory block, then we must
5377 		 * allocate an associated pagedep to track additions and
5378 		 * deletions.
5379 		 */
5380 		if ((ip->i_mode & IFMT) == IFDIR)
5381 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5382 			    &pagedep);
5383 	}
5384 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5385 		panic("softdep_setup_allocdirect: lost block");
5386 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5387 	    ("softdep_setup_allocdirect: newblk already initialized"));
5388 	/*
5389 	 * Convert the newblk to an allocdirect.
5390 	 */
5391 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5392 	adp = (struct allocdirect *)newblk;
5393 	newblk->nb_freefrag = freefrag;
5394 	adp->ad_offset = off;
5395 	adp->ad_oldblkno = oldblkno;
5396 	adp->ad_newsize = newsize;
5397 	adp->ad_oldsize = oldsize;
5398 
5399 	/*
5400 	 * Finish initializing the journal.
5401 	 */
5402 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5403 		jnewblk->jn_ino = ip->i_number;
5404 		jnewblk->jn_lbn = lbn;
5405 		add_to_journal(&jnewblk->jn_list);
5406 	}
5407 	if (freefrag && freefrag->ff_jdep != NULL &&
5408 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5409 		add_to_journal(freefrag->ff_jdep);
5410 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5411 	adp->ad_inodedep = inodedep;
5412 
5413 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5414 	/*
5415 	 * The list of allocdirects must be kept in sorted and ascending
5416 	 * order so that the rollback routines can quickly determine the
5417 	 * first uncommitted block (the size of the file stored on disk
5418 	 * ends at the end of the lowest committed fragment, or if there
5419 	 * are no fragments, at the end of the highest committed block).
5420 	 * Since files generally grow, the typical case is that the new
5421 	 * block is to be added at the end of the list. We speed this
5422 	 * special case by checking against the last allocdirect in the
5423 	 * list before laboriously traversing the list looking for the
5424 	 * insertion point.
5425 	 */
5426 	adphead = &inodedep->id_newinoupdt;
5427 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5428 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5429 		/* insert at end of list */
5430 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5431 		if (oldadp != NULL && oldadp->ad_offset == off)
5432 			allocdirect_merge(adphead, adp, oldadp);
5433 		FREE_LOCK(ITOUMP(ip));
5434 		return;
5435 	}
5436 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5437 		if (oldadp->ad_offset >= off)
5438 			break;
5439 	}
5440 	if (oldadp == NULL)
5441 		panic("softdep_setup_allocdirect: lost entry");
5442 	/* insert in middle of list */
5443 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5444 	if (oldadp->ad_offset == off)
5445 		allocdirect_merge(adphead, adp, oldadp);
5446 
5447 	FREE_LOCK(ITOUMP(ip));
5448 }
5449 
5450 /*
5451  * Merge a newer and older journal record to be stored either in a
5452  * newblock or freefrag.  This handles aggregating journal records for
5453  * fragment allocation into a second record as well as replacing a
5454  * journal free with an aborted journal allocation.  A segment for the
5455  * oldest record will be placed on wkhd if it has been written.  If not
5456  * the segment for the newer record will suffice.
5457  */
5458 static struct worklist *
5459 jnewblk_merge(new, old, wkhd)
5460 	struct worklist *new;
5461 	struct worklist *old;
5462 	struct workhead *wkhd;
5463 {
5464 	struct jnewblk *njnewblk;
5465 	struct jnewblk *jnewblk;
5466 
5467 	/* Handle NULLs to simplify callers. */
5468 	if (new == NULL)
5469 		return (old);
5470 	if (old == NULL)
5471 		return (new);
5472 	/* Replace a jfreefrag with a jnewblk. */
5473 	if (new->wk_type == D_JFREEFRAG) {
5474 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5475 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5476 			    old, new);
5477 		cancel_jfreefrag(WK_JFREEFRAG(new));
5478 		return (old);
5479 	}
5480 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5481 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5482 		    old->wk_type, new->wk_type);
5483 	/*
5484 	 * Handle merging of two jnewblk records that describe
5485 	 * different sets of fragments in the same block.
5486 	 */
5487 	jnewblk = WK_JNEWBLK(old);
5488 	njnewblk = WK_JNEWBLK(new);
5489 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5490 		panic("jnewblk_merge: Merging disparate blocks.");
5491 	/*
5492 	 * The record may be rolled back in the cg.
5493 	 */
5494 	if (jnewblk->jn_state & UNDONE) {
5495 		jnewblk->jn_state &= ~UNDONE;
5496 		njnewblk->jn_state |= UNDONE;
5497 		njnewblk->jn_state &= ~ATTACHED;
5498 	}
5499 	/*
5500 	 * We modify the newer addref and free the older so that if neither
5501 	 * has been written the most up-to-date copy will be on disk.  If
5502 	 * both have been written but rolled back we only temporarily need
5503 	 * one of them to fix the bits when the cg write completes.
5504 	 */
5505 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5506 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5507 	cancel_jnewblk(jnewblk, wkhd);
5508 	WORKLIST_REMOVE(&jnewblk->jn_list);
5509 	free_jnewblk(jnewblk);
5510 	return (new);
5511 }
5512 
5513 /*
5514  * Replace an old allocdirect dependency with a newer one.
5515  */
5516 static void
5517 allocdirect_merge(adphead, newadp, oldadp)
5518 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5519 	struct allocdirect *newadp;	/* allocdirect being added */
5520 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5521 {
5522 	struct worklist *wk;
5523 	struct freefrag *freefrag;
5524 
5525 	freefrag = NULL;
5526 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5527 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5528 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5529 	    newadp->ad_offset >= UFS_NDADDR)
5530 		panic("%s %jd != new %jd || old size %ld != new %ld",
5531 		    "allocdirect_merge: old blkno",
5532 		    (intmax_t)newadp->ad_oldblkno,
5533 		    (intmax_t)oldadp->ad_newblkno,
5534 		    newadp->ad_oldsize, oldadp->ad_newsize);
5535 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5536 	newadp->ad_oldsize = oldadp->ad_oldsize;
5537 	/*
5538 	 * If the old dependency had a fragment to free or had never
5539 	 * previously had a block allocated, then the new dependency
5540 	 * can immediately post its freefrag and adopt the old freefrag.
5541 	 * This action is done by swapping the freefrag dependencies.
5542 	 * The new dependency gains the old one's freefrag, and the
5543 	 * old one gets the new one and then immediately puts it on
5544 	 * the worklist when it is freed by free_newblk. It is
5545 	 * not possible to do this swap when the old dependency had a
5546 	 * non-zero size but no previous fragment to free. This condition
5547 	 * arises when the new block is an extension of the old block.
5548 	 * Here, the first part of the fragment allocated to the new
5549 	 * dependency is part of the block currently claimed on disk by
5550 	 * the old dependency, so cannot legitimately be freed until the
5551 	 * conditions for the new dependency are fulfilled.
5552 	 */
5553 	freefrag = newadp->ad_freefrag;
5554 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5555 		newadp->ad_freefrag = oldadp->ad_freefrag;
5556 		oldadp->ad_freefrag = freefrag;
5557 	}
5558 	/*
5559 	 * If we are tracking a new directory-block allocation,
5560 	 * move it from the old allocdirect to the new allocdirect.
5561 	 */
5562 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5563 		WORKLIST_REMOVE(wk);
5564 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5565 			panic("allocdirect_merge: extra newdirblk");
5566 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5567 	}
5568 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5569 	/*
5570 	 * We need to move any journal dependencies over to the freefrag
5571 	 * that releases this block if it exists.  Otherwise we are
5572 	 * extending an existing block and we'll wait until that is
5573 	 * complete to release the journal space and extend the
5574 	 * new journal to cover this old space as well.
5575 	 */
5576 	if (freefrag == NULL) {
5577 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5578 			panic("allocdirect_merge: %jd != %jd",
5579 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5580 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5581 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5582 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5583 		    &newadp->ad_block.nb_jwork);
5584 		oldadp->ad_block.nb_jnewblk = NULL;
5585 		cancel_newblk(&oldadp->ad_block, NULL,
5586 		    &newadp->ad_block.nb_jwork);
5587 	} else {
5588 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5589 		    &freefrag->ff_list, &freefrag->ff_jwork);
5590 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5591 		    &freefrag->ff_jwork);
5592 	}
5593 	free_newblk(&oldadp->ad_block);
5594 }
5595 
5596 /*
5597  * Allocate a jfreefrag structure to journal a single block free.
5598  */
5599 static struct jfreefrag *
5600 newjfreefrag(freefrag, ip, blkno, size, lbn)
5601 	struct freefrag *freefrag;
5602 	struct inode *ip;
5603 	ufs2_daddr_t blkno;
5604 	long size;
5605 	ufs_lbn_t lbn;
5606 {
5607 	struct jfreefrag *jfreefrag;
5608 	struct fs *fs;
5609 
5610 	fs = ITOFS(ip);
5611 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5612 	    M_SOFTDEP_FLAGS);
5613 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5614 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5615 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5616 	jfreefrag->fr_ino = ip->i_number;
5617 	jfreefrag->fr_lbn = lbn;
5618 	jfreefrag->fr_blkno = blkno;
5619 	jfreefrag->fr_frags = numfrags(fs, size);
5620 	jfreefrag->fr_freefrag = freefrag;
5621 
5622 	return (jfreefrag);
5623 }
5624 
5625 /*
5626  * Allocate a new freefrag structure.
5627  */
5628 static struct freefrag *
5629 newfreefrag(ip, blkno, size, lbn, key)
5630 	struct inode *ip;
5631 	ufs2_daddr_t blkno;
5632 	long size;
5633 	ufs_lbn_t lbn;
5634 	u_long key;
5635 {
5636 	struct freefrag *freefrag;
5637 	struct ufsmount *ump;
5638 	struct fs *fs;
5639 
5640 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5641 	    ip->i_number, blkno, size, lbn);
5642 	ump = ITOUMP(ip);
5643 	fs = ump->um_fs;
5644 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5645 		panic("newfreefrag: frag size");
5646 	freefrag = malloc(sizeof(struct freefrag),
5647 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5648 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5649 	freefrag->ff_state = ATTACHED;
5650 	LIST_INIT(&freefrag->ff_jwork);
5651 	freefrag->ff_inum = ip->i_number;
5652 	freefrag->ff_vtype = ITOV(ip)->v_type;
5653 	freefrag->ff_blkno = blkno;
5654 	freefrag->ff_fragsize = size;
5655 	freefrag->ff_key = key;
5656 
5657 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5658 		freefrag->ff_jdep = (struct worklist *)
5659 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5660 	} else {
5661 		freefrag->ff_state |= DEPCOMPLETE;
5662 		freefrag->ff_jdep = NULL;
5663 	}
5664 
5665 	return (freefrag);
5666 }
5667 
5668 /*
5669  * This workitem de-allocates fragments that were replaced during
5670  * file block allocation.
5671  */
5672 static void
5673 handle_workitem_freefrag(freefrag)
5674 	struct freefrag *freefrag;
5675 {
5676 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5677 	struct workhead wkhd;
5678 
5679 	CTR3(KTR_SUJ,
5680 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5681 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5682 	/*
5683 	 * It would be illegal to add new completion items to the
5684 	 * freefrag after it was schedule to be done so it must be
5685 	 * safe to modify the list head here.
5686 	 */
5687 	LIST_INIT(&wkhd);
5688 	ACQUIRE_LOCK(ump);
5689 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5690 	/*
5691 	 * If the journal has not been written we must cancel it here.
5692 	 */
5693 	if (freefrag->ff_jdep) {
5694 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5695 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5696 			    freefrag->ff_jdep->wk_type);
5697 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5698 	}
5699 	FREE_LOCK(ump);
5700 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5701 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5702 	   &wkhd, freefrag->ff_key);
5703 	ACQUIRE_LOCK(ump);
5704 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5705 	FREE_LOCK(ump);
5706 }
5707 
5708 /*
5709  * Set up a dependency structure for an external attributes data block.
5710  * This routine follows much of the structure of softdep_setup_allocdirect.
5711  * See the description of softdep_setup_allocdirect above for details.
5712  */
5713 void
5714 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5715 	struct inode *ip;
5716 	ufs_lbn_t off;
5717 	ufs2_daddr_t newblkno;
5718 	ufs2_daddr_t oldblkno;
5719 	long newsize;
5720 	long oldsize;
5721 	struct buf *bp;
5722 {
5723 	struct allocdirect *adp, *oldadp;
5724 	struct allocdirectlst *adphead;
5725 	struct freefrag *freefrag;
5726 	struct inodedep *inodedep;
5727 	struct jnewblk *jnewblk;
5728 	struct newblk *newblk;
5729 	struct mount *mp;
5730 	struct ufsmount *ump;
5731 	ufs_lbn_t lbn;
5732 
5733 	mp = ITOVFS(ip);
5734 	ump = VFSTOUFS(mp);
5735 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5736 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5737 	KASSERT(off < UFS_NXADDR,
5738 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5739 
5740 	lbn = bp->b_lblkno;
5741 	if (oldblkno && oldblkno != newblkno)
5742 		/*
5743 		 * The usual case is that a smaller fragment that
5744 		 * was just allocated has been replaced with a bigger
5745 		 * fragment or a full-size block. If it is marked as
5746 		 * B_DELWRI, the current contents have not been written
5747 		 * to disk. It is possible that the block was written
5748 		 * earlier, but very uncommon. If the block has never
5749 		 * been written, there is no need to send a BIO_DELETE
5750 		 * for it when it is freed. The gain from avoiding the
5751 		 * TRIMs for the common case of unwritten blocks far
5752 		 * exceeds the cost of the write amplification for the
5753 		 * uncommon case of failing to send a TRIM for a block
5754 		 * that had been written.
5755 		 */
5756 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5757 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5758 	else
5759 		freefrag = NULL;
5760 
5761 	ACQUIRE_LOCK(ump);
5762 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5763 		panic("softdep_setup_allocext: lost block");
5764 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5765 	    ("softdep_setup_allocext: newblk already initialized"));
5766 	/*
5767 	 * Convert the newblk to an allocdirect.
5768 	 */
5769 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5770 	adp = (struct allocdirect *)newblk;
5771 	newblk->nb_freefrag = freefrag;
5772 	adp->ad_offset = off;
5773 	adp->ad_oldblkno = oldblkno;
5774 	adp->ad_newsize = newsize;
5775 	adp->ad_oldsize = oldsize;
5776 	adp->ad_state |=  EXTDATA;
5777 
5778 	/*
5779 	 * Finish initializing the journal.
5780 	 */
5781 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5782 		jnewblk->jn_ino = ip->i_number;
5783 		jnewblk->jn_lbn = lbn;
5784 		add_to_journal(&jnewblk->jn_list);
5785 	}
5786 	if (freefrag && freefrag->ff_jdep != NULL &&
5787 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5788 		add_to_journal(freefrag->ff_jdep);
5789 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5790 	adp->ad_inodedep = inodedep;
5791 
5792 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5793 	/*
5794 	 * The list of allocdirects must be kept in sorted and ascending
5795 	 * order so that the rollback routines can quickly determine the
5796 	 * first uncommitted block (the size of the file stored on disk
5797 	 * ends at the end of the lowest committed fragment, or if there
5798 	 * are no fragments, at the end of the highest committed block).
5799 	 * Since files generally grow, the typical case is that the new
5800 	 * block is to be added at the end of the list. We speed this
5801 	 * special case by checking against the last allocdirect in the
5802 	 * list before laboriously traversing the list looking for the
5803 	 * insertion point.
5804 	 */
5805 	adphead = &inodedep->id_newextupdt;
5806 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5807 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5808 		/* insert at end of list */
5809 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5810 		if (oldadp != NULL && oldadp->ad_offset == off)
5811 			allocdirect_merge(adphead, adp, oldadp);
5812 		FREE_LOCK(ump);
5813 		return;
5814 	}
5815 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5816 		if (oldadp->ad_offset >= off)
5817 			break;
5818 	}
5819 	if (oldadp == NULL)
5820 		panic("softdep_setup_allocext: lost entry");
5821 	/* insert in middle of list */
5822 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5823 	if (oldadp->ad_offset == off)
5824 		allocdirect_merge(adphead, adp, oldadp);
5825 	FREE_LOCK(ump);
5826 }
5827 
5828 /*
5829  * Indirect block allocation dependencies.
5830  *
5831  * The same dependencies that exist for a direct block also exist when
5832  * a new block is allocated and pointed to by an entry in a block of
5833  * indirect pointers. The undo/redo states described above are also
5834  * used here. Because an indirect block contains many pointers that
5835  * may have dependencies, a second copy of the entire in-memory indirect
5836  * block is kept. The buffer cache copy is always completely up-to-date.
5837  * The second copy, which is used only as a source for disk writes,
5838  * contains only the safe pointers (i.e., those that have no remaining
5839  * update dependencies). The second copy is freed when all pointers
5840  * are safe. The cache is not allowed to replace indirect blocks with
5841  * pending update dependencies. If a buffer containing an indirect
5842  * block with dependencies is written, these routines will mark it
5843  * dirty again. It can only be successfully written once all the
5844  * dependencies are removed. The ffs_fsync routine in conjunction with
5845  * softdep_sync_metadata work together to get all the dependencies
5846  * removed so that a file can be successfully written to disk. Three
5847  * procedures are used when setting up indirect block pointer
5848  * dependencies. The division is necessary because of the organization
5849  * of the "balloc" routine and because of the distinction between file
5850  * pages and file metadata blocks.
5851  */
5852 
5853 /*
5854  * Allocate a new allocindir structure.
5855  */
5856 static struct allocindir *
5857 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5858 	struct inode *ip;	/* inode for file being extended */
5859 	int ptrno;		/* offset of pointer in indirect block */
5860 	ufs2_daddr_t newblkno;	/* disk block number being added */
5861 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5862 	ufs_lbn_t lbn;
5863 {
5864 	struct newblk *newblk;
5865 	struct allocindir *aip;
5866 	struct freefrag *freefrag;
5867 	struct jnewblk *jnewblk;
5868 
5869 	if (oldblkno)
5870 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
5871 		    SINGLETON_KEY);
5872 	else
5873 		freefrag = NULL;
5874 	ACQUIRE_LOCK(ITOUMP(ip));
5875 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5876 		panic("new_allocindir: lost block");
5877 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5878 	    ("newallocindir: newblk already initialized"));
5879 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5880 	newblk->nb_freefrag = freefrag;
5881 	aip = (struct allocindir *)newblk;
5882 	aip->ai_offset = ptrno;
5883 	aip->ai_oldblkno = oldblkno;
5884 	aip->ai_lbn = lbn;
5885 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5886 		jnewblk->jn_ino = ip->i_number;
5887 		jnewblk->jn_lbn = lbn;
5888 		add_to_journal(&jnewblk->jn_list);
5889 	}
5890 	if (freefrag && freefrag->ff_jdep != NULL &&
5891 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5892 		add_to_journal(freefrag->ff_jdep);
5893 	return (aip);
5894 }
5895 
5896 /*
5897  * Called just before setting an indirect block pointer
5898  * to a newly allocated file page.
5899  */
5900 void
5901 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5902 	struct inode *ip;	/* inode for file being extended */
5903 	ufs_lbn_t lbn;		/* allocated block number within file */
5904 	struct buf *bp;		/* buffer with indirect blk referencing page */
5905 	int ptrno;		/* offset of pointer in indirect block */
5906 	ufs2_daddr_t newblkno;	/* disk block number being added */
5907 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5908 	struct buf *nbp;	/* buffer holding allocated page */
5909 {
5910 	struct inodedep *inodedep;
5911 	struct freefrag *freefrag;
5912 	struct allocindir *aip;
5913 	struct pagedep *pagedep;
5914 	struct mount *mp;
5915 	struct ufsmount *ump;
5916 
5917 	mp = ITOVFS(ip);
5918 	ump = VFSTOUFS(mp);
5919 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5920 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5921 	KASSERT(lbn == nbp->b_lblkno,
5922 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5923 	    lbn, bp->b_lblkno));
5924 	CTR4(KTR_SUJ,
5925 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5926 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5927 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5928 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5929 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5930 	/*
5931 	 * If we are allocating a directory page, then we must
5932 	 * allocate an associated pagedep to track additions and
5933 	 * deletions.
5934 	 */
5935 	if ((ip->i_mode & IFMT) == IFDIR)
5936 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5937 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5938 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5939 	FREE_LOCK(ump);
5940 	if (freefrag)
5941 		handle_workitem_freefrag(freefrag);
5942 }
5943 
5944 /*
5945  * Called just before setting an indirect block pointer to a
5946  * newly allocated indirect block.
5947  */
5948 void
5949 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5950 	struct buf *nbp;	/* newly allocated indirect block */
5951 	struct inode *ip;	/* inode for file being extended */
5952 	struct buf *bp;		/* indirect block referencing allocated block */
5953 	int ptrno;		/* offset of pointer in indirect block */
5954 	ufs2_daddr_t newblkno;	/* disk block number being added */
5955 {
5956 	struct inodedep *inodedep;
5957 	struct allocindir *aip;
5958 	struct ufsmount *ump;
5959 	ufs_lbn_t lbn;
5960 
5961 	ump = ITOUMP(ip);
5962 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5963 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5964 	CTR3(KTR_SUJ,
5965 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5966 	    ip->i_number, newblkno, ptrno);
5967 	lbn = nbp->b_lblkno;
5968 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5969 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5970 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5971 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5972 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5973 		panic("softdep_setup_allocindir_meta: Block already existed");
5974 	FREE_LOCK(ump);
5975 }
5976 
5977 static void
5978 indirdep_complete(indirdep)
5979 	struct indirdep *indirdep;
5980 {
5981 	struct allocindir *aip;
5982 
5983 	LIST_REMOVE(indirdep, ir_next);
5984 	indirdep->ir_state |= DEPCOMPLETE;
5985 
5986 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5987 		LIST_REMOVE(aip, ai_next);
5988 		free_newblk(&aip->ai_block);
5989 	}
5990 	/*
5991 	 * If this indirdep is not attached to a buf it was simply waiting
5992 	 * on completion to clear completehd.  free_indirdep() asserts
5993 	 * that nothing is dangling.
5994 	 */
5995 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5996 		free_indirdep(indirdep);
5997 }
5998 
5999 static struct indirdep *
6000 indirdep_lookup(mp, ip, bp)
6001 	struct mount *mp;
6002 	struct inode *ip;
6003 	struct buf *bp;
6004 {
6005 	struct indirdep *indirdep, *newindirdep;
6006 	struct newblk *newblk;
6007 	struct ufsmount *ump;
6008 	struct worklist *wk;
6009 	struct fs *fs;
6010 	ufs2_daddr_t blkno;
6011 
6012 	ump = VFSTOUFS(mp);
6013 	LOCK_OWNED(ump);
6014 	indirdep = NULL;
6015 	newindirdep = NULL;
6016 	fs = ump->um_fs;
6017 	for (;;) {
6018 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6019 			if (wk->wk_type != D_INDIRDEP)
6020 				continue;
6021 			indirdep = WK_INDIRDEP(wk);
6022 			break;
6023 		}
6024 		/* Found on the buffer worklist, no new structure to free. */
6025 		if (indirdep != NULL && newindirdep == NULL)
6026 			return (indirdep);
6027 		if (indirdep != NULL && newindirdep != NULL)
6028 			panic("indirdep_lookup: simultaneous create");
6029 		/* None found on the buffer and a new structure is ready. */
6030 		if (indirdep == NULL && newindirdep != NULL)
6031 			break;
6032 		/* None found and no new structure available. */
6033 		FREE_LOCK(ump);
6034 		newindirdep = malloc(sizeof(struct indirdep),
6035 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
6036 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6037 		newindirdep->ir_state = ATTACHED;
6038 		if (I_IS_UFS1(ip))
6039 			newindirdep->ir_state |= UFS1FMT;
6040 		TAILQ_INIT(&newindirdep->ir_trunc);
6041 		newindirdep->ir_saveddata = NULL;
6042 		LIST_INIT(&newindirdep->ir_deplisthd);
6043 		LIST_INIT(&newindirdep->ir_donehd);
6044 		LIST_INIT(&newindirdep->ir_writehd);
6045 		LIST_INIT(&newindirdep->ir_completehd);
6046 		if (bp->b_blkno == bp->b_lblkno) {
6047 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6048 			    NULL, NULL);
6049 			bp->b_blkno = blkno;
6050 		}
6051 		newindirdep->ir_freeblks = NULL;
6052 		newindirdep->ir_savebp =
6053 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6054 		newindirdep->ir_bp = bp;
6055 		BUF_KERNPROC(newindirdep->ir_savebp);
6056 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6057 		ACQUIRE_LOCK(ump);
6058 	}
6059 	indirdep = newindirdep;
6060 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6061 	/*
6062 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6063 	 * that we don't free dependencies until the pointers are valid.
6064 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6065 	 * than using the hash.
6066 	 */
6067 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6068 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6069 	else
6070 		indirdep->ir_state |= DEPCOMPLETE;
6071 	return (indirdep);
6072 }
6073 
6074 /*
6075  * Called to finish the allocation of the "aip" allocated
6076  * by one of the two routines above.
6077  */
6078 static struct freefrag *
6079 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6080 	struct buf *bp;		/* in-memory copy of the indirect block */
6081 	struct inode *ip;	/* inode for file being extended */
6082 	struct inodedep *inodedep; /* Inodedep for ip */
6083 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6084 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6085 {
6086 	struct fs *fs;
6087 	struct indirdep *indirdep;
6088 	struct allocindir *oldaip;
6089 	struct freefrag *freefrag;
6090 	struct mount *mp;
6091 	struct ufsmount *ump;
6092 
6093 	mp = ITOVFS(ip);
6094 	ump = VFSTOUFS(mp);
6095 	LOCK_OWNED(ump);
6096 	fs = ump->um_fs;
6097 	if (bp->b_lblkno >= 0)
6098 		panic("setup_allocindir_phase2: not indir blk");
6099 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6100 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6101 	indirdep = indirdep_lookup(mp, ip, bp);
6102 	KASSERT(indirdep->ir_savebp != NULL,
6103 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6104 	aip->ai_indirdep = indirdep;
6105 	/*
6106 	 * Check for an unwritten dependency for this indirect offset.  If
6107 	 * there is, merge the old dependency into the new one.  This happens
6108 	 * as a result of reallocblk only.
6109 	 */
6110 	freefrag = NULL;
6111 	if (aip->ai_oldblkno != 0) {
6112 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6113 			if (oldaip->ai_offset == aip->ai_offset) {
6114 				freefrag = allocindir_merge(aip, oldaip);
6115 				goto done;
6116 			}
6117 		}
6118 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6119 			if (oldaip->ai_offset == aip->ai_offset) {
6120 				freefrag = allocindir_merge(aip, oldaip);
6121 				goto done;
6122 			}
6123 		}
6124 	}
6125 done:
6126 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6127 	return (freefrag);
6128 }
6129 
6130 /*
6131  * Merge two allocindirs which refer to the same block.  Move newblock
6132  * dependencies and setup the freefrags appropriately.
6133  */
6134 static struct freefrag *
6135 allocindir_merge(aip, oldaip)
6136 	struct allocindir *aip;
6137 	struct allocindir *oldaip;
6138 {
6139 	struct freefrag *freefrag;
6140 	struct worklist *wk;
6141 
6142 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6143 		panic("allocindir_merge: blkno");
6144 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6145 	freefrag = aip->ai_freefrag;
6146 	aip->ai_freefrag = oldaip->ai_freefrag;
6147 	oldaip->ai_freefrag = NULL;
6148 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6149 	/*
6150 	 * If we are tracking a new directory-block allocation,
6151 	 * move it from the old allocindir to the new allocindir.
6152 	 */
6153 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6154 		WORKLIST_REMOVE(wk);
6155 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6156 			panic("allocindir_merge: extra newdirblk");
6157 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6158 	}
6159 	/*
6160 	 * We can skip journaling for this freefrag and just complete
6161 	 * any pending journal work for the allocindir that is being
6162 	 * removed after the freefrag completes.
6163 	 */
6164 	if (freefrag->ff_jdep)
6165 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6166 	LIST_REMOVE(oldaip, ai_next);
6167 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6168 	    &freefrag->ff_list, &freefrag->ff_jwork);
6169 	free_newblk(&oldaip->ai_block);
6170 
6171 	return (freefrag);
6172 }
6173 
6174 static inline void
6175 setup_freedirect(freeblks, ip, i, needj)
6176 	struct freeblks *freeblks;
6177 	struct inode *ip;
6178 	int i;
6179 	int needj;
6180 {
6181 	struct ufsmount *ump;
6182 	ufs2_daddr_t blkno;
6183 	int frags;
6184 
6185 	blkno = DIP(ip, i_db[i]);
6186 	if (blkno == 0)
6187 		return;
6188 	DIP_SET(ip, i_db[i], 0);
6189 	ump = ITOUMP(ip);
6190 	frags = sblksize(ump->um_fs, ip->i_size, i);
6191 	frags = numfrags(ump->um_fs, frags);
6192 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6193 }
6194 
6195 static inline void
6196 setup_freeext(freeblks, ip, i, needj)
6197 	struct freeblks *freeblks;
6198 	struct inode *ip;
6199 	int i;
6200 	int needj;
6201 {
6202 	struct ufsmount *ump;
6203 	ufs2_daddr_t blkno;
6204 	int frags;
6205 
6206 	blkno = ip->i_din2->di_extb[i];
6207 	if (blkno == 0)
6208 		return;
6209 	ip->i_din2->di_extb[i] = 0;
6210 	ump = ITOUMP(ip);
6211 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6212 	frags = numfrags(ump->um_fs, frags);
6213 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6214 }
6215 
6216 static inline void
6217 setup_freeindir(freeblks, ip, i, lbn, needj)
6218 	struct freeblks *freeblks;
6219 	struct inode *ip;
6220 	int i;
6221 	ufs_lbn_t lbn;
6222 	int needj;
6223 {
6224 	struct ufsmount *ump;
6225 	ufs2_daddr_t blkno;
6226 
6227 	blkno = DIP(ip, i_ib[i]);
6228 	if (blkno == 0)
6229 		return;
6230 	DIP_SET(ip, i_ib[i], 0);
6231 	ump = ITOUMP(ip);
6232 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6233 	    0, needj);
6234 }
6235 
6236 static inline struct freeblks *
6237 newfreeblks(mp, ip)
6238 	struct mount *mp;
6239 	struct inode *ip;
6240 {
6241 	struct freeblks *freeblks;
6242 
6243 	freeblks = malloc(sizeof(struct freeblks),
6244 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6245 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6246 	LIST_INIT(&freeblks->fb_jblkdephd);
6247 	LIST_INIT(&freeblks->fb_jwork);
6248 	freeblks->fb_ref = 0;
6249 	freeblks->fb_cgwait = 0;
6250 	freeblks->fb_state = ATTACHED;
6251 	freeblks->fb_uid = ip->i_uid;
6252 	freeblks->fb_inum = ip->i_number;
6253 	freeblks->fb_vtype = ITOV(ip)->v_type;
6254 	freeblks->fb_modrev = DIP(ip, i_modrev);
6255 	freeblks->fb_devvp = ITODEVVP(ip);
6256 	freeblks->fb_chkcnt = 0;
6257 	freeblks->fb_len = 0;
6258 
6259 	return (freeblks);
6260 }
6261 
6262 static void
6263 trunc_indirdep(indirdep, freeblks, bp, off)
6264 	struct indirdep *indirdep;
6265 	struct freeblks *freeblks;
6266 	struct buf *bp;
6267 	int off;
6268 {
6269 	struct allocindir *aip, *aipn;
6270 
6271 	/*
6272 	 * The first set of allocindirs won't be in savedbp.
6273 	 */
6274 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6275 		if (aip->ai_offset > off)
6276 			cancel_allocindir(aip, bp, freeblks, 1);
6277 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6278 		if (aip->ai_offset > off)
6279 			cancel_allocindir(aip, bp, freeblks, 1);
6280 	/*
6281 	 * These will exist in savedbp.
6282 	 */
6283 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6284 		if (aip->ai_offset > off)
6285 			cancel_allocindir(aip, NULL, freeblks, 0);
6286 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6287 		if (aip->ai_offset > off)
6288 			cancel_allocindir(aip, NULL, freeblks, 0);
6289 }
6290 
6291 /*
6292  * Follow the chain of indirects down to lastlbn creating a freework
6293  * structure for each.  This will be used to start indir_trunc() at
6294  * the right offset and create the journal records for the parrtial
6295  * truncation.  A second step will handle the truncated dependencies.
6296  */
6297 static int
6298 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6299 	struct freeblks *freeblks;
6300 	struct inode *ip;
6301 	ufs_lbn_t lbn;
6302 	ufs_lbn_t lastlbn;
6303 	ufs2_daddr_t blkno;
6304 {
6305 	struct indirdep *indirdep;
6306 	struct indirdep *indirn;
6307 	struct freework *freework;
6308 	struct newblk *newblk;
6309 	struct mount *mp;
6310 	struct ufsmount *ump;
6311 	struct buf *bp;
6312 	uint8_t *start;
6313 	uint8_t *end;
6314 	ufs_lbn_t lbnadd;
6315 	int level;
6316 	int error;
6317 	int off;
6318 
6319 
6320 	freework = NULL;
6321 	if (blkno == 0)
6322 		return (0);
6323 	mp = freeblks->fb_list.wk_mp;
6324 	ump = VFSTOUFS(mp);
6325 	/*
6326 	 * Here, calls to VOP_BMAP() will fail.  However, we already have
6327 	 * the on-disk address, so we just pass it to bread() instead of
6328 	 * having bread() attempt to calculate it using VOP_BMAP().
6329 	 */
6330 	error = breadn_flags(ITOV(ip), lbn, blkptrtodb(ump, blkno),
6331 	    (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6332 	if (error)
6333 		return (error);
6334 	level = lbn_level(lbn);
6335 	lbnadd = lbn_offset(ump->um_fs, level);
6336 	/*
6337 	 * Compute the offset of the last block we want to keep.  Store
6338 	 * in the freework the first block we want to completely free.
6339 	 */
6340 	off = (lastlbn - -(lbn + level)) / lbnadd;
6341 	if (off + 1 == NINDIR(ump->um_fs))
6342 		goto nowork;
6343 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6344 	/*
6345 	 * Link the freework into the indirdep.  This will prevent any new
6346 	 * allocations from proceeding until we are finished with the
6347 	 * truncate and the block is written.
6348 	 */
6349 	ACQUIRE_LOCK(ump);
6350 	indirdep = indirdep_lookup(mp, ip, bp);
6351 	if (indirdep->ir_freeblks)
6352 		panic("setup_trunc_indir: indirdep already truncated.");
6353 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6354 	freework->fw_indir = indirdep;
6355 	/*
6356 	 * Cancel any allocindirs that will not make it to disk.
6357 	 * We have to do this for all copies of the indirdep that
6358 	 * live on this newblk.
6359 	 */
6360 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6361 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6362 		    &newblk) == 0)
6363 			panic("setup_trunc_indir: lost block");
6364 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6365 			trunc_indirdep(indirn, freeblks, bp, off);
6366 	} else
6367 		trunc_indirdep(indirdep, freeblks, bp, off);
6368 	FREE_LOCK(ump);
6369 	/*
6370 	 * Creation is protected by the buf lock. The saveddata is only
6371 	 * needed if a full truncation follows a partial truncation but it
6372 	 * is difficult to allocate in that case so we fetch it anyway.
6373 	 */
6374 	if (indirdep->ir_saveddata == NULL)
6375 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6376 		    M_SOFTDEP_FLAGS);
6377 nowork:
6378 	/* Fetch the blkno of the child and the zero start offset. */
6379 	if (I_IS_UFS1(ip)) {
6380 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6381 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6382 	} else {
6383 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6384 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6385 	}
6386 	if (freework) {
6387 		/* Zero the truncated pointers. */
6388 		end = bp->b_data + bp->b_bcount;
6389 		bzero(start, end - start);
6390 		bdwrite(bp);
6391 	} else
6392 		bqrelse(bp);
6393 	if (level == 0)
6394 		return (0);
6395 	lbn++; /* adjust level */
6396 	lbn -= (off * lbnadd);
6397 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6398 }
6399 
6400 /*
6401  * Complete the partial truncation of an indirect block setup by
6402  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6403  * copy and writes them to disk before the freeblks is allowed to complete.
6404  */
6405 static void
6406 complete_trunc_indir(freework)
6407 	struct freework *freework;
6408 {
6409 	struct freework *fwn;
6410 	struct indirdep *indirdep;
6411 	struct ufsmount *ump;
6412 	struct buf *bp;
6413 	uintptr_t start;
6414 	int count;
6415 
6416 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6417 	LOCK_OWNED(ump);
6418 	indirdep = freework->fw_indir;
6419 	for (;;) {
6420 		bp = indirdep->ir_bp;
6421 		/* See if the block was discarded. */
6422 		if (bp == NULL)
6423 			break;
6424 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6425 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6426 			break;
6427 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6428 		    LOCK_PTR(ump)) == 0)
6429 			BUF_UNLOCK(bp);
6430 		ACQUIRE_LOCK(ump);
6431 	}
6432 	freework->fw_state |= DEPCOMPLETE;
6433 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6434 	/*
6435 	 * Zero the pointers in the saved copy.
6436 	 */
6437 	if (indirdep->ir_state & UFS1FMT)
6438 		start = sizeof(ufs1_daddr_t);
6439 	else
6440 		start = sizeof(ufs2_daddr_t);
6441 	start *= freework->fw_start;
6442 	count = indirdep->ir_savebp->b_bcount - start;
6443 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6444 	bzero((char *)start, count);
6445 	/*
6446 	 * We need to start the next truncation in the list if it has not
6447 	 * been started yet.
6448 	 */
6449 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6450 	if (fwn != NULL) {
6451 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6452 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6453 		if ((fwn->fw_state & ONWORKLIST) == 0)
6454 			freework_enqueue(fwn);
6455 	}
6456 	/*
6457 	 * If bp is NULL the block was fully truncated, restore
6458 	 * the saved block list otherwise free it if it is no
6459 	 * longer needed.
6460 	 */
6461 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6462 		if (bp == NULL)
6463 			bcopy(indirdep->ir_saveddata,
6464 			    indirdep->ir_savebp->b_data,
6465 			    indirdep->ir_savebp->b_bcount);
6466 		free(indirdep->ir_saveddata, M_INDIRDEP);
6467 		indirdep->ir_saveddata = NULL;
6468 	}
6469 	/*
6470 	 * When bp is NULL there is a full truncation pending.  We
6471 	 * must wait for this full truncation to be journaled before
6472 	 * we can release this freework because the disk pointers will
6473 	 * never be written as zero.
6474 	 */
6475 	if (bp == NULL)  {
6476 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6477 			handle_written_freework(freework);
6478 		else
6479 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6480 			   &freework->fw_list);
6481 	} else {
6482 		/* Complete when the real copy is written. */
6483 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6484 		BUF_UNLOCK(bp);
6485 	}
6486 }
6487 
6488 /*
6489  * Calculate the number of blocks we are going to release where datablocks
6490  * is the current total and length is the new file size.
6491  */
6492 static ufs2_daddr_t
6493 blkcount(fs, datablocks, length)
6494 	struct fs *fs;
6495 	ufs2_daddr_t datablocks;
6496 	off_t length;
6497 {
6498 	off_t totblks, numblks;
6499 
6500 	totblks = 0;
6501 	numblks = howmany(length, fs->fs_bsize);
6502 	if (numblks <= UFS_NDADDR) {
6503 		totblks = howmany(length, fs->fs_fsize);
6504 		goto out;
6505 	}
6506         totblks = blkstofrags(fs, numblks);
6507 	numblks -= UFS_NDADDR;
6508 	/*
6509 	 * Count all single, then double, then triple indirects required.
6510 	 * Subtracting one indirects worth of blocks for each pass
6511 	 * acknowledges one of each pointed to by the inode.
6512 	 */
6513 	for (;;) {
6514 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6515 		numblks -= NINDIR(fs);
6516 		if (numblks <= 0)
6517 			break;
6518 		numblks = howmany(numblks, NINDIR(fs));
6519 	}
6520 out:
6521 	totblks = fsbtodb(fs, totblks);
6522 	/*
6523 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6524 	 * references.  We will correct it later in handle_complete_freeblks()
6525 	 * when we know the real count.
6526 	 */
6527 	if (totblks > datablocks)
6528 		return (0);
6529 	return (datablocks - totblks);
6530 }
6531 
6532 /*
6533  * Handle freeblocks for journaled softupdate filesystems.
6534  *
6535  * Contrary to normal softupdates, we must preserve the block pointers in
6536  * indirects until their subordinates are free.  This is to avoid journaling
6537  * every block that is freed which may consume more space than the journal
6538  * itself.  The recovery program will see the free block journals at the
6539  * base of the truncated area and traverse them to reclaim space.  The
6540  * pointers in the inode may be cleared immediately after the journal
6541  * records are written because each direct and indirect pointer in the
6542  * inode is recorded in a journal.  This permits full truncation to proceed
6543  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6544  *
6545  * The algorithm is as follows:
6546  * 1) Traverse the in-memory state and create journal entries to release
6547  *    the relevant blocks and full indirect trees.
6548  * 2) Traverse the indirect block chain adding partial truncation freework
6549  *    records to indirects in the path to lastlbn.  The freework will
6550  *    prevent new allocation dependencies from being satisfied in this
6551  *    indirect until the truncation completes.
6552  * 3) Read and lock the inode block, performing an update with the new size
6553  *    and pointers.  This prevents truncated data from becoming valid on
6554  *    disk through step 4.
6555  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6556  *    eliminate journal work for those records that do not require it.
6557  * 5) Schedule the journal records to be written followed by the inode block.
6558  * 6) Allocate any necessary frags for the end of file.
6559  * 7) Zero any partially truncated blocks.
6560  *
6561  * From this truncation proceeds asynchronously using the freework and
6562  * indir_trunc machinery.  The file will not be extended again into a
6563  * partially truncated indirect block until all work is completed but
6564  * the normal dependency mechanism ensures that it is rolled back/forward
6565  * as appropriate.  Further truncation may occur without delay and is
6566  * serialized in indir_trunc().
6567  */
6568 void
6569 softdep_journal_freeblocks(ip, cred, length, flags)
6570 	struct inode *ip;	/* The inode whose length is to be reduced */
6571 	struct ucred *cred;
6572 	off_t length;		/* The new length for the file */
6573 	int flags;		/* IO_EXT and/or IO_NORMAL */
6574 {
6575 	struct freeblks *freeblks, *fbn;
6576 	struct worklist *wk, *wkn;
6577 	struct inodedep *inodedep;
6578 	struct jblkdep *jblkdep;
6579 	struct allocdirect *adp, *adpn;
6580 	struct ufsmount *ump;
6581 	struct fs *fs;
6582 	struct buf *bp;
6583 	struct vnode *vp;
6584 	struct mount *mp;
6585 	ufs2_daddr_t extblocks, datablocks;
6586 	ufs_lbn_t tmpval, lbn, lastlbn;
6587 	int frags, lastoff, iboff, allocblock, needj, error, i;
6588 
6589 	ump = ITOUMP(ip);
6590 	mp = UFSTOVFS(ump);
6591 	fs = ump->um_fs;
6592 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6593 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6594 	vp = ITOV(ip);
6595 	needj = 1;
6596 	iboff = -1;
6597 	allocblock = 0;
6598 	extblocks = 0;
6599 	datablocks = 0;
6600 	frags = 0;
6601 	freeblks = newfreeblks(mp, ip);
6602 	ACQUIRE_LOCK(ump);
6603 	/*
6604 	 * If we're truncating a removed file that will never be written
6605 	 * we don't need to journal the block frees.  The canceled journals
6606 	 * for the allocations will suffice.
6607 	 */
6608 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6609 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6610 	    length == 0)
6611 		needj = 0;
6612 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6613 	    ip->i_number, length, needj);
6614 	FREE_LOCK(ump);
6615 	/*
6616 	 * Calculate the lbn that we are truncating to.  This results in -1
6617 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6618 	 * to keep, not the first lbn we want to truncate.
6619 	 */
6620 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6621 	lastoff = blkoff(fs, length);
6622 	/*
6623 	 * Compute frags we are keeping in lastlbn.  0 means all.
6624 	 */
6625 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6626 		frags = fragroundup(fs, lastoff);
6627 		/* adp offset of last valid allocdirect. */
6628 		iboff = lastlbn;
6629 	} else if (lastlbn > 0)
6630 		iboff = UFS_NDADDR;
6631 	if (fs->fs_magic == FS_UFS2_MAGIC)
6632 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6633 	/*
6634 	 * Handle normal data blocks and indirects.  This section saves
6635 	 * values used after the inode update to complete frag and indirect
6636 	 * truncation.
6637 	 */
6638 	if ((flags & IO_NORMAL) != 0) {
6639 		/*
6640 		 * Handle truncation of whole direct and indirect blocks.
6641 		 */
6642 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6643 			setup_freedirect(freeblks, ip, i, needj);
6644 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6645 		    i < UFS_NIADDR;
6646 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6647 			/* Release a whole indirect tree. */
6648 			if (lbn > lastlbn) {
6649 				setup_freeindir(freeblks, ip, i, -lbn -i,
6650 				    needj);
6651 				continue;
6652 			}
6653 			iboff = i + UFS_NDADDR;
6654 			/*
6655 			 * Traverse partially truncated indirect tree.
6656 			 */
6657 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6658 				setup_trunc_indir(freeblks, ip, -lbn - i,
6659 				    lastlbn, DIP(ip, i_ib[i]));
6660 		}
6661 		/*
6662 		 * Handle partial truncation to a frag boundary.
6663 		 */
6664 		if (frags) {
6665 			ufs2_daddr_t blkno;
6666 			long oldfrags;
6667 
6668 			oldfrags = blksize(fs, ip, lastlbn);
6669 			blkno = DIP(ip, i_db[lastlbn]);
6670 			if (blkno && oldfrags != frags) {
6671 				oldfrags -= frags;
6672 				oldfrags = numfrags(fs, oldfrags);
6673 				blkno += numfrags(fs, frags);
6674 				newfreework(ump, freeblks, NULL, lastlbn,
6675 				    blkno, oldfrags, 0, needj);
6676 				if (needj)
6677 					adjust_newfreework(freeblks,
6678 					    numfrags(fs, frags));
6679 			} else if (blkno == 0)
6680 				allocblock = 1;
6681 		}
6682 		/*
6683 		 * Add a journal record for partial truncate if we are
6684 		 * handling indirect blocks.  Non-indirects need no extra
6685 		 * journaling.
6686 		 */
6687 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6688 			UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
6689 			newjtrunc(freeblks, length, 0);
6690 		}
6691 		ip->i_size = length;
6692 		DIP_SET(ip, i_size, ip->i_size);
6693 		datablocks = DIP(ip, i_blocks) - extblocks;
6694 		if (length != 0)
6695 			datablocks = blkcount(fs, datablocks, length);
6696 		freeblks->fb_len = length;
6697 	}
6698 	if ((flags & IO_EXT) != 0) {
6699 		for (i = 0; i < UFS_NXADDR; i++)
6700 			setup_freeext(freeblks, ip, i, needj);
6701 		ip->i_din2->di_extsize = 0;
6702 		datablocks += extblocks;
6703 	}
6704 #ifdef QUOTA
6705 	/* Reference the quotas in case the block count is wrong in the end. */
6706 	quotaref(vp, freeblks->fb_quota);
6707 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6708 #endif
6709 	freeblks->fb_chkcnt = -datablocks;
6710 	UFS_LOCK(ump);
6711 	fs->fs_pendingblocks += datablocks;
6712 	UFS_UNLOCK(ump);
6713 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6714 	/*
6715 	 * Handle truncation of incomplete alloc direct dependencies.  We
6716 	 * hold the inode block locked to prevent incomplete dependencies
6717 	 * from reaching the disk while we are eliminating those that
6718 	 * have been truncated.  This is a partially inlined ffs_update().
6719 	 */
6720 	ufs_itimes(vp);
6721 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6722 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6723 	    (int)fs->fs_bsize, cred, &bp);
6724 	if (error) {
6725 		softdep_error("softdep_journal_freeblocks", error);
6726 		return;
6727 	}
6728 	if (bp->b_bufsize == fs->fs_bsize)
6729 		bp->b_flags |= B_CLUSTEROK;
6730 	softdep_update_inodeblock(ip, bp, 0);
6731 	if (ump->um_fstype == UFS1) {
6732 		*((struct ufs1_dinode *)bp->b_data +
6733 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6734 	} else {
6735 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6736 		*((struct ufs2_dinode *)bp->b_data +
6737 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6738 	}
6739 	ACQUIRE_LOCK(ump);
6740 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6741 	if ((inodedep->id_state & IOSTARTED) != 0)
6742 		panic("softdep_setup_freeblocks: inode busy");
6743 	/*
6744 	 * Add the freeblks structure to the list of operations that
6745 	 * must await the zero'ed inode being written to disk. If we
6746 	 * still have a bitmap dependency (needj), then the inode
6747 	 * has never been written to disk, so we can process the
6748 	 * freeblks below once we have deleted the dependencies.
6749 	 */
6750 	if (needj)
6751 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6752 	else
6753 		freeblks->fb_state |= COMPLETE;
6754 	if ((flags & IO_NORMAL) != 0) {
6755 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6756 			if (adp->ad_offset > iboff)
6757 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6758 				    freeblks);
6759 			/*
6760 			 * Truncate the allocdirect.  We could eliminate
6761 			 * or modify journal records as well.
6762 			 */
6763 			else if (adp->ad_offset == iboff && frags)
6764 				adp->ad_newsize = frags;
6765 		}
6766 	}
6767 	if ((flags & IO_EXT) != 0)
6768 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6769 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6770 			    freeblks);
6771 	/*
6772 	 * Scan the bufwait list for newblock dependencies that will never
6773 	 * make it to disk.
6774 	 */
6775 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6776 		if (wk->wk_type != D_ALLOCDIRECT)
6777 			continue;
6778 		adp = WK_ALLOCDIRECT(wk);
6779 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6780 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6781 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6782 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6783 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6784 		}
6785 	}
6786 	/*
6787 	 * Add journal work.
6788 	 */
6789 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6790 		add_to_journal(&jblkdep->jb_list);
6791 	FREE_LOCK(ump);
6792 	bdwrite(bp);
6793 	/*
6794 	 * Truncate dependency structures beyond length.
6795 	 */
6796 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6797 	/*
6798 	 * This is only set when we need to allocate a fragment because
6799 	 * none existed at the end of a frag-sized file.  It handles only
6800 	 * allocating a new, zero filled block.
6801 	 */
6802 	if (allocblock) {
6803 		ip->i_size = length - lastoff;
6804 		DIP_SET(ip, i_size, ip->i_size);
6805 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6806 		if (error != 0) {
6807 			softdep_error("softdep_journal_freeblks", error);
6808 			return;
6809 		}
6810 		ip->i_size = length;
6811 		DIP_SET(ip, i_size, length);
6812 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
6813 		allocbuf(bp, frags);
6814 		ffs_update(vp, 0);
6815 		bawrite(bp);
6816 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6817 		int size;
6818 
6819 		/*
6820 		 * Zero the end of a truncated frag or block.
6821 		 */
6822 		size = sblksize(fs, length, lastlbn);
6823 		error = bread(vp, lastlbn, size, cred, &bp);
6824 		if (error) {
6825 			softdep_error("softdep_journal_freeblks", error);
6826 			return;
6827 		}
6828 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6829 		bawrite(bp);
6830 
6831 	}
6832 	ACQUIRE_LOCK(ump);
6833 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6834 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6835 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6836 	/*
6837 	 * We zero earlier truncations so they don't erroneously
6838 	 * update i_blocks.
6839 	 */
6840 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6841 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6842 			fbn->fb_len = 0;
6843 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6844 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6845 		freeblks->fb_state |= INPROGRESS;
6846 	else
6847 		freeblks = NULL;
6848 	FREE_LOCK(ump);
6849 	if (freeblks)
6850 		handle_workitem_freeblocks(freeblks, 0);
6851 	trunc_pages(ip, length, extblocks, flags);
6852 
6853 }
6854 
6855 /*
6856  * Flush a JOP_SYNC to the journal.
6857  */
6858 void
6859 softdep_journal_fsync(ip)
6860 	struct inode *ip;
6861 {
6862 	struct jfsync *jfsync;
6863 	struct ufsmount *ump;
6864 
6865 	ump = ITOUMP(ip);
6866 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6867 	    ("softdep_journal_fsync called on non-softdep filesystem"));
6868 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6869 		return;
6870 	ip->i_flag &= ~IN_TRUNCATED;
6871 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6872 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6873 	jfsync->jfs_size = ip->i_size;
6874 	jfsync->jfs_ino = ip->i_number;
6875 	ACQUIRE_LOCK(ump);
6876 	add_to_journal(&jfsync->jfs_list);
6877 	jwait(&jfsync->jfs_list, MNT_WAIT);
6878 	FREE_LOCK(ump);
6879 }
6880 
6881 /*
6882  * Block de-allocation dependencies.
6883  *
6884  * When blocks are de-allocated, the on-disk pointers must be nullified before
6885  * the blocks are made available for use by other files.  (The true
6886  * requirement is that old pointers must be nullified before new on-disk
6887  * pointers are set.  We chose this slightly more stringent requirement to
6888  * reduce complexity.) Our implementation handles this dependency by updating
6889  * the inode (or indirect block) appropriately but delaying the actual block
6890  * de-allocation (i.e., freemap and free space count manipulation) until
6891  * after the updated versions reach stable storage.  After the disk is
6892  * updated, the blocks can be safely de-allocated whenever it is convenient.
6893  * This implementation handles only the common case of reducing a file's
6894  * length to zero. Other cases are handled by the conventional synchronous
6895  * write approach.
6896  *
6897  * The ffs implementation with which we worked double-checks
6898  * the state of the block pointers and file size as it reduces
6899  * a file's length.  Some of this code is replicated here in our
6900  * soft updates implementation.  The freeblks->fb_chkcnt field is
6901  * used to transfer a part of this information to the procedure
6902  * that eventually de-allocates the blocks.
6903  *
6904  * This routine should be called from the routine that shortens
6905  * a file's length, before the inode's size or block pointers
6906  * are modified. It will save the block pointer information for
6907  * later release and zero the inode so that the calling routine
6908  * can release it.
6909  */
6910 void
6911 softdep_setup_freeblocks(ip, length, flags)
6912 	struct inode *ip;	/* The inode whose length is to be reduced */
6913 	off_t length;		/* The new length for the file */
6914 	int flags;		/* IO_EXT and/or IO_NORMAL */
6915 {
6916 	struct ufs1_dinode *dp1;
6917 	struct ufs2_dinode *dp2;
6918 	struct freeblks *freeblks;
6919 	struct inodedep *inodedep;
6920 	struct allocdirect *adp;
6921 	struct ufsmount *ump;
6922 	struct buf *bp;
6923 	struct fs *fs;
6924 	ufs2_daddr_t extblocks, datablocks;
6925 	struct mount *mp;
6926 	int i, delay, error;
6927 	ufs_lbn_t tmpval;
6928 	ufs_lbn_t lbn;
6929 
6930 	ump = ITOUMP(ip);
6931 	mp = UFSTOVFS(ump);
6932 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6933 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6934 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6935 	    ip->i_number, length);
6936 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6937 	fs = ump->um_fs;
6938 	if ((error = bread(ump->um_devvp,
6939 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6940 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6941 		brelse(bp);
6942 		softdep_error("softdep_setup_freeblocks", error);
6943 		return;
6944 	}
6945 	freeblks = newfreeblks(mp, ip);
6946 	extblocks = 0;
6947 	datablocks = 0;
6948 	if (fs->fs_magic == FS_UFS2_MAGIC)
6949 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6950 	if ((flags & IO_NORMAL) != 0) {
6951 		for (i = 0; i < UFS_NDADDR; i++)
6952 			setup_freedirect(freeblks, ip, i, 0);
6953 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6954 		    i < UFS_NIADDR;
6955 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6956 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6957 		ip->i_size = 0;
6958 		DIP_SET(ip, i_size, 0);
6959 		datablocks = DIP(ip, i_blocks) - extblocks;
6960 	}
6961 	if ((flags & IO_EXT) != 0) {
6962 		for (i = 0; i < UFS_NXADDR; i++)
6963 			setup_freeext(freeblks, ip, i, 0);
6964 		ip->i_din2->di_extsize = 0;
6965 		datablocks += extblocks;
6966 	}
6967 #ifdef QUOTA
6968 	/* Reference the quotas in case the block count is wrong in the end. */
6969 	quotaref(ITOV(ip), freeblks->fb_quota);
6970 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6971 #endif
6972 	freeblks->fb_chkcnt = -datablocks;
6973 	UFS_LOCK(ump);
6974 	fs->fs_pendingblocks += datablocks;
6975 	UFS_UNLOCK(ump);
6976 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6977 	/*
6978 	 * Push the zero'ed inode to its disk buffer so that we are free
6979 	 * to delete its dependencies below. Once the dependencies are gone
6980 	 * the buffer can be safely released.
6981 	 */
6982 	if (ump->um_fstype == UFS1) {
6983 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6984 		    ino_to_fsbo(fs, ip->i_number));
6985 		ip->i_din1->di_freelink = dp1->di_freelink;
6986 		*dp1 = *ip->i_din1;
6987 	} else {
6988 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6989 		    ino_to_fsbo(fs, ip->i_number));
6990 		ip->i_din2->di_freelink = dp2->di_freelink;
6991 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6992 		*dp2 = *ip->i_din2;
6993 	}
6994 	/*
6995 	 * Find and eliminate any inode dependencies.
6996 	 */
6997 	ACQUIRE_LOCK(ump);
6998 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6999 	if ((inodedep->id_state & IOSTARTED) != 0)
7000 		panic("softdep_setup_freeblocks: inode busy");
7001 	/*
7002 	 * Add the freeblks structure to the list of operations that
7003 	 * must await the zero'ed inode being written to disk. If we
7004 	 * still have a bitmap dependency (delay == 0), then the inode
7005 	 * has never been written to disk, so we can process the
7006 	 * freeblks below once we have deleted the dependencies.
7007 	 */
7008 	delay = (inodedep->id_state & DEPCOMPLETE);
7009 	if (delay)
7010 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7011 	else
7012 		freeblks->fb_state |= COMPLETE;
7013 	/*
7014 	 * Because the file length has been truncated to zero, any
7015 	 * pending block allocation dependency structures associated
7016 	 * with this inode are obsolete and can simply be de-allocated.
7017 	 * We must first merge the two dependency lists to get rid of
7018 	 * any duplicate freefrag structures, then purge the merged list.
7019 	 * If we still have a bitmap dependency, then the inode has never
7020 	 * been written to disk, so we can free any fragments without delay.
7021 	 */
7022 	if (flags & IO_NORMAL) {
7023 		merge_inode_lists(&inodedep->id_newinoupdt,
7024 		    &inodedep->id_inoupdt);
7025 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7026 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7027 			    freeblks);
7028 	}
7029 	if (flags & IO_EXT) {
7030 		merge_inode_lists(&inodedep->id_newextupdt,
7031 		    &inodedep->id_extupdt);
7032 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7033 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7034 			    freeblks);
7035 	}
7036 	FREE_LOCK(ump);
7037 	bdwrite(bp);
7038 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7039 	ACQUIRE_LOCK(ump);
7040 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7041 		(void) free_inodedep(inodedep);
7042 	freeblks->fb_state |= DEPCOMPLETE;
7043 	/*
7044 	 * If the inode with zeroed block pointers is now on disk
7045 	 * we can start freeing blocks.
7046 	 */
7047 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7048 		freeblks->fb_state |= INPROGRESS;
7049 	else
7050 		freeblks = NULL;
7051 	FREE_LOCK(ump);
7052 	if (freeblks)
7053 		handle_workitem_freeblocks(freeblks, 0);
7054 	trunc_pages(ip, length, extblocks, flags);
7055 }
7056 
7057 /*
7058  * Eliminate pages from the page cache that back parts of this inode and
7059  * adjust the vnode pager's idea of our size.  This prevents stale data
7060  * from hanging around in the page cache.
7061  */
7062 static void
7063 trunc_pages(ip, length, extblocks, flags)
7064 	struct inode *ip;
7065 	off_t length;
7066 	ufs2_daddr_t extblocks;
7067 	int flags;
7068 {
7069 	struct vnode *vp;
7070 	struct fs *fs;
7071 	ufs_lbn_t lbn;
7072 	off_t end, extend;
7073 
7074 	vp = ITOV(ip);
7075 	fs = ITOFS(ip);
7076 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7077 	if ((flags & IO_EXT) != 0)
7078 		vn_pages_remove(vp, extend, 0);
7079 	if ((flags & IO_NORMAL) == 0)
7080 		return;
7081 	BO_LOCK(&vp->v_bufobj);
7082 	drain_output(vp);
7083 	BO_UNLOCK(&vp->v_bufobj);
7084 	/*
7085 	 * The vnode pager eliminates file pages we eliminate indirects
7086 	 * below.
7087 	 */
7088 	vnode_pager_setsize(vp, length);
7089 	/*
7090 	 * Calculate the end based on the last indirect we want to keep.  If
7091 	 * the block extends into indirects we can just use the negative of
7092 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7093 	 * be careful not to remove those, if they exist.  double and triple
7094 	 * indirect lbns do not overlap with others so it is not important
7095 	 * to verify how many levels are required.
7096 	 */
7097 	lbn = lblkno(fs, length);
7098 	if (lbn >= UFS_NDADDR) {
7099 		/* Calculate the virtual lbn of the triple indirect. */
7100 		lbn = -lbn - (UFS_NIADDR - 1);
7101 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7102 	} else
7103 		end = extend;
7104 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7105 }
7106 
7107 /*
7108  * See if the buf bp is in the range eliminated by truncation.
7109  */
7110 static int
7111 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7112 	struct buf *bp;
7113 	int *blkoffp;
7114 	ufs_lbn_t lastlbn;
7115 	int lastoff;
7116 	int flags;
7117 {
7118 	ufs_lbn_t lbn;
7119 
7120 	*blkoffp = 0;
7121 	/* Only match ext/normal blocks as appropriate. */
7122 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7123 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7124 		return (0);
7125 	/* ALTDATA is always a full truncation. */
7126 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7127 		return (1);
7128 	/* -1 is full truncation. */
7129 	if (lastlbn == -1)
7130 		return (1);
7131 	/*
7132 	 * If this is a partial truncate we only want those
7133 	 * blocks and indirect blocks that cover the range
7134 	 * we're after.
7135 	 */
7136 	lbn = bp->b_lblkno;
7137 	if (lbn < 0)
7138 		lbn = -(lbn + lbn_level(lbn));
7139 	if (lbn < lastlbn)
7140 		return (0);
7141 	/* Here we only truncate lblkno if it's partial. */
7142 	if (lbn == lastlbn) {
7143 		if (lastoff == 0)
7144 			return (0);
7145 		*blkoffp = lastoff;
7146 	}
7147 	return (1);
7148 }
7149 
7150 /*
7151  * Eliminate any dependencies that exist in memory beyond lblkno:off
7152  */
7153 static void
7154 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7155 	struct inode *ip;
7156 	struct freeblks *freeblks;
7157 	ufs_lbn_t lastlbn;
7158 	int lastoff;
7159 	int flags;
7160 {
7161 	struct bufobj *bo;
7162 	struct vnode *vp;
7163 	struct buf *bp;
7164 	int blkoff;
7165 
7166 	/*
7167 	 * We must wait for any I/O in progress to finish so that
7168 	 * all potential buffers on the dirty list will be visible.
7169 	 * Once they are all there, walk the list and get rid of
7170 	 * any dependencies.
7171 	 */
7172 	vp = ITOV(ip);
7173 	bo = &vp->v_bufobj;
7174 	BO_LOCK(bo);
7175 	drain_output(vp);
7176 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7177 		bp->b_vflags &= ~BV_SCANNED;
7178 restart:
7179 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7180 		if (bp->b_vflags & BV_SCANNED)
7181 			continue;
7182 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7183 			bp->b_vflags |= BV_SCANNED;
7184 			continue;
7185 		}
7186 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7187 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7188 			goto restart;
7189 		BO_UNLOCK(bo);
7190 		if (deallocate_dependencies(bp, freeblks, blkoff))
7191 			bqrelse(bp);
7192 		else
7193 			brelse(bp);
7194 		BO_LOCK(bo);
7195 		goto restart;
7196 	}
7197 	/*
7198 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7199 	 */
7200 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7201 		bp->b_vflags &= ~BV_SCANNED;
7202 cleanrestart:
7203 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7204 		if (bp->b_vflags & BV_SCANNED)
7205 			continue;
7206 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7207 			bp->b_vflags |= BV_SCANNED;
7208 			continue;
7209 		}
7210 		if (BUF_LOCK(bp,
7211 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7212 		    BO_LOCKPTR(bo)) == ENOLCK) {
7213 			BO_LOCK(bo);
7214 			goto cleanrestart;
7215 		}
7216 		bp->b_vflags |= BV_SCANNED;
7217 		bremfree(bp);
7218 		if (blkoff != 0) {
7219 			allocbuf(bp, blkoff);
7220 			bqrelse(bp);
7221 		} else {
7222 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7223 			brelse(bp);
7224 		}
7225 		BO_LOCK(bo);
7226 		goto cleanrestart;
7227 	}
7228 	drain_output(vp);
7229 	BO_UNLOCK(bo);
7230 }
7231 
7232 static int
7233 cancel_pagedep(pagedep, freeblks, blkoff)
7234 	struct pagedep *pagedep;
7235 	struct freeblks *freeblks;
7236 	int blkoff;
7237 {
7238 	struct jremref *jremref;
7239 	struct jmvref *jmvref;
7240 	struct dirrem *dirrem, *tmp;
7241 	int i;
7242 
7243 	/*
7244 	 * Copy any directory remove dependencies to the list
7245 	 * to be processed after the freeblks proceeds.  If
7246 	 * directory entry never made it to disk they
7247 	 * can be dumped directly onto the work list.
7248 	 */
7249 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7250 		/* Skip this directory removal if it is intended to remain. */
7251 		if (dirrem->dm_offset < blkoff)
7252 			continue;
7253 		/*
7254 		 * If there are any dirrems we wait for the journal write
7255 		 * to complete and then restart the buf scan as the lock
7256 		 * has been dropped.
7257 		 */
7258 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7259 			jwait(&jremref->jr_list, MNT_WAIT);
7260 			return (ERESTART);
7261 		}
7262 		LIST_REMOVE(dirrem, dm_next);
7263 		dirrem->dm_dirinum = pagedep->pd_ino;
7264 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7265 	}
7266 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7267 		jwait(&jmvref->jm_list, MNT_WAIT);
7268 		return (ERESTART);
7269 	}
7270 	/*
7271 	 * When we're partially truncating a pagedep we just want to flush
7272 	 * journal entries and return.  There can not be any adds in the
7273 	 * truncated portion of the directory and newblk must remain if
7274 	 * part of the block remains.
7275 	 */
7276 	if (blkoff != 0) {
7277 		struct diradd *dap;
7278 
7279 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7280 			if (dap->da_offset > blkoff)
7281 				panic("cancel_pagedep: diradd %p off %d > %d",
7282 				    dap, dap->da_offset, blkoff);
7283 		for (i = 0; i < DAHASHSZ; i++)
7284 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7285 				if (dap->da_offset > blkoff)
7286 					panic("cancel_pagedep: diradd %p off %d > %d",
7287 					    dap, dap->da_offset, blkoff);
7288 		return (0);
7289 	}
7290 	/*
7291 	 * There should be no directory add dependencies present
7292 	 * as the directory could not be truncated until all
7293 	 * children were removed.
7294 	 */
7295 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7296 	    ("deallocate_dependencies: pendinghd != NULL"));
7297 	for (i = 0; i < DAHASHSZ; i++)
7298 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7299 		    ("deallocate_dependencies: diraddhd != NULL"));
7300 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7301 		free_newdirblk(pagedep->pd_newdirblk);
7302 	if (free_pagedep(pagedep) == 0)
7303 		panic("Failed to free pagedep %p", pagedep);
7304 	return (0);
7305 }
7306 
7307 /*
7308  * Reclaim any dependency structures from a buffer that is about to
7309  * be reallocated to a new vnode. The buffer must be locked, thus,
7310  * no I/O completion operations can occur while we are manipulating
7311  * its associated dependencies. The mutex is held so that other I/O's
7312  * associated with related dependencies do not occur.
7313  */
7314 static int
7315 deallocate_dependencies(bp, freeblks, off)
7316 	struct buf *bp;
7317 	struct freeblks *freeblks;
7318 	int off;
7319 {
7320 	struct indirdep *indirdep;
7321 	struct pagedep *pagedep;
7322 	struct worklist *wk, *wkn;
7323 	struct ufsmount *ump;
7324 
7325 	ump = softdep_bp_to_mp(bp);
7326 	if (ump == NULL)
7327 		goto done;
7328 	ACQUIRE_LOCK(ump);
7329 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7330 		switch (wk->wk_type) {
7331 		case D_INDIRDEP:
7332 			indirdep = WK_INDIRDEP(wk);
7333 			if (bp->b_lblkno >= 0 ||
7334 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7335 				panic("deallocate_dependencies: not indir");
7336 			cancel_indirdep(indirdep, bp, freeblks);
7337 			continue;
7338 
7339 		case D_PAGEDEP:
7340 			pagedep = WK_PAGEDEP(wk);
7341 			if (cancel_pagedep(pagedep, freeblks, off)) {
7342 				FREE_LOCK(ump);
7343 				return (ERESTART);
7344 			}
7345 			continue;
7346 
7347 		case D_ALLOCINDIR:
7348 			/*
7349 			 * Simply remove the allocindir, we'll find it via
7350 			 * the indirdep where we can clear pointers if
7351 			 * needed.
7352 			 */
7353 			WORKLIST_REMOVE(wk);
7354 			continue;
7355 
7356 		case D_FREEWORK:
7357 			/*
7358 			 * A truncation is waiting for the zero'd pointers
7359 			 * to be written.  It can be freed when the freeblks
7360 			 * is journaled.
7361 			 */
7362 			WORKLIST_REMOVE(wk);
7363 			wk->wk_state |= ONDEPLIST;
7364 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7365 			break;
7366 
7367 		case D_ALLOCDIRECT:
7368 			if (off != 0)
7369 				continue;
7370 			/* FALLTHROUGH */
7371 		default:
7372 			panic("deallocate_dependencies: Unexpected type %s",
7373 			    TYPENAME(wk->wk_type));
7374 			/* NOTREACHED */
7375 		}
7376 	}
7377 	FREE_LOCK(ump);
7378 done:
7379 	/*
7380 	 * Don't throw away this buf, we were partially truncating and
7381 	 * some deps may always remain.
7382 	 */
7383 	if (off) {
7384 		allocbuf(bp, off);
7385 		bp->b_vflags |= BV_SCANNED;
7386 		return (EBUSY);
7387 	}
7388 	bp->b_flags |= B_INVAL | B_NOCACHE;
7389 
7390 	return (0);
7391 }
7392 
7393 /*
7394  * An allocdirect is being canceled due to a truncate.  We must make sure
7395  * the journal entry is released in concert with the blkfree that releases
7396  * the storage.  Completed journal entries must not be released until the
7397  * space is no longer pointed to by the inode or in the bitmap.
7398  */
7399 static void
7400 cancel_allocdirect(adphead, adp, freeblks)
7401 	struct allocdirectlst *adphead;
7402 	struct allocdirect *adp;
7403 	struct freeblks *freeblks;
7404 {
7405 	struct freework *freework;
7406 	struct newblk *newblk;
7407 	struct worklist *wk;
7408 
7409 	TAILQ_REMOVE(adphead, adp, ad_next);
7410 	newblk = (struct newblk *)adp;
7411 	freework = NULL;
7412 	/*
7413 	 * Find the correct freework structure.
7414 	 */
7415 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7416 		if (wk->wk_type != D_FREEWORK)
7417 			continue;
7418 		freework = WK_FREEWORK(wk);
7419 		if (freework->fw_blkno == newblk->nb_newblkno)
7420 			break;
7421 	}
7422 	if (freework == NULL)
7423 		panic("cancel_allocdirect: Freework not found");
7424 	/*
7425 	 * If a newblk exists at all we still have the journal entry that
7426 	 * initiated the allocation so we do not need to journal the free.
7427 	 */
7428 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7429 	/*
7430 	 * If the journal hasn't been written the jnewblk must be passed
7431 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7432 	 * this by linking the journal dependency into the freework to be
7433 	 * freed when freework_freeblock() is called.  If the journal has
7434 	 * been written we can simply reclaim the journal space when the
7435 	 * freeblks work is complete.
7436 	 */
7437 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7438 	    &freeblks->fb_jwork);
7439 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7440 }
7441 
7442 
7443 /*
7444  * Cancel a new block allocation.  May be an indirect or direct block.  We
7445  * remove it from various lists and return any journal record that needs to
7446  * be resolved by the caller.
7447  *
7448  * A special consideration is made for indirects which were never pointed
7449  * at on disk and will never be found once this block is released.
7450  */
7451 static struct jnewblk *
7452 cancel_newblk(newblk, wk, wkhd)
7453 	struct newblk *newblk;
7454 	struct worklist *wk;
7455 	struct workhead *wkhd;
7456 {
7457 	struct jnewblk *jnewblk;
7458 
7459 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7460 
7461 	newblk->nb_state |= GOINGAWAY;
7462 	/*
7463 	 * Previously we traversed the completedhd on each indirdep
7464 	 * attached to this newblk to cancel them and gather journal
7465 	 * work.  Since we need only the oldest journal segment and
7466 	 * the lowest point on the tree will always have the oldest
7467 	 * journal segment we are free to release the segments
7468 	 * of any subordinates and may leave the indirdep list to
7469 	 * indirdep_complete() when this newblk is freed.
7470 	 */
7471 	if (newblk->nb_state & ONDEPLIST) {
7472 		newblk->nb_state &= ~ONDEPLIST;
7473 		LIST_REMOVE(newblk, nb_deps);
7474 	}
7475 	if (newblk->nb_state & ONWORKLIST)
7476 		WORKLIST_REMOVE(&newblk->nb_list);
7477 	/*
7478 	 * If the journal entry hasn't been written we save a pointer to
7479 	 * the dependency that frees it until it is written or the
7480 	 * superseding operation completes.
7481 	 */
7482 	jnewblk = newblk->nb_jnewblk;
7483 	if (jnewblk != NULL && wk != NULL) {
7484 		newblk->nb_jnewblk = NULL;
7485 		jnewblk->jn_dep = wk;
7486 	}
7487 	if (!LIST_EMPTY(&newblk->nb_jwork))
7488 		jwork_move(wkhd, &newblk->nb_jwork);
7489 	/*
7490 	 * When truncating we must free the newdirblk early to remove
7491 	 * the pagedep from the hash before returning.
7492 	 */
7493 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7494 		free_newdirblk(WK_NEWDIRBLK(wk));
7495 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7496 		panic("cancel_newblk: extra newdirblk");
7497 
7498 	return (jnewblk);
7499 }
7500 
7501 /*
7502  * Schedule the freefrag associated with a newblk to be released once
7503  * the pointers are written and the previous block is no longer needed.
7504  */
7505 static void
7506 newblk_freefrag(newblk)
7507 	struct newblk *newblk;
7508 {
7509 	struct freefrag *freefrag;
7510 
7511 	if (newblk->nb_freefrag == NULL)
7512 		return;
7513 	freefrag = newblk->nb_freefrag;
7514 	newblk->nb_freefrag = NULL;
7515 	freefrag->ff_state |= COMPLETE;
7516 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7517 		add_to_worklist(&freefrag->ff_list, 0);
7518 }
7519 
7520 /*
7521  * Free a newblk. Generate a new freefrag work request if appropriate.
7522  * This must be called after the inode pointer and any direct block pointers
7523  * are valid or fully removed via truncate or frag extension.
7524  */
7525 static void
7526 free_newblk(newblk)
7527 	struct newblk *newblk;
7528 {
7529 	struct indirdep *indirdep;
7530 	struct worklist *wk;
7531 
7532 	KASSERT(newblk->nb_jnewblk == NULL,
7533 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7534 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7535 	    ("free_newblk: unclaimed newblk"));
7536 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7537 	newblk_freefrag(newblk);
7538 	if (newblk->nb_state & ONDEPLIST)
7539 		LIST_REMOVE(newblk, nb_deps);
7540 	if (newblk->nb_state & ONWORKLIST)
7541 		WORKLIST_REMOVE(&newblk->nb_list);
7542 	LIST_REMOVE(newblk, nb_hash);
7543 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7544 		free_newdirblk(WK_NEWDIRBLK(wk));
7545 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7546 		panic("free_newblk: extra newdirblk");
7547 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7548 		indirdep_complete(indirdep);
7549 	handle_jwork(&newblk->nb_jwork);
7550 	WORKITEM_FREE(newblk, D_NEWBLK);
7551 }
7552 
7553 /*
7554  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7555  */
7556 static void
7557 free_newdirblk(newdirblk)
7558 	struct newdirblk *newdirblk;
7559 {
7560 	struct pagedep *pagedep;
7561 	struct diradd *dap;
7562 	struct worklist *wk;
7563 
7564 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7565 	WORKLIST_REMOVE(&newdirblk->db_list);
7566 	/*
7567 	 * If the pagedep is still linked onto the directory buffer
7568 	 * dependency chain, then some of the entries on the
7569 	 * pd_pendinghd list may not be committed to disk yet. In
7570 	 * this case, we will simply clear the NEWBLOCK flag and
7571 	 * let the pd_pendinghd list be processed when the pagedep
7572 	 * is next written. If the pagedep is no longer on the buffer
7573 	 * dependency chain, then all the entries on the pd_pending
7574 	 * list are committed to disk and we can free them here.
7575 	 */
7576 	pagedep = newdirblk->db_pagedep;
7577 	pagedep->pd_state &= ~NEWBLOCK;
7578 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7579 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7580 			free_diradd(dap, NULL);
7581 		/*
7582 		 * If no dependencies remain, the pagedep will be freed.
7583 		 */
7584 		free_pagedep(pagedep);
7585 	}
7586 	/* Should only ever be one item in the list. */
7587 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7588 		WORKLIST_REMOVE(wk);
7589 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7590 	}
7591 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7592 }
7593 
7594 /*
7595  * Prepare an inode to be freed. The actual free operation is not
7596  * done until the zero'ed inode has been written to disk.
7597  */
7598 void
7599 softdep_freefile(pvp, ino, mode)
7600 	struct vnode *pvp;
7601 	ino_t ino;
7602 	int mode;
7603 {
7604 	struct inode *ip = VTOI(pvp);
7605 	struct inodedep *inodedep;
7606 	struct freefile *freefile;
7607 	struct freeblks *freeblks;
7608 	struct ufsmount *ump;
7609 
7610 	ump = ITOUMP(ip);
7611 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7612 	    ("softdep_freefile called on non-softdep filesystem"));
7613 	/*
7614 	 * This sets up the inode de-allocation dependency.
7615 	 */
7616 	freefile = malloc(sizeof(struct freefile),
7617 		M_FREEFILE, M_SOFTDEP_FLAGS);
7618 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7619 	freefile->fx_mode = mode;
7620 	freefile->fx_oldinum = ino;
7621 	freefile->fx_devvp = ump->um_devvp;
7622 	LIST_INIT(&freefile->fx_jwork);
7623 	UFS_LOCK(ump);
7624 	ump->um_fs->fs_pendinginodes += 1;
7625 	UFS_UNLOCK(ump);
7626 
7627 	/*
7628 	 * If the inodedep does not exist, then the zero'ed inode has
7629 	 * been written to disk. If the allocated inode has never been
7630 	 * written to disk, then the on-disk inode is zero'ed. In either
7631 	 * case we can free the file immediately.  If the journal was
7632 	 * canceled before being written the inode will never make it to
7633 	 * disk and we must send the canceled journal entrys to
7634 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7635 	 * Any blocks waiting on the inode to write can be safely freed
7636 	 * here as it will never been written.
7637 	 */
7638 	ACQUIRE_LOCK(ump);
7639 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7640 	if (inodedep) {
7641 		/*
7642 		 * Clear out freeblks that no longer need to reference
7643 		 * this inode.
7644 		 */
7645 		while ((freeblks =
7646 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7647 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7648 			    fb_next);
7649 			freeblks->fb_state &= ~ONDEPLIST;
7650 		}
7651 		/*
7652 		 * Remove this inode from the unlinked list.
7653 		 */
7654 		if (inodedep->id_state & UNLINKED) {
7655 			/*
7656 			 * Save the journal work to be freed with the bitmap
7657 			 * before we clear UNLINKED.  Otherwise it can be lost
7658 			 * if the inode block is written.
7659 			 */
7660 			handle_bufwait(inodedep, &freefile->fx_jwork);
7661 			clear_unlinked_inodedep(inodedep);
7662 			/*
7663 			 * Re-acquire inodedep as we've dropped the
7664 			 * per-filesystem lock in clear_unlinked_inodedep().
7665 			 */
7666 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7667 		}
7668 	}
7669 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7670 		FREE_LOCK(ump);
7671 		handle_workitem_freefile(freefile);
7672 		return;
7673 	}
7674 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7675 		inodedep->id_state |= GOINGAWAY;
7676 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7677 	FREE_LOCK(ump);
7678 	if (ip->i_number == ino)
7679 		UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
7680 }
7681 
7682 /*
7683  * Check to see if an inode has never been written to disk. If
7684  * so free the inodedep and return success, otherwise return failure.
7685  *
7686  * If we still have a bitmap dependency, then the inode has never
7687  * been written to disk. Drop the dependency as it is no longer
7688  * necessary since the inode is being deallocated. We set the
7689  * ALLCOMPLETE flags since the bitmap now properly shows that the
7690  * inode is not allocated. Even if the inode is actively being
7691  * written, it has been rolled back to its zero'ed state, so we
7692  * are ensured that a zero inode is what is on the disk. For short
7693  * lived files, this change will usually result in removing all the
7694  * dependencies from the inode so that it can be freed immediately.
7695  */
7696 static int
7697 check_inode_unwritten(inodedep)
7698 	struct inodedep *inodedep;
7699 {
7700 
7701 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7702 
7703 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7704 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7705 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7706 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7707 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7708 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7709 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7710 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7711 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7712 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7713 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7714 	    inodedep->id_mkdiradd != NULL ||
7715 	    inodedep->id_nlinkdelta != 0)
7716 		return (0);
7717 	/*
7718 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7719 	 * trying to allocate memory without holding "Softdep Lock".
7720 	 */
7721 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7722 	    inodedep->id_savedino1 == NULL)
7723 		return (0);
7724 
7725 	if (inodedep->id_state & ONDEPLIST)
7726 		LIST_REMOVE(inodedep, id_deps);
7727 	inodedep->id_state &= ~ONDEPLIST;
7728 	inodedep->id_state |= ALLCOMPLETE;
7729 	inodedep->id_bmsafemap = NULL;
7730 	if (inodedep->id_state & ONWORKLIST)
7731 		WORKLIST_REMOVE(&inodedep->id_list);
7732 	if (inodedep->id_savedino1 != NULL) {
7733 		free(inodedep->id_savedino1, M_SAVEDINO);
7734 		inodedep->id_savedino1 = NULL;
7735 	}
7736 	if (free_inodedep(inodedep) == 0)
7737 		panic("check_inode_unwritten: busy inode");
7738 	return (1);
7739 }
7740 
7741 static int
7742 check_inodedep_free(inodedep)
7743 	struct inodedep *inodedep;
7744 {
7745 
7746 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7747 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7748 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7749 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7750 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7751 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7752 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7753 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7754 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7755 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7756 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7757 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7758 	    inodedep->id_mkdiradd != NULL ||
7759 	    inodedep->id_nlinkdelta != 0 ||
7760 	    inodedep->id_savedino1 != NULL)
7761 		return (0);
7762 	return (1);
7763 }
7764 
7765 /*
7766  * Try to free an inodedep structure. Return 1 if it could be freed.
7767  */
7768 static int
7769 free_inodedep(inodedep)
7770 	struct inodedep *inodedep;
7771 {
7772 
7773 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7774 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7775 	    !check_inodedep_free(inodedep))
7776 		return (0);
7777 	if (inodedep->id_state & ONDEPLIST)
7778 		LIST_REMOVE(inodedep, id_deps);
7779 	LIST_REMOVE(inodedep, id_hash);
7780 	WORKITEM_FREE(inodedep, D_INODEDEP);
7781 	return (1);
7782 }
7783 
7784 /*
7785  * Free the block referenced by a freework structure.  The parent freeblks
7786  * structure is released and completed when the final cg bitmap reaches
7787  * the disk.  This routine may be freeing a jnewblk which never made it to
7788  * disk in which case we do not have to wait as the operation is undone
7789  * in memory immediately.
7790  */
7791 static void
7792 freework_freeblock(freework, key)
7793 	struct freework *freework;
7794 	u_long key;
7795 {
7796 	struct freeblks *freeblks;
7797 	struct jnewblk *jnewblk;
7798 	struct ufsmount *ump;
7799 	struct workhead wkhd;
7800 	struct fs *fs;
7801 	int bsize;
7802 	int needj;
7803 
7804 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7805 	LOCK_OWNED(ump);
7806 	/*
7807 	 * Handle partial truncate separately.
7808 	 */
7809 	if (freework->fw_indir) {
7810 		complete_trunc_indir(freework);
7811 		return;
7812 	}
7813 	freeblks = freework->fw_freeblks;
7814 	fs = ump->um_fs;
7815 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7816 	bsize = lfragtosize(fs, freework->fw_frags);
7817 	LIST_INIT(&wkhd);
7818 	/*
7819 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7820 	 * on the indirblk hashtable and prevents premature freeing.
7821 	 */
7822 	freework->fw_state |= DEPCOMPLETE;
7823 	/*
7824 	 * SUJ needs to wait for the segment referencing freed indirect
7825 	 * blocks to expire so that we know the checker will not confuse
7826 	 * a re-allocated indirect block with its old contents.
7827 	 */
7828 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7829 		indirblk_insert(freework);
7830 	/*
7831 	 * If we are canceling an existing jnewblk pass it to the free
7832 	 * routine, otherwise pass the freeblk which will ultimately
7833 	 * release the freeblks.  If we're not journaling, we can just
7834 	 * free the freeblks immediately.
7835 	 */
7836 	jnewblk = freework->fw_jnewblk;
7837 	if (jnewblk != NULL) {
7838 		cancel_jnewblk(jnewblk, &wkhd);
7839 		needj = 0;
7840 	} else if (needj) {
7841 		freework->fw_state |= DELAYEDFREE;
7842 		freeblks->fb_cgwait++;
7843 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7844 	}
7845 	FREE_LOCK(ump);
7846 	freeblks_free(ump, freeblks, btodb(bsize));
7847 	CTR4(KTR_SUJ,
7848 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
7849 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7850 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7851 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
7852 	ACQUIRE_LOCK(ump);
7853 	/*
7854 	 * The jnewblk will be discarded and the bits in the map never
7855 	 * made it to disk.  We can immediately free the freeblk.
7856 	 */
7857 	if (needj == 0)
7858 		handle_written_freework(freework);
7859 }
7860 
7861 /*
7862  * We enqueue freework items that need processing back on the freeblks and
7863  * add the freeblks to the worklist.  This makes it easier to find all work
7864  * required to flush a truncation in process_truncates().
7865  */
7866 static void
7867 freework_enqueue(freework)
7868 	struct freework *freework;
7869 {
7870 	struct freeblks *freeblks;
7871 
7872 	freeblks = freework->fw_freeblks;
7873 	if ((freework->fw_state & INPROGRESS) == 0)
7874 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7875 	if ((freeblks->fb_state &
7876 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7877 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7878 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7879 }
7880 
7881 /*
7882  * Start, continue, or finish the process of freeing an indirect block tree.
7883  * The free operation may be paused at any point with fw_off containing the
7884  * offset to restart from.  This enables us to implement some flow control
7885  * for large truncates which may fan out and generate a huge number of
7886  * dependencies.
7887  */
7888 static void
7889 handle_workitem_indirblk(freework)
7890 	struct freework *freework;
7891 {
7892 	struct freeblks *freeblks;
7893 	struct ufsmount *ump;
7894 	struct fs *fs;
7895 
7896 	freeblks = freework->fw_freeblks;
7897 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7898 	fs = ump->um_fs;
7899 	if (freework->fw_state & DEPCOMPLETE) {
7900 		handle_written_freework(freework);
7901 		return;
7902 	}
7903 	if (freework->fw_off == NINDIR(fs)) {
7904 		freework_freeblock(freework, SINGLETON_KEY);
7905 		return;
7906 	}
7907 	freework->fw_state |= INPROGRESS;
7908 	FREE_LOCK(ump);
7909 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7910 	    freework->fw_lbn);
7911 	ACQUIRE_LOCK(ump);
7912 }
7913 
7914 /*
7915  * Called when a freework structure attached to a cg buf is written.  The
7916  * ref on either the parent or the freeblks structure is released and
7917  * the freeblks is added back to the worklist if there is more work to do.
7918  */
7919 static void
7920 handle_written_freework(freework)
7921 	struct freework *freework;
7922 {
7923 	struct freeblks *freeblks;
7924 	struct freework *parent;
7925 
7926 	freeblks = freework->fw_freeblks;
7927 	parent = freework->fw_parent;
7928 	if (freework->fw_state & DELAYEDFREE)
7929 		freeblks->fb_cgwait--;
7930 	freework->fw_state |= COMPLETE;
7931 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7932 		WORKITEM_FREE(freework, D_FREEWORK);
7933 	if (parent) {
7934 		if (--parent->fw_ref == 0)
7935 			freework_enqueue(parent);
7936 		return;
7937 	}
7938 	if (--freeblks->fb_ref != 0)
7939 		return;
7940 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7941 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7942 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7943 }
7944 
7945 /*
7946  * This workitem routine performs the block de-allocation.
7947  * The workitem is added to the pending list after the updated
7948  * inode block has been written to disk.  As mentioned above,
7949  * checks regarding the number of blocks de-allocated (compared
7950  * to the number of blocks allocated for the file) are also
7951  * performed in this function.
7952  */
7953 static int
7954 handle_workitem_freeblocks(freeblks, flags)
7955 	struct freeblks *freeblks;
7956 	int flags;
7957 {
7958 	struct freework *freework;
7959 	struct newblk *newblk;
7960 	struct allocindir *aip;
7961 	struct ufsmount *ump;
7962 	struct worklist *wk;
7963 	u_long key;
7964 
7965 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7966 	    ("handle_workitem_freeblocks: Journal entries not written."));
7967 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7968 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
7969 	ACQUIRE_LOCK(ump);
7970 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7971 		WORKLIST_REMOVE(wk);
7972 		switch (wk->wk_type) {
7973 		case D_DIRREM:
7974 			wk->wk_state |= COMPLETE;
7975 			add_to_worklist(wk, 0);
7976 			continue;
7977 
7978 		case D_ALLOCDIRECT:
7979 			free_newblk(WK_NEWBLK(wk));
7980 			continue;
7981 
7982 		case D_ALLOCINDIR:
7983 			aip = WK_ALLOCINDIR(wk);
7984 			freework = NULL;
7985 			if (aip->ai_state & DELAYEDFREE) {
7986 				FREE_LOCK(ump);
7987 				freework = newfreework(ump, freeblks, NULL,
7988 				    aip->ai_lbn, aip->ai_newblkno,
7989 				    ump->um_fs->fs_frag, 0, 0);
7990 				ACQUIRE_LOCK(ump);
7991 			}
7992 			newblk = WK_NEWBLK(wk);
7993 			if (newblk->nb_jnewblk) {
7994 				freework->fw_jnewblk = newblk->nb_jnewblk;
7995 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7996 				newblk->nb_jnewblk = NULL;
7997 			}
7998 			free_newblk(newblk);
7999 			continue;
8000 
8001 		case D_FREEWORK:
8002 			freework = WK_FREEWORK(wk);
8003 			if (freework->fw_lbn <= -UFS_NDADDR)
8004 				handle_workitem_indirblk(freework);
8005 			else
8006 				freework_freeblock(freework, key);
8007 			continue;
8008 		default:
8009 			panic("handle_workitem_freeblocks: Unknown type %s",
8010 			    TYPENAME(wk->wk_type));
8011 		}
8012 	}
8013 	if (freeblks->fb_ref != 0) {
8014 		freeblks->fb_state &= ~INPROGRESS;
8015 		wake_worklist(&freeblks->fb_list);
8016 		freeblks = NULL;
8017 	}
8018 	FREE_LOCK(ump);
8019 	ffs_blkrelease_finish(ump, key);
8020 	if (freeblks)
8021 		return handle_complete_freeblocks(freeblks, flags);
8022 	return (0);
8023 }
8024 
8025 /*
8026  * Handle completion of block free via truncate.  This allows fs_pending
8027  * to track the actual free block count more closely than if we only updated
8028  * it at the end.  We must be careful to handle cases where the block count
8029  * on free was incorrect.
8030  */
8031 static void
8032 freeblks_free(ump, freeblks, blocks)
8033 	struct ufsmount *ump;
8034 	struct freeblks *freeblks;
8035 	int blocks;
8036 {
8037 	struct fs *fs;
8038 	ufs2_daddr_t remain;
8039 
8040 	UFS_LOCK(ump);
8041 	remain = -freeblks->fb_chkcnt;
8042 	freeblks->fb_chkcnt += blocks;
8043 	if (remain > 0) {
8044 		if (remain < blocks)
8045 			blocks = remain;
8046 		fs = ump->um_fs;
8047 		fs->fs_pendingblocks -= blocks;
8048 	}
8049 	UFS_UNLOCK(ump);
8050 }
8051 
8052 /*
8053  * Once all of the freework workitems are complete we can retire the
8054  * freeblocks dependency and any journal work awaiting completion.  This
8055  * can not be called until all other dependencies are stable on disk.
8056  */
8057 static int
8058 handle_complete_freeblocks(freeblks, flags)
8059 	struct freeblks *freeblks;
8060 	int flags;
8061 {
8062 	struct inodedep *inodedep;
8063 	struct inode *ip;
8064 	struct vnode *vp;
8065 	struct fs *fs;
8066 	struct ufsmount *ump;
8067 	ufs2_daddr_t spare;
8068 
8069 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8070 	fs = ump->um_fs;
8071 	flags = LK_EXCLUSIVE | flags;
8072 	spare = freeblks->fb_chkcnt;
8073 
8074 	/*
8075 	 * If we did not release the expected number of blocks we may have
8076 	 * to adjust the inode block count here.  Only do so if it wasn't
8077 	 * a truncation to zero and the modrev still matches.
8078 	 */
8079 	if (spare && freeblks->fb_len != 0) {
8080 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8081 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8082 			return (EBUSY);
8083 		ip = VTOI(vp);
8084 		if (ip->i_mode == 0) {
8085 			vgone(vp);
8086 		} else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8087 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8088 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8089 			/*
8090 			 * We must wait so this happens before the
8091 			 * journal is reclaimed.
8092 			 */
8093 			ffs_update(vp, 1);
8094 		}
8095 		vput(vp);
8096 	}
8097 	if (spare < 0) {
8098 		UFS_LOCK(ump);
8099 		fs->fs_pendingblocks += spare;
8100 		UFS_UNLOCK(ump);
8101 	}
8102 #ifdef QUOTA
8103 	/* Handle spare. */
8104 	if (spare)
8105 		quotaadj(freeblks->fb_quota, ump, -spare);
8106 	quotarele(freeblks->fb_quota);
8107 #endif
8108 	ACQUIRE_LOCK(ump);
8109 	if (freeblks->fb_state & ONDEPLIST) {
8110 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8111 		    0, &inodedep);
8112 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8113 		freeblks->fb_state &= ~ONDEPLIST;
8114 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8115 			free_inodedep(inodedep);
8116 	}
8117 	/*
8118 	 * All of the freeblock deps must be complete prior to this call
8119 	 * so it's now safe to complete earlier outstanding journal entries.
8120 	 */
8121 	handle_jwork(&freeblks->fb_jwork);
8122 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8123 	FREE_LOCK(ump);
8124 	return (0);
8125 }
8126 
8127 /*
8128  * Release blocks associated with the freeblks and stored in the indirect
8129  * block dbn. If level is greater than SINGLE, the block is an indirect block
8130  * and recursive calls to indirtrunc must be used to cleanse other indirect
8131  * blocks.
8132  *
8133  * This handles partial and complete truncation of blocks.  Partial is noted
8134  * with goingaway == 0.  In this case the freework is completed after the
8135  * zero'd indirects are written to disk.  For full truncation the freework
8136  * is completed after the block is freed.
8137  */
8138 static void
8139 indir_trunc(freework, dbn, lbn)
8140 	struct freework *freework;
8141 	ufs2_daddr_t dbn;
8142 	ufs_lbn_t lbn;
8143 {
8144 	struct freework *nfreework;
8145 	struct workhead wkhd;
8146 	struct freeblks *freeblks;
8147 	struct buf *bp;
8148 	struct fs *fs;
8149 	struct indirdep *indirdep;
8150 	struct mount *mp;
8151 	struct ufsmount *ump;
8152 	ufs1_daddr_t *bap1;
8153 	ufs2_daddr_t nb, nnb, *bap2;
8154 	ufs_lbn_t lbnadd, nlbn;
8155 	u_long key;
8156 	int nblocks, ufs1fmt, freedblocks;
8157 	int goingaway, freedeps, needj, level, cnt, i;
8158 
8159 	freeblks = freework->fw_freeblks;
8160 	mp = freeblks->fb_list.wk_mp;
8161 	ump = VFSTOUFS(mp);
8162 	fs = ump->um_fs;
8163 	/*
8164 	 * Get buffer of block pointers to be freed.  There are three cases:
8165 	 *
8166 	 * 1) Partial truncate caches the indirdep pointer in the freework
8167 	 *    which provides us a back copy to the save bp which holds the
8168 	 *    pointers we want to clear.  When this completes the zero
8169 	 *    pointers are written to the real copy.
8170 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8171 	 *    eliminated the real copy and placed the indirdep on the saved
8172 	 *    copy.  The indirdep and buf are discarded when this completes.
8173 	 * 3) The indirect was not in memory, we read a copy off of the disk
8174 	 *    using the devvp and drop and invalidate the buffer when we're
8175 	 *    done.
8176 	 */
8177 	goingaway = 1;
8178 	indirdep = NULL;
8179 	if (freework->fw_indir != NULL) {
8180 		goingaway = 0;
8181 		indirdep = freework->fw_indir;
8182 		bp = indirdep->ir_savebp;
8183 		if (bp == NULL || bp->b_blkno != dbn)
8184 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8185 			    bp, (intmax_t)dbn);
8186 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8187 		/*
8188 		 * The lock prevents the buf dep list from changing and
8189 	 	 * indirects on devvp should only ever have one dependency.
8190 		 */
8191 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8192 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8193 			panic("indir_trunc: Bad indirdep %p from buf %p",
8194 			    indirdep, bp);
8195 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8196 	    NOCRED, &bp) != 0) {
8197 		brelse(bp);
8198 		return;
8199 	}
8200 	ACQUIRE_LOCK(ump);
8201 	/* Protects against a race with complete_trunc_indir(). */
8202 	freework->fw_state &= ~INPROGRESS;
8203 	/*
8204 	 * If we have an indirdep we need to enforce the truncation order
8205 	 * and discard it when it is complete.
8206 	 */
8207 	if (indirdep) {
8208 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8209 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8210 			/*
8211 			 * Add the complete truncate to the list on the
8212 			 * indirdep to enforce in-order processing.
8213 			 */
8214 			if (freework->fw_indir == NULL)
8215 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8216 				    freework, fw_next);
8217 			FREE_LOCK(ump);
8218 			return;
8219 		}
8220 		/*
8221 		 * If we're goingaway, free the indirdep.  Otherwise it will
8222 		 * linger until the write completes.
8223 		 */
8224 		if (goingaway)
8225 			free_indirdep(indirdep);
8226 	}
8227 	FREE_LOCK(ump);
8228 	/* Initialize pointers depending on block size. */
8229 	if (ump->um_fstype == UFS1) {
8230 		bap1 = (ufs1_daddr_t *)bp->b_data;
8231 		nb = bap1[freework->fw_off];
8232 		ufs1fmt = 1;
8233 		bap2 = NULL;
8234 	} else {
8235 		bap2 = (ufs2_daddr_t *)bp->b_data;
8236 		nb = bap2[freework->fw_off];
8237 		ufs1fmt = 0;
8238 		bap1 = NULL;
8239 	}
8240 	level = lbn_level(lbn);
8241 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8242 	lbnadd = lbn_offset(fs, level);
8243 	nblocks = btodb(fs->fs_bsize);
8244 	nfreework = freework;
8245 	freedeps = 0;
8246 	cnt = 0;
8247 	/*
8248 	 * Reclaim blocks.  Traverses into nested indirect levels and
8249 	 * arranges for the current level to be freed when subordinates
8250 	 * are free when journaling.
8251 	 */
8252 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8253 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8254 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8255 		    fs->fs_bsize) != 0)
8256 			nb = 0;
8257 		if (i != NINDIR(fs) - 1) {
8258 			if (ufs1fmt)
8259 				nnb = bap1[i+1];
8260 			else
8261 				nnb = bap2[i+1];
8262 		} else
8263 			nnb = 0;
8264 		if (nb == 0)
8265 			continue;
8266 		cnt++;
8267 		if (level != 0) {
8268 			nlbn = (lbn + 1) - (i * lbnadd);
8269 			if (needj != 0) {
8270 				nfreework = newfreework(ump, freeblks, freework,
8271 				    nlbn, nb, fs->fs_frag, 0, 0);
8272 				freedeps++;
8273 			}
8274 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8275 		} else {
8276 			struct freedep *freedep;
8277 
8278 			/*
8279 			 * Attempt to aggregate freedep dependencies for
8280 			 * all blocks being released to the same CG.
8281 			 */
8282 			LIST_INIT(&wkhd);
8283 			if (needj != 0 &&
8284 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8285 				freedep = newfreedep(freework);
8286 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8287 				    &freedep->fd_list);
8288 				freedeps++;
8289 			}
8290 			CTR3(KTR_SUJ,
8291 			    "indir_trunc: ino %jd blkno %jd size %d",
8292 			    freeblks->fb_inum, nb, fs->fs_bsize);
8293 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8294 			    fs->fs_bsize, freeblks->fb_inum,
8295 			    freeblks->fb_vtype, &wkhd, key);
8296 		}
8297 	}
8298 	ffs_blkrelease_finish(ump, key);
8299 	if (goingaway) {
8300 		bp->b_flags |= B_INVAL | B_NOCACHE;
8301 		brelse(bp);
8302 	}
8303 	freedblocks = 0;
8304 	if (level == 0)
8305 		freedblocks = (nblocks * cnt);
8306 	if (needj == 0)
8307 		freedblocks += nblocks;
8308 	freeblks_free(ump, freeblks, freedblocks);
8309 	/*
8310 	 * If we are journaling set up the ref counts and offset so this
8311 	 * indirect can be completed when its children are free.
8312 	 */
8313 	if (needj) {
8314 		ACQUIRE_LOCK(ump);
8315 		freework->fw_off = i;
8316 		freework->fw_ref += freedeps;
8317 		freework->fw_ref -= NINDIR(fs) + 1;
8318 		if (level == 0)
8319 			freeblks->fb_cgwait += freedeps;
8320 		if (freework->fw_ref == 0)
8321 			freework_freeblock(freework, SINGLETON_KEY);
8322 		FREE_LOCK(ump);
8323 		return;
8324 	}
8325 	/*
8326 	 * If we're not journaling we can free the indirect now.
8327 	 */
8328 	dbn = dbtofsb(fs, dbn);
8329 	CTR3(KTR_SUJ,
8330 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8331 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8332 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8333 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8334 	/* Non SUJ softdep does single-threaded truncations. */
8335 	if (freework->fw_blkno == dbn) {
8336 		freework->fw_state |= ALLCOMPLETE;
8337 		ACQUIRE_LOCK(ump);
8338 		handle_written_freework(freework);
8339 		FREE_LOCK(ump);
8340 	}
8341 	return;
8342 }
8343 
8344 /*
8345  * Cancel an allocindir when it is removed via truncation.  When bp is not
8346  * NULL the indirect never appeared on disk and is scheduled to be freed
8347  * independently of the indir so we can more easily track journal work.
8348  */
8349 static void
8350 cancel_allocindir(aip, bp, freeblks, trunc)
8351 	struct allocindir *aip;
8352 	struct buf *bp;
8353 	struct freeblks *freeblks;
8354 	int trunc;
8355 {
8356 	struct indirdep *indirdep;
8357 	struct freefrag *freefrag;
8358 	struct newblk *newblk;
8359 
8360 	newblk = (struct newblk *)aip;
8361 	LIST_REMOVE(aip, ai_next);
8362 	/*
8363 	 * We must eliminate the pointer in bp if it must be freed on its
8364 	 * own due to partial truncate or pending journal work.
8365 	 */
8366 	if (bp && (trunc || newblk->nb_jnewblk)) {
8367 		/*
8368 		 * Clear the pointer and mark the aip to be freed
8369 		 * directly if it never existed on disk.
8370 		 */
8371 		aip->ai_state |= DELAYEDFREE;
8372 		indirdep = aip->ai_indirdep;
8373 		if (indirdep->ir_state & UFS1FMT)
8374 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8375 		else
8376 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8377 	}
8378 	/*
8379 	 * When truncating the previous pointer will be freed via
8380 	 * savedbp.  Eliminate the freefrag which would dup free.
8381 	 */
8382 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8383 		newblk->nb_freefrag = NULL;
8384 		if (freefrag->ff_jdep)
8385 			cancel_jfreefrag(
8386 			    WK_JFREEFRAG(freefrag->ff_jdep));
8387 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8388 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8389 	}
8390 	/*
8391 	 * If the journal hasn't been written the jnewblk must be passed
8392 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8393 	 * this by leaving the journal dependency on the newblk to be freed
8394 	 * when a freework is created in handle_workitem_freeblocks().
8395 	 */
8396 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8397 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8398 }
8399 
8400 /*
8401  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8402  * in to a newdirblk so any subsequent additions are tracked properly.  The
8403  * caller is responsible for adding the mkdir1 dependency to the journal
8404  * and updating id_mkdiradd.  This function returns with the per-filesystem
8405  * lock held.
8406  */
8407 static struct mkdir *
8408 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8409 	struct diradd *dap;
8410 	ino_t newinum;
8411 	ino_t dinum;
8412 	struct buf *newdirbp;
8413 	struct mkdir **mkdirp;
8414 {
8415 	struct newblk *newblk;
8416 	struct pagedep *pagedep;
8417 	struct inodedep *inodedep;
8418 	struct newdirblk *newdirblk;
8419 	struct mkdir *mkdir1, *mkdir2;
8420 	struct worklist *wk;
8421 	struct jaddref *jaddref;
8422 	struct ufsmount *ump;
8423 	struct mount *mp;
8424 
8425 	mp = dap->da_list.wk_mp;
8426 	ump = VFSTOUFS(mp);
8427 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8428 	    M_SOFTDEP_FLAGS);
8429 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8430 	LIST_INIT(&newdirblk->db_mkdir);
8431 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8432 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8433 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8434 	mkdir1->md_diradd = dap;
8435 	mkdir1->md_jaddref = NULL;
8436 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8437 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8438 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8439 	mkdir2->md_diradd = dap;
8440 	mkdir2->md_jaddref = NULL;
8441 	if (MOUNTEDSUJ(mp) == 0) {
8442 		mkdir1->md_state |= DEPCOMPLETE;
8443 		mkdir2->md_state |= DEPCOMPLETE;
8444 	}
8445 	/*
8446 	 * Dependency on "." and ".." being written to disk.
8447 	 */
8448 	mkdir1->md_buf = newdirbp;
8449 	ACQUIRE_LOCK(VFSTOUFS(mp));
8450 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8451 	/*
8452 	 * We must link the pagedep, allocdirect, and newdirblk for
8453 	 * the initial file page so the pointer to the new directory
8454 	 * is not written until the directory contents are live and
8455 	 * any subsequent additions are not marked live until the
8456 	 * block is reachable via the inode.
8457 	 */
8458 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8459 		panic("setup_newdir: lost pagedep");
8460 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8461 		if (wk->wk_type == D_ALLOCDIRECT)
8462 			break;
8463 	if (wk == NULL)
8464 		panic("setup_newdir: lost allocdirect");
8465 	if (pagedep->pd_state & NEWBLOCK)
8466 		panic("setup_newdir: NEWBLOCK already set");
8467 	newblk = WK_NEWBLK(wk);
8468 	pagedep->pd_state |= NEWBLOCK;
8469 	pagedep->pd_newdirblk = newdirblk;
8470 	newdirblk->db_pagedep = pagedep;
8471 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8472 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8473 	/*
8474 	 * Look up the inodedep for the parent directory so that we
8475 	 * can link mkdir2 into the pending dotdot jaddref or
8476 	 * the inode write if there is none.  If the inode is
8477 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8478 	 * been satisfied and mkdir2 can be freed.
8479 	 */
8480 	inodedep_lookup(mp, dinum, 0, &inodedep);
8481 	if (MOUNTEDSUJ(mp)) {
8482 		if (inodedep == NULL)
8483 			panic("setup_newdir: Lost parent.");
8484 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8485 		    inoreflst);
8486 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8487 		    (jaddref->ja_state & MKDIR_PARENT),
8488 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8489 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8490 		mkdir2->md_jaddref = jaddref;
8491 		jaddref->ja_mkdir = mkdir2;
8492 	} else if (inodedep == NULL ||
8493 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8494 		dap->da_state &= ~MKDIR_PARENT;
8495 		WORKITEM_FREE(mkdir2, D_MKDIR);
8496 		mkdir2 = NULL;
8497 	} else {
8498 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8499 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8500 	}
8501 	*mkdirp = mkdir2;
8502 
8503 	return (mkdir1);
8504 }
8505 
8506 /*
8507  * Directory entry addition dependencies.
8508  *
8509  * When adding a new directory entry, the inode (with its incremented link
8510  * count) must be written to disk before the directory entry's pointer to it.
8511  * Also, if the inode is newly allocated, the corresponding freemap must be
8512  * updated (on disk) before the directory entry's pointer. These requirements
8513  * are met via undo/redo on the directory entry's pointer, which consists
8514  * simply of the inode number.
8515  *
8516  * As directory entries are added and deleted, the free space within a
8517  * directory block can become fragmented.  The ufs filesystem will compact
8518  * a fragmented directory block to make space for a new entry. When this
8519  * occurs, the offsets of previously added entries change. Any "diradd"
8520  * dependency structures corresponding to these entries must be updated with
8521  * the new offsets.
8522  */
8523 
8524 /*
8525  * This routine is called after the in-memory inode's link
8526  * count has been incremented, but before the directory entry's
8527  * pointer to the inode has been set.
8528  */
8529 int
8530 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8531 	struct buf *bp;		/* buffer containing directory block */
8532 	struct inode *dp;	/* inode for directory */
8533 	off_t diroffset;	/* offset of new entry in directory */
8534 	ino_t newinum;		/* inode referenced by new directory entry */
8535 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8536 	int isnewblk;		/* entry is in a newly allocated block */
8537 {
8538 	int offset;		/* offset of new entry within directory block */
8539 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8540 	struct fs *fs;
8541 	struct diradd *dap;
8542 	struct newblk *newblk;
8543 	struct pagedep *pagedep;
8544 	struct inodedep *inodedep;
8545 	struct newdirblk *newdirblk;
8546 	struct mkdir *mkdir1, *mkdir2;
8547 	struct jaddref *jaddref;
8548 	struct ufsmount *ump;
8549 	struct mount *mp;
8550 	int isindir;
8551 
8552 	mp = ITOVFS(dp);
8553 	ump = VFSTOUFS(mp);
8554 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8555 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8556 	/*
8557 	 * Whiteouts have no dependencies.
8558 	 */
8559 	if (newinum == UFS_WINO) {
8560 		if (newdirbp != NULL)
8561 			bdwrite(newdirbp);
8562 		return (0);
8563 	}
8564 	jaddref = NULL;
8565 	mkdir1 = mkdir2 = NULL;
8566 	fs = ump->um_fs;
8567 	lbn = lblkno(fs, diroffset);
8568 	offset = blkoff(fs, diroffset);
8569 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8570 		M_SOFTDEP_FLAGS|M_ZERO);
8571 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8572 	dap->da_offset = offset;
8573 	dap->da_newinum = newinum;
8574 	dap->da_state = ATTACHED;
8575 	LIST_INIT(&dap->da_jwork);
8576 	isindir = bp->b_lblkno >= UFS_NDADDR;
8577 	newdirblk = NULL;
8578 	if (isnewblk &&
8579 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8580 		newdirblk = malloc(sizeof(struct newdirblk),
8581 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8582 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8583 		LIST_INIT(&newdirblk->db_mkdir);
8584 	}
8585 	/*
8586 	 * If we're creating a new directory setup the dependencies and set
8587 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8588 	 * we can move on.
8589 	 */
8590 	if (newdirbp == NULL) {
8591 		dap->da_state |= DEPCOMPLETE;
8592 		ACQUIRE_LOCK(ump);
8593 	} else {
8594 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8595 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8596 		    &mkdir2);
8597 	}
8598 	/*
8599 	 * Link into parent directory pagedep to await its being written.
8600 	 */
8601 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8602 #ifdef INVARIANTS
8603 	if (diradd_lookup(pagedep, offset) != NULL)
8604 		panic("softdep_setup_directory_add: %p already at off %d\n",
8605 		    diradd_lookup(pagedep, offset), offset);
8606 #endif
8607 	dap->da_pagedep = pagedep;
8608 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8609 	    da_pdlist);
8610 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8611 	/*
8612 	 * If we're journaling, link the diradd into the jaddref so it
8613 	 * may be completed after the journal entry is written.  Otherwise,
8614 	 * link the diradd into its inodedep.  If the inode is not yet
8615 	 * written place it on the bufwait list, otherwise do the post-inode
8616 	 * write processing to put it on the id_pendinghd list.
8617 	 */
8618 	if (MOUNTEDSUJ(mp)) {
8619 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8620 		    inoreflst);
8621 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8622 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8623 		jaddref->ja_diroff = diroffset;
8624 		jaddref->ja_diradd = dap;
8625 		add_to_journal(&jaddref->ja_list);
8626 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8627 		diradd_inode_written(dap, inodedep);
8628 	else
8629 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8630 	/*
8631 	 * Add the journal entries for . and .. links now that the primary
8632 	 * link is written.
8633 	 */
8634 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8635 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8636 		    inoreflst, if_deps);
8637 		KASSERT(jaddref != NULL &&
8638 		    jaddref->ja_ino == jaddref->ja_parent &&
8639 		    (jaddref->ja_state & MKDIR_BODY),
8640 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8641 		    jaddref));
8642 		mkdir1->md_jaddref = jaddref;
8643 		jaddref->ja_mkdir = mkdir1;
8644 		/*
8645 		 * It is important that the dotdot journal entry
8646 		 * is added prior to the dot entry since dot writes
8647 		 * both the dot and dotdot links.  These both must
8648 		 * be added after the primary link for the journal
8649 		 * to remain consistent.
8650 		 */
8651 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8652 		add_to_journal(&jaddref->ja_list);
8653 	}
8654 	/*
8655 	 * If we are adding a new directory remember this diradd so that if
8656 	 * we rename it we can keep the dot and dotdot dependencies.  If
8657 	 * we are adding a new name for an inode that has a mkdiradd we
8658 	 * must be in rename and we have to move the dot and dotdot
8659 	 * dependencies to this new name.  The old name is being orphaned
8660 	 * soon.
8661 	 */
8662 	if (mkdir1 != NULL) {
8663 		if (inodedep->id_mkdiradd != NULL)
8664 			panic("softdep_setup_directory_add: Existing mkdir");
8665 		inodedep->id_mkdiradd = dap;
8666 	} else if (inodedep->id_mkdiradd)
8667 		merge_diradd(inodedep, dap);
8668 	if (newdirblk != NULL) {
8669 		/*
8670 		 * There is nothing to do if we are already tracking
8671 		 * this block.
8672 		 */
8673 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8674 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8675 			FREE_LOCK(ump);
8676 			return (0);
8677 		}
8678 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8679 		    == 0)
8680 			panic("softdep_setup_directory_add: lost entry");
8681 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8682 		pagedep->pd_state |= NEWBLOCK;
8683 		pagedep->pd_newdirblk = newdirblk;
8684 		newdirblk->db_pagedep = pagedep;
8685 		FREE_LOCK(ump);
8686 		/*
8687 		 * If we extended into an indirect signal direnter to sync.
8688 		 */
8689 		if (isindir)
8690 			return (1);
8691 		return (0);
8692 	}
8693 	FREE_LOCK(ump);
8694 	return (0);
8695 }
8696 
8697 /*
8698  * This procedure is called to change the offset of a directory
8699  * entry when compacting a directory block which must be owned
8700  * exclusively by the caller. Note that the actual entry movement
8701  * must be done in this procedure to ensure that no I/O completions
8702  * occur while the move is in progress.
8703  */
8704 void
8705 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8706 	struct buf *bp;		/* Buffer holding directory block. */
8707 	struct inode *dp;	/* inode for directory */
8708 	caddr_t base;		/* address of dp->i_offset */
8709 	caddr_t oldloc;		/* address of old directory location */
8710 	caddr_t newloc;		/* address of new directory location */
8711 	int entrysize;		/* size of directory entry */
8712 {
8713 	int offset, oldoffset, newoffset;
8714 	struct pagedep *pagedep;
8715 	struct jmvref *jmvref;
8716 	struct diradd *dap;
8717 	struct direct *de;
8718 	struct mount *mp;
8719 	struct ufsmount *ump;
8720 	ufs_lbn_t lbn;
8721 	int flags;
8722 
8723 	mp = ITOVFS(dp);
8724 	ump = VFSTOUFS(mp);
8725 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8726 	    ("softdep_change_directoryentry_offset called on "
8727 	     "non-softdep filesystem"));
8728 	de = (struct direct *)oldloc;
8729 	jmvref = NULL;
8730 	flags = 0;
8731 	/*
8732 	 * Moves are always journaled as it would be too complex to
8733 	 * determine if any affected adds or removes are present in the
8734 	 * journal.
8735 	 */
8736 	if (MOUNTEDSUJ(mp)) {
8737 		flags = DEPALLOC;
8738 		jmvref = newjmvref(dp, de->d_ino,
8739 		    dp->i_offset + (oldloc - base),
8740 		    dp->i_offset + (newloc - base));
8741 	}
8742 	lbn = lblkno(ump->um_fs, dp->i_offset);
8743 	offset = blkoff(ump->um_fs, dp->i_offset);
8744 	oldoffset = offset + (oldloc - base);
8745 	newoffset = offset + (newloc - base);
8746 	ACQUIRE_LOCK(ump);
8747 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8748 		goto done;
8749 	dap = diradd_lookup(pagedep, oldoffset);
8750 	if (dap) {
8751 		dap->da_offset = newoffset;
8752 		newoffset = DIRADDHASH(newoffset);
8753 		oldoffset = DIRADDHASH(oldoffset);
8754 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8755 		    newoffset != oldoffset) {
8756 			LIST_REMOVE(dap, da_pdlist);
8757 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8758 			    dap, da_pdlist);
8759 		}
8760 	}
8761 done:
8762 	if (jmvref) {
8763 		jmvref->jm_pagedep = pagedep;
8764 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8765 		add_to_journal(&jmvref->jm_list);
8766 	}
8767 	bcopy(oldloc, newloc, entrysize);
8768 	FREE_LOCK(ump);
8769 }
8770 
8771 /*
8772  * Move the mkdir dependencies and journal work from one diradd to another
8773  * when renaming a directory.  The new name must depend on the mkdir deps
8774  * completing as the old name did.  Directories can only have one valid link
8775  * at a time so one must be canonical.
8776  */
8777 static void
8778 merge_diradd(inodedep, newdap)
8779 	struct inodedep *inodedep;
8780 	struct diradd *newdap;
8781 {
8782 	struct diradd *olddap;
8783 	struct mkdir *mkdir, *nextmd;
8784 	struct ufsmount *ump;
8785 	short state;
8786 
8787 	olddap = inodedep->id_mkdiradd;
8788 	inodedep->id_mkdiradd = newdap;
8789 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8790 		newdap->da_state &= ~DEPCOMPLETE;
8791 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8792 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8793 		     mkdir = nextmd) {
8794 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8795 			if (mkdir->md_diradd != olddap)
8796 				continue;
8797 			mkdir->md_diradd = newdap;
8798 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8799 			newdap->da_state |= state;
8800 			olddap->da_state &= ~state;
8801 			if ((olddap->da_state &
8802 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8803 				break;
8804 		}
8805 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8806 			panic("merge_diradd: unfound ref");
8807 	}
8808 	/*
8809 	 * Any mkdir related journal items are not safe to be freed until
8810 	 * the new name is stable.
8811 	 */
8812 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8813 	olddap->da_state |= DEPCOMPLETE;
8814 	complete_diradd(olddap);
8815 }
8816 
8817 /*
8818  * Move the diradd to the pending list when all diradd dependencies are
8819  * complete.
8820  */
8821 static void
8822 complete_diradd(dap)
8823 	struct diradd *dap;
8824 {
8825 	struct pagedep *pagedep;
8826 
8827 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8828 		if (dap->da_state & DIRCHG)
8829 			pagedep = dap->da_previous->dm_pagedep;
8830 		else
8831 			pagedep = dap->da_pagedep;
8832 		LIST_REMOVE(dap, da_pdlist);
8833 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8834 	}
8835 }
8836 
8837 /*
8838  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8839  * add entries and conditonally journal the remove.
8840  */
8841 static void
8842 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8843 	struct diradd *dap;
8844 	struct dirrem *dirrem;
8845 	struct jremref *jremref;
8846 	struct jremref *dotremref;
8847 	struct jremref *dotdotremref;
8848 {
8849 	struct inodedep *inodedep;
8850 	struct jaddref *jaddref;
8851 	struct inoref *inoref;
8852 	struct ufsmount *ump;
8853 	struct mkdir *mkdir;
8854 
8855 	/*
8856 	 * If no remove references were allocated we're on a non-journaled
8857 	 * filesystem and can skip the cancel step.
8858 	 */
8859 	if (jremref == NULL) {
8860 		free_diradd(dap, NULL);
8861 		return;
8862 	}
8863 	/*
8864 	 * Cancel the primary name an free it if it does not require
8865 	 * journaling.
8866 	 */
8867 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8868 	    0, &inodedep) != 0) {
8869 		/* Abort the addref that reference this diradd.  */
8870 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8871 			if (inoref->if_list.wk_type != D_JADDREF)
8872 				continue;
8873 			jaddref = (struct jaddref *)inoref;
8874 			if (jaddref->ja_diradd != dap)
8875 				continue;
8876 			if (cancel_jaddref(jaddref, inodedep,
8877 			    &dirrem->dm_jwork) == 0) {
8878 				free_jremref(jremref);
8879 				jremref = NULL;
8880 			}
8881 			break;
8882 		}
8883 	}
8884 	/*
8885 	 * Cancel subordinate names and free them if they do not require
8886 	 * journaling.
8887 	 */
8888 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8889 		ump = VFSTOUFS(dap->da_list.wk_mp);
8890 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8891 			if (mkdir->md_diradd != dap)
8892 				continue;
8893 			if ((jaddref = mkdir->md_jaddref) == NULL)
8894 				continue;
8895 			mkdir->md_jaddref = NULL;
8896 			if (mkdir->md_state & MKDIR_PARENT) {
8897 				if (cancel_jaddref(jaddref, NULL,
8898 				    &dirrem->dm_jwork) == 0) {
8899 					free_jremref(dotdotremref);
8900 					dotdotremref = NULL;
8901 				}
8902 			} else {
8903 				if (cancel_jaddref(jaddref, inodedep,
8904 				    &dirrem->dm_jwork) == 0) {
8905 					free_jremref(dotremref);
8906 					dotremref = NULL;
8907 				}
8908 			}
8909 		}
8910 	}
8911 
8912 	if (jremref)
8913 		journal_jremref(dirrem, jremref, inodedep);
8914 	if (dotremref)
8915 		journal_jremref(dirrem, dotremref, inodedep);
8916 	if (dotdotremref)
8917 		journal_jremref(dirrem, dotdotremref, NULL);
8918 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8919 	free_diradd(dap, &dirrem->dm_jwork);
8920 }
8921 
8922 /*
8923  * Free a diradd dependency structure.
8924  */
8925 static void
8926 free_diradd(dap, wkhd)
8927 	struct diradd *dap;
8928 	struct workhead *wkhd;
8929 {
8930 	struct dirrem *dirrem;
8931 	struct pagedep *pagedep;
8932 	struct inodedep *inodedep;
8933 	struct mkdir *mkdir, *nextmd;
8934 	struct ufsmount *ump;
8935 
8936 	ump = VFSTOUFS(dap->da_list.wk_mp);
8937 	LOCK_OWNED(ump);
8938 	LIST_REMOVE(dap, da_pdlist);
8939 	if (dap->da_state & ONWORKLIST)
8940 		WORKLIST_REMOVE(&dap->da_list);
8941 	if ((dap->da_state & DIRCHG) == 0) {
8942 		pagedep = dap->da_pagedep;
8943 	} else {
8944 		dirrem = dap->da_previous;
8945 		pagedep = dirrem->dm_pagedep;
8946 		dirrem->dm_dirinum = pagedep->pd_ino;
8947 		dirrem->dm_state |= COMPLETE;
8948 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8949 			add_to_worklist(&dirrem->dm_list, 0);
8950 	}
8951 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8952 	    0, &inodedep) != 0)
8953 		if (inodedep->id_mkdiradd == dap)
8954 			inodedep->id_mkdiradd = NULL;
8955 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8956 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8957 		     mkdir = nextmd) {
8958 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8959 			if (mkdir->md_diradd != dap)
8960 				continue;
8961 			dap->da_state &=
8962 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8963 			LIST_REMOVE(mkdir, md_mkdirs);
8964 			if (mkdir->md_state & ONWORKLIST)
8965 				WORKLIST_REMOVE(&mkdir->md_list);
8966 			if (mkdir->md_jaddref != NULL)
8967 				panic("free_diradd: Unexpected jaddref");
8968 			WORKITEM_FREE(mkdir, D_MKDIR);
8969 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8970 				break;
8971 		}
8972 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8973 			panic("free_diradd: unfound ref");
8974 	}
8975 	if (inodedep)
8976 		free_inodedep(inodedep);
8977 	/*
8978 	 * Free any journal segments waiting for the directory write.
8979 	 */
8980 	handle_jwork(&dap->da_jwork);
8981 	WORKITEM_FREE(dap, D_DIRADD);
8982 }
8983 
8984 /*
8985  * Directory entry removal dependencies.
8986  *
8987  * When removing a directory entry, the entry's inode pointer must be
8988  * zero'ed on disk before the corresponding inode's link count is decremented
8989  * (possibly freeing the inode for re-use). This dependency is handled by
8990  * updating the directory entry but delaying the inode count reduction until
8991  * after the directory block has been written to disk. After this point, the
8992  * inode count can be decremented whenever it is convenient.
8993  */
8994 
8995 /*
8996  * This routine should be called immediately after removing
8997  * a directory entry.  The inode's link count should not be
8998  * decremented by the calling procedure -- the soft updates
8999  * code will do this task when it is safe.
9000  */
9001 void
9002 softdep_setup_remove(bp, dp, ip, isrmdir)
9003 	struct buf *bp;		/* buffer containing directory block */
9004 	struct inode *dp;	/* inode for the directory being modified */
9005 	struct inode *ip;	/* inode for directory entry being removed */
9006 	int isrmdir;		/* indicates if doing RMDIR */
9007 {
9008 	struct dirrem *dirrem, *prevdirrem;
9009 	struct inodedep *inodedep;
9010 	struct ufsmount *ump;
9011 	int direct;
9012 
9013 	ump = ITOUMP(ip);
9014 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9015 	    ("softdep_setup_remove called on non-softdep filesystem"));
9016 	/*
9017 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9018 	 * newdirrem() to setup the full directory remove which requires
9019 	 * isrmdir > 1.
9020 	 */
9021 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9022 	/*
9023 	 * Add the dirrem to the inodedep's pending remove list for quick
9024 	 * discovery later.
9025 	 */
9026 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9027 		panic("softdep_setup_remove: Lost inodedep.");
9028 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9029 	dirrem->dm_state |= ONDEPLIST;
9030 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9031 
9032 	/*
9033 	 * If the COMPLETE flag is clear, then there were no active
9034 	 * entries and we want to roll back to a zeroed entry until
9035 	 * the new inode is committed to disk. If the COMPLETE flag is
9036 	 * set then we have deleted an entry that never made it to
9037 	 * disk. If the entry we deleted resulted from a name change,
9038 	 * then the old name still resides on disk. We cannot delete
9039 	 * its inode (returned to us in prevdirrem) until the zeroed
9040 	 * directory entry gets to disk. The new inode has never been
9041 	 * referenced on the disk, so can be deleted immediately.
9042 	 */
9043 	if ((dirrem->dm_state & COMPLETE) == 0) {
9044 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9045 		    dm_next);
9046 		FREE_LOCK(ump);
9047 	} else {
9048 		if (prevdirrem != NULL)
9049 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9050 			    prevdirrem, dm_next);
9051 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9052 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9053 		FREE_LOCK(ump);
9054 		if (direct)
9055 			handle_workitem_remove(dirrem, 0);
9056 	}
9057 }
9058 
9059 /*
9060  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9061  * pd_pendinghd list of a pagedep.
9062  */
9063 static struct diradd *
9064 diradd_lookup(pagedep, offset)
9065 	struct pagedep *pagedep;
9066 	int offset;
9067 {
9068 	struct diradd *dap;
9069 
9070 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9071 		if (dap->da_offset == offset)
9072 			return (dap);
9073 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9074 		if (dap->da_offset == offset)
9075 			return (dap);
9076 	return (NULL);
9077 }
9078 
9079 /*
9080  * Search for a .. diradd dependency in a directory that is being removed.
9081  * If the directory was renamed to a new parent we have a diradd rather
9082  * than a mkdir for the .. entry.  We need to cancel it now before
9083  * it is found in truncate().
9084  */
9085 static struct jremref *
9086 cancel_diradd_dotdot(ip, dirrem, jremref)
9087 	struct inode *ip;
9088 	struct dirrem *dirrem;
9089 	struct jremref *jremref;
9090 {
9091 	struct pagedep *pagedep;
9092 	struct diradd *dap;
9093 	struct worklist *wk;
9094 
9095 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9096 		return (jremref);
9097 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9098 	if (dap == NULL)
9099 		return (jremref);
9100 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9101 	/*
9102 	 * Mark any journal work as belonging to the parent so it is freed
9103 	 * with the .. reference.
9104 	 */
9105 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9106 		wk->wk_state |= MKDIR_PARENT;
9107 	return (NULL);
9108 }
9109 
9110 /*
9111  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9112  * replace it with a dirrem/diradd pair as a result of re-parenting a
9113  * directory.  This ensures that we don't simultaneously have a mkdir and
9114  * a diradd for the same .. entry.
9115  */
9116 static struct jremref *
9117 cancel_mkdir_dotdot(ip, dirrem, jremref)
9118 	struct inode *ip;
9119 	struct dirrem *dirrem;
9120 	struct jremref *jremref;
9121 {
9122 	struct inodedep *inodedep;
9123 	struct jaddref *jaddref;
9124 	struct ufsmount *ump;
9125 	struct mkdir *mkdir;
9126 	struct diradd *dap;
9127 	struct mount *mp;
9128 
9129 	mp = ITOVFS(ip);
9130 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9131 		return (jremref);
9132 	dap = inodedep->id_mkdiradd;
9133 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9134 		return (jremref);
9135 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9136 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9137 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9138 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9139 			break;
9140 	if (mkdir == NULL)
9141 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9142 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9143 		mkdir->md_jaddref = NULL;
9144 		jaddref->ja_state &= ~MKDIR_PARENT;
9145 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9146 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9147 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9148 			journal_jremref(dirrem, jremref, inodedep);
9149 			jremref = NULL;
9150 		}
9151 	}
9152 	if (mkdir->md_state & ONWORKLIST)
9153 		WORKLIST_REMOVE(&mkdir->md_list);
9154 	mkdir->md_state |= ALLCOMPLETE;
9155 	complete_mkdir(mkdir);
9156 	return (jremref);
9157 }
9158 
9159 static void
9160 journal_jremref(dirrem, jremref, inodedep)
9161 	struct dirrem *dirrem;
9162 	struct jremref *jremref;
9163 	struct inodedep *inodedep;
9164 {
9165 
9166 	if (inodedep == NULL)
9167 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9168 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9169 			panic("journal_jremref: Lost inodedep");
9170 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9171 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9172 	add_to_journal(&jremref->jr_list);
9173 }
9174 
9175 static void
9176 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9177 	struct dirrem *dirrem;
9178 	struct jremref *jremref;
9179 	struct jremref *dotremref;
9180 	struct jremref *dotdotremref;
9181 {
9182 	struct inodedep *inodedep;
9183 
9184 
9185 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9186 	    &inodedep) == 0)
9187 		panic("dirrem_journal: Lost inodedep");
9188 	journal_jremref(dirrem, jremref, inodedep);
9189 	if (dotremref)
9190 		journal_jremref(dirrem, dotremref, inodedep);
9191 	if (dotdotremref)
9192 		journal_jremref(dirrem, dotdotremref, NULL);
9193 }
9194 
9195 /*
9196  * Allocate a new dirrem if appropriate and return it along with
9197  * its associated pagedep. Called without a lock, returns with lock.
9198  */
9199 static struct dirrem *
9200 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9201 	struct buf *bp;		/* buffer containing directory block */
9202 	struct inode *dp;	/* inode for the directory being modified */
9203 	struct inode *ip;	/* inode for directory entry being removed */
9204 	int isrmdir;		/* indicates if doing RMDIR */
9205 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9206 {
9207 	int offset;
9208 	ufs_lbn_t lbn;
9209 	struct diradd *dap;
9210 	struct dirrem *dirrem;
9211 	struct pagedep *pagedep;
9212 	struct jremref *jremref;
9213 	struct jremref *dotremref;
9214 	struct jremref *dotdotremref;
9215 	struct vnode *dvp;
9216 	struct ufsmount *ump;
9217 
9218 	/*
9219 	 * Whiteouts have no deletion dependencies.
9220 	 */
9221 	if (ip == NULL)
9222 		panic("newdirrem: whiteout");
9223 	dvp = ITOV(dp);
9224 	ump = ITOUMP(dp);
9225 
9226 	/*
9227 	 * If the system is over its limit and our filesystem is
9228 	 * responsible for more than our share of that usage and
9229 	 * we are not a snapshot, request some inodedep cleanup.
9230 	 * Limiting the number of dirrem structures will also limit
9231 	 * the number of freefile and freeblks structures.
9232 	 */
9233 	ACQUIRE_LOCK(ump);
9234 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9235 		schedule_cleanup(UFSTOVFS(ump));
9236 	else
9237 		FREE_LOCK(ump);
9238 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9239 	    M_ZERO);
9240 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9241 	LIST_INIT(&dirrem->dm_jremrefhd);
9242 	LIST_INIT(&dirrem->dm_jwork);
9243 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9244 	dirrem->dm_oldinum = ip->i_number;
9245 	*prevdirremp = NULL;
9246 	/*
9247 	 * Allocate remove reference structures to track journal write
9248 	 * dependencies.  We will always have one for the link and
9249 	 * when doing directories we will always have one more for dot.
9250 	 * When renaming a directory we skip the dotdot link change so
9251 	 * this is not needed.
9252 	 */
9253 	jremref = dotremref = dotdotremref = NULL;
9254 	if (DOINGSUJ(dvp)) {
9255 		if (isrmdir) {
9256 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9257 			    ip->i_effnlink + 2);
9258 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9259 			    ip->i_effnlink + 1);
9260 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9261 			    dp->i_effnlink + 1);
9262 			dotdotremref->jr_state |= MKDIR_PARENT;
9263 		} else
9264 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9265 			    ip->i_effnlink + 1);
9266 	}
9267 	ACQUIRE_LOCK(ump);
9268 	lbn = lblkno(ump->um_fs, dp->i_offset);
9269 	offset = blkoff(ump->um_fs, dp->i_offset);
9270 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9271 	    &pagedep);
9272 	dirrem->dm_pagedep = pagedep;
9273 	dirrem->dm_offset = offset;
9274 	/*
9275 	 * If we're renaming a .. link to a new directory, cancel any
9276 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9277 	 * the jremref is preserved for any potential diradd in this
9278 	 * location.  This can not coincide with a rmdir.
9279 	 */
9280 	if (dp->i_offset == DOTDOT_OFFSET) {
9281 		if (isrmdir)
9282 			panic("newdirrem: .. directory change during remove?");
9283 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9284 	}
9285 	/*
9286 	 * If we're removing a directory search for the .. dependency now and
9287 	 * cancel it.  Any pending journal work will be added to the dirrem
9288 	 * to be completed when the workitem remove completes.
9289 	 */
9290 	if (isrmdir)
9291 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9292 	/*
9293 	 * Check for a diradd dependency for the same directory entry.
9294 	 * If present, then both dependencies become obsolete and can
9295 	 * be de-allocated.
9296 	 */
9297 	dap = diradd_lookup(pagedep, offset);
9298 	if (dap == NULL) {
9299 		/*
9300 		 * Link the jremref structures into the dirrem so they are
9301 		 * written prior to the pagedep.
9302 		 */
9303 		if (jremref)
9304 			dirrem_journal(dirrem, jremref, dotremref,
9305 			    dotdotremref);
9306 		return (dirrem);
9307 	}
9308 	/*
9309 	 * Must be ATTACHED at this point.
9310 	 */
9311 	if ((dap->da_state & ATTACHED) == 0)
9312 		panic("newdirrem: not ATTACHED");
9313 	if (dap->da_newinum != ip->i_number)
9314 		panic("newdirrem: inum %ju should be %ju",
9315 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9316 	/*
9317 	 * If we are deleting a changed name that never made it to disk,
9318 	 * then return the dirrem describing the previous inode (which
9319 	 * represents the inode currently referenced from this entry on disk).
9320 	 */
9321 	if ((dap->da_state & DIRCHG) != 0) {
9322 		*prevdirremp = dap->da_previous;
9323 		dap->da_state &= ~DIRCHG;
9324 		dap->da_pagedep = pagedep;
9325 	}
9326 	/*
9327 	 * We are deleting an entry that never made it to disk.
9328 	 * Mark it COMPLETE so we can delete its inode immediately.
9329 	 */
9330 	dirrem->dm_state |= COMPLETE;
9331 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9332 #ifdef INVARIANTS
9333 	if (isrmdir == 0) {
9334 		struct worklist *wk;
9335 
9336 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9337 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9338 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9339 	}
9340 #endif
9341 
9342 	return (dirrem);
9343 }
9344 
9345 /*
9346  * Directory entry change dependencies.
9347  *
9348  * Changing an existing directory entry requires that an add operation
9349  * be completed first followed by a deletion. The semantics for the addition
9350  * are identical to the description of adding a new entry above except
9351  * that the rollback is to the old inode number rather than zero. Once
9352  * the addition dependency is completed, the removal is done as described
9353  * in the removal routine above.
9354  */
9355 
9356 /*
9357  * This routine should be called immediately after changing
9358  * a directory entry.  The inode's link count should not be
9359  * decremented by the calling procedure -- the soft updates
9360  * code will perform this task when it is safe.
9361  */
9362 void
9363 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9364 	struct buf *bp;		/* buffer containing directory block */
9365 	struct inode *dp;	/* inode for the directory being modified */
9366 	struct inode *ip;	/* inode for directory entry being removed */
9367 	ino_t newinum;		/* new inode number for changed entry */
9368 	int isrmdir;		/* indicates if doing RMDIR */
9369 {
9370 	int offset;
9371 	struct diradd *dap = NULL;
9372 	struct dirrem *dirrem, *prevdirrem;
9373 	struct pagedep *pagedep;
9374 	struct inodedep *inodedep;
9375 	struct jaddref *jaddref;
9376 	struct mount *mp;
9377 	struct ufsmount *ump;
9378 
9379 	mp = ITOVFS(dp);
9380 	ump = VFSTOUFS(mp);
9381 	offset = blkoff(ump->um_fs, dp->i_offset);
9382 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9383 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9384 
9385 	/*
9386 	 * Whiteouts do not need diradd dependencies.
9387 	 */
9388 	if (newinum != UFS_WINO) {
9389 		dap = malloc(sizeof(struct diradd),
9390 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9391 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9392 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9393 		dap->da_offset = offset;
9394 		dap->da_newinum = newinum;
9395 		LIST_INIT(&dap->da_jwork);
9396 	}
9397 
9398 	/*
9399 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9400 	 */
9401 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9402 	pagedep = dirrem->dm_pagedep;
9403 	/*
9404 	 * The possible values for isrmdir:
9405 	 *	0 - non-directory file rename
9406 	 *	1 - directory rename within same directory
9407 	 *   inum - directory rename to new directory of given inode number
9408 	 * When renaming to a new directory, we are both deleting and
9409 	 * creating a new directory entry, so the link count on the new
9410 	 * directory should not change. Thus we do not need the followup
9411 	 * dirrem which is usually done in handle_workitem_remove. We set
9412 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9413 	 * followup dirrem.
9414 	 */
9415 	if (isrmdir > 1)
9416 		dirrem->dm_state |= DIRCHG;
9417 
9418 	/*
9419 	 * Whiteouts have no additional dependencies,
9420 	 * so just put the dirrem on the correct list.
9421 	 */
9422 	if (newinum == UFS_WINO) {
9423 		if ((dirrem->dm_state & COMPLETE) == 0) {
9424 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9425 			    dm_next);
9426 		} else {
9427 			dirrem->dm_dirinum = pagedep->pd_ino;
9428 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9429 				add_to_worklist(&dirrem->dm_list, 0);
9430 		}
9431 		FREE_LOCK(ump);
9432 		return;
9433 	}
9434 	/*
9435 	 * Add the dirrem to the inodedep's pending remove list for quick
9436 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9437 	 * will not fail.
9438 	 */
9439 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9440 		panic("softdep_setup_directory_change: Lost inodedep.");
9441 	dirrem->dm_state |= ONDEPLIST;
9442 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9443 
9444 	/*
9445 	 * If the COMPLETE flag is clear, then there were no active
9446 	 * entries and we want to roll back to the previous inode until
9447 	 * the new inode is committed to disk. If the COMPLETE flag is
9448 	 * set, then we have deleted an entry that never made it to disk.
9449 	 * If the entry we deleted resulted from a name change, then the old
9450 	 * inode reference still resides on disk. Any rollback that we do
9451 	 * needs to be to that old inode (returned to us in prevdirrem). If
9452 	 * the entry we deleted resulted from a create, then there is
9453 	 * no entry on the disk, so we want to roll back to zero rather
9454 	 * than the uncommitted inode. In either of the COMPLETE cases we
9455 	 * want to immediately free the unwritten and unreferenced inode.
9456 	 */
9457 	if ((dirrem->dm_state & COMPLETE) == 0) {
9458 		dap->da_previous = dirrem;
9459 	} else {
9460 		if (prevdirrem != NULL) {
9461 			dap->da_previous = prevdirrem;
9462 		} else {
9463 			dap->da_state &= ~DIRCHG;
9464 			dap->da_pagedep = pagedep;
9465 		}
9466 		dirrem->dm_dirinum = pagedep->pd_ino;
9467 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9468 			add_to_worklist(&dirrem->dm_list, 0);
9469 	}
9470 	/*
9471 	 * Lookup the jaddref for this journal entry.  We must finish
9472 	 * initializing it and make the diradd write dependent on it.
9473 	 * If we're not journaling, put it on the id_bufwait list if the
9474 	 * inode is not yet written. If it is written, do the post-inode
9475 	 * write processing to put it on the id_pendinghd list.
9476 	 */
9477 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9478 	if (MOUNTEDSUJ(mp)) {
9479 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9480 		    inoreflst);
9481 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9482 		    ("softdep_setup_directory_change: bad jaddref %p",
9483 		    jaddref));
9484 		jaddref->ja_diroff = dp->i_offset;
9485 		jaddref->ja_diradd = dap;
9486 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9487 		    dap, da_pdlist);
9488 		add_to_journal(&jaddref->ja_list);
9489 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9490 		dap->da_state |= COMPLETE;
9491 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9492 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9493 	} else {
9494 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9495 		    dap, da_pdlist);
9496 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9497 	}
9498 	/*
9499 	 * If we're making a new name for a directory that has not been
9500 	 * committed when need to move the dot and dotdot references to
9501 	 * this new name.
9502 	 */
9503 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9504 		merge_diradd(inodedep, dap);
9505 	FREE_LOCK(ump);
9506 }
9507 
9508 /*
9509  * Called whenever the link count on an inode is changed.
9510  * It creates an inode dependency so that the new reference(s)
9511  * to the inode cannot be committed to disk until the updated
9512  * inode has been written.
9513  */
9514 void
9515 softdep_change_linkcnt(ip)
9516 	struct inode *ip;	/* the inode with the increased link count */
9517 {
9518 	struct inodedep *inodedep;
9519 	struct ufsmount *ump;
9520 
9521 	ump = ITOUMP(ip);
9522 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9523 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9524 	ACQUIRE_LOCK(ump);
9525 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9526 	if (ip->i_nlink < ip->i_effnlink)
9527 		panic("softdep_change_linkcnt: bad delta");
9528 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9529 	FREE_LOCK(ump);
9530 }
9531 
9532 /*
9533  * Attach a sbdep dependency to the superblock buf so that we can keep
9534  * track of the head of the linked list of referenced but unlinked inodes.
9535  */
9536 void
9537 softdep_setup_sbupdate(ump, fs, bp)
9538 	struct ufsmount *ump;
9539 	struct fs *fs;
9540 	struct buf *bp;
9541 {
9542 	struct sbdep *sbdep;
9543 	struct worklist *wk;
9544 
9545 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9546 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9547 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9548 		if (wk->wk_type == D_SBDEP)
9549 			break;
9550 	if (wk != NULL)
9551 		return;
9552 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9553 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9554 	sbdep->sb_fs = fs;
9555 	sbdep->sb_ump = ump;
9556 	ACQUIRE_LOCK(ump);
9557 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9558 	FREE_LOCK(ump);
9559 }
9560 
9561 /*
9562  * Return the first unlinked inodedep which is ready to be the head of the
9563  * list.  The inodedep and all those after it must have valid next pointers.
9564  */
9565 static struct inodedep *
9566 first_unlinked_inodedep(ump)
9567 	struct ufsmount *ump;
9568 {
9569 	struct inodedep *inodedep;
9570 	struct inodedep *idp;
9571 
9572 	LOCK_OWNED(ump);
9573 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9574 	    inodedep; inodedep = idp) {
9575 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9576 			return (NULL);
9577 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9578 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9579 			break;
9580 		if ((inodedep->id_state & UNLINKPREV) == 0)
9581 			break;
9582 	}
9583 	return (inodedep);
9584 }
9585 
9586 /*
9587  * Set the sujfree unlinked head pointer prior to writing a superblock.
9588  */
9589 static void
9590 initiate_write_sbdep(sbdep)
9591 	struct sbdep *sbdep;
9592 {
9593 	struct inodedep *inodedep;
9594 	struct fs *bpfs;
9595 	struct fs *fs;
9596 
9597 	bpfs = sbdep->sb_fs;
9598 	fs = sbdep->sb_ump->um_fs;
9599 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9600 	if (inodedep) {
9601 		fs->fs_sujfree = inodedep->id_ino;
9602 		inodedep->id_state |= UNLINKPREV;
9603 	} else
9604 		fs->fs_sujfree = 0;
9605 	bpfs->fs_sujfree = fs->fs_sujfree;
9606 	/*
9607 	 * Because we have made changes to the superblock, we need to
9608 	 * recompute its check-hash.
9609 	 */
9610 	bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9611 }
9612 
9613 /*
9614  * After a superblock is written determine whether it must be written again
9615  * due to a changing unlinked list head.
9616  */
9617 static int
9618 handle_written_sbdep(sbdep, bp)
9619 	struct sbdep *sbdep;
9620 	struct buf *bp;
9621 {
9622 	struct inodedep *inodedep;
9623 	struct fs *fs;
9624 
9625 	LOCK_OWNED(sbdep->sb_ump);
9626 	fs = sbdep->sb_fs;
9627 	/*
9628 	 * If the superblock doesn't match the in-memory list start over.
9629 	 */
9630 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9631 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9632 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9633 		bdirty(bp);
9634 		return (1);
9635 	}
9636 	WORKITEM_FREE(sbdep, D_SBDEP);
9637 	if (fs->fs_sujfree == 0)
9638 		return (0);
9639 	/*
9640 	 * Now that we have a record of this inode in stable store allow it
9641 	 * to be written to free up pending work.  Inodes may see a lot of
9642 	 * write activity after they are unlinked which we must not hold up.
9643 	 */
9644 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9645 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9646 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9647 			    inodedep, inodedep->id_state);
9648 		if (inodedep->id_state & UNLINKONLIST)
9649 			break;
9650 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9651 	}
9652 
9653 	return (0);
9654 }
9655 
9656 /*
9657  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9658  */
9659 static void
9660 unlinked_inodedep(mp, inodedep)
9661 	struct mount *mp;
9662 	struct inodedep *inodedep;
9663 {
9664 	struct ufsmount *ump;
9665 
9666 	ump = VFSTOUFS(mp);
9667 	LOCK_OWNED(ump);
9668 	if (MOUNTEDSUJ(mp) == 0)
9669 		return;
9670 	ump->um_fs->fs_fmod = 1;
9671 	if (inodedep->id_state & UNLINKED)
9672 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9673 	inodedep->id_state |= UNLINKED;
9674 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9675 }
9676 
9677 /*
9678  * Remove an inodedep from the unlinked inodedep list.  This may require
9679  * disk writes if the inode has made it that far.
9680  */
9681 static void
9682 clear_unlinked_inodedep(inodedep)
9683 	struct inodedep *inodedep;
9684 {
9685 	struct ufs2_dinode *dip;
9686 	struct ufsmount *ump;
9687 	struct inodedep *idp;
9688 	struct inodedep *idn;
9689 	struct fs *fs, *bpfs;
9690 	struct buf *bp;
9691 	ino_t ino;
9692 	ino_t nino;
9693 	ino_t pino;
9694 	int error;
9695 
9696 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9697 	fs = ump->um_fs;
9698 	ino = inodedep->id_ino;
9699 	error = 0;
9700 	for (;;) {
9701 		LOCK_OWNED(ump);
9702 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9703 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9704 		    inodedep));
9705 		/*
9706 		 * If nothing has yet been written simply remove us from
9707 		 * the in memory list and return.  This is the most common
9708 		 * case where handle_workitem_remove() loses the final
9709 		 * reference.
9710 		 */
9711 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9712 			break;
9713 		/*
9714 		 * If we have a NEXT pointer and no PREV pointer we can simply
9715 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9716 		 * careful not to clear PREV if the superblock points at
9717 		 * next as well.
9718 		 */
9719 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9720 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9721 			if (idn && fs->fs_sujfree != idn->id_ino)
9722 				idn->id_state &= ~UNLINKPREV;
9723 			break;
9724 		}
9725 		/*
9726 		 * Here we have an inodedep which is actually linked into
9727 		 * the list.  We must remove it by forcing a write to the
9728 		 * link before us, whether it be the superblock or an inode.
9729 		 * Unfortunately the list may change while we're waiting
9730 		 * on the buf lock for either resource so we must loop until
9731 		 * we lock the right one.  If both the superblock and an
9732 		 * inode point to this inode we must clear the inode first
9733 		 * followed by the superblock.
9734 		 */
9735 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9736 		pino = 0;
9737 		if (idp && (idp->id_state & UNLINKNEXT))
9738 			pino = idp->id_ino;
9739 		FREE_LOCK(ump);
9740 		if (pino == 0) {
9741 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9742 			    (int)fs->fs_sbsize, 0, 0, 0);
9743 		} else {
9744 			error = bread(ump->um_devvp,
9745 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9746 			    (int)fs->fs_bsize, NOCRED, &bp);
9747 			if (error)
9748 				brelse(bp);
9749 		}
9750 		ACQUIRE_LOCK(ump);
9751 		if (error)
9752 			break;
9753 		/* If the list has changed restart the loop. */
9754 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9755 		nino = 0;
9756 		if (idp && (idp->id_state & UNLINKNEXT))
9757 			nino = idp->id_ino;
9758 		if (nino != pino ||
9759 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9760 			FREE_LOCK(ump);
9761 			brelse(bp);
9762 			ACQUIRE_LOCK(ump);
9763 			continue;
9764 		}
9765 		nino = 0;
9766 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9767 		if (idn)
9768 			nino = idn->id_ino;
9769 		/*
9770 		 * Remove us from the in memory list.  After this we cannot
9771 		 * access the inodedep.
9772 		 */
9773 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9774 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9775 		    inodedep));
9776 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9777 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9778 		FREE_LOCK(ump);
9779 		/*
9780 		 * The predecessor's next pointer is manually updated here
9781 		 * so that the NEXT flag is never cleared for an element
9782 		 * that is in the list.
9783 		 */
9784 		if (pino == 0) {
9785 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9786 			bpfs = (struct fs *)bp->b_data;
9787 			ffs_oldfscompat_write(bpfs, ump);
9788 			softdep_setup_sbupdate(ump, bpfs, bp);
9789 			/*
9790 			 * Because we may have made changes to the superblock,
9791 			 * we need to recompute its check-hash.
9792 			 */
9793 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9794 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
9795 			((struct ufs1_dinode *)bp->b_data +
9796 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9797 		} else {
9798 			dip = (struct ufs2_dinode *)bp->b_data +
9799 			    ino_to_fsbo(fs, pino);
9800 			dip->di_freelink = nino;
9801 			ffs_update_dinode_ckhash(fs, dip);
9802 		}
9803 		/*
9804 		 * If the bwrite fails we have no recourse to recover.  The
9805 		 * filesystem is corrupted already.
9806 		 */
9807 		bwrite(bp);
9808 		ACQUIRE_LOCK(ump);
9809 		/*
9810 		 * If the superblock pointer still needs to be cleared force
9811 		 * a write here.
9812 		 */
9813 		if (fs->fs_sujfree == ino) {
9814 			FREE_LOCK(ump);
9815 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9816 			    (int)fs->fs_sbsize, 0, 0, 0);
9817 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9818 			bpfs = (struct fs *)bp->b_data;
9819 			ffs_oldfscompat_write(bpfs, ump);
9820 			softdep_setup_sbupdate(ump, bpfs, bp);
9821 			/*
9822 			 * Because we may have made changes to the superblock,
9823 			 * we need to recompute its check-hash.
9824 			 */
9825 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9826 			bwrite(bp);
9827 			ACQUIRE_LOCK(ump);
9828 		}
9829 
9830 		if (fs->fs_sujfree != ino)
9831 			return;
9832 		panic("clear_unlinked_inodedep: Failed to clear free head");
9833 	}
9834 	if (inodedep->id_ino == fs->fs_sujfree)
9835 		panic("clear_unlinked_inodedep: Freeing head of free list");
9836 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9837 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9838 	return;
9839 }
9840 
9841 /*
9842  * This workitem decrements the inode's link count.
9843  * If the link count reaches zero, the file is removed.
9844  */
9845 static int
9846 handle_workitem_remove(dirrem, flags)
9847 	struct dirrem *dirrem;
9848 	int flags;
9849 {
9850 	struct inodedep *inodedep;
9851 	struct workhead dotdotwk;
9852 	struct worklist *wk;
9853 	struct ufsmount *ump;
9854 	struct mount *mp;
9855 	struct vnode *vp;
9856 	struct inode *ip;
9857 	ino_t oldinum;
9858 
9859 	if (dirrem->dm_state & ONWORKLIST)
9860 		panic("handle_workitem_remove: dirrem %p still on worklist",
9861 		    dirrem);
9862 	oldinum = dirrem->dm_oldinum;
9863 	mp = dirrem->dm_list.wk_mp;
9864 	ump = VFSTOUFS(mp);
9865 	flags |= LK_EXCLUSIVE;
9866 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9867 		return (EBUSY);
9868 	ip = VTOI(vp);
9869 	MPASS(ip->i_mode != 0);
9870 	ACQUIRE_LOCK(ump);
9871 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9872 		panic("handle_workitem_remove: lost inodedep");
9873 	if (dirrem->dm_state & ONDEPLIST)
9874 		LIST_REMOVE(dirrem, dm_inonext);
9875 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9876 	    ("handle_workitem_remove:  Journal entries not written."));
9877 
9878 	/*
9879 	 * Move all dependencies waiting on the remove to complete
9880 	 * from the dirrem to the inode inowait list to be completed
9881 	 * after the inode has been updated and written to disk.
9882 	 *
9883 	 * Any marked MKDIR_PARENT are saved to be completed when the
9884 	 * dotdot ref is removed unless DIRCHG is specified.  For
9885 	 * directory change operations there will be no further
9886 	 * directory writes and the jsegdeps need to be moved along
9887 	 * with the rest to be completed when the inode is free or
9888 	 * stable in the inode free list.
9889 	 */
9890 	LIST_INIT(&dotdotwk);
9891 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9892 		WORKLIST_REMOVE(wk);
9893 		if ((dirrem->dm_state & DIRCHG) == 0 &&
9894 		    wk->wk_state & MKDIR_PARENT) {
9895 			wk->wk_state &= ~MKDIR_PARENT;
9896 			WORKLIST_INSERT(&dotdotwk, wk);
9897 			continue;
9898 		}
9899 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9900 	}
9901 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9902 	/*
9903 	 * Normal file deletion.
9904 	 */
9905 	if ((dirrem->dm_state & RMDIR) == 0) {
9906 		ip->i_nlink--;
9907 		KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
9908 		    "%ju negative i_nlink %d", (intmax_t)ip->i_number,
9909 		    ip->i_nlink));
9910 		DIP_SET(ip, i_nlink, ip->i_nlink);
9911 		UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9912 		if (ip->i_nlink < ip->i_effnlink)
9913 			panic("handle_workitem_remove: bad file delta");
9914 		if (ip->i_nlink == 0)
9915 			unlinked_inodedep(mp, inodedep);
9916 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9917 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9918 		    ("handle_workitem_remove: worklist not empty. %s",
9919 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9920 		WORKITEM_FREE(dirrem, D_DIRREM);
9921 		FREE_LOCK(ump);
9922 		goto out;
9923 	}
9924 	/*
9925 	 * Directory deletion. Decrement reference count for both the
9926 	 * just deleted parent directory entry and the reference for ".".
9927 	 * Arrange to have the reference count on the parent decremented
9928 	 * to account for the loss of "..".
9929 	 */
9930 	ip->i_nlink -= 2;
9931 	KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
9932 	    "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
9933 	DIP_SET(ip, i_nlink, ip->i_nlink);
9934 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9935 	if (ip->i_nlink < ip->i_effnlink)
9936 		panic("handle_workitem_remove: bad dir delta");
9937 	if (ip->i_nlink == 0)
9938 		unlinked_inodedep(mp, inodedep);
9939 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9940 	/*
9941 	 * Rename a directory to a new parent. Since, we are both deleting
9942 	 * and creating a new directory entry, the link count on the new
9943 	 * directory should not change. Thus we skip the followup dirrem.
9944 	 */
9945 	if (dirrem->dm_state & DIRCHG) {
9946 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9947 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9948 		WORKITEM_FREE(dirrem, D_DIRREM);
9949 		FREE_LOCK(ump);
9950 		goto out;
9951 	}
9952 	dirrem->dm_state = ONDEPLIST;
9953 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9954 	/*
9955 	 * Place the dirrem on the parent's diremhd list.
9956 	 */
9957 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9958 		panic("handle_workitem_remove: lost dir inodedep");
9959 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9960 	/*
9961 	 * If the allocated inode has never been written to disk, then
9962 	 * the on-disk inode is zero'ed and we can remove the file
9963 	 * immediately.  When journaling if the inode has been marked
9964 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9965 	 */
9966 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9967 	if (inodedep == NULL ||
9968 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9969 	    check_inode_unwritten(inodedep)) {
9970 		FREE_LOCK(ump);
9971 		vput(vp);
9972 		return handle_workitem_remove(dirrem, flags);
9973 	}
9974 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9975 	FREE_LOCK(ump);
9976 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9977 out:
9978 	ffs_update(vp, 0);
9979 	vput(vp);
9980 	return (0);
9981 }
9982 
9983 /*
9984  * Inode de-allocation dependencies.
9985  *
9986  * When an inode's link count is reduced to zero, it can be de-allocated. We
9987  * found it convenient to postpone de-allocation until after the inode is
9988  * written to disk with its new link count (zero).  At this point, all of the
9989  * on-disk inode's block pointers are nullified and, with careful dependency
9990  * list ordering, all dependencies related to the inode will be satisfied and
9991  * the corresponding dependency structures de-allocated.  So, if/when the
9992  * inode is reused, there will be no mixing of old dependencies with new
9993  * ones.  This artificial dependency is set up by the block de-allocation
9994  * procedure above (softdep_setup_freeblocks) and completed by the
9995  * following procedure.
9996  */
9997 static void
9998 handle_workitem_freefile(freefile)
9999 	struct freefile *freefile;
10000 {
10001 	struct workhead wkhd;
10002 	struct fs *fs;
10003 	struct ufsmount *ump;
10004 	int error;
10005 #ifdef INVARIANTS
10006 	struct inodedep *idp;
10007 #endif
10008 
10009 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
10010 	fs = ump->um_fs;
10011 #ifdef INVARIANTS
10012 	ACQUIRE_LOCK(ump);
10013 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10014 	FREE_LOCK(ump);
10015 	if (error)
10016 		panic("handle_workitem_freefile: inodedep %p survived", idp);
10017 #endif
10018 	UFS_LOCK(ump);
10019 	fs->fs_pendinginodes -= 1;
10020 	UFS_UNLOCK(ump);
10021 	LIST_INIT(&wkhd);
10022 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10023 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10024 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10025 		softdep_error("handle_workitem_freefile", error);
10026 	ACQUIRE_LOCK(ump);
10027 	WORKITEM_FREE(freefile, D_FREEFILE);
10028 	FREE_LOCK(ump);
10029 }
10030 
10031 
10032 /*
10033  * Helper function which unlinks marker element from work list and returns
10034  * the next element on the list.
10035  */
10036 static __inline struct worklist *
10037 markernext(struct worklist *marker)
10038 {
10039 	struct worklist *next;
10040 
10041 	next = LIST_NEXT(marker, wk_list);
10042 	LIST_REMOVE(marker, wk_list);
10043 	return next;
10044 }
10045 
10046 /*
10047  * Disk writes.
10048  *
10049  * The dependency structures constructed above are most actively used when file
10050  * system blocks are written to disk.  No constraints are placed on when a
10051  * block can be written, but unsatisfied update dependencies are made safe by
10052  * modifying (or replacing) the source memory for the duration of the disk
10053  * write.  When the disk write completes, the memory block is again brought
10054  * up-to-date.
10055  *
10056  * In-core inode structure reclamation.
10057  *
10058  * Because there are a finite number of "in-core" inode structures, they are
10059  * reused regularly.  By transferring all inode-related dependencies to the
10060  * in-memory inode block and indexing them separately (via "inodedep"s), we
10061  * can allow "in-core" inode structures to be reused at any time and avoid
10062  * any increase in contention.
10063  *
10064  * Called just before entering the device driver to initiate a new disk I/O.
10065  * The buffer must be locked, thus, no I/O completion operations can occur
10066  * while we are manipulating its associated dependencies.
10067  */
10068 static void
10069 softdep_disk_io_initiation(bp)
10070 	struct buf *bp;		/* structure describing disk write to occur */
10071 {
10072 	struct worklist *wk;
10073 	struct worklist marker;
10074 	struct inodedep *inodedep;
10075 	struct freeblks *freeblks;
10076 	struct jblkdep *jblkdep;
10077 	struct newblk *newblk;
10078 	struct ufsmount *ump;
10079 
10080 	/*
10081 	 * We only care about write operations. There should never
10082 	 * be dependencies for reads.
10083 	 */
10084 	if (bp->b_iocmd != BIO_WRITE)
10085 		panic("softdep_disk_io_initiation: not write");
10086 
10087 	if (bp->b_vflags & BV_BKGRDINPROG)
10088 		panic("softdep_disk_io_initiation: Writing buffer with "
10089 		    "background write in progress: %p", bp);
10090 
10091 	ump = softdep_bp_to_mp(bp);
10092 	if (ump == NULL)
10093 		return;
10094 
10095 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10096 	PHOLD(curproc);			/* Don't swap out kernel stack */
10097 	ACQUIRE_LOCK(ump);
10098 	/*
10099 	 * Do any necessary pre-I/O processing.
10100 	 */
10101 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10102 	     wk = markernext(&marker)) {
10103 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10104 		switch (wk->wk_type) {
10105 
10106 		case D_PAGEDEP:
10107 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10108 			continue;
10109 
10110 		case D_INODEDEP:
10111 			inodedep = WK_INODEDEP(wk);
10112 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10113 				initiate_write_inodeblock_ufs1(inodedep, bp);
10114 			else
10115 				initiate_write_inodeblock_ufs2(inodedep, bp);
10116 			continue;
10117 
10118 		case D_INDIRDEP:
10119 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10120 			continue;
10121 
10122 		case D_BMSAFEMAP:
10123 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10124 			continue;
10125 
10126 		case D_JSEG:
10127 			WK_JSEG(wk)->js_buf = NULL;
10128 			continue;
10129 
10130 		case D_FREEBLKS:
10131 			freeblks = WK_FREEBLKS(wk);
10132 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10133 			/*
10134 			 * We have to wait for the freeblks to be journaled
10135 			 * before we can write an inodeblock with updated
10136 			 * pointers.  Be careful to arrange the marker so
10137 			 * we revisit the freeblks if it's not removed by
10138 			 * the first jwait().
10139 			 */
10140 			if (jblkdep != NULL) {
10141 				LIST_REMOVE(&marker, wk_list);
10142 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10143 				jwait(&jblkdep->jb_list, MNT_WAIT);
10144 			}
10145 			continue;
10146 		case D_ALLOCDIRECT:
10147 		case D_ALLOCINDIR:
10148 			/*
10149 			 * We have to wait for the jnewblk to be journaled
10150 			 * before we can write to a block if the contents
10151 			 * may be confused with an earlier file's indirect
10152 			 * at recovery time.  Handle the marker as described
10153 			 * above.
10154 			 */
10155 			newblk = WK_NEWBLK(wk);
10156 			if (newblk->nb_jnewblk != NULL &&
10157 			    indirblk_lookup(newblk->nb_list.wk_mp,
10158 			    newblk->nb_newblkno)) {
10159 				LIST_REMOVE(&marker, wk_list);
10160 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10161 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10162 			}
10163 			continue;
10164 
10165 		case D_SBDEP:
10166 			initiate_write_sbdep(WK_SBDEP(wk));
10167 			continue;
10168 
10169 		case D_MKDIR:
10170 		case D_FREEWORK:
10171 		case D_FREEDEP:
10172 		case D_JSEGDEP:
10173 			continue;
10174 
10175 		default:
10176 			panic("handle_disk_io_initiation: Unexpected type %s",
10177 			    TYPENAME(wk->wk_type));
10178 			/* NOTREACHED */
10179 		}
10180 	}
10181 	FREE_LOCK(ump);
10182 	PRELE(curproc);			/* Allow swapout of kernel stack */
10183 }
10184 
10185 /*
10186  * Called from within the procedure above to deal with unsatisfied
10187  * allocation dependencies in a directory. The buffer must be locked,
10188  * thus, no I/O completion operations can occur while we are
10189  * manipulating its associated dependencies.
10190  */
10191 static void
10192 initiate_write_filepage(pagedep, bp)
10193 	struct pagedep *pagedep;
10194 	struct buf *bp;
10195 {
10196 	struct jremref *jremref;
10197 	struct jmvref *jmvref;
10198 	struct dirrem *dirrem;
10199 	struct diradd *dap;
10200 	struct direct *ep;
10201 	int i;
10202 
10203 	if (pagedep->pd_state & IOSTARTED) {
10204 		/*
10205 		 * This can only happen if there is a driver that does not
10206 		 * understand chaining. Here biodone will reissue the call
10207 		 * to strategy for the incomplete buffers.
10208 		 */
10209 		printf("initiate_write_filepage: already started\n");
10210 		return;
10211 	}
10212 	pagedep->pd_state |= IOSTARTED;
10213 	/*
10214 	 * Wait for all journal remove dependencies to hit the disk.
10215 	 * We can not allow any potentially conflicting directory adds
10216 	 * to be visible before removes and rollback is too difficult.
10217 	 * The per-filesystem lock may be dropped and re-acquired, however
10218 	 * we hold the buf locked so the dependency can not go away.
10219 	 */
10220 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10221 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10222 			jwait(&jremref->jr_list, MNT_WAIT);
10223 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10224 		jwait(&jmvref->jm_list, MNT_WAIT);
10225 	for (i = 0; i < DAHASHSZ; i++) {
10226 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10227 			ep = (struct direct *)
10228 			    ((char *)bp->b_data + dap->da_offset);
10229 			if (ep->d_ino != dap->da_newinum)
10230 				panic("%s: dir inum %ju != new %ju",
10231 				    "initiate_write_filepage",
10232 				    (uintmax_t)ep->d_ino,
10233 				    (uintmax_t)dap->da_newinum);
10234 			if (dap->da_state & DIRCHG)
10235 				ep->d_ino = dap->da_previous->dm_oldinum;
10236 			else
10237 				ep->d_ino = 0;
10238 			dap->da_state &= ~ATTACHED;
10239 			dap->da_state |= UNDONE;
10240 		}
10241 	}
10242 }
10243 
10244 /*
10245  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10246  * Note that any bug fixes made to this routine must be done in the
10247  * version found below.
10248  *
10249  * Called from within the procedure above to deal with unsatisfied
10250  * allocation dependencies in an inodeblock. The buffer must be
10251  * locked, thus, no I/O completion operations can occur while we
10252  * are manipulating its associated dependencies.
10253  */
10254 static void
10255 initiate_write_inodeblock_ufs1(inodedep, bp)
10256 	struct inodedep *inodedep;
10257 	struct buf *bp;			/* The inode block */
10258 {
10259 	struct allocdirect *adp, *lastadp;
10260 	struct ufs1_dinode *dp;
10261 	struct ufs1_dinode *sip;
10262 	struct inoref *inoref;
10263 	struct ufsmount *ump;
10264 	struct fs *fs;
10265 	ufs_lbn_t i;
10266 #ifdef INVARIANTS
10267 	ufs_lbn_t prevlbn = 0;
10268 #endif
10269 	int deplist;
10270 
10271 	if (inodedep->id_state & IOSTARTED)
10272 		panic("initiate_write_inodeblock_ufs1: already started");
10273 	inodedep->id_state |= IOSTARTED;
10274 	fs = inodedep->id_fs;
10275 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10276 	LOCK_OWNED(ump);
10277 	dp = (struct ufs1_dinode *)bp->b_data +
10278 	    ino_to_fsbo(fs, inodedep->id_ino);
10279 
10280 	/*
10281 	 * If we're on the unlinked list but have not yet written our
10282 	 * next pointer initialize it here.
10283 	 */
10284 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10285 		struct inodedep *inon;
10286 
10287 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10288 		dp->di_freelink = inon ? inon->id_ino : 0;
10289 	}
10290 	/*
10291 	 * If the bitmap is not yet written, then the allocated
10292 	 * inode cannot be written to disk.
10293 	 */
10294 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10295 		if (inodedep->id_savedino1 != NULL)
10296 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10297 		FREE_LOCK(ump);
10298 		sip = malloc(sizeof(struct ufs1_dinode),
10299 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10300 		ACQUIRE_LOCK(ump);
10301 		inodedep->id_savedino1 = sip;
10302 		*inodedep->id_savedino1 = *dp;
10303 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10304 		dp->di_gen = inodedep->id_savedino1->di_gen;
10305 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10306 		return;
10307 	}
10308 	/*
10309 	 * If no dependencies, then there is nothing to roll back.
10310 	 */
10311 	inodedep->id_savedsize = dp->di_size;
10312 	inodedep->id_savedextsize = 0;
10313 	inodedep->id_savednlink = dp->di_nlink;
10314 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10315 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10316 		return;
10317 	/*
10318 	 * Revert the link count to that of the first unwritten journal entry.
10319 	 */
10320 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10321 	if (inoref)
10322 		dp->di_nlink = inoref->if_nlink;
10323 	/*
10324 	 * Set the dependencies to busy.
10325 	 */
10326 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10327 	     adp = TAILQ_NEXT(adp, ad_next)) {
10328 #ifdef INVARIANTS
10329 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10330 			panic("softdep_write_inodeblock: lbn order");
10331 		prevlbn = adp->ad_offset;
10332 		if (adp->ad_offset < UFS_NDADDR &&
10333 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10334 			panic("initiate_write_inodeblock_ufs1: "
10335 			    "direct pointer #%jd mismatch %d != %jd",
10336 			    (intmax_t)adp->ad_offset,
10337 			    dp->di_db[adp->ad_offset],
10338 			    (intmax_t)adp->ad_newblkno);
10339 		if (adp->ad_offset >= UFS_NDADDR &&
10340 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10341 			panic("initiate_write_inodeblock_ufs1: "
10342 			    "indirect pointer #%jd mismatch %d != %jd",
10343 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10344 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10345 			    (intmax_t)adp->ad_newblkno);
10346 		deplist |= 1 << adp->ad_offset;
10347 		if ((adp->ad_state & ATTACHED) == 0)
10348 			panic("initiate_write_inodeblock_ufs1: "
10349 			    "Unknown state 0x%x", adp->ad_state);
10350 #endif /* INVARIANTS */
10351 		adp->ad_state &= ~ATTACHED;
10352 		adp->ad_state |= UNDONE;
10353 	}
10354 	/*
10355 	 * The on-disk inode cannot claim to be any larger than the last
10356 	 * fragment that has been written. Otherwise, the on-disk inode
10357 	 * might have fragments that were not the last block in the file
10358 	 * which would corrupt the filesystem.
10359 	 */
10360 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10361 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10362 		if (adp->ad_offset >= UFS_NDADDR)
10363 			break;
10364 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10365 		/* keep going until hitting a rollback to a frag */
10366 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10367 			continue;
10368 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10369 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10370 #ifdef INVARIANTS
10371 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10372 				panic("initiate_write_inodeblock_ufs1: "
10373 				    "lost dep1");
10374 #endif /* INVARIANTS */
10375 			dp->di_db[i] = 0;
10376 		}
10377 		for (i = 0; i < UFS_NIADDR; i++) {
10378 #ifdef INVARIANTS
10379 			if (dp->di_ib[i] != 0 &&
10380 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10381 				panic("initiate_write_inodeblock_ufs1: "
10382 				    "lost dep2");
10383 #endif /* INVARIANTS */
10384 			dp->di_ib[i] = 0;
10385 		}
10386 		return;
10387 	}
10388 	/*
10389 	 * If we have zero'ed out the last allocated block of the file,
10390 	 * roll back the size to the last currently allocated block.
10391 	 * We know that this last allocated block is a full-sized as
10392 	 * we already checked for fragments in the loop above.
10393 	 */
10394 	if (lastadp != NULL &&
10395 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10396 		for (i = lastadp->ad_offset; i >= 0; i--)
10397 			if (dp->di_db[i] != 0)
10398 				break;
10399 		dp->di_size = (i + 1) * fs->fs_bsize;
10400 	}
10401 	/*
10402 	 * The only dependencies are for indirect blocks.
10403 	 *
10404 	 * The file size for indirect block additions is not guaranteed.
10405 	 * Such a guarantee would be non-trivial to achieve. The conventional
10406 	 * synchronous write implementation also does not make this guarantee.
10407 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10408 	 * can be over-estimated without destroying integrity when the file
10409 	 * moves into the indirect blocks (i.e., is large). If we want to
10410 	 * postpone fsck, we are stuck with this argument.
10411 	 */
10412 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10413 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10414 }
10415 
10416 /*
10417  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10418  * Note that any bug fixes made to this routine must be done in the
10419  * version found above.
10420  *
10421  * Called from within the procedure above to deal with unsatisfied
10422  * allocation dependencies in an inodeblock. The buffer must be
10423  * locked, thus, no I/O completion operations can occur while we
10424  * are manipulating its associated dependencies.
10425  */
10426 static void
10427 initiate_write_inodeblock_ufs2(inodedep, bp)
10428 	struct inodedep *inodedep;
10429 	struct buf *bp;			/* The inode block */
10430 {
10431 	struct allocdirect *adp, *lastadp;
10432 	struct ufs2_dinode *dp;
10433 	struct ufs2_dinode *sip;
10434 	struct inoref *inoref;
10435 	struct ufsmount *ump;
10436 	struct fs *fs;
10437 	ufs_lbn_t i;
10438 #ifdef INVARIANTS
10439 	ufs_lbn_t prevlbn = 0;
10440 #endif
10441 	int deplist;
10442 
10443 	if (inodedep->id_state & IOSTARTED)
10444 		panic("initiate_write_inodeblock_ufs2: already started");
10445 	inodedep->id_state |= IOSTARTED;
10446 	fs = inodedep->id_fs;
10447 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10448 	LOCK_OWNED(ump);
10449 	dp = (struct ufs2_dinode *)bp->b_data +
10450 	    ino_to_fsbo(fs, inodedep->id_ino);
10451 
10452 	/*
10453 	 * If we're on the unlinked list but have not yet written our
10454 	 * next pointer initialize it here.
10455 	 */
10456 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10457 		struct inodedep *inon;
10458 
10459 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10460 		dp->di_freelink = inon ? inon->id_ino : 0;
10461 		ffs_update_dinode_ckhash(fs, dp);
10462 	}
10463 	/*
10464 	 * If the bitmap is not yet written, then the allocated
10465 	 * inode cannot be written to disk.
10466 	 */
10467 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10468 		if (inodedep->id_savedino2 != NULL)
10469 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10470 		FREE_LOCK(ump);
10471 		sip = malloc(sizeof(struct ufs2_dinode),
10472 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10473 		ACQUIRE_LOCK(ump);
10474 		inodedep->id_savedino2 = sip;
10475 		*inodedep->id_savedino2 = *dp;
10476 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10477 		dp->di_gen = inodedep->id_savedino2->di_gen;
10478 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10479 		return;
10480 	}
10481 	/*
10482 	 * If no dependencies, then there is nothing to roll back.
10483 	 */
10484 	inodedep->id_savedsize = dp->di_size;
10485 	inodedep->id_savedextsize = dp->di_extsize;
10486 	inodedep->id_savednlink = dp->di_nlink;
10487 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10488 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10489 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10490 		return;
10491 	/*
10492 	 * Revert the link count to that of the first unwritten journal entry.
10493 	 */
10494 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10495 	if (inoref)
10496 		dp->di_nlink = inoref->if_nlink;
10497 
10498 	/*
10499 	 * Set the ext data dependencies to busy.
10500 	 */
10501 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10502 	     adp = TAILQ_NEXT(adp, ad_next)) {
10503 #ifdef INVARIANTS
10504 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10505 			panic("initiate_write_inodeblock_ufs2: lbn order");
10506 		prevlbn = adp->ad_offset;
10507 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10508 			panic("initiate_write_inodeblock_ufs2: "
10509 			    "ext pointer #%jd mismatch %jd != %jd",
10510 			    (intmax_t)adp->ad_offset,
10511 			    (intmax_t)dp->di_extb[adp->ad_offset],
10512 			    (intmax_t)adp->ad_newblkno);
10513 		deplist |= 1 << adp->ad_offset;
10514 		if ((adp->ad_state & ATTACHED) == 0)
10515 			panic("initiate_write_inodeblock_ufs2: Unknown "
10516 			    "state 0x%x", adp->ad_state);
10517 #endif /* INVARIANTS */
10518 		adp->ad_state &= ~ATTACHED;
10519 		adp->ad_state |= UNDONE;
10520 	}
10521 	/*
10522 	 * The on-disk inode cannot claim to be any larger than the last
10523 	 * fragment that has been written. Otherwise, the on-disk inode
10524 	 * might have fragments that were not the last block in the ext
10525 	 * data which would corrupt the filesystem.
10526 	 */
10527 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10528 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10529 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10530 		/* keep going until hitting a rollback to a frag */
10531 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10532 			continue;
10533 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10534 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10535 #ifdef INVARIANTS
10536 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10537 				panic("initiate_write_inodeblock_ufs2: "
10538 				    "lost dep1");
10539 #endif /* INVARIANTS */
10540 			dp->di_extb[i] = 0;
10541 		}
10542 		lastadp = NULL;
10543 		break;
10544 	}
10545 	/*
10546 	 * If we have zero'ed out the last allocated block of the ext
10547 	 * data, roll back the size to the last currently allocated block.
10548 	 * We know that this last allocated block is a full-sized as
10549 	 * we already checked for fragments in the loop above.
10550 	 */
10551 	if (lastadp != NULL &&
10552 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10553 		for (i = lastadp->ad_offset; i >= 0; i--)
10554 			if (dp->di_extb[i] != 0)
10555 				break;
10556 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10557 	}
10558 	/*
10559 	 * Set the file data dependencies to busy.
10560 	 */
10561 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10562 	     adp = TAILQ_NEXT(adp, ad_next)) {
10563 #ifdef INVARIANTS
10564 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10565 			panic("softdep_write_inodeblock: lbn order");
10566 		if ((adp->ad_state & ATTACHED) == 0)
10567 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10568 		prevlbn = adp->ad_offset;
10569 		if (adp->ad_offset < UFS_NDADDR &&
10570 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10571 			panic("initiate_write_inodeblock_ufs2: "
10572 			    "direct pointer #%jd mismatch %jd != %jd",
10573 			    (intmax_t)adp->ad_offset,
10574 			    (intmax_t)dp->di_db[adp->ad_offset],
10575 			    (intmax_t)adp->ad_newblkno);
10576 		if (adp->ad_offset >= UFS_NDADDR &&
10577 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10578 			panic("initiate_write_inodeblock_ufs2: "
10579 			    "indirect pointer #%jd mismatch %jd != %jd",
10580 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10581 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10582 			    (intmax_t)adp->ad_newblkno);
10583 		deplist |= 1 << adp->ad_offset;
10584 		if ((adp->ad_state & ATTACHED) == 0)
10585 			panic("initiate_write_inodeblock_ufs2: Unknown "
10586 			     "state 0x%x", adp->ad_state);
10587 #endif /* INVARIANTS */
10588 		adp->ad_state &= ~ATTACHED;
10589 		adp->ad_state |= UNDONE;
10590 	}
10591 	/*
10592 	 * The on-disk inode cannot claim to be any larger than the last
10593 	 * fragment that has been written. Otherwise, the on-disk inode
10594 	 * might have fragments that were not the last block in the file
10595 	 * which would corrupt the filesystem.
10596 	 */
10597 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10598 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10599 		if (adp->ad_offset >= UFS_NDADDR)
10600 			break;
10601 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10602 		/* keep going until hitting a rollback to a frag */
10603 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10604 			continue;
10605 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10606 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10607 #ifdef INVARIANTS
10608 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10609 				panic("initiate_write_inodeblock_ufs2: "
10610 				    "lost dep2");
10611 #endif /* INVARIANTS */
10612 			dp->di_db[i] = 0;
10613 		}
10614 		for (i = 0; i < UFS_NIADDR; i++) {
10615 #ifdef INVARIANTS
10616 			if (dp->di_ib[i] != 0 &&
10617 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10618 				panic("initiate_write_inodeblock_ufs2: "
10619 				    "lost dep3");
10620 #endif /* INVARIANTS */
10621 			dp->di_ib[i] = 0;
10622 		}
10623 		ffs_update_dinode_ckhash(fs, dp);
10624 		return;
10625 	}
10626 	/*
10627 	 * If we have zero'ed out the last allocated block of the file,
10628 	 * roll back the size to the last currently allocated block.
10629 	 * We know that this last allocated block is a full-sized as
10630 	 * we already checked for fragments in the loop above.
10631 	 */
10632 	if (lastadp != NULL &&
10633 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10634 		for (i = lastadp->ad_offset; i >= 0; i--)
10635 			if (dp->di_db[i] != 0)
10636 				break;
10637 		dp->di_size = (i + 1) * fs->fs_bsize;
10638 	}
10639 	/*
10640 	 * The only dependencies are for indirect blocks.
10641 	 *
10642 	 * The file size for indirect block additions is not guaranteed.
10643 	 * Such a guarantee would be non-trivial to achieve. The conventional
10644 	 * synchronous write implementation also does not make this guarantee.
10645 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10646 	 * can be over-estimated without destroying integrity when the file
10647 	 * moves into the indirect blocks (i.e., is large). If we want to
10648 	 * postpone fsck, we are stuck with this argument.
10649 	 */
10650 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10651 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10652 	ffs_update_dinode_ckhash(fs, dp);
10653 }
10654 
10655 /*
10656  * Cancel an indirdep as a result of truncation.  Release all of the
10657  * children allocindirs and place their journal work on the appropriate
10658  * list.
10659  */
10660 static void
10661 cancel_indirdep(indirdep, bp, freeblks)
10662 	struct indirdep *indirdep;
10663 	struct buf *bp;
10664 	struct freeblks *freeblks;
10665 {
10666 	struct allocindir *aip;
10667 
10668 	/*
10669 	 * None of the indirect pointers will ever be visible,
10670 	 * so they can simply be tossed. GOINGAWAY ensures
10671 	 * that allocated pointers will be saved in the buffer
10672 	 * cache until they are freed. Note that they will
10673 	 * only be able to be found by their physical address
10674 	 * since the inode mapping the logical address will
10675 	 * be gone. The save buffer used for the safe copy
10676 	 * was allocated in setup_allocindir_phase2 using
10677 	 * the physical address so it could be used for this
10678 	 * purpose. Hence we swap the safe copy with the real
10679 	 * copy, allowing the safe copy to be freed and holding
10680 	 * on to the real copy for later use in indir_trunc.
10681 	 */
10682 	if (indirdep->ir_state & GOINGAWAY)
10683 		panic("cancel_indirdep: already gone");
10684 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10685 		indirdep->ir_state |= DEPCOMPLETE;
10686 		LIST_REMOVE(indirdep, ir_next);
10687 	}
10688 	indirdep->ir_state |= GOINGAWAY;
10689 	/*
10690 	 * Pass in bp for blocks still have journal writes
10691 	 * pending so we can cancel them on their own.
10692 	 */
10693 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10694 		cancel_allocindir(aip, bp, freeblks, 0);
10695 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10696 		cancel_allocindir(aip, NULL, freeblks, 0);
10697 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10698 		cancel_allocindir(aip, NULL, freeblks, 0);
10699 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10700 		cancel_allocindir(aip, NULL, freeblks, 0);
10701 	/*
10702 	 * If there are pending partial truncations we need to keep the
10703 	 * old block copy around until they complete.  This is because
10704 	 * the current b_data is not a perfect superset of the available
10705 	 * blocks.
10706 	 */
10707 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10708 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10709 	else
10710 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10711 	WORKLIST_REMOVE(&indirdep->ir_list);
10712 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10713 	indirdep->ir_bp = NULL;
10714 	indirdep->ir_freeblks = freeblks;
10715 }
10716 
10717 /*
10718  * Free an indirdep once it no longer has new pointers to track.
10719  */
10720 static void
10721 free_indirdep(indirdep)
10722 	struct indirdep *indirdep;
10723 {
10724 
10725 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10726 	    ("free_indirdep: Indir trunc list not empty."));
10727 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10728 	    ("free_indirdep: Complete head not empty."));
10729 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10730 	    ("free_indirdep: write head not empty."));
10731 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10732 	    ("free_indirdep: done head not empty."));
10733 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10734 	    ("free_indirdep: deplist head not empty."));
10735 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10736 	    ("free_indirdep: %p still on newblk list.", indirdep));
10737 	KASSERT(indirdep->ir_saveddata == NULL,
10738 	    ("free_indirdep: %p still has saved data.", indirdep));
10739 	if (indirdep->ir_state & ONWORKLIST)
10740 		WORKLIST_REMOVE(&indirdep->ir_list);
10741 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10742 }
10743 
10744 /*
10745  * Called before a write to an indirdep.  This routine is responsible for
10746  * rolling back pointers to a safe state which includes only those
10747  * allocindirs which have been completed.
10748  */
10749 static void
10750 initiate_write_indirdep(indirdep, bp)
10751 	struct indirdep *indirdep;
10752 	struct buf *bp;
10753 {
10754 	struct ufsmount *ump;
10755 
10756 	indirdep->ir_state |= IOSTARTED;
10757 	if (indirdep->ir_state & GOINGAWAY)
10758 		panic("disk_io_initiation: indirdep gone");
10759 	/*
10760 	 * If there are no remaining dependencies, this will be writing
10761 	 * the real pointers.
10762 	 */
10763 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10764 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10765 		return;
10766 	/*
10767 	 * Replace up-to-date version with safe version.
10768 	 */
10769 	if (indirdep->ir_saveddata == NULL) {
10770 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10771 		LOCK_OWNED(ump);
10772 		FREE_LOCK(ump);
10773 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10774 		    M_SOFTDEP_FLAGS);
10775 		ACQUIRE_LOCK(ump);
10776 	}
10777 	indirdep->ir_state &= ~ATTACHED;
10778 	indirdep->ir_state |= UNDONE;
10779 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10780 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10781 	    bp->b_bcount);
10782 }
10783 
10784 /*
10785  * Called when an inode has been cleared in a cg bitmap.  This finally
10786  * eliminates any canceled jaddrefs
10787  */
10788 void
10789 softdep_setup_inofree(mp, bp, ino, wkhd)
10790 	struct mount *mp;
10791 	struct buf *bp;
10792 	ino_t ino;
10793 	struct workhead *wkhd;
10794 {
10795 	struct worklist *wk, *wkn;
10796 	struct inodedep *inodedep;
10797 	struct ufsmount *ump;
10798 	uint8_t *inosused;
10799 	struct cg *cgp;
10800 	struct fs *fs;
10801 
10802 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10803 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10804 	ump = VFSTOUFS(mp);
10805 	ACQUIRE_LOCK(ump);
10806 	fs = ump->um_fs;
10807 	cgp = (struct cg *)bp->b_data;
10808 	inosused = cg_inosused(cgp);
10809 	if (isset(inosused, ino % fs->fs_ipg))
10810 		panic("softdep_setup_inofree: inode %ju not freed.",
10811 		    (uintmax_t)ino);
10812 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10813 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10814 		    (uintmax_t)ino, inodedep);
10815 	if (wkhd) {
10816 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10817 			if (wk->wk_type != D_JADDREF)
10818 				continue;
10819 			WORKLIST_REMOVE(wk);
10820 			/*
10821 			 * We can free immediately even if the jaddref
10822 			 * isn't attached in a background write as now
10823 			 * the bitmaps are reconciled.
10824 			 */
10825 			wk->wk_state |= COMPLETE | ATTACHED;
10826 			free_jaddref(WK_JADDREF(wk));
10827 		}
10828 		jwork_move(&bp->b_dep, wkhd);
10829 	}
10830 	FREE_LOCK(ump);
10831 }
10832 
10833 /*
10834  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10835  * map.  Any dependencies waiting for the write to clear are added to the
10836  * buf's list and any jnewblks that are being canceled are discarded
10837  * immediately.
10838  */
10839 void
10840 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10841 	struct mount *mp;
10842 	struct buf *bp;
10843 	ufs2_daddr_t blkno;
10844 	int frags;
10845 	struct workhead *wkhd;
10846 {
10847 	struct bmsafemap *bmsafemap;
10848 	struct jnewblk *jnewblk;
10849 	struct ufsmount *ump;
10850 	struct worklist *wk;
10851 	struct fs *fs;
10852 #ifdef INVARIANTS
10853 	uint8_t *blksfree;
10854 	struct cg *cgp;
10855 	ufs2_daddr_t jstart;
10856 	ufs2_daddr_t jend;
10857 	ufs2_daddr_t end;
10858 	long bno;
10859 	int i;
10860 #endif
10861 
10862 	CTR3(KTR_SUJ,
10863 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10864 	    blkno, frags, wkhd);
10865 
10866 	ump = VFSTOUFS(mp);
10867 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10868 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10869 	ACQUIRE_LOCK(ump);
10870 	/* Lookup the bmsafemap so we track when it is dirty. */
10871 	fs = ump->um_fs;
10872 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10873 	/*
10874 	 * Detach any jnewblks which have been canceled.  They must linger
10875 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10876 	 * an unjournaled allocation from hitting the disk.
10877 	 */
10878 	if (wkhd) {
10879 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10880 			CTR2(KTR_SUJ,
10881 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10882 			    blkno, wk->wk_type);
10883 			WORKLIST_REMOVE(wk);
10884 			if (wk->wk_type != D_JNEWBLK) {
10885 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10886 				continue;
10887 			}
10888 			jnewblk = WK_JNEWBLK(wk);
10889 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10890 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10891 #ifdef INVARIANTS
10892 			/*
10893 			 * Assert that this block is free in the bitmap
10894 			 * before we discard the jnewblk.
10895 			 */
10896 			cgp = (struct cg *)bp->b_data;
10897 			blksfree = cg_blksfree(cgp);
10898 			bno = dtogd(fs, jnewblk->jn_blkno);
10899 			for (i = jnewblk->jn_oldfrags;
10900 			    i < jnewblk->jn_frags; i++) {
10901 				if (isset(blksfree, bno + i))
10902 					continue;
10903 				panic("softdep_setup_blkfree: not free");
10904 			}
10905 #endif
10906 			/*
10907 			 * Even if it's not attached we can free immediately
10908 			 * as the new bitmap is correct.
10909 			 */
10910 			wk->wk_state |= COMPLETE | ATTACHED;
10911 			free_jnewblk(jnewblk);
10912 		}
10913 	}
10914 
10915 #ifdef INVARIANTS
10916 	/*
10917 	 * Assert that we are not freeing a block which has an outstanding
10918 	 * allocation dependency.
10919 	 */
10920 	fs = VFSTOUFS(mp)->um_fs;
10921 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10922 	end = blkno + frags;
10923 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10924 		/*
10925 		 * Don't match against blocks that will be freed when the
10926 		 * background write is done.
10927 		 */
10928 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10929 		    (COMPLETE | DEPCOMPLETE))
10930 			continue;
10931 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10932 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10933 		if ((blkno >= jstart && blkno < jend) ||
10934 		    (end > jstart && end <= jend)) {
10935 			printf("state 0x%X %jd - %d %d dep %p\n",
10936 			    jnewblk->jn_state, jnewblk->jn_blkno,
10937 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10938 			    jnewblk->jn_dep);
10939 			panic("softdep_setup_blkfree: "
10940 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10941 			    blkno, end, frags, jstart, jend);
10942 		}
10943 	}
10944 #endif
10945 	FREE_LOCK(ump);
10946 }
10947 
10948 /*
10949  * Revert a block allocation when the journal record that describes it
10950  * is not yet written.
10951  */
10952 static int
10953 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10954 	struct jnewblk *jnewblk;
10955 	struct fs *fs;
10956 	struct cg *cgp;
10957 	uint8_t *blksfree;
10958 {
10959 	ufs1_daddr_t fragno;
10960 	long cgbno, bbase;
10961 	int frags, blk;
10962 	int i;
10963 
10964 	frags = 0;
10965 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10966 	/*
10967 	 * We have to test which frags need to be rolled back.  We may
10968 	 * be operating on a stale copy when doing background writes.
10969 	 */
10970 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10971 		if (isclr(blksfree, cgbno + i))
10972 			frags++;
10973 	if (frags == 0)
10974 		return (0);
10975 	/*
10976 	 * This is mostly ffs_blkfree() sans some validation and
10977 	 * superblock updates.
10978 	 */
10979 	if (frags == fs->fs_frag) {
10980 		fragno = fragstoblks(fs, cgbno);
10981 		ffs_setblock(fs, blksfree, fragno);
10982 		ffs_clusteracct(fs, cgp, fragno, 1);
10983 		cgp->cg_cs.cs_nbfree++;
10984 	} else {
10985 		cgbno += jnewblk->jn_oldfrags;
10986 		bbase = cgbno - fragnum(fs, cgbno);
10987 		/* Decrement the old frags.  */
10988 		blk = blkmap(fs, blksfree, bbase);
10989 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10990 		/* Deallocate the fragment */
10991 		for (i = 0; i < frags; i++)
10992 			setbit(blksfree, cgbno + i);
10993 		cgp->cg_cs.cs_nffree += frags;
10994 		/* Add back in counts associated with the new frags */
10995 		blk = blkmap(fs, blksfree, bbase);
10996 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10997 		/* If a complete block has been reassembled, account for it. */
10998 		fragno = fragstoblks(fs, bbase);
10999 		if (ffs_isblock(fs, blksfree, fragno)) {
11000 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
11001 			ffs_clusteracct(fs, cgp, fragno, 1);
11002 			cgp->cg_cs.cs_nbfree++;
11003 		}
11004 	}
11005 	stat_jnewblk++;
11006 	jnewblk->jn_state &= ~ATTACHED;
11007 	jnewblk->jn_state |= UNDONE;
11008 
11009 	return (frags);
11010 }
11011 
11012 static void
11013 initiate_write_bmsafemap(bmsafemap, bp)
11014 	struct bmsafemap *bmsafemap;
11015 	struct buf *bp;			/* The cg block. */
11016 {
11017 	struct jaddref *jaddref;
11018 	struct jnewblk *jnewblk;
11019 	uint8_t *inosused;
11020 	uint8_t *blksfree;
11021 	struct cg *cgp;
11022 	struct fs *fs;
11023 	ino_t ino;
11024 
11025 	/*
11026 	 * If this is a background write, we did this at the time that
11027 	 * the copy was made, so do not need to do it again.
11028 	 */
11029 	if (bmsafemap->sm_state & IOSTARTED)
11030 		return;
11031 	bmsafemap->sm_state |= IOSTARTED;
11032 	/*
11033 	 * Clear any inode allocations which are pending journal writes.
11034 	 */
11035 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11036 		cgp = (struct cg *)bp->b_data;
11037 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11038 		inosused = cg_inosused(cgp);
11039 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11040 			ino = jaddref->ja_ino % fs->fs_ipg;
11041 			if (isset(inosused, ino)) {
11042 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11043 					cgp->cg_cs.cs_ndir--;
11044 				cgp->cg_cs.cs_nifree++;
11045 				clrbit(inosused, ino);
11046 				jaddref->ja_state &= ~ATTACHED;
11047 				jaddref->ja_state |= UNDONE;
11048 				stat_jaddref++;
11049 			} else
11050 				panic("initiate_write_bmsafemap: inode %ju "
11051 				    "marked free", (uintmax_t)jaddref->ja_ino);
11052 		}
11053 	}
11054 	/*
11055 	 * Clear any block allocations which are pending journal writes.
11056 	 */
11057 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11058 		cgp = (struct cg *)bp->b_data;
11059 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11060 		blksfree = cg_blksfree(cgp);
11061 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11062 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11063 				continue;
11064 			panic("initiate_write_bmsafemap: block %jd "
11065 			    "marked free", jnewblk->jn_blkno);
11066 		}
11067 	}
11068 	/*
11069 	 * Move allocation lists to the written lists so they can be
11070 	 * cleared once the block write is complete.
11071 	 */
11072 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11073 	    inodedep, id_deps);
11074 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11075 	    newblk, nb_deps);
11076 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11077 	    wk_list);
11078 }
11079 
11080 /*
11081  * This routine is called during the completion interrupt
11082  * service routine for a disk write (from the procedure called
11083  * by the device driver to inform the filesystem caches of
11084  * a request completion).  It should be called early in this
11085  * procedure, before the block is made available to other
11086  * processes or other routines are called.
11087  *
11088  */
11089 static void
11090 softdep_disk_write_complete(bp)
11091 	struct buf *bp;		/* describes the completed disk write */
11092 {
11093 	struct worklist *wk;
11094 	struct worklist *owk;
11095 	struct ufsmount *ump;
11096 	struct workhead reattach;
11097 	struct freeblks *freeblks;
11098 	struct buf *sbp;
11099 
11100 	ump = softdep_bp_to_mp(bp);
11101 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11102 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11103 	     "with outstanding dependencies for buffer %p", bp));
11104 	if (ump == NULL)
11105 		return;
11106 	/*
11107 	 * If an error occurred while doing the write, then the data
11108 	 * has not hit the disk and the dependencies cannot be processed.
11109 	 * But we do have to go through and roll forward any dependencies
11110 	 * that were rolled back before the disk write.
11111 	 */
11112 	sbp = NULL;
11113 	ACQUIRE_LOCK(ump);
11114 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11115 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11116 			switch (wk->wk_type) {
11117 
11118 			case D_PAGEDEP:
11119 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11120 				continue;
11121 
11122 			case D_INODEDEP:
11123 				handle_written_inodeblock(WK_INODEDEP(wk),
11124 				    bp, 0);
11125 				continue;
11126 
11127 			case D_BMSAFEMAP:
11128 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11129 				    bp, 0);
11130 				continue;
11131 
11132 			case D_INDIRDEP:
11133 				handle_written_indirdep(WK_INDIRDEP(wk),
11134 				    bp, &sbp, 0);
11135 				continue;
11136 			default:
11137 				/* nothing to roll forward */
11138 				continue;
11139 			}
11140 		}
11141 		FREE_LOCK(ump);
11142 		if (sbp)
11143 			brelse(sbp);
11144 		return;
11145 	}
11146 	LIST_INIT(&reattach);
11147 
11148 	/*
11149 	 * Ump SU lock must not be released anywhere in this code segment.
11150 	 */
11151 	owk = NULL;
11152 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11153 		WORKLIST_REMOVE(wk);
11154 		atomic_add_long(&dep_write[wk->wk_type], 1);
11155 		if (wk == owk)
11156 			panic("duplicate worklist: %p\n", wk);
11157 		owk = wk;
11158 		switch (wk->wk_type) {
11159 
11160 		case D_PAGEDEP:
11161 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11162 			    WRITESUCCEEDED))
11163 				WORKLIST_INSERT(&reattach, wk);
11164 			continue;
11165 
11166 		case D_INODEDEP:
11167 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11168 			    WRITESUCCEEDED))
11169 				WORKLIST_INSERT(&reattach, wk);
11170 			continue;
11171 
11172 		case D_BMSAFEMAP:
11173 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11174 			    WRITESUCCEEDED))
11175 				WORKLIST_INSERT(&reattach, wk);
11176 			continue;
11177 
11178 		case D_MKDIR:
11179 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11180 			continue;
11181 
11182 		case D_ALLOCDIRECT:
11183 			wk->wk_state |= COMPLETE;
11184 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11185 			continue;
11186 
11187 		case D_ALLOCINDIR:
11188 			wk->wk_state |= COMPLETE;
11189 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11190 			continue;
11191 
11192 		case D_INDIRDEP:
11193 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11194 			    WRITESUCCEEDED))
11195 				WORKLIST_INSERT(&reattach, wk);
11196 			continue;
11197 
11198 		case D_FREEBLKS:
11199 			wk->wk_state |= COMPLETE;
11200 			freeblks = WK_FREEBLKS(wk);
11201 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11202 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11203 				add_to_worklist(wk, WK_NODELAY);
11204 			continue;
11205 
11206 		case D_FREEWORK:
11207 			handle_written_freework(WK_FREEWORK(wk));
11208 			break;
11209 
11210 		case D_JSEGDEP:
11211 			free_jsegdep(WK_JSEGDEP(wk));
11212 			continue;
11213 
11214 		case D_JSEG:
11215 			handle_written_jseg(WK_JSEG(wk), bp);
11216 			continue;
11217 
11218 		case D_SBDEP:
11219 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11220 				WORKLIST_INSERT(&reattach, wk);
11221 			continue;
11222 
11223 		case D_FREEDEP:
11224 			free_freedep(WK_FREEDEP(wk));
11225 			continue;
11226 
11227 		default:
11228 			panic("handle_disk_write_complete: Unknown type %s",
11229 			    TYPENAME(wk->wk_type));
11230 			/* NOTREACHED */
11231 		}
11232 	}
11233 	/*
11234 	 * Reattach any requests that must be redone.
11235 	 */
11236 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11237 		WORKLIST_REMOVE(wk);
11238 		WORKLIST_INSERT(&bp->b_dep, wk);
11239 	}
11240 	FREE_LOCK(ump);
11241 	if (sbp)
11242 		brelse(sbp);
11243 }
11244 
11245 /*
11246  * Called from within softdep_disk_write_complete above.
11247  */
11248 static void
11249 handle_allocdirect_partdone(adp, wkhd)
11250 	struct allocdirect *adp;	/* the completed allocdirect */
11251 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11252 {
11253 	struct allocdirectlst *listhead;
11254 	struct allocdirect *listadp;
11255 	struct inodedep *inodedep;
11256 	long bsize;
11257 
11258 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11259 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11260 		return;
11261 	/*
11262 	 * The on-disk inode cannot claim to be any larger than the last
11263 	 * fragment that has been written. Otherwise, the on-disk inode
11264 	 * might have fragments that were not the last block in the file
11265 	 * which would corrupt the filesystem. Thus, we cannot free any
11266 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11267 	 * these blocks must be rolled back to zero before writing the inode.
11268 	 * We check the currently active set of allocdirects in id_inoupdt
11269 	 * or id_extupdt as appropriate.
11270 	 */
11271 	inodedep = adp->ad_inodedep;
11272 	bsize = inodedep->id_fs->fs_bsize;
11273 	if (adp->ad_state & EXTDATA)
11274 		listhead = &inodedep->id_extupdt;
11275 	else
11276 		listhead = &inodedep->id_inoupdt;
11277 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11278 		/* found our block */
11279 		if (listadp == adp)
11280 			break;
11281 		/* continue if ad_oldlbn is not a fragment */
11282 		if (listadp->ad_oldsize == 0 ||
11283 		    listadp->ad_oldsize == bsize)
11284 			continue;
11285 		/* hit a fragment */
11286 		return;
11287 	}
11288 	/*
11289 	 * If we have reached the end of the current list without
11290 	 * finding the just finished dependency, then it must be
11291 	 * on the future dependency list. Future dependencies cannot
11292 	 * be freed until they are moved to the current list.
11293 	 */
11294 	if (listadp == NULL) {
11295 #ifdef INVARIANTS
11296 		if (adp->ad_state & EXTDATA)
11297 			listhead = &inodedep->id_newextupdt;
11298 		else
11299 			listhead = &inodedep->id_newinoupdt;
11300 		TAILQ_FOREACH(listadp, listhead, ad_next)
11301 			/* found our block */
11302 			if (listadp == adp)
11303 				break;
11304 		if (listadp == NULL)
11305 			panic("handle_allocdirect_partdone: lost dep");
11306 #endif /* INVARIANTS */
11307 		return;
11308 	}
11309 	/*
11310 	 * If we have found the just finished dependency, then queue
11311 	 * it along with anything that follows it that is complete.
11312 	 * Since the pointer has not yet been written in the inode
11313 	 * as the dependency prevents it, place the allocdirect on the
11314 	 * bufwait list where it will be freed once the pointer is
11315 	 * valid.
11316 	 */
11317 	if (wkhd == NULL)
11318 		wkhd = &inodedep->id_bufwait;
11319 	for (; adp; adp = listadp) {
11320 		listadp = TAILQ_NEXT(adp, ad_next);
11321 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11322 			return;
11323 		TAILQ_REMOVE(listhead, adp, ad_next);
11324 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11325 	}
11326 }
11327 
11328 /*
11329  * Called from within softdep_disk_write_complete above.  This routine
11330  * completes successfully written allocindirs.
11331  */
11332 static void
11333 handle_allocindir_partdone(aip)
11334 	struct allocindir *aip;		/* the completed allocindir */
11335 {
11336 	struct indirdep *indirdep;
11337 
11338 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11339 		return;
11340 	indirdep = aip->ai_indirdep;
11341 	LIST_REMOVE(aip, ai_next);
11342 	/*
11343 	 * Don't set a pointer while the buffer is undergoing IO or while
11344 	 * we have active truncations.
11345 	 */
11346 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11347 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11348 		return;
11349 	}
11350 	if (indirdep->ir_state & UFS1FMT)
11351 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11352 		    aip->ai_newblkno;
11353 	else
11354 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11355 		    aip->ai_newblkno;
11356 	/*
11357 	 * Await the pointer write before freeing the allocindir.
11358 	 */
11359 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11360 }
11361 
11362 /*
11363  * Release segments held on a jwork list.
11364  */
11365 static void
11366 handle_jwork(wkhd)
11367 	struct workhead *wkhd;
11368 {
11369 	struct worklist *wk;
11370 
11371 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11372 		WORKLIST_REMOVE(wk);
11373 		switch (wk->wk_type) {
11374 		case D_JSEGDEP:
11375 			free_jsegdep(WK_JSEGDEP(wk));
11376 			continue;
11377 		case D_FREEDEP:
11378 			free_freedep(WK_FREEDEP(wk));
11379 			continue;
11380 		case D_FREEFRAG:
11381 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11382 			WORKITEM_FREE(wk, D_FREEFRAG);
11383 			continue;
11384 		case D_FREEWORK:
11385 			handle_written_freework(WK_FREEWORK(wk));
11386 			continue;
11387 		default:
11388 			panic("handle_jwork: Unknown type %s\n",
11389 			    TYPENAME(wk->wk_type));
11390 		}
11391 	}
11392 }
11393 
11394 /*
11395  * Handle the bufwait list on an inode when it is safe to release items
11396  * held there.  This normally happens after an inode block is written but
11397  * may be delayed and handled later if there are pending journal items that
11398  * are not yet safe to be released.
11399  */
11400 static struct freefile *
11401 handle_bufwait(inodedep, refhd)
11402 	struct inodedep *inodedep;
11403 	struct workhead *refhd;
11404 {
11405 	struct jaddref *jaddref;
11406 	struct freefile *freefile;
11407 	struct worklist *wk;
11408 
11409 	freefile = NULL;
11410 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11411 		WORKLIST_REMOVE(wk);
11412 		switch (wk->wk_type) {
11413 		case D_FREEFILE:
11414 			/*
11415 			 * We defer adding freefile to the worklist
11416 			 * until all other additions have been made to
11417 			 * ensure that it will be done after all the
11418 			 * old blocks have been freed.
11419 			 */
11420 			if (freefile != NULL)
11421 				panic("handle_bufwait: freefile");
11422 			freefile = WK_FREEFILE(wk);
11423 			continue;
11424 
11425 		case D_MKDIR:
11426 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11427 			continue;
11428 
11429 		case D_DIRADD:
11430 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11431 			continue;
11432 
11433 		case D_FREEFRAG:
11434 			wk->wk_state |= COMPLETE;
11435 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11436 				add_to_worklist(wk, 0);
11437 			continue;
11438 
11439 		case D_DIRREM:
11440 			wk->wk_state |= COMPLETE;
11441 			add_to_worklist(wk, 0);
11442 			continue;
11443 
11444 		case D_ALLOCDIRECT:
11445 		case D_ALLOCINDIR:
11446 			free_newblk(WK_NEWBLK(wk));
11447 			continue;
11448 
11449 		case D_JNEWBLK:
11450 			wk->wk_state |= COMPLETE;
11451 			free_jnewblk(WK_JNEWBLK(wk));
11452 			continue;
11453 
11454 		/*
11455 		 * Save freed journal segments and add references on
11456 		 * the supplied list which will delay their release
11457 		 * until the cg bitmap is cleared on disk.
11458 		 */
11459 		case D_JSEGDEP:
11460 			if (refhd == NULL)
11461 				free_jsegdep(WK_JSEGDEP(wk));
11462 			else
11463 				WORKLIST_INSERT(refhd, wk);
11464 			continue;
11465 
11466 		case D_JADDREF:
11467 			jaddref = WK_JADDREF(wk);
11468 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11469 			    if_deps);
11470 			/*
11471 			 * Transfer any jaddrefs to the list to be freed with
11472 			 * the bitmap if we're handling a removed file.
11473 			 */
11474 			if (refhd == NULL) {
11475 				wk->wk_state |= COMPLETE;
11476 				free_jaddref(jaddref);
11477 			} else
11478 				WORKLIST_INSERT(refhd, wk);
11479 			continue;
11480 
11481 		default:
11482 			panic("handle_bufwait: Unknown type %p(%s)",
11483 			    wk, TYPENAME(wk->wk_type));
11484 			/* NOTREACHED */
11485 		}
11486 	}
11487 	return (freefile);
11488 }
11489 /*
11490  * Called from within softdep_disk_write_complete above to restore
11491  * in-memory inode block contents to their most up-to-date state. Note
11492  * that this routine is always called from interrupt level with further
11493  * interrupts from this device blocked.
11494  *
11495  * If the write did not succeed, we will do all the roll-forward
11496  * operations, but we will not take the actions that will allow its
11497  * dependencies to be processed.
11498  */
11499 static int
11500 handle_written_inodeblock(inodedep, bp, flags)
11501 	struct inodedep *inodedep;
11502 	struct buf *bp;		/* buffer containing the inode block */
11503 	int flags;
11504 {
11505 	struct freefile *freefile;
11506 	struct allocdirect *adp, *nextadp;
11507 	struct ufs1_dinode *dp1 = NULL;
11508 	struct ufs2_dinode *dp2 = NULL;
11509 	struct workhead wkhd;
11510 	int hadchanges, fstype;
11511 	ino_t freelink;
11512 
11513 	LIST_INIT(&wkhd);
11514 	hadchanges = 0;
11515 	freefile = NULL;
11516 	if ((inodedep->id_state & IOSTARTED) == 0)
11517 		panic("handle_written_inodeblock: not started");
11518 	inodedep->id_state &= ~IOSTARTED;
11519 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11520 		fstype = UFS1;
11521 		dp1 = (struct ufs1_dinode *)bp->b_data +
11522 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11523 		freelink = dp1->di_freelink;
11524 	} else {
11525 		fstype = UFS2;
11526 		dp2 = (struct ufs2_dinode *)bp->b_data +
11527 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11528 		freelink = dp2->di_freelink;
11529 	}
11530 	/*
11531 	 * Leave this inodeblock dirty until it's in the list.
11532 	 */
11533 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11534 	    (flags & WRITESUCCEEDED)) {
11535 		struct inodedep *inon;
11536 
11537 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11538 		if ((inon == NULL && freelink == 0) ||
11539 		    (inon && inon->id_ino == freelink)) {
11540 			if (inon)
11541 				inon->id_state |= UNLINKPREV;
11542 			inodedep->id_state |= UNLINKNEXT;
11543 		}
11544 		hadchanges = 1;
11545 	}
11546 	/*
11547 	 * If we had to rollback the inode allocation because of
11548 	 * bitmaps being incomplete, then simply restore it.
11549 	 * Keep the block dirty so that it will not be reclaimed until
11550 	 * all associated dependencies have been cleared and the
11551 	 * corresponding updates written to disk.
11552 	 */
11553 	if (inodedep->id_savedino1 != NULL) {
11554 		hadchanges = 1;
11555 		if (fstype == UFS1)
11556 			*dp1 = *inodedep->id_savedino1;
11557 		else
11558 			*dp2 = *inodedep->id_savedino2;
11559 		free(inodedep->id_savedino1, M_SAVEDINO);
11560 		inodedep->id_savedino1 = NULL;
11561 		if ((bp->b_flags & B_DELWRI) == 0)
11562 			stat_inode_bitmap++;
11563 		bdirty(bp);
11564 		/*
11565 		 * If the inode is clear here and GOINGAWAY it will never
11566 		 * be written.  Process the bufwait and clear any pending
11567 		 * work which may include the freefile.
11568 		 */
11569 		if (inodedep->id_state & GOINGAWAY)
11570 			goto bufwait;
11571 		return (1);
11572 	}
11573 	if (flags & WRITESUCCEEDED)
11574 		inodedep->id_state |= COMPLETE;
11575 	/*
11576 	 * Roll forward anything that had to be rolled back before
11577 	 * the inode could be updated.
11578 	 */
11579 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11580 		nextadp = TAILQ_NEXT(adp, ad_next);
11581 		if (adp->ad_state & ATTACHED)
11582 			panic("handle_written_inodeblock: new entry");
11583 		if (fstype == UFS1) {
11584 			if (adp->ad_offset < UFS_NDADDR) {
11585 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11586 					panic("%s %s #%jd mismatch %d != %jd",
11587 					    "handle_written_inodeblock:",
11588 					    "direct pointer",
11589 					    (intmax_t)adp->ad_offset,
11590 					    dp1->di_db[adp->ad_offset],
11591 					    (intmax_t)adp->ad_oldblkno);
11592 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11593 			} else {
11594 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11595 				    0)
11596 					panic("%s: %s #%jd allocated as %d",
11597 					    "handle_written_inodeblock",
11598 					    "indirect pointer",
11599 					    (intmax_t)adp->ad_offset -
11600 					    UFS_NDADDR,
11601 					    dp1->di_ib[adp->ad_offset -
11602 					    UFS_NDADDR]);
11603 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11604 				    adp->ad_newblkno;
11605 			}
11606 		} else {
11607 			if (adp->ad_offset < UFS_NDADDR) {
11608 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11609 					panic("%s: %s #%jd %s %jd != %jd",
11610 					    "handle_written_inodeblock",
11611 					    "direct pointer",
11612 					    (intmax_t)adp->ad_offset, "mismatch",
11613 					    (intmax_t)dp2->di_db[adp->ad_offset],
11614 					    (intmax_t)adp->ad_oldblkno);
11615 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11616 			} else {
11617 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11618 				    0)
11619 					panic("%s: %s #%jd allocated as %jd",
11620 					    "handle_written_inodeblock",
11621 					    "indirect pointer",
11622 					    (intmax_t)adp->ad_offset -
11623 					    UFS_NDADDR,
11624 					    (intmax_t)
11625 					    dp2->di_ib[adp->ad_offset -
11626 					    UFS_NDADDR]);
11627 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11628 				    adp->ad_newblkno;
11629 			}
11630 		}
11631 		adp->ad_state &= ~UNDONE;
11632 		adp->ad_state |= ATTACHED;
11633 		hadchanges = 1;
11634 	}
11635 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11636 		nextadp = TAILQ_NEXT(adp, ad_next);
11637 		if (adp->ad_state & ATTACHED)
11638 			panic("handle_written_inodeblock: new entry");
11639 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11640 			panic("%s: direct pointers #%jd %s %jd != %jd",
11641 			    "handle_written_inodeblock",
11642 			    (intmax_t)adp->ad_offset, "mismatch",
11643 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11644 			    (intmax_t)adp->ad_oldblkno);
11645 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11646 		adp->ad_state &= ~UNDONE;
11647 		adp->ad_state |= ATTACHED;
11648 		hadchanges = 1;
11649 	}
11650 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11651 		stat_direct_blk_ptrs++;
11652 	/*
11653 	 * Reset the file size to its most up-to-date value.
11654 	 */
11655 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11656 		panic("handle_written_inodeblock: bad size");
11657 	if (inodedep->id_savednlink > UFS_LINK_MAX)
11658 		panic("handle_written_inodeblock: Invalid link count "
11659 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11660 		    inodedep);
11661 	if (fstype == UFS1) {
11662 		if (dp1->di_nlink != inodedep->id_savednlink) {
11663 			dp1->di_nlink = inodedep->id_savednlink;
11664 			hadchanges = 1;
11665 		}
11666 		if (dp1->di_size != inodedep->id_savedsize) {
11667 			dp1->di_size = inodedep->id_savedsize;
11668 			hadchanges = 1;
11669 		}
11670 	} else {
11671 		if (dp2->di_nlink != inodedep->id_savednlink) {
11672 			dp2->di_nlink = inodedep->id_savednlink;
11673 			hadchanges = 1;
11674 		}
11675 		if (dp2->di_size != inodedep->id_savedsize) {
11676 			dp2->di_size = inodedep->id_savedsize;
11677 			hadchanges = 1;
11678 		}
11679 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11680 			dp2->di_extsize = inodedep->id_savedextsize;
11681 			hadchanges = 1;
11682 		}
11683 	}
11684 	inodedep->id_savedsize = -1;
11685 	inodedep->id_savedextsize = -1;
11686 	inodedep->id_savednlink = -1;
11687 	/*
11688 	 * If there were any rollbacks in the inode block, then it must be
11689 	 * marked dirty so that its will eventually get written back in
11690 	 * its correct form.
11691 	 */
11692 	if (hadchanges) {
11693 		if (fstype == UFS2)
11694 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11695 		bdirty(bp);
11696 	}
11697 bufwait:
11698 	/*
11699 	 * If the write did not succeed, we have done all the roll-forward
11700 	 * operations, but we cannot take the actions that will allow its
11701 	 * dependencies to be processed.
11702 	 */
11703 	if ((flags & WRITESUCCEEDED) == 0)
11704 		return (hadchanges);
11705 	/*
11706 	 * Process any allocdirects that completed during the update.
11707 	 */
11708 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11709 		handle_allocdirect_partdone(adp, &wkhd);
11710 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11711 		handle_allocdirect_partdone(adp, &wkhd);
11712 	/*
11713 	 * Process deallocations that were held pending until the
11714 	 * inode had been written to disk. Freeing of the inode
11715 	 * is delayed until after all blocks have been freed to
11716 	 * avoid creation of new <vfsid, inum, lbn> triples
11717 	 * before the old ones have been deleted.  Completely
11718 	 * unlinked inodes are not processed until the unlinked
11719 	 * inode list is written or the last reference is removed.
11720 	 */
11721 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11722 		freefile = handle_bufwait(inodedep, NULL);
11723 		if (freefile && !LIST_EMPTY(&wkhd)) {
11724 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11725 			freefile = NULL;
11726 		}
11727 	}
11728 	/*
11729 	 * Move rolled forward dependency completions to the bufwait list
11730 	 * now that those that were already written have been processed.
11731 	 */
11732 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11733 		panic("handle_written_inodeblock: bufwait but no changes");
11734 	jwork_move(&inodedep->id_bufwait, &wkhd);
11735 
11736 	if (freefile != NULL) {
11737 		/*
11738 		 * If the inode is goingaway it was never written.  Fake up
11739 		 * the state here so free_inodedep() can succeed.
11740 		 */
11741 		if (inodedep->id_state & GOINGAWAY)
11742 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11743 		if (free_inodedep(inodedep) == 0)
11744 			panic("handle_written_inodeblock: live inodedep %p",
11745 			    inodedep);
11746 		add_to_worklist(&freefile->fx_list, 0);
11747 		return (0);
11748 	}
11749 
11750 	/*
11751 	 * If no outstanding dependencies, free it.
11752 	 */
11753 	if (free_inodedep(inodedep) ||
11754 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11755 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11756 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11757 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11758 		return (0);
11759 	return (hadchanges);
11760 }
11761 
11762 /*
11763  * Perform needed roll-forwards and kick off any dependencies that
11764  * can now be processed.
11765  *
11766  * If the write did not succeed, we will do all the roll-forward
11767  * operations, but we will not take the actions that will allow its
11768  * dependencies to be processed.
11769  */
11770 static int
11771 handle_written_indirdep(indirdep, bp, bpp, flags)
11772 	struct indirdep *indirdep;
11773 	struct buf *bp;
11774 	struct buf **bpp;
11775 	int flags;
11776 {
11777 	struct allocindir *aip;
11778 	struct buf *sbp;
11779 	int chgs;
11780 
11781 	if (indirdep->ir_state & GOINGAWAY)
11782 		panic("handle_written_indirdep: indirdep gone");
11783 	if ((indirdep->ir_state & IOSTARTED) == 0)
11784 		panic("handle_written_indirdep: IO not started");
11785 	chgs = 0;
11786 	/*
11787 	 * If there were rollbacks revert them here.
11788 	 */
11789 	if (indirdep->ir_saveddata) {
11790 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11791 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11792 			free(indirdep->ir_saveddata, M_INDIRDEP);
11793 			indirdep->ir_saveddata = NULL;
11794 		}
11795 		chgs = 1;
11796 	}
11797 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11798 	indirdep->ir_state |= ATTACHED;
11799 	/*
11800 	 * If the write did not succeed, we have done all the roll-forward
11801 	 * operations, but we cannot take the actions that will allow its
11802 	 * dependencies to be processed.
11803 	 */
11804 	if ((flags & WRITESUCCEEDED) == 0) {
11805 		stat_indir_blk_ptrs++;
11806 		bdirty(bp);
11807 		return (1);
11808 	}
11809 	/*
11810 	 * Move allocindirs with written pointers to the completehd if
11811 	 * the indirdep's pointer is not yet written.  Otherwise
11812 	 * free them here.
11813 	 */
11814 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11815 		LIST_REMOVE(aip, ai_next);
11816 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11817 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11818 			    ai_next);
11819 			newblk_freefrag(&aip->ai_block);
11820 			continue;
11821 		}
11822 		free_newblk(&aip->ai_block);
11823 	}
11824 	/*
11825 	 * Move allocindirs that have finished dependency processing from
11826 	 * the done list to the write list after updating the pointers.
11827 	 */
11828 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11829 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11830 			handle_allocindir_partdone(aip);
11831 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11832 				panic("disk_write_complete: not gone");
11833 			chgs = 1;
11834 		}
11835 	}
11836 	/*
11837 	 * Preserve the indirdep if there were any changes or if it is not
11838 	 * yet valid on disk.
11839 	 */
11840 	if (chgs) {
11841 		stat_indir_blk_ptrs++;
11842 		bdirty(bp);
11843 		return (1);
11844 	}
11845 	/*
11846 	 * If there were no changes we can discard the savedbp and detach
11847 	 * ourselves from the buf.  We are only carrying completed pointers
11848 	 * in this case.
11849 	 */
11850 	sbp = indirdep->ir_savebp;
11851 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11852 	indirdep->ir_savebp = NULL;
11853 	indirdep->ir_bp = NULL;
11854 	if (*bpp != NULL)
11855 		panic("handle_written_indirdep: bp already exists.");
11856 	*bpp = sbp;
11857 	/*
11858 	 * The indirdep may not be freed until its parent points at it.
11859 	 */
11860 	if (indirdep->ir_state & DEPCOMPLETE)
11861 		free_indirdep(indirdep);
11862 
11863 	return (0);
11864 }
11865 
11866 /*
11867  * Process a diradd entry after its dependent inode has been written.
11868  */
11869 static void
11870 diradd_inode_written(dap, inodedep)
11871 	struct diradd *dap;
11872 	struct inodedep *inodedep;
11873 {
11874 
11875 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
11876 	dap->da_state |= COMPLETE;
11877 	complete_diradd(dap);
11878 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11879 }
11880 
11881 /*
11882  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11883  * be called with the per-filesystem lock and the buf lock on the cg held.
11884  */
11885 static int
11886 bmsafemap_backgroundwrite(bmsafemap, bp)
11887 	struct bmsafemap *bmsafemap;
11888 	struct buf *bp;
11889 {
11890 	int dirty;
11891 
11892 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11893 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11894 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11895 	/*
11896 	 * If we're initiating a background write we need to process the
11897 	 * rollbacks as they exist now, not as they exist when IO starts.
11898 	 * No other consumers will look at the contents of the shadowed
11899 	 * buf so this is safe to do here.
11900 	 */
11901 	if (bp->b_xflags & BX_BKGRDMARKER)
11902 		initiate_write_bmsafemap(bmsafemap, bp);
11903 
11904 	return (dirty);
11905 }
11906 
11907 /*
11908  * Re-apply an allocation when a cg write is complete.
11909  */
11910 static int
11911 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11912 	struct jnewblk *jnewblk;
11913 	struct fs *fs;
11914 	struct cg *cgp;
11915 	uint8_t *blksfree;
11916 {
11917 	ufs1_daddr_t fragno;
11918 	ufs2_daddr_t blkno;
11919 	long cgbno, bbase;
11920 	int frags, blk;
11921 	int i;
11922 
11923 	frags = 0;
11924 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11925 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11926 		if (isclr(blksfree, cgbno + i))
11927 			panic("jnewblk_rollforward: re-allocated fragment");
11928 		frags++;
11929 	}
11930 	if (frags == fs->fs_frag) {
11931 		blkno = fragstoblks(fs, cgbno);
11932 		ffs_clrblock(fs, blksfree, (long)blkno);
11933 		ffs_clusteracct(fs, cgp, blkno, -1);
11934 		cgp->cg_cs.cs_nbfree--;
11935 	} else {
11936 		bbase = cgbno - fragnum(fs, cgbno);
11937 		cgbno += jnewblk->jn_oldfrags;
11938                 /* If a complete block had been reassembled, account for it. */
11939 		fragno = fragstoblks(fs, bbase);
11940 		if (ffs_isblock(fs, blksfree, fragno)) {
11941 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11942 			ffs_clusteracct(fs, cgp, fragno, -1);
11943 			cgp->cg_cs.cs_nbfree--;
11944 		}
11945 		/* Decrement the old frags.  */
11946 		blk = blkmap(fs, blksfree, bbase);
11947 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11948 		/* Allocate the fragment */
11949 		for (i = 0; i < frags; i++)
11950 			clrbit(blksfree, cgbno + i);
11951 		cgp->cg_cs.cs_nffree -= frags;
11952 		/* Add back in counts associated with the new frags */
11953 		blk = blkmap(fs, blksfree, bbase);
11954 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11955 	}
11956 	return (frags);
11957 }
11958 
11959 /*
11960  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11961  * changes if it's not a background write.  Set all written dependencies
11962  * to DEPCOMPLETE and free the structure if possible.
11963  *
11964  * If the write did not succeed, we will do all the roll-forward
11965  * operations, but we will not take the actions that will allow its
11966  * dependencies to be processed.
11967  */
11968 static int
11969 handle_written_bmsafemap(bmsafemap, bp, flags)
11970 	struct bmsafemap *bmsafemap;
11971 	struct buf *bp;
11972 	int flags;
11973 {
11974 	struct newblk *newblk;
11975 	struct inodedep *inodedep;
11976 	struct jaddref *jaddref, *jatmp;
11977 	struct jnewblk *jnewblk, *jntmp;
11978 	struct ufsmount *ump;
11979 	uint8_t *inosused;
11980 	uint8_t *blksfree;
11981 	struct cg *cgp;
11982 	struct fs *fs;
11983 	ino_t ino;
11984 	int foreground;
11985 	int chgs;
11986 
11987 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11988 		panic("handle_written_bmsafemap: Not started\n");
11989 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11990 	chgs = 0;
11991 	bmsafemap->sm_state &= ~IOSTARTED;
11992 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11993 	/*
11994 	 * If write was successful, release journal work that was waiting
11995 	 * on the write. Otherwise move the work back.
11996 	 */
11997 	if (flags & WRITESUCCEEDED)
11998 		handle_jwork(&bmsafemap->sm_freewr);
11999 	else
12000 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12001 		    worklist, wk_list);
12002 
12003 	/*
12004 	 * Restore unwritten inode allocation pending jaddref writes.
12005 	 */
12006 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
12007 		cgp = (struct cg *)bp->b_data;
12008 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12009 		inosused = cg_inosused(cgp);
12010 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
12011 		    ja_bmdeps, jatmp) {
12012 			if ((jaddref->ja_state & UNDONE) == 0)
12013 				continue;
12014 			ino = jaddref->ja_ino % fs->fs_ipg;
12015 			if (isset(inosused, ino))
12016 				panic("handle_written_bmsafemap: "
12017 				    "re-allocated inode");
12018 			/* Do the roll-forward only if it's a real copy. */
12019 			if (foreground) {
12020 				if ((jaddref->ja_mode & IFMT) == IFDIR)
12021 					cgp->cg_cs.cs_ndir++;
12022 				cgp->cg_cs.cs_nifree--;
12023 				setbit(inosused, ino);
12024 				chgs = 1;
12025 			}
12026 			jaddref->ja_state &= ~UNDONE;
12027 			jaddref->ja_state |= ATTACHED;
12028 			free_jaddref(jaddref);
12029 		}
12030 	}
12031 	/*
12032 	 * Restore any block allocations which are pending journal writes.
12033 	 */
12034 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12035 		cgp = (struct cg *)bp->b_data;
12036 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12037 		blksfree = cg_blksfree(cgp);
12038 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12039 		    jntmp) {
12040 			if ((jnewblk->jn_state & UNDONE) == 0)
12041 				continue;
12042 			/* Do the roll-forward only if it's a real copy. */
12043 			if (foreground &&
12044 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12045 				chgs = 1;
12046 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12047 			jnewblk->jn_state |= ATTACHED;
12048 			free_jnewblk(jnewblk);
12049 		}
12050 	}
12051 	/*
12052 	 * If the write did not succeed, we have done all the roll-forward
12053 	 * operations, but we cannot take the actions that will allow its
12054 	 * dependencies to be processed.
12055 	 */
12056 	if ((flags & WRITESUCCEEDED) == 0) {
12057 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12058 		    newblk, nb_deps);
12059 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12060 		    worklist, wk_list);
12061 		if (foreground)
12062 			bdirty(bp);
12063 		return (1);
12064 	}
12065 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12066 		newblk->nb_state |= DEPCOMPLETE;
12067 		newblk->nb_state &= ~ONDEPLIST;
12068 		newblk->nb_bmsafemap = NULL;
12069 		LIST_REMOVE(newblk, nb_deps);
12070 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12071 			handle_allocdirect_partdone(
12072 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12073 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12074 			handle_allocindir_partdone(
12075 			    WK_ALLOCINDIR(&newblk->nb_list));
12076 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12077 			panic("handle_written_bmsafemap: Unexpected type: %s",
12078 			    TYPENAME(newblk->nb_list.wk_type));
12079 	}
12080 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12081 		inodedep->id_state |= DEPCOMPLETE;
12082 		inodedep->id_state &= ~ONDEPLIST;
12083 		LIST_REMOVE(inodedep, id_deps);
12084 		inodedep->id_bmsafemap = NULL;
12085 	}
12086 	LIST_REMOVE(bmsafemap, sm_next);
12087 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12088 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12089 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12090 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12091 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12092 		LIST_REMOVE(bmsafemap, sm_hash);
12093 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12094 		return (0);
12095 	}
12096 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12097 	if (foreground)
12098 		bdirty(bp);
12099 	return (1);
12100 }
12101 
12102 /*
12103  * Try to free a mkdir dependency.
12104  */
12105 static void
12106 complete_mkdir(mkdir)
12107 	struct mkdir *mkdir;
12108 {
12109 	struct diradd *dap;
12110 
12111 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12112 		return;
12113 	LIST_REMOVE(mkdir, md_mkdirs);
12114 	dap = mkdir->md_diradd;
12115 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12116 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12117 		dap->da_state |= DEPCOMPLETE;
12118 		complete_diradd(dap);
12119 	}
12120 	WORKITEM_FREE(mkdir, D_MKDIR);
12121 }
12122 
12123 /*
12124  * Handle the completion of a mkdir dependency.
12125  */
12126 static void
12127 handle_written_mkdir(mkdir, type)
12128 	struct mkdir *mkdir;
12129 	int type;
12130 {
12131 
12132 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12133 		panic("handle_written_mkdir: bad type");
12134 	mkdir->md_state |= COMPLETE;
12135 	complete_mkdir(mkdir);
12136 }
12137 
12138 static int
12139 free_pagedep(pagedep)
12140 	struct pagedep *pagedep;
12141 {
12142 	int i;
12143 
12144 	if (pagedep->pd_state & NEWBLOCK)
12145 		return (0);
12146 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12147 		return (0);
12148 	for (i = 0; i < DAHASHSZ; i++)
12149 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12150 			return (0);
12151 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12152 		return (0);
12153 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12154 		return (0);
12155 	if (pagedep->pd_state & ONWORKLIST)
12156 		WORKLIST_REMOVE(&pagedep->pd_list);
12157 	LIST_REMOVE(pagedep, pd_hash);
12158 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12159 
12160 	return (1);
12161 }
12162 
12163 /*
12164  * Called from within softdep_disk_write_complete above.
12165  * A write operation was just completed. Removed inodes can
12166  * now be freed and associated block pointers may be committed.
12167  * Note that this routine is always called from interrupt level
12168  * with further interrupts from this device blocked.
12169  *
12170  * If the write did not succeed, we will do all the roll-forward
12171  * operations, but we will not take the actions that will allow its
12172  * dependencies to be processed.
12173  */
12174 static int
12175 handle_written_filepage(pagedep, bp, flags)
12176 	struct pagedep *pagedep;
12177 	struct buf *bp;		/* buffer containing the written page */
12178 	int flags;
12179 {
12180 	struct dirrem *dirrem;
12181 	struct diradd *dap, *nextdap;
12182 	struct direct *ep;
12183 	int i, chgs;
12184 
12185 	if ((pagedep->pd_state & IOSTARTED) == 0)
12186 		panic("handle_written_filepage: not started");
12187 	pagedep->pd_state &= ~IOSTARTED;
12188 	if ((flags & WRITESUCCEEDED) == 0)
12189 		goto rollforward;
12190 	/*
12191 	 * Process any directory removals that have been committed.
12192 	 */
12193 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12194 		LIST_REMOVE(dirrem, dm_next);
12195 		dirrem->dm_state |= COMPLETE;
12196 		dirrem->dm_dirinum = pagedep->pd_ino;
12197 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12198 		    ("handle_written_filepage: Journal entries not written."));
12199 		add_to_worklist(&dirrem->dm_list, 0);
12200 	}
12201 	/*
12202 	 * Free any directory additions that have been committed.
12203 	 * If it is a newly allocated block, we have to wait until
12204 	 * the on-disk directory inode claims the new block.
12205 	 */
12206 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12207 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12208 			free_diradd(dap, NULL);
12209 rollforward:
12210 	/*
12211 	 * Uncommitted directory entries must be restored.
12212 	 */
12213 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12214 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12215 		     dap = nextdap) {
12216 			nextdap = LIST_NEXT(dap, da_pdlist);
12217 			if (dap->da_state & ATTACHED)
12218 				panic("handle_written_filepage: attached");
12219 			ep = (struct direct *)
12220 			    ((char *)bp->b_data + dap->da_offset);
12221 			ep->d_ino = dap->da_newinum;
12222 			dap->da_state &= ~UNDONE;
12223 			dap->da_state |= ATTACHED;
12224 			chgs = 1;
12225 			/*
12226 			 * If the inode referenced by the directory has
12227 			 * been written out, then the dependency can be
12228 			 * moved to the pending list.
12229 			 */
12230 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12231 				LIST_REMOVE(dap, da_pdlist);
12232 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12233 				    da_pdlist);
12234 			}
12235 		}
12236 	}
12237 	/*
12238 	 * If there were any rollbacks in the directory, then it must be
12239 	 * marked dirty so that its will eventually get written back in
12240 	 * its correct form.
12241 	 */
12242 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12243 		if ((bp->b_flags & B_DELWRI) == 0)
12244 			stat_dir_entry++;
12245 		bdirty(bp);
12246 		return (1);
12247 	}
12248 	/*
12249 	 * If we are not waiting for a new directory block to be
12250 	 * claimed by its inode, then the pagedep will be freed.
12251 	 * Otherwise it will remain to track any new entries on
12252 	 * the page in case they are fsync'ed.
12253 	 */
12254 	free_pagedep(pagedep);
12255 	return (0);
12256 }
12257 
12258 /*
12259  * Writing back in-core inode structures.
12260  *
12261  * The filesystem only accesses an inode's contents when it occupies an
12262  * "in-core" inode structure.  These "in-core" structures are separate from
12263  * the page frames used to cache inode blocks.  Only the latter are
12264  * transferred to/from the disk.  So, when the updated contents of the
12265  * "in-core" inode structure are copied to the corresponding in-memory inode
12266  * block, the dependencies are also transferred.  The following procedure is
12267  * called when copying a dirty "in-core" inode to a cached inode block.
12268  */
12269 
12270 /*
12271  * Called when an inode is loaded from disk. If the effective link count
12272  * differed from the actual link count when it was last flushed, then we
12273  * need to ensure that the correct effective link count is put back.
12274  */
12275 void
12276 softdep_load_inodeblock(ip)
12277 	struct inode *ip;	/* the "in_core" copy of the inode */
12278 {
12279 	struct inodedep *inodedep;
12280 	struct ufsmount *ump;
12281 
12282 	ump = ITOUMP(ip);
12283 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12284 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12285 	/*
12286 	 * Check for alternate nlink count.
12287 	 */
12288 	ip->i_effnlink = ip->i_nlink;
12289 	ACQUIRE_LOCK(ump);
12290 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12291 		FREE_LOCK(ump);
12292 		return;
12293 	}
12294 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12295 	KASSERT(ip->i_effnlink >= 0,
12296 	    ("softdep_load_inodeblock: negative i_effnlink"));
12297 	FREE_LOCK(ump);
12298 }
12299 
12300 /*
12301  * This routine is called just before the "in-core" inode
12302  * information is to be copied to the in-memory inode block.
12303  * Recall that an inode block contains several inodes. If
12304  * the force flag is set, then the dependencies will be
12305  * cleared so that the update can always be made. Note that
12306  * the buffer is locked when this routine is called, so we
12307  * will never be in the middle of writing the inode block
12308  * to disk.
12309  */
12310 void
12311 softdep_update_inodeblock(ip, bp, waitfor)
12312 	struct inode *ip;	/* the "in_core" copy of the inode */
12313 	struct buf *bp;		/* the buffer containing the inode block */
12314 	int waitfor;		/* nonzero => update must be allowed */
12315 {
12316 	struct inodedep *inodedep;
12317 	struct inoref *inoref;
12318 	struct ufsmount *ump;
12319 	struct worklist *wk;
12320 	struct mount *mp;
12321 	struct buf *ibp;
12322 	struct fs *fs;
12323 	int error;
12324 
12325 	ump = ITOUMP(ip);
12326 	mp = UFSTOVFS(ump);
12327 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12328 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12329 	fs = ump->um_fs;
12330 	/*
12331 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12332 	 * does not have access to the in-core ip so must write directly into
12333 	 * the inode block buffer when setting freelink.
12334 	 */
12335 	if (fs->fs_magic == FS_UFS1_MAGIC)
12336 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12337 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12338 	else
12339 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12340 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12341 	/*
12342 	 * If the effective link count is not equal to the actual link
12343 	 * count, then we must track the difference in an inodedep while
12344 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12345 	 * if there is no existing inodedep, then there are no dependencies
12346 	 * to track.
12347 	 */
12348 	ACQUIRE_LOCK(ump);
12349 again:
12350 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12351 		FREE_LOCK(ump);
12352 		if (ip->i_effnlink != ip->i_nlink)
12353 			panic("softdep_update_inodeblock: bad link count");
12354 		return;
12355 	}
12356 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12357 		panic("softdep_update_inodeblock: bad delta");
12358 	/*
12359 	 * If we're flushing all dependencies we must also move any waiting
12360 	 * for journal writes onto the bufwait list prior to I/O.
12361 	 */
12362 	if (waitfor) {
12363 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12364 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12365 			    == DEPCOMPLETE) {
12366 				jwait(&inoref->if_list, MNT_WAIT);
12367 				goto again;
12368 			}
12369 		}
12370 	}
12371 	/*
12372 	 * Changes have been initiated. Anything depending on these
12373 	 * changes cannot occur until this inode has been written.
12374 	 */
12375 	inodedep->id_state &= ~COMPLETE;
12376 	if ((inodedep->id_state & ONWORKLIST) == 0)
12377 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12378 	/*
12379 	 * Any new dependencies associated with the incore inode must
12380 	 * now be moved to the list associated with the buffer holding
12381 	 * the in-memory copy of the inode. Once merged process any
12382 	 * allocdirects that are completed by the merger.
12383 	 */
12384 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12385 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12386 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12387 		    NULL);
12388 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12389 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12390 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12391 		    NULL);
12392 	/*
12393 	 * Now that the inode has been pushed into the buffer, the
12394 	 * operations dependent on the inode being written to disk
12395 	 * can be moved to the id_bufwait so that they will be
12396 	 * processed when the buffer I/O completes.
12397 	 */
12398 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12399 		WORKLIST_REMOVE(wk);
12400 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12401 	}
12402 	/*
12403 	 * Newly allocated inodes cannot be written until the bitmap
12404 	 * that allocates them have been written (indicated by
12405 	 * DEPCOMPLETE being set in id_state). If we are doing a
12406 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12407 	 * to be written so that the update can be done.
12408 	 */
12409 	if (waitfor == 0) {
12410 		FREE_LOCK(ump);
12411 		return;
12412 	}
12413 retry:
12414 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12415 		FREE_LOCK(ump);
12416 		return;
12417 	}
12418 	ibp = inodedep->id_bmsafemap->sm_buf;
12419 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12420 	if (ibp == NULL) {
12421 		/*
12422 		 * If ibp came back as NULL, the dependency could have been
12423 		 * freed while we slept.  Look it up again, and check to see
12424 		 * that it has completed.
12425 		 */
12426 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12427 			goto retry;
12428 		FREE_LOCK(ump);
12429 		return;
12430 	}
12431 	FREE_LOCK(ump);
12432 	if ((error = bwrite(ibp)) != 0)
12433 		softdep_error("softdep_update_inodeblock: bwrite", error);
12434 }
12435 
12436 /*
12437  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12438  * old inode dependency list (such as id_inoupdt).
12439  */
12440 static void
12441 merge_inode_lists(newlisthead, oldlisthead)
12442 	struct allocdirectlst *newlisthead;
12443 	struct allocdirectlst *oldlisthead;
12444 {
12445 	struct allocdirect *listadp, *newadp;
12446 
12447 	newadp = TAILQ_FIRST(newlisthead);
12448 	if (newadp != NULL)
12449 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12450 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12451 		if (listadp->ad_offset < newadp->ad_offset) {
12452 			listadp = TAILQ_NEXT(listadp, ad_next);
12453 			continue;
12454 		}
12455 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12456 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12457 		if (listadp->ad_offset == newadp->ad_offset) {
12458 			allocdirect_merge(oldlisthead, newadp,
12459 			    listadp);
12460 			listadp = newadp;
12461 		}
12462 		newadp = TAILQ_FIRST(newlisthead);
12463 	}
12464 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12465 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12466 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12467 	}
12468 }
12469 
12470 /*
12471  * If we are doing an fsync, then we must ensure that any directory
12472  * entries for the inode have been written after the inode gets to disk.
12473  */
12474 int
12475 softdep_fsync(vp)
12476 	struct vnode *vp;	/* the "in_core" copy of the inode */
12477 {
12478 	struct inodedep *inodedep;
12479 	struct pagedep *pagedep;
12480 	struct inoref *inoref;
12481 	struct ufsmount *ump;
12482 	struct worklist *wk;
12483 	struct diradd *dap;
12484 	struct mount *mp;
12485 	struct vnode *pvp;
12486 	struct inode *ip;
12487 	struct buf *bp;
12488 	struct fs *fs;
12489 	struct thread *td = curthread;
12490 	int error, flushparent, pagedep_new_block;
12491 	ino_t parentino;
12492 	ufs_lbn_t lbn;
12493 
12494 	ip = VTOI(vp);
12495 	mp = vp->v_mount;
12496 	ump = VFSTOUFS(mp);
12497 	fs = ump->um_fs;
12498 	if (MOUNTEDSOFTDEP(mp) == 0)
12499 		return (0);
12500 	ACQUIRE_LOCK(ump);
12501 restart:
12502 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12503 		FREE_LOCK(ump);
12504 		return (0);
12505 	}
12506 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12507 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12508 		    == DEPCOMPLETE) {
12509 			jwait(&inoref->if_list, MNT_WAIT);
12510 			goto restart;
12511 		}
12512 	}
12513 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12514 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12515 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12516 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12517 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12518 		panic("softdep_fsync: pending ops %p", inodedep);
12519 	for (error = 0, flushparent = 0; ; ) {
12520 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12521 			break;
12522 		if (wk->wk_type != D_DIRADD)
12523 			panic("softdep_fsync: Unexpected type %s",
12524 			    TYPENAME(wk->wk_type));
12525 		dap = WK_DIRADD(wk);
12526 		/*
12527 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12528 		 * dependency or is contained in a newly allocated block.
12529 		 */
12530 		if (dap->da_state & DIRCHG)
12531 			pagedep = dap->da_previous->dm_pagedep;
12532 		else
12533 			pagedep = dap->da_pagedep;
12534 		parentino = pagedep->pd_ino;
12535 		lbn = pagedep->pd_lbn;
12536 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12537 			panic("softdep_fsync: dirty");
12538 		if ((dap->da_state & MKDIR_PARENT) ||
12539 		    (pagedep->pd_state & NEWBLOCK))
12540 			flushparent = 1;
12541 		else
12542 			flushparent = 0;
12543 		/*
12544 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12545 		 * then we will not be able to release and recover the
12546 		 * vnode below, so we just have to give up on writing its
12547 		 * directory entry out. It will eventually be written, just
12548 		 * not now, but then the user was not asking to have it
12549 		 * written, so we are not breaking any promises.
12550 		 */
12551 		if (VN_IS_DOOMED(vp))
12552 			break;
12553 		/*
12554 		 * We prevent deadlock by always fetching inodes from the
12555 		 * root, moving down the directory tree. Thus, when fetching
12556 		 * our parent directory, we first try to get the lock. If
12557 		 * that fails, we must unlock ourselves before requesting
12558 		 * the lock on our parent. See the comment in ufs_lookup
12559 		 * for details on possible races.
12560 		 */
12561 		FREE_LOCK(ump);
12562 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12563 		    FFSV_FORCEINSMQ)) {
12564 			/*
12565 			 * Unmount cannot proceed after unlock because
12566 			 * caller must have called vn_start_write().
12567 			 */
12568 			VOP_UNLOCK(vp);
12569 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12570 			    &pvp, FFSV_FORCEINSMQ);
12571 			MPASS(VTOI(pvp)->i_mode != 0);
12572 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12573 			if (VN_IS_DOOMED(vp)) {
12574 				if (error == 0)
12575 					vput(pvp);
12576 				error = ENOENT;
12577 			}
12578 			if (error != 0)
12579 				return (error);
12580 		}
12581 		/*
12582 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12583 		 * that are contained in direct blocks will be resolved by
12584 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12585 		 * may require a complete sync'ing of the directory. So, we
12586 		 * try the cheap and fast ffs_update first, and if that fails,
12587 		 * then we do the slower ffs_syncvnode of the directory.
12588 		 */
12589 		if (flushparent) {
12590 			int locked;
12591 
12592 			if ((error = ffs_update(pvp, 1)) != 0) {
12593 				vput(pvp);
12594 				return (error);
12595 			}
12596 			ACQUIRE_LOCK(ump);
12597 			locked = 1;
12598 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12599 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12600 					if (wk->wk_type != D_DIRADD)
12601 						panic("softdep_fsync: Unexpected type %s",
12602 						      TYPENAME(wk->wk_type));
12603 					dap = WK_DIRADD(wk);
12604 					if (dap->da_state & DIRCHG)
12605 						pagedep = dap->da_previous->dm_pagedep;
12606 					else
12607 						pagedep = dap->da_pagedep;
12608 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12609 					FREE_LOCK(ump);
12610 					locked = 0;
12611 					if (pagedep_new_block && (error =
12612 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12613 						vput(pvp);
12614 						return (error);
12615 					}
12616 				}
12617 			}
12618 			if (locked)
12619 				FREE_LOCK(ump);
12620 		}
12621 		/*
12622 		 * Flush directory page containing the inode's name.
12623 		 */
12624 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12625 		    &bp);
12626 		if (error == 0)
12627 			error = bwrite(bp);
12628 		else
12629 			brelse(bp);
12630 		vput(pvp);
12631 		if (error != 0)
12632 			return (error);
12633 		ACQUIRE_LOCK(ump);
12634 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12635 			break;
12636 	}
12637 	FREE_LOCK(ump);
12638 	return (0);
12639 }
12640 
12641 /*
12642  * Flush all the dirty bitmaps associated with the block device
12643  * before flushing the rest of the dirty blocks so as to reduce
12644  * the number of dependencies that will have to be rolled back.
12645  *
12646  * XXX Unused?
12647  */
12648 void
12649 softdep_fsync_mountdev(vp)
12650 	struct vnode *vp;
12651 {
12652 	struct buf *bp, *nbp;
12653 	struct worklist *wk;
12654 	struct bufobj *bo;
12655 
12656 	if (!vn_isdisk(vp, NULL))
12657 		panic("softdep_fsync_mountdev: vnode not a disk");
12658 	bo = &vp->v_bufobj;
12659 restart:
12660 	BO_LOCK(bo);
12661 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12662 		/*
12663 		 * If it is already scheduled, skip to the next buffer.
12664 		 */
12665 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12666 			continue;
12667 
12668 		if ((bp->b_flags & B_DELWRI) == 0)
12669 			panic("softdep_fsync_mountdev: not dirty");
12670 		/*
12671 		 * We are only interested in bitmaps with outstanding
12672 		 * dependencies.
12673 		 */
12674 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12675 		    wk->wk_type != D_BMSAFEMAP ||
12676 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12677 			BUF_UNLOCK(bp);
12678 			continue;
12679 		}
12680 		BO_UNLOCK(bo);
12681 		bremfree(bp);
12682 		(void) bawrite(bp);
12683 		goto restart;
12684 	}
12685 	drain_output(vp);
12686 	BO_UNLOCK(bo);
12687 }
12688 
12689 /*
12690  * Sync all cylinder groups that were dirty at the time this function is
12691  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12692  * is used to flush freedep activity that may be holding up writes to a
12693  * indirect block.
12694  */
12695 static int
12696 sync_cgs(mp, waitfor)
12697 	struct mount *mp;
12698 	int waitfor;
12699 {
12700 	struct bmsafemap *bmsafemap;
12701 	struct bmsafemap *sentinel;
12702 	struct ufsmount *ump;
12703 	struct buf *bp;
12704 	int error;
12705 
12706 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12707 	sentinel->sm_cg = -1;
12708 	ump = VFSTOUFS(mp);
12709 	error = 0;
12710 	ACQUIRE_LOCK(ump);
12711 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12712 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12713 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12714 		/* Skip sentinels and cgs with no work to release. */
12715 		if (bmsafemap->sm_cg == -1 ||
12716 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12717 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12718 			LIST_REMOVE(sentinel, sm_next);
12719 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12720 			continue;
12721 		}
12722 		/*
12723 		 * If we don't get the lock and we're waiting try again, if
12724 		 * not move on to the next buf and try to sync it.
12725 		 */
12726 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12727 		if (bp == NULL && waitfor == MNT_WAIT)
12728 			continue;
12729 		LIST_REMOVE(sentinel, sm_next);
12730 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12731 		if (bp == NULL)
12732 			continue;
12733 		FREE_LOCK(ump);
12734 		if (waitfor == MNT_NOWAIT)
12735 			bawrite(bp);
12736 		else
12737 			error = bwrite(bp);
12738 		ACQUIRE_LOCK(ump);
12739 		if (error)
12740 			break;
12741 	}
12742 	LIST_REMOVE(sentinel, sm_next);
12743 	FREE_LOCK(ump);
12744 	free(sentinel, M_BMSAFEMAP);
12745 	return (error);
12746 }
12747 
12748 /*
12749  * This routine is called when we are trying to synchronously flush a
12750  * file. This routine must eliminate any filesystem metadata dependencies
12751  * so that the syncing routine can succeed.
12752  */
12753 int
12754 softdep_sync_metadata(struct vnode *vp)
12755 {
12756 	struct inode *ip;
12757 	int error;
12758 
12759 	ip = VTOI(vp);
12760 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12761 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12762 	/*
12763 	 * Ensure that any direct block dependencies have been cleared,
12764 	 * truncations are started, and inode references are journaled.
12765 	 */
12766 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12767 	/*
12768 	 * Write all journal records to prevent rollbacks on devvp.
12769 	 */
12770 	if (vp->v_type == VCHR)
12771 		softdep_flushjournal(vp->v_mount);
12772 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12773 	/*
12774 	 * Ensure that all truncates are written so we won't find deps on
12775 	 * indirect blocks.
12776 	 */
12777 	process_truncates(vp);
12778 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12779 
12780 	return (error);
12781 }
12782 
12783 /*
12784  * This routine is called when we are attempting to sync a buf with
12785  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12786  * other IO it can but returns EBUSY if the buffer is not yet able to
12787  * be written.  Dependencies which will not cause rollbacks will always
12788  * return 0.
12789  */
12790 int
12791 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12792 {
12793 	struct indirdep *indirdep;
12794 	struct pagedep *pagedep;
12795 	struct allocindir *aip;
12796 	struct newblk *newblk;
12797 	struct ufsmount *ump;
12798 	struct buf *nbp;
12799 	struct worklist *wk;
12800 	int i, error;
12801 
12802 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12803 	    ("softdep_sync_buf called on non-softdep filesystem"));
12804 	/*
12805 	 * For VCHR we just don't want to force flush any dependencies that
12806 	 * will cause rollbacks.
12807 	 */
12808 	if (vp->v_type == VCHR) {
12809 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12810 			return (EBUSY);
12811 		return (0);
12812 	}
12813 	ump = VFSTOUFS(vp->v_mount);
12814 	ACQUIRE_LOCK(ump);
12815 	/*
12816 	 * As we hold the buffer locked, none of its dependencies
12817 	 * will disappear.
12818 	 */
12819 	error = 0;
12820 top:
12821 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12822 		switch (wk->wk_type) {
12823 
12824 		case D_ALLOCDIRECT:
12825 		case D_ALLOCINDIR:
12826 			newblk = WK_NEWBLK(wk);
12827 			if (newblk->nb_jnewblk != NULL) {
12828 				if (waitfor == MNT_NOWAIT) {
12829 					error = EBUSY;
12830 					goto out_unlock;
12831 				}
12832 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12833 				goto top;
12834 			}
12835 			if (newblk->nb_state & DEPCOMPLETE ||
12836 			    waitfor == MNT_NOWAIT)
12837 				continue;
12838 			nbp = newblk->nb_bmsafemap->sm_buf;
12839 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12840 			if (nbp == NULL)
12841 				goto top;
12842 			FREE_LOCK(ump);
12843 			if ((error = bwrite(nbp)) != 0)
12844 				goto out;
12845 			ACQUIRE_LOCK(ump);
12846 			continue;
12847 
12848 		case D_INDIRDEP:
12849 			indirdep = WK_INDIRDEP(wk);
12850 			if (waitfor == MNT_NOWAIT) {
12851 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12852 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12853 					error = EBUSY;
12854 					goto out_unlock;
12855 				}
12856 			}
12857 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12858 				panic("softdep_sync_buf: truncation pending.");
12859 		restart:
12860 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12861 				newblk = (struct newblk *)aip;
12862 				if (newblk->nb_jnewblk != NULL) {
12863 					jwait(&newblk->nb_jnewblk->jn_list,
12864 					    waitfor);
12865 					goto restart;
12866 				}
12867 				if (newblk->nb_state & DEPCOMPLETE)
12868 					continue;
12869 				nbp = newblk->nb_bmsafemap->sm_buf;
12870 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12871 				if (nbp == NULL)
12872 					goto restart;
12873 				FREE_LOCK(ump);
12874 				if ((error = bwrite(nbp)) != 0)
12875 					goto out;
12876 				ACQUIRE_LOCK(ump);
12877 				goto restart;
12878 			}
12879 			continue;
12880 
12881 		case D_PAGEDEP:
12882 			/*
12883 			 * Only flush directory entries in synchronous passes.
12884 			 */
12885 			if (waitfor != MNT_WAIT) {
12886 				error = EBUSY;
12887 				goto out_unlock;
12888 			}
12889 			/*
12890 			 * While syncing snapshots, we must allow recursive
12891 			 * lookups.
12892 			 */
12893 			BUF_AREC(bp);
12894 			/*
12895 			 * We are trying to sync a directory that may
12896 			 * have dependencies on both its own metadata
12897 			 * and/or dependencies on the inodes of any
12898 			 * recently allocated files. We walk its diradd
12899 			 * lists pushing out the associated inode.
12900 			 */
12901 			pagedep = WK_PAGEDEP(wk);
12902 			for (i = 0; i < DAHASHSZ; i++) {
12903 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12904 					continue;
12905 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12906 				    &pagedep->pd_diraddhd[i]))) {
12907 					BUF_NOREC(bp);
12908 					goto out_unlock;
12909 				}
12910 			}
12911 			BUF_NOREC(bp);
12912 			continue;
12913 
12914 		case D_FREEWORK:
12915 		case D_FREEDEP:
12916 		case D_JSEGDEP:
12917 		case D_JNEWBLK:
12918 			continue;
12919 
12920 		default:
12921 			panic("softdep_sync_buf: Unknown type %s",
12922 			    TYPENAME(wk->wk_type));
12923 			/* NOTREACHED */
12924 		}
12925 	}
12926 out_unlock:
12927 	FREE_LOCK(ump);
12928 out:
12929 	return (error);
12930 }
12931 
12932 /*
12933  * Flush the dependencies associated with an inodedep.
12934  */
12935 static int
12936 flush_inodedep_deps(vp, mp, ino)
12937 	struct vnode *vp;
12938 	struct mount *mp;
12939 	ino_t ino;
12940 {
12941 	struct inodedep *inodedep;
12942 	struct inoref *inoref;
12943 	struct ufsmount *ump;
12944 	int error, waitfor;
12945 
12946 	/*
12947 	 * This work is done in two passes. The first pass grabs most
12948 	 * of the buffers and begins asynchronously writing them. The
12949 	 * only way to wait for these asynchronous writes is to sleep
12950 	 * on the filesystem vnode which may stay busy for a long time
12951 	 * if the filesystem is active. So, instead, we make a second
12952 	 * pass over the dependencies blocking on each write. In the
12953 	 * usual case we will be blocking against a write that we
12954 	 * initiated, so when it is done the dependency will have been
12955 	 * resolved. Thus the second pass is expected to end quickly.
12956 	 * We give a brief window at the top of the loop to allow
12957 	 * any pending I/O to complete.
12958 	 */
12959 	ump = VFSTOUFS(mp);
12960 	LOCK_OWNED(ump);
12961 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12962 		if (error)
12963 			return (error);
12964 		FREE_LOCK(ump);
12965 		ACQUIRE_LOCK(ump);
12966 restart:
12967 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12968 			return (0);
12969 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12970 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12971 			    == DEPCOMPLETE) {
12972 				jwait(&inoref->if_list, MNT_WAIT);
12973 				goto restart;
12974 			}
12975 		}
12976 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12977 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12978 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12979 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12980 			continue;
12981 		/*
12982 		 * If pass2, we are done, otherwise do pass 2.
12983 		 */
12984 		if (waitfor == MNT_WAIT)
12985 			break;
12986 		waitfor = MNT_WAIT;
12987 	}
12988 	/*
12989 	 * Try freeing inodedep in case all dependencies have been removed.
12990 	 */
12991 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12992 		(void) free_inodedep(inodedep);
12993 	return (0);
12994 }
12995 
12996 /*
12997  * Flush an inode dependency list.
12998  */
12999 static int
13000 flush_deplist(listhead, waitfor, errorp)
13001 	struct allocdirectlst *listhead;
13002 	int waitfor;
13003 	int *errorp;
13004 {
13005 	struct allocdirect *adp;
13006 	struct newblk *newblk;
13007 	struct ufsmount *ump;
13008 	struct buf *bp;
13009 
13010 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
13011 		return (0);
13012 	ump = VFSTOUFS(adp->ad_list.wk_mp);
13013 	LOCK_OWNED(ump);
13014 	TAILQ_FOREACH(adp, listhead, ad_next) {
13015 		newblk = (struct newblk *)adp;
13016 		if (newblk->nb_jnewblk != NULL) {
13017 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13018 			return (1);
13019 		}
13020 		if (newblk->nb_state & DEPCOMPLETE)
13021 			continue;
13022 		bp = newblk->nb_bmsafemap->sm_buf;
13023 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13024 		if (bp == NULL) {
13025 			if (waitfor == MNT_NOWAIT)
13026 				continue;
13027 			return (1);
13028 		}
13029 		FREE_LOCK(ump);
13030 		if (waitfor == MNT_NOWAIT)
13031 			bawrite(bp);
13032 		else
13033 			*errorp = bwrite(bp);
13034 		ACQUIRE_LOCK(ump);
13035 		return (1);
13036 	}
13037 	return (0);
13038 }
13039 
13040 /*
13041  * Flush dependencies associated with an allocdirect block.
13042  */
13043 static int
13044 flush_newblk_dep(vp, mp, lbn)
13045 	struct vnode *vp;
13046 	struct mount *mp;
13047 	ufs_lbn_t lbn;
13048 {
13049 	struct newblk *newblk;
13050 	struct ufsmount *ump;
13051 	struct bufobj *bo;
13052 	struct inode *ip;
13053 	struct buf *bp;
13054 	ufs2_daddr_t blkno;
13055 	int error;
13056 
13057 	error = 0;
13058 	bo = &vp->v_bufobj;
13059 	ip = VTOI(vp);
13060 	blkno = DIP(ip, i_db[lbn]);
13061 	if (blkno == 0)
13062 		panic("flush_newblk_dep: Missing block");
13063 	ump = VFSTOUFS(mp);
13064 	ACQUIRE_LOCK(ump);
13065 	/*
13066 	 * Loop until all dependencies related to this block are satisfied.
13067 	 * We must be careful to restart after each sleep in case a write
13068 	 * completes some part of this process for us.
13069 	 */
13070 	for (;;) {
13071 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13072 			FREE_LOCK(ump);
13073 			break;
13074 		}
13075 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13076 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13077 		/*
13078 		 * Flush the journal.
13079 		 */
13080 		if (newblk->nb_jnewblk != NULL) {
13081 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13082 			continue;
13083 		}
13084 		/*
13085 		 * Write the bitmap dependency.
13086 		 */
13087 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13088 			bp = newblk->nb_bmsafemap->sm_buf;
13089 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13090 			if (bp == NULL)
13091 				continue;
13092 			FREE_LOCK(ump);
13093 			error = bwrite(bp);
13094 			if (error)
13095 				break;
13096 			ACQUIRE_LOCK(ump);
13097 			continue;
13098 		}
13099 		/*
13100 		 * Write the buffer.
13101 		 */
13102 		FREE_LOCK(ump);
13103 		BO_LOCK(bo);
13104 		bp = gbincore(bo, lbn);
13105 		if (bp != NULL) {
13106 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13107 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13108 			if (error == ENOLCK) {
13109 				ACQUIRE_LOCK(ump);
13110 				error = 0;
13111 				continue; /* Slept, retry */
13112 			}
13113 			if (error != 0)
13114 				break;	/* Failed */
13115 			if (bp->b_flags & B_DELWRI) {
13116 				bremfree(bp);
13117 				error = bwrite(bp);
13118 				if (error)
13119 					break;
13120 			} else
13121 				BUF_UNLOCK(bp);
13122 		} else
13123 			BO_UNLOCK(bo);
13124 		/*
13125 		 * We have to wait for the direct pointers to
13126 		 * point at the newdirblk before the dependency
13127 		 * will go away.
13128 		 */
13129 		error = ffs_update(vp, 1);
13130 		if (error)
13131 			break;
13132 		ACQUIRE_LOCK(ump);
13133 	}
13134 	return (error);
13135 }
13136 
13137 /*
13138  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13139  */
13140 static int
13141 flush_pagedep_deps(pvp, mp, diraddhdp)
13142 	struct vnode *pvp;
13143 	struct mount *mp;
13144 	struct diraddhd *diraddhdp;
13145 {
13146 	struct inodedep *inodedep;
13147 	struct inoref *inoref;
13148 	struct ufsmount *ump;
13149 	struct diradd *dap;
13150 	struct vnode *vp;
13151 	int error = 0;
13152 	struct buf *bp;
13153 	ino_t inum;
13154 	struct diraddhd unfinished;
13155 
13156 	LIST_INIT(&unfinished);
13157 	ump = VFSTOUFS(mp);
13158 	LOCK_OWNED(ump);
13159 restart:
13160 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13161 		/*
13162 		 * Flush ourselves if this directory entry
13163 		 * has a MKDIR_PARENT dependency.
13164 		 */
13165 		if (dap->da_state & MKDIR_PARENT) {
13166 			FREE_LOCK(ump);
13167 			if ((error = ffs_update(pvp, 1)) != 0)
13168 				break;
13169 			ACQUIRE_LOCK(ump);
13170 			/*
13171 			 * If that cleared dependencies, go on to next.
13172 			 */
13173 			if (dap != LIST_FIRST(diraddhdp))
13174 				continue;
13175 			/*
13176 			 * All MKDIR_PARENT dependencies and all the
13177 			 * NEWBLOCK pagedeps that are contained in direct
13178 			 * blocks were resolved by doing above ffs_update.
13179 			 * Pagedeps contained in indirect blocks may
13180 			 * require a complete sync'ing of the directory.
13181 			 * We are in the midst of doing a complete sync,
13182 			 * so if they are not resolved in this pass we
13183 			 * defer them for now as they will be sync'ed by
13184 			 * our caller shortly.
13185 			 */
13186 			LIST_REMOVE(dap, da_pdlist);
13187 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13188 			continue;
13189 		}
13190 		/*
13191 		 * A newly allocated directory must have its "." and
13192 		 * ".." entries written out before its name can be
13193 		 * committed in its parent.
13194 		 */
13195 		inum = dap->da_newinum;
13196 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13197 			panic("flush_pagedep_deps: lost inode1");
13198 		/*
13199 		 * Wait for any pending journal adds to complete so we don't
13200 		 * cause rollbacks while syncing.
13201 		 */
13202 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13203 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13204 			    == DEPCOMPLETE) {
13205 				jwait(&inoref->if_list, MNT_WAIT);
13206 				goto restart;
13207 			}
13208 		}
13209 		if (dap->da_state & MKDIR_BODY) {
13210 			FREE_LOCK(ump);
13211 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13212 			    FFSV_FORCEINSMQ)))
13213 				break;
13214 			MPASS(VTOI(vp)->i_mode != 0);
13215 			error = flush_newblk_dep(vp, mp, 0);
13216 			/*
13217 			 * If we still have the dependency we might need to
13218 			 * update the vnode to sync the new link count to
13219 			 * disk.
13220 			 */
13221 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13222 				error = ffs_update(vp, 1);
13223 			vput(vp);
13224 			if (error != 0)
13225 				break;
13226 			ACQUIRE_LOCK(ump);
13227 			/*
13228 			 * If that cleared dependencies, go on to next.
13229 			 */
13230 			if (dap != LIST_FIRST(diraddhdp))
13231 				continue;
13232 			if (dap->da_state & MKDIR_BODY) {
13233 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13234 				    &inodedep);
13235 				panic("flush_pagedep_deps: MKDIR_BODY "
13236 				    "inodedep %p dap %p vp %p",
13237 				    inodedep, dap, vp);
13238 			}
13239 		}
13240 		/*
13241 		 * Flush the inode on which the directory entry depends.
13242 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13243 		 * the only remaining dependency is that the updated inode
13244 		 * count must get pushed to disk. The inode has already
13245 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13246 		 * the time of the reference count change. So we need only
13247 		 * locate that buffer, ensure that there will be no rollback
13248 		 * caused by a bitmap dependency, then write the inode buffer.
13249 		 */
13250 retry:
13251 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13252 			panic("flush_pagedep_deps: lost inode");
13253 		/*
13254 		 * If the inode still has bitmap dependencies,
13255 		 * push them to disk.
13256 		 */
13257 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13258 			bp = inodedep->id_bmsafemap->sm_buf;
13259 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13260 			if (bp == NULL)
13261 				goto retry;
13262 			FREE_LOCK(ump);
13263 			if ((error = bwrite(bp)) != 0)
13264 				break;
13265 			ACQUIRE_LOCK(ump);
13266 			if (dap != LIST_FIRST(diraddhdp))
13267 				continue;
13268 		}
13269 		/*
13270 		 * If the inode is still sitting in a buffer waiting
13271 		 * to be written or waiting for the link count to be
13272 		 * adjusted update it here to flush it to disk.
13273 		 */
13274 		if (dap == LIST_FIRST(diraddhdp)) {
13275 			FREE_LOCK(ump);
13276 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13277 			    FFSV_FORCEINSMQ)))
13278 				break;
13279 			MPASS(VTOI(vp)->i_mode != 0);
13280 			error = ffs_update(vp, 1);
13281 			vput(vp);
13282 			if (error)
13283 				break;
13284 			ACQUIRE_LOCK(ump);
13285 		}
13286 		/*
13287 		 * If we have failed to get rid of all the dependencies
13288 		 * then something is seriously wrong.
13289 		 */
13290 		if (dap == LIST_FIRST(diraddhdp)) {
13291 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13292 			panic("flush_pagedep_deps: failed to flush "
13293 			    "inodedep %p ino %ju dap %p",
13294 			    inodedep, (uintmax_t)inum, dap);
13295 		}
13296 	}
13297 	if (error)
13298 		ACQUIRE_LOCK(ump);
13299 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13300 		LIST_REMOVE(dap, da_pdlist);
13301 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13302 	}
13303 	return (error);
13304 }
13305 
13306 /*
13307  * A large burst of file addition or deletion activity can drive the
13308  * memory load excessively high. First attempt to slow things down
13309  * using the techniques below. If that fails, this routine requests
13310  * the offending operations to fall back to running synchronously
13311  * until the memory load returns to a reasonable level.
13312  */
13313 int
13314 softdep_slowdown(vp)
13315 	struct vnode *vp;
13316 {
13317 	struct ufsmount *ump;
13318 	int jlow;
13319 	int max_softdeps_hard;
13320 
13321 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13322 	    ("softdep_slowdown called on non-softdep filesystem"));
13323 	ump = VFSTOUFS(vp->v_mount);
13324 	ACQUIRE_LOCK(ump);
13325 	jlow = 0;
13326 	/*
13327 	 * Check for journal space if needed.
13328 	 */
13329 	if (DOINGSUJ(vp)) {
13330 		if (journal_space(ump, 0) == 0)
13331 			jlow = 1;
13332 	}
13333 	/*
13334 	 * If the system is under its limits and our filesystem is
13335 	 * not responsible for more than our share of the usage and
13336 	 * we are not low on journal space, then no need to slow down.
13337 	 */
13338 	max_softdeps_hard = max_softdeps * 11 / 10;
13339 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13340 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13341 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13342 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13343 	    ump->softdep_curdeps[D_DIRREM] <
13344 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13345 	    ump->softdep_curdeps[D_INODEDEP] <
13346 	    max_softdeps_hard / stat_flush_threads &&
13347 	    ump->softdep_curdeps[D_INDIRDEP] <
13348 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13349 	    ump->softdep_curdeps[D_FREEBLKS] <
13350 	    max_softdeps_hard / stat_flush_threads) {
13351 		FREE_LOCK(ump);
13352   		return (0);
13353 	}
13354 	/*
13355 	 * If the journal is low or our filesystem is over its limit
13356 	 * then speedup the cleanup.
13357 	 */
13358 	if (ump->softdep_curdeps[D_INDIRDEP] <
13359 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13360 		softdep_speedup(ump);
13361 	stat_sync_limit_hit += 1;
13362 	FREE_LOCK(ump);
13363 	/*
13364 	 * We only slow down the rate at which new dependencies are
13365 	 * generated if we are not using journaling. With journaling,
13366 	 * the cleanup should always be sufficient to keep things
13367 	 * under control.
13368 	 */
13369 	if (DOINGSUJ(vp))
13370 		return (0);
13371 	return (1);
13372 }
13373 
13374 /*
13375  * Called by the allocation routines when they are about to fail
13376  * in the hope that we can free up the requested resource (inodes
13377  * or disk space).
13378  *
13379  * First check to see if the work list has anything on it. If it has,
13380  * clean up entries until we successfully free the requested resource.
13381  * Because this process holds inodes locked, we cannot handle any remove
13382  * requests that might block on a locked inode as that could lead to
13383  * deadlock. If the worklist yields none of the requested resource,
13384  * start syncing out vnodes to free up the needed space.
13385  */
13386 int
13387 softdep_request_cleanup(fs, vp, cred, resource)
13388 	struct fs *fs;
13389 	struct vnode *vp;
13390 	struct ucred *cred;
13391 	int resource;
13392 {
13393 	struct ufsmount *ump;
13394 	struct mount *mp;
13395 	long starttime;
13396 	ufs2_daddr_t needed;
13397 	int error, failed_vnode;
13398 
13399 	/*
13400 	 * If we are being called because of a process doing a
13401 	 * copy-on-write, then it is not safe to process any
13402 	 * worklist items as we will recurse into the copyonwrite
13403 	 * routine.  This will result in an incoherent snapshot.
13404 	 * If the vnode that we hold is a snapshot, we must avoid
13405 	 * handling other resources that could cause deadlock.
13406 	 */
13407 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13408 		return (0);
13409 
13410 	if (resource == FLUSH_BLOCKS_WAIT)
13411 		stat_cleanup_blkrequests += 1;
13412 	else
13413 		stat_cleanup_inorequests += 1;
13414 
13415 	mp = vp->v_mount;
13416 	ump = VFSTOUFS(mp);
13417 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13418 	UFS_UNLOCK(ump);
13419 	error = ffs_update(vp, 1);
13420 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13421 		UFS_LOCK(ump);
13422 		return (0);
13423 	}
13424 	/*
13425 	 * If we are in need of resources, start by cleaning up
13426 	 * any block removals associated with our inode.
13427 	 */
13428 	ACQUIRE_LOCK(ump);
13429 	process_removes(vp);
13430 	process_truncates(vp);
13431 	FREE_LOCK(ump);
13432 	/*
13433 	 * Now clean up at least as many resources as we will need.
13434 	 *
13435 	 * When requested to clean up inodes, the number that are needed
13436 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13437 	 * plus a bit of slop (2) in case some more writers show up while
13438 	 * we are cleaning.
13439 	 *
13440 	 * When requested to free up space, the amount of space that
13441 	 * we need is enough blocks to allocate a full-sized segment
13442 	 * (fs_contigsumsize). The number of such segments that will
13443 	 * be needed is set by the number of simultaneous writers
13444 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13445 	 * writers show up while we are cleaning.
13446 	 *
13447 	 * Additionally, if we are unpriviledged and allocating space,
13448 	 * we need to ensure that we clean up enough blocks to get the
13449 	 * needed number of blocks over the threshold of the minimum
13450 	 * number of blocks required to be kept free by the filesystem
13451 	 * (fs_minfree).
13452 	 */
13453 	if (resource == FLUSH_INODES_WAIT) {
13454 		needed = vfs_mount_fetch_counter(vp->v_mount,
13455 		    MNT_COUNT_WRITEOPCOUNT) + 2;
13456 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13457 		needed = (vfs_mount_fetch_counter(vp->v_mount,
13458 		    MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13459 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13460 			needed += fragstoblks(fs,
13461 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13462 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13463 	} else {
13464 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13465 		    resource);
13466 		UFS_LOCK(ump);
13467 		return (0);
13468 	}
13469 	starttime = time_second;
13470 retry:
13471 	if (resource == FLUSH_BLOCKS_WAIT &&
13472 	    fs->fs_cstotal.cs_nbfree <= needed)
13473 		softdep_send_speedup(ump, needed * fs->fs_bsize,
13474 		    BIO_SPEEDUP_TRIM);
13475 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13476 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13477 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13478 	    fs->fs_cstotal.cs_nifree <= needed)) {
13479 		ACQUIRE_LOCK(ump);
13480 		if (ump->softdep_on_worklist > 0 &&
13481 		    process_worklist_item(UFSTOVFS(ump),
13482 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13483 			stat_worklist_push += 1;
13484 		FREE_LOCK(ump);
13485 	}
13486 	/*
13487 	 * If we still need resources and there are no more worklist
13488 	 * entries to process to obtain them, we have to start flushing
13489 	 * the dirty vnodes to force the release of additional requests
13490 	 * to the worklist that we can then process to reap addition
13491 	 * resources. We walk the vnodes associated with the mount point
13492 	 * until we get the needed worklist requests that we can reap.
13493 	 *
13494 	 * If there are several threads all needing to clean the same
13495 	 * mount point, only one is allowed to walk the mount list.
13496 	 * When several threads all try to walk the same mount list,
13497 	 * they end up competing with each other and often end up in
13498 	 * livelock. This approach ensures that forward progress is
13499 	 * made at the cost of occational ENOSPC errors being returned
13500 	 * that might otherwise have been avoided.
13501 	 */
13502 	error = 1;
13503 	if ((resource == FLUSH_BLOCKS_WAIT &&
13504 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13505 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13506 	     fs->fs_cstotal.cs_nifree <= needed)) {
13507 		ACQUIRE_LOCK(ump);
13508 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13509 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13510 			FREE_LOCK(ump);
13511 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13512 			ACQUIRE_LOCK(ump);
13513 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13514 			FREE_LOCK(ump);
13515 			if (ump->softdep_on_worklist > 0) {
13516 				stat_cleanup_retries += 1;
13517 				if (!failed_vnode)
13518 					goto retry;
13519 			}
13520 		} else {
13521 			FREE_LOCK(ump);
13522 			error = 0;
13523 		}
13524 		stat_cleanup_failures += 1;
13525 	}
13526 	if (time_second - starttime > stat_cleanup_high_delay)
13527 		stat_cleanup_high_delay = time_second - starttime;
13528 	UFS_LOCK(ump);
13529 	return (error);
13530 }
13531 
13532 /*
13533  * Scan the vnodes for the specified mount point flushing out any
13534  * vnodes that can be locked without waiting. Finally, try to flush
13535  * the device associated with the mount point if it can be locked
13536  * without waiting.
13537  *
13538  * We return 0 if we were able to lock every vnode in our scan.
13539  * If we had to skip one or more vnodes, we return 1.
13540  */
13541 static int
13542 softdep_request_cleanup_flush(mp, ump)
13543 	struct mount *mp;
13544 	struct ufsmount *ump;
13545 {
13546 	struct thread *td;
13547 	struct vnode *lvp, *mvp;
13548 	int failed_vnode;
13549 
13550 	failed_vnode = 0;
13551 	td = curthread;
13552 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13553 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13554 			VI_UNLOCK(lvp);
13555 			continue;
13556 		}
13557 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13558 		    td) != 0) {
13559 			failed_vnode = 1;
13560 			continue;
13561 		}
13562 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13563 			vput(lvp);
13564 			continue;
13565 		}
13566 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13567 		vput(lvp);
13568 	}
13569 	lvp = ump->um_devvp;
13570 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13571 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13572 		VOP_UNLOCK(lvp);
13573 	}
13574 	return (failed_vnode);
13575 }
13576 
13577 static bool
13578 softdep_excess_items(struct ufsmount *ump, int item)
13579 {
13580 
13581 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13582 	return (dep_current[item] > max_softdeps &&
13583 	    ump->softdep_curdeps[item] > max_softdeps /
13584 	    stat_flush_threads);
13585 }
13586 
13587 static void
13588 schedule_cleanup(struct mount *mp)
13589 {
13590 	struct ufsmount *ump;
13591 	struct thread *td;
13592 
13593 	ump = VFSTOUFS(mp);
13594 	LOCK_OWNED(ump);
13595 	FREE_LOCK(ump);
13596 	td = curthread;
13597 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13598 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13599 		/*
13600 		 * No ast is delivered to kernel threads, so nobody
13601 		 * would deref the mp.  Some kernel threads
13602 		 * explicitely check for AST, e.g. NFS daemon does
13603 		 * this in the serving loop.
13604 		 */
13605 		return;
13606 	}
13607 	if (td->td_su != NULL)
13608 		vfs_rel(td->td_su);
13609 	vfs_ref(mp);
13610 	td->td_su = mp;
13611 	thread_lock(td);
13612 	td->td_flags |= TDF_ASTPENDING;
13613 	thread_unlock(td);
13614 }
13615 
13616 static void
13617 softdep_ast_cleanup_proc(struct thread *td)
13618 {
13619 	struct mount *mp;
13620 	struct ufsmount *ump;
13621 	int error;
13622 	bool req;
13623 
13624 	while ((mp = td->td_su) != NULL) {
13625 		td->td_su = NULL;
13626 		error = vfs_busy(mp, MBF_NOWAIT);
13627 		vfs_rel(mp);
13628 		if (error != 0)
13629 			return;
13630 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13631 			ump = VFSTOUFS(mp);
13632 			for (;;) {
13633 				req = false;
13634 				ACQUIRE_LOCK(ump);
13635 				if (softdep_excess_items(ump, D_INODEDEP)) {
13636 					req = true;
13637 					request_cleanup(mp, FLUSH_INODES);
13638 				}
13639 				if (softdep_excess_items(ump, D_DIRREM)) {
13640 					req = true;
13641 					request_cleanup(mp, FLUSH_BLOCKS);
13642 				}
13643 				FREE_LOCK(ump);
13644 				if (softdep_excess_items(ump, D_NEWBLK) ||
13645 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13646 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13647 					error = vn_start_write(NULL, &mp,
13648 					    V_WAIT);
13649 					if (error == 0) {
13650 						req = true;
13651 						VFS_SYNC(mp, MNT_WAIT);
13652 						vn_finished_write(mp);
13653 					}
13654 				}
13655 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13656 					break;
13657 			}
13658 		}
13659 		vfs_unbusy(mp);
13660 	}
13661 	if ((mp = td->td_su) != NULL) {
13662 		td->td_su = NULL;
13663 		vfs_rel(mp);
13664 	}
13665 }
13666 
13667 /*
13668  * If memory utilization has gotten too high, deliberately slow things
13669  * down and speed up the I/O processing.
13670  */
13671 static int
13672 request_cleanup(mp, resource)
13673 	struct mount *mp;
13674 	int resource;
13675 {
13676 	struct thread *td = curthread;
13677 	struct ufsmount *ump;
13678 
13679 	ump = VFSTOUFS(mp);
13680 	LOCK_OWNED(ump);
13681 	/*
13682 	 * We never hold up the filesystem syncer or buf daemon.
13683 	 */
13684 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13685 		return (0);
13686 	/*
13687 	 * First check to see if the work list has gotten backlogged.
13688 	 * If it has, co-opt this process to help clean up two entries.
13689 	 * Because this process may hold inodes locked, we cannot
13690 	 * handle any remove requests that might block on a locked
13691 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13692 	 * to avoid recursively processing the worklist.
13693 	 */
13694 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13695 		td->td_pflags |= TDP_SOFTDEP;
13696 		process_worklist_item(mp, 2, LK_NOWAIT);
13697 		td->td_pflags &= ~TDP_SOFTDEP;
13698 		stat_worklist_push += 2;
13699 		return(1);
13700 	}
13701 	/*
13702 	 * Next, we attempt to speed up the syncer process. If that
13703 	 * is successful, then we allow the process to continue.
13704 	 */
13705 	if (softdep_speedup(ump) &&
13706 	    resource != FLUSH_BLOCKS_WAIT &&
13707 	    resource != FLUSH_INODES_WAIT)
13708 		return(0);
13709 	/*
13710 	 * If we are resource constrained on inode dependencies, try
13711 	 * flushing some dirty inodes. Otherwise, we are constrained
13712 	 * by file deletions, so try accelerating flushes of directories
13713 	 * with removal dependencies. We would like to do the cleanup
13714 	 * here, but we probably hold an inode locked at this point and
13715 	 * that might deadlock against one that we try to clean. So,
13716 	 * the best that we can do is request the syncer daemon to do
13717 	 * the cleanup for us.
13718 	 */
13719 	switch (resource) {
13720 
13721 	case FLUSH_INODES:
13722 	case FLUSH_INODES_WAIT:
13723 		ACQUIRE_GBLLOCK(&lk);
13724 		stat_ino_limit_push += 1;
13725 		req_clear_inodedeps += 1;
13726 		FREE_GBLLOCK(&lk);
13727 		stat_countp = &stat_ino_limit_hit;
13728 		break;
13729 
13730 	case FLUSH_BLOCKS:
13731 	case FLUSH_BLOCKS_WAIT:
13732 		ACQUIRE_GBLLOCK(&lk);
13733 		stat_blk_limit_push += 1;
13734 		req_clear_remove += 1;
13735 		FREE_GBLLOCK(&lk);
13736 		stat_countp = &stat_blk_limit_hit;
13737 		break;
13738 
13739 	default:
13740 		panic("request_cleanup: unknown type");
13741 	}
13742 	/*
13743 	 * Hopefully the syncer daemon will catch up and awaken us.
13744 	 * We wait at most tickdelay before proceeding in any case.
13745 	 */
13746 	ACQUIRE_GBLLOCK(&lk);
13747 	FREE_LOCK(ump);
13748 	proc_waiting += 1;
13749 	if (callout_pending(&softdep_callout) == FALSE)
13750 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13751 		    pause_timer, 0);
13752 
13753 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13754 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13755 	proc_waiting -= 1;
13756 	FREE_GBLLOCK(&lk);
13757 	ACQUIRE_LOCK(ump);
13758 	return (1);
13759 }
13760 
13761 /*
13762  * Awaken processes pausing in request_cleanup and clear proc_waiting
13763  * to indicate that there is no longer a timer running. Pause_timer
13764  * will be called with the global softdep mutex (&lk) locked.
13765  */
13766 static void
13767 pause_timer(arg)
13768 	void *arg;
13769 {
13770 
13771 	GBLLOCK_OWNED(&lk);
13772 	/*
13773 	 * The callout_ API has acquired mtx and will hold it around this
13774 	 * function call.
13775 	 */
13776 	*stat_countp += proc_waiting;
13777 	wakeup(&proc_waiting);
13778 }
13779 
13780 /*
13781  * If requested, try removing inode or removal dependencies.
13782  */
13783 static void
13784 check_clear_deps(mp)
13785 	struct mount *mp;
13786 {
13787 	struct ufsmount *ump;
13788 	bool suj_susp;
13789 
13790 	/*
13791 	 * Tell the lower layers that any TRIM or WRITE transactions that have
13792 	 * been delayed for performance reasons should proceed to help alleviate
13793 	 * the shortage faster. The race between checking req_* and the softdep
13794 	 * mutex (lk) is fine since this is an advisory operation that at most
13795 	 * causes deferred work to be done sooner.
13796 	 */
13797 	ump = VFSTOUFS(mp);
13798 	suj_susp = MOUNTEDSUJ(mp) && ump->softdep_jblocks->jb_suspended;
13799 	if (req_clear_remove || req_clear_inodedeps || suj_susp) {
13800 		FREE_LOCK(ump);
13801 		softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
13802 		ACQUIRE_LOCK(ump);
13803 	}
13804 
13805 	/*
13806 	 * If we are suspended, it may be because of our using
13807 	 * too many inodedeps, so help clear them out.
13808 	 */
13809 	if (suj_susp)
13810 		clear_inodedeps(mp);
13811 
13812 	/*
13813 	 * General requests for cleanup of backed up dependencies
13814 	 */
13815 	ACQUIRE_GBLLOCK(&lk);
13816 	if (req_clear_inodedeps) {
13817 		req_clear_inodedeps -= 1;
13818 		FREE_GBLLOCK(&lk);
13819 		clear_inodedeps(mp);
13820 		ACQUIRE_GBLLOCK(&lk);
13821 		wakeup(&proc_waiting);
13822 	}
13823 	if (req_clear_remove) {
13824 		req_clear_remove -= 1;
13825 		FREE_GBLLOCK(&lk);
13826 		clear_remove(mp);
13827 		ACQUIRE_GBLLOCK(&lk);
13828 		wakeup(&proc_waiting);
13829 	}
13830 	FREE_GBLLOCK(&lk);
13831 }
13832 
13833 /*
13834  * Flush out a directory with at least one removal dependency in an effort to
13835  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13836  */
13837 static void
13838 clear_remove(mp)
13839 	struct mount *mp;
13840 {
13841 	struct pagedep_hashhead *pagedephd;
13842 	struct pagedep *pagedep;
13843 	struct ufsmount *ump;
13844 	struct vnode *vp;
13845 	struct bufobj *bo;
13846 	int error, cnt;
13847 	ino_t ino;
13848 
13849 	ump = VFSTOUFS(mp);
13850 	LOCK_OWNED(ump);
13851 
13852 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13853 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13854 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13855 			ump->pagedep_nextclean = 0;
13856 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13857 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13858 				continue;
13859 			ino = pagedep->pd_ino;
13860 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13861 				continue;
13862 			FREE_LOCK(ump);
13863 
13864 			/*
13865 			 * Let unmount clear deps
13866 			 */
13867 			error = vfs_busy(mp, MBF_NOWAIT);
13868 			if (error != 0)
13869 				goto finish_write;
13870 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13871 			     FFSV_FORCEINSMQ);
13872 			vfs_unbusy(mp);
13873 			if (error != 0) {
13874 				softdep_error("clear_remove: vget", error);
13875 				goto finish_write;
13876 			}
13877 			MPASS(VTOI(vp)->i_mode != 0);
13878 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13879 				softdep_error("clear_remove: fsync", error);
13880 			bo = &vp->v_bufobj;
13881 			BO_LOCK(bo);
13882 			drain_output(vp);
13883 			BO_UNLOCK(bo);
13884 			vput(vp);
13885 		finish_write:
13886 			vn_finished_write(mp);
13887 			ACQUIRE_LOCK(ump);
13888 			return;
13889 		}
13890 	}
13891 }
13892 
13893 /*
13894  * Clear out a block of dirty inodes in an effort to reduce
13895  * the number of inodedep dependency structures.
13896  */
13897 static void
13898 clear_inodedeps(mp)
13899 	struct mount *mp;
13900 {
13901 	struct inodedep_hashhead *inodedephd;
13902 	struct inodedep *inodedep;
13903 	struct ufsmount *ump;
13904 	struct vnode *vp;
13905 	struct fs *fs;
13906 	int error, cnt;
13907 	ino_t firstino, lastino, ino;
13908 
13909 	ump = VFSTOUFS(mp);
13910 	fs = ump->um_fs;
13911 	LOCK_OWNED(ump);
13912 	/*
13913 	 * Pick a random inode dependency to be cleared.
13914 	 * We will then gather up all the inodes in its block
13915 	 * that have dependencies and flush them out.
13916 	 */
13917 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13918 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13919 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13920 			ump->inodedep_nextclean = 0;
13921 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13922 			break;
13923 	}
13924 	if (inodedep == NULL)
13925 		return;
13926 	/*
13927 	 * Find the last inode in the block with dependencies.
13928 	 */
13929 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13930 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13931 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13932 			break;
13933 	/*
13934 	 * Asynchronously push all but the last inode with dependencies.
13935 	 * Synchronously push the last inode with dependencies to ensure
13936 	 * that the inode block gets written to free up the inodedeps.
13937 	 */
13938 	for (ino = firstino; ino <= lastino; ino++) {
13939 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13940 			continue;
13941 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13942 			continue;
13943 		FREE_LOCK(ump);
13944 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13945 		if (error != 0) {
13946 			vn_finished_write(mp);
13947 			ACQUIRE_LOCK(ump);
13948 			return;
13949 		}
13950 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13951 		    FFSV_FORCEINSMQ)) != 0) {
13952 			softdep_error("clear_inodedeps: vget", error);
13953 			vfs_unbusy(mp);
13954 			vn_finished_write(mp);
13955 			ACQUIRE_LOCK(ump);
13956 			return;
13957 		}
13958 		vfs_unbusy(mp);
13959 		if (VTOI(vp)->i_mode == 0) {
13960 			vgone(vp);
13961 		} else if (ino == lastino) {
13962 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13963 				softdep_error("clear_inodedeps: fsync1", error);
13964 		} else {
13965 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13966 				softdep_error("clear_inodedeps: fsync2", error);
13967 			BO_LOCK(&vp->v_bufobj);
13968 			drain_output(vp);
13969 			BO_UNLOCK(&vp->v_bufobj);
13970 		}
13971 		vput(vp);
13972 		vn_finished_write(mp);
13973 		ACQUIRE_LOCK(ump);
13974 	}
13975 }
13976 
13977 void
13978 softdep_buf_append(bp, wkhd)
13979 	struct buf *bp;
13980 	struct workhead *wkhd;
13981 {
13982 	struct worklist *wk;
13983 	struct ufsmount *ump;
13984 
13985 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13986 		return;
13987 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13988 	    ("softdep_buf_append called on non-softdep filesystem"));
13989 	ump = VFSTOUFS(wk->wk_mp);
13990 	ACQUIRE_LOCK(ump);
13991 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13992 		WORKLIST_REMOVE(wk);
13993 		WORKLIST_INSERT(&bp->b_dep, wk);
13994 	}
13995 	FREE_LOCK(ump);
13996 
13997 }
13998 
13999 void
14000 softdep_inode_append(ip, cred, wkhd)
14001 	struct inode *ip;
14002 	struct ucred *cred;
14003 	struct workhead *wkhd;
14004 {
14005 	struct buf *bp;
14006 	struct fs *fs;
14007 	struct ufsmount *ump;
14008 	int error;
14009 
14010 	ump = ITOUMP(ip);
14011 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
14012 	    ("softdep_inode_append called on non-softdep filesystem"));
14013 	fs = ump->um_fs;
14014 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14015 	    (int)fs->fs_bsize, cred, &bp);
14016 	if (error) {
14017 		bqrelse(bp);
14018 		softdep_freework(wkhd);
14019 		return;
14020 	}
14021 	softdep_buf_append(bp, wkhd);
14022 	bqrelse(bp);
14023 }
14024 
14025 void
14026 softdep_freework(wkhd)
14027 	struct workhead *wkhd;
14028 {
14029 	struct worklist *wk;
14030 	struct ufsmount *ump;
14031 
14032 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14033 		return;
14034 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14035 	    ("softdep_freework called on non-softdep filesystem"));
14036 	ump = VFSTOUFS(wk->wk_mp);
14037 	ACQUIRE_LOCK(ump);
14038 	handle_jwork(wkhd);
14039 	FREE_LOCK(ump);
14040 }
14041 
14042 static struct ufsmount *
14043 softdep_bp_to_mp(bp)
14044 	struct buf *bp;
14045 {
14046 	struct mount *mp;
14047 	struct vnode *vp;
14048 
14049 	if (LIST_EMPTY(&bp->b_dep))
14050 		return (NULL);
14051 	vp = bp->b_vp;
14052 	KASSERT(vp != NULL,
14053 	    ("%s, buffer with dependencies lacks vnode", __func__));
14054 
14055 	/*
14056 	 * The ump mount point is stable after we get a correct
14057 	 * pointer, since bp is locked and this prevents unmount from
14058 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
14059 	 * head wk_mp, because we do not yet own SU ump lock and
14060 	 * workitem might be freed while dereferenced.
14061 	 */
14062 retry:
14063 	switch (vp->v_type) {
14064 	case VCHR:
14065 		VI_LOCK(vp);
14066 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14067 		VI_UNLOCK(vp);
14068 		if (mp == NULL)
14069 			goto retry;
14070 		break;
14071 	case VREG:
14072 	case VDIR:
14073 	case VLNK:
14074 	case VFIFO:
14075 	case VSOCK:
14076 		mp = vp->v_mount;
14077 		break;
14078 	case VBLK:
14079 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14080 		/* FALLTHROUGH */
14081 	case VNON:
14082 	case VBAD:
14083 	case VMARKER:
14084 		mp = NULL;
14085 		break;
14086 	default:
14087 		vn_printf(vp, "unknown vnode type");
14088 		mp = NULL;
14089 		break;
14090 	}
14091 	return (VFSTOUFS(mp));
14092 }
14093 
14094 /*
14095  * Function to determine if the buffer has outstanding dependencies
14096  * that will cause a roll-back if the buffer is written. If wantcount
14097  * is set, return number of dependencies, otherwise just yes or no.
14098  */
14099 static int
14100 softdep_count_dependencies(bp, wantcount)
14101 	struct buf *bp;
14102 	int wantcount;
14103 {
14104 	struct worklist *wk;
14105 	struct ufsmount *ump;
14106 	struct bmsafemap *bmsafemap;
14107 	struct freework *freework;
14108 	struct inodedep *inodedep;
14109 	struct indirdep *indirdep;
14110 	struct freeblks *freeblks;
14111 	struct allocindir *aip;
14112 	struct pagedep *pagedep;
14113 	struct dirrem *dirrem;
14114 	struct newblk *newblk;
14115 	struct mkdir *mkdir;
14116 	struct diradd *dap;
14117 	int i, retval;
14118 
14119 	ump = softdep_bp_to_mp(bp);
14120 	if (ump == NULL)
14121 		return (0);
14122 	retval = 0;
14123 	ACQUIRE_LOCK(ump);
14124 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14125 		switch (wk->wk_type) {
14126 
14127 		case D_INODEDEP:
14128 			inodedep = WK_INODEDEP(wk);
14129 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14130 				/* bitmap allocation dependency */
14131 				retval += 1;
14132 				if (!wantcount)
14133 					goto out;
14134 			}
14135 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14136 				/* direct block pointer dependency */
14137 				retval += 1;
14138 				if (!wantcount)
14139 					goto out;
14140 			}
14141 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14142 				/* direct block pointer dependency */
14143 				retval += 1;
14144 				if (!wantcount)
14145 					goto out;
14146 			}
14147 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14148 				/* Add reference dependency. */
14149 				retval += 1;
14150 				if (!wantcount)
14151 					goto out;
14152 			}
14153 			continue;
14154 
14155 		case D_INDIRDEP:
14156 			indirdep = WK_INDIRDEP(wk);
14157 
14158 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14159 				/* indirect truncation dependency */
14160 				retval += 1;
14161 				if (!wantcount)
14162 					goto out;
14163 			}
14164 
14165 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14166 				/* indirect block pointer dependency */
14167 				retval += 1;
14168 				if (!wantcount)
14169 					goto out;
14170 			}
14171 			continue;
14172 
14173 		case D_PAGEDEP:
14174 			pagedep = WK_PAGEDEP(wk);
14175 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14176 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14177 					/* Journal remove ref dependency. */
14178 					retval += 1;
14179 					if (!wantcount)
14180 						goto out;
14181 				}
14182 			}
14183 			for (i = 0; i < DAHASHSZ; i++) {
14184 
14185 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14186 					/* directory entry dependency */
14187 					retval += 1;
14188 					if (!wantcount)
14189 						goto out;
14190 				}
14191 			}
14192 			continue;
14193 
14194 		case D_BMSAFEMAP:
14195 			bmsafemap = WK_BMSAFEMAP(wk);
14196 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14197 				/* Add reference dependency. */
14198 				retval += 1;
14199 				if (!wantcount)
14200 					goto out;
14201 			}
14202 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14203 				/* Allocate block dependency. */
14204 				retval += 1;
14205 				if (!wantcount)
14206 					goto out;
14207 			}
14208 			continue;
14209 
14210 		case D_FREEBLKS:
14211 			freeblks = WK_FREEBLKS(wk);
14212 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14213 				/* Freeblk journal dependency. */
14214 				retval += 1;
14215 				if (!wantcount)
14216 					goto out;
14217 			}
14218 			continue;
14219 
14220 		case D_ALLOCDIRECT:
14221 		case D_ALLOCINDIR:
14222 			newblk = WK_NEWBLK(wk);
14223 			if (newblk->nb_jnewblk) {
14224 				/* Journal allocate dependency. */
14225 				retval += 1;
14226 				if (!wantcount)
14227 					goto out;
14228 			}
14229 			continue;
14230 
14231 		case D_MKDIR:
14232 			mkdir = WK_MKDIR(wk);
14233 			if (mkdir->md_jaddref) {
14234 				/* Journal reference dependency. */
14235 				retval += 1;
14236 				if (!wantcount)
14237 					goto out;
14238 			}
14239 			continue;
14240 
14241 		case D_FREEWORK:
14242 		case D_FREEDEP:
14243 		case D_JSEGDEP:
14244 		case D_JSEG:
14245 		case D_SBDEP:
14246 			/* never a dependency on these blocks */
14247 			continue;
14248 
14249 		default:
14250 			panic("softdep_count_dependencies: Unexpected type %s",
14251 			    TYPENAME(wk->wk_type));
14252 			/* NOTREACHED */
14253 		}
14254 	}
14255 out:
14256 	FREE_LOCK(ump);
14257 	return (retval);
14258 }
14259 
14260 /*
14261  * Acquire exclusive access to a buffer.
14262  * Must be called with a locked mtx parameter.
14263  * Return acquired buffer or NULL on failure.
14264  */
14265 static struct buf *
14266 getdirtybuf(bp, lock, waitfor)
14267 	struct buf *bp;
14268 	struct rwlock *lock;
14269 	int waitfor;
14270 {
14271 	int error;
14272 
14273 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14274 		if (waitfor != MNT_WAIT)
14275 			return (NULL);
14276 		error = BUF_LOCK(bp,
14277 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14278 		/*
14279 		 * Even if we successfully acquire bp here, we have dropped
14280 		 * lock, which may violates our guarantee.
14281 		 */
14282 		if (error == 0)
14283 			BUF_UNLOCK(bp);
14284 		else if (error != ENOLCK)
14285 			panic("getdirtybuf: inconsistent lock: %d", error);
14286 		rw_wlock(lock);
14287 		return (NULL);
14288 	}
14289 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14290 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14291 			rw_wunlock(lock);
14292 			BO_LOCK(bp->b_bufobj);
14293 			BUF_UNLOCK(bp);
14294 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14295 				bp->b_vflags |= BV_BKGRDWAIT;
14296 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14297 				       PRIBIO | PDROP, "getbuf", 0);
14298 			} else
14299 				BO_UNLOCK(bp->b_bufobj);
14300 			rw_wlock(lock);
14301 			return (NULL);
14302 		}
14303 		BUF_UNLOCK(bp);
14304 		if (waitfor != MNT_WAIT)
14305 			return (NULL);
14306 #ifdef DEBUG_VFS_LOCKS
14307 		if (bp->b_vp->v_type != VCHR)
14308 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14309 #endif
14310 		bp->b_vflags |= BV_BKGRDWAIT;
14311 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14312 		return (NULL);
14313 	}
14314 	if ((bp->b_flags & B_DELWRI) == 0) {
14315 		BUF_UNLOCK(bp);
14316 		return (NULL);
14317 	}
14318 	bremfree(bp);
14319 	return (bp);
14320 }
14321 
14322 
14323 /*
14324  * Check if it is safe to suspend the file system now.  On entry,
14325  * the vnode interlock for devvp should be held.  Return 0 with
14326  * the mount interlock held if the file system can be suspended now,
14327  * otherwise return EAGAIN with the mount interlock held.
14328  */
14329 int
14330 softdep_check_suspend(struct mount *mp,
14331 		      struct vnode *devvp,
14332 		      int softdep_depcnt,
14333 		      int softdep_accdepcnt,
14334 		      int secondary_writes,
14335 		      int secondary_accwrites)
14336 {
14337 	struct bufobj *bo;
14338 	struct ufsmount *ump;
14339 	struct inodedep *inodedep;
14340 	int error, unlinked;
14341 
14342 	bo = &devvp->v_bufobj;
14343 	ASSERT_BO_WLOCKED(bo);
14344 
14345 	/*
14346 	 * If we are not running with soft updates, then we need only
14347 	 * deal with secondary writes as we try to suspend.
14348 	 */
14349 	if (MOUNTEDSOFTDEP(mp) == 0) {
14350 		MNT_ILOCK(mp);
14351 		while (mp->mnt_secondary_writes != 0) {
14352 			BO_UNLOCK(bo);
14353 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14354 			    (PUSER - 1) | PDROP, "secwr", 0);
14355 			BO_LOCK(bo);
14356 			MNT_ILOCK(mp);
14357 		}
14358 
14359 		/*
14360 		 * Reasons for needing more work before suspend:
14361 		 * - Dirty buffers on devvp.
14362 		 * - Secondary writes occurred after start of vnode sync loop
14363 		 */
14364 		error = 0;
14365 		if (bo->bo_numoutput > 0 ||
14366 		    bo->bo_dirty.bv_cnt > 0 ||
14367 		    secondary_writes != 0 ||
14368 		    mp->mnt_secondary_writes != 0 ||
14369 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14370 			error = EAGAIN;
14371 		BO_UNLOCK(bo);
14372 		return (error);
14373 	}
14374 
14375 	/*
14376 	 * If we are running with soft updates, then we need to coordinate
14377 	 * with them as we try to suspend.
14378 	 */
14379 	ump = VFSTOUFS(mp);
14380 	for (;;) {
14381 		if (!TRY_ACQUIRE_LOCK(ump)) {
14382 			BO_UNLOCK(bo);
14383 			ACQUIRE_LOCK(ump);
14384 			FREE_LOCK(ump);
14385 			BO_LOCK(bo);
14386 			continue;
14387 		}
14388 		MNT_ILOCK(mp);
14389 		if (mp->mnt_secondary_writes != 0) {
14390 			FREE_LOCK(ump);
14391 			BO_UNLOCK(bo);
14392 			msleep(&mp->mnt_secondary_writes,
14393 			       MNT_MTX(mp),
14394 			       (PUSER - 1) | PDROP, "secwr", 0);
14395 			BO_LOCK(bo);
14396 			continue;
14397 		}
14398 		break;
14399 	}
14400 
14401 	unlinked = 0;
14402 	if (MOUNTEDSUJ(mp)) {
14403 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14404 		    inodedep != NULL;
14405 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14406 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14407 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14408 			    UNLINKONLIST) ||
14409 			    !check_inodedep_free(inodedep))
14410 				continue;
14411 			unlinked++;
14412 		}
14413 	}
14414 
14415 	/*
14416 	 * Reasons for needing more work before suspend:
14417 	 * - Dirty buffers on devvp.
14418 	 * - Softdep activity occurred after start of vnode sync loop
14419 	 * - Secondary writes occurred after start of vnode sync loop
14420 	 */
14421 	error = 0;
14422 	if (bo->bo_numoutput > 0 ||
14423 	    bo->bo_dirty.bv_cnt > 0 ||
14424 	    softdep_depcnt != unlinked ||
14425 	    ump->softdep_deps != unlinked ||
14426 	    softdep_accdepcnt != ump->softdep_accdeps ||
14427 	    secondary_writes != 0 ||
14428 	    mp->mnt_secondary_writes != 0 ||
14429 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14430 		error = EAGAIN;
14431 	FREE_LOCK(ump);
14432 	BO_UNLOCK(bo);
14433 	return (error);
14434 }
14435 
14436 
14437 /*
14438  * Get the number of dependency structures for the file system, both
14439  * the current number and the total number allocated.  These will
14440  * later be used to detect that softdep processing has occurred.
14441  */
14442 void
14443 softdep_get_depcounts(struct mount *mp,
14444 		      int *softdep_depsp,
14445 		      int *softdep_accdepsp)
14446 {
14447 	struct ufsmount *ump;
14448 
14449 	if (MOUNTEDSOFTDEP(mp) == 0) {
14450 		*softdep_depsp = 0;
14451 		*softdep_accdepsp = 0;
14452 		return;
14453 	}
14454 	ump = VFSTOUFS(mp);
14455 	ACQUIRE_LOCK(ump);
14456 	*softdep_depsp = ump->softdep_deps;
14457 	*softdep_accdepsp = ump->softdep_accdeps;
14458 	FREE_LOCK(ump);
14459 }
14460 
14461 /*
14462  * Wait for pending output on a vnode to complete.
14463  */
14464 static void
14465 drain_output(vp)
14466 	struct vnode *vp;
14467 {
14468 
14469 	ASSERT_VOP_LOCKED(vp, "drain_output");
14470 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14471 }
14472 
14473 /*
14474  * Called whenever a buffer that is being invalidated or reallocated
14475  * contains dependencies. This should only happen if an I/O error has
14476  * occurred. The routine is called with the buffer locked.
14477  */
14478 static void
14479 softdep_deallocate_dependencies(bp)
14480 	struct buf *bp;
14481 {
14482 
14483 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14484 		panic("softdep_deallocate_dependencies: dangling deps");
14485 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14486 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14487 	else
14488 		printf("softdep_deallocate_dependencies: "
14489 		    "got error %d while accessing filesystem\n", bp->b_error);
14490 	if (bp->b_error != ENXIO)
14491 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14492 }
14493 
14494 /*
14495  * Function to handle asynchronous write errors in the filesystem.
14496  */
14497 static void
14498 softdep_error(func, error)
14499 	char *func;
14500 	int error;
14501 {
14502 
14503 	/* XXX should do something better! */
14504 	printf("%s: got error %d while accessing filesystem\n", func, error);
14505 }
14506 
14507 #ifdef DDB
14508 
14509 /* exported to ffs_vfsops.c */
14510 extern void db_print_ffs(struct ufsmount *ump);
14511 void
14512 db_print_ffs(struct ufsmount *ump)
14513 {
14514 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14515 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14516 	db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14517 	    ump->um_fs, ump->softdep_on_worklist,
14518 	    ump->softdep_deps, ump->softdep_req);
14519 }
14520 
14521 static void
14522 worklist_print(struct worklist *wk, int verbose)
14523 {
14524 
14525 	if (!verbose) {
14526 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14527 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14528 		return;
14529 	}
14530 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14531 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14532 	    LIST_NEXT(wk, wk_list));
14533 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14534 }
14535 
14536 static void
14537 inodedep_print(struct inodedep *inodedep, int verbose)
14538 {
14539 
14540 	worklist_print(&inodedep->id_list, 0);
14541 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14542 	    inodedep->id_fs,
14543 	    (intmax_t)inodedep->id_ino,
14544 	    (intmax_t)fsbtodb(inodedep->id_fs,
14545 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14546 	    (intmax_t)inodedep->id_nlinkdelta,
14547 	    (intmax_t)inodedep->id_savednlink);
14548 
14549 	if (verbose == 0)
14550 		return;
14551 
14552 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14553 	    inodedep->id_bmsafemap,
14554 	    inodedep->id_mkdiradd,
14555 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14556 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14557 	    LIST_FIRST(&inodedep->id_dirremhd),
14558 	    LIST_FIRST(&inodedep->id_pendinghd),
14559 	    LIST_FIRST(&inodedep->id_bufwait));
14560 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14561 	    LIST_FIRST(&inodedep->id_inowait),
14562 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14563 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14564 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14565 	    TAILQ_FIRST(&inodedep->id_extupdt),
14566 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14567 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14568 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14569 	    inodedep->id_savedino1,
14570 	    (intmax_t)inodedep->id_savedsize,
14571 	    (intmax_t)inodedep->id_savedextsize);
14572 }
14573 
14574 static void
14575 newblk_print(struct newblk *nbp)
14576 {
14577 
14578 	worklist_print(&nbp->nb_list, 0);
14579 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14580 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14581 	    &nbp->nb_jnewblk,
14582 	    &nbp->nb_bmsafemap,
14583 	    &nbp->nb_freefrag);
14584 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14585 	    LIST_FIRST(&nbp->nb_indirdeps),
14586 	    LIST_FIRST(&nbp->nb_newdirblk),
14587 	    LIST_FIRST(&nbp->nb_jwork));
14588 }
14589 
14590 static void
14591 allocdirect_print(struct allocdirect *adp)
14592 {
14593 
14594 	newblk_print(&adp->ad_block);
14595 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14596 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14597 	db_printf("    offset %d, inodedep %p\n",
14598 	    adp->ad_offset, adp->ad_inodedep);
14599 }
14600 
14601 static void
14602 allocindir_print(struct allocindir *aip)
14603 {
14604 
14605 	newblk_print(&aip->ai_block);
14606 	db_printf("    oldblkno %jd, lbn %jd\n",
14607 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14608 	db_printf("    offset %d, indirdep %p\n",
14609 	    aip->ai_offset, aip->ai_indirdep);
14610 }
14611 
14612 static void
14613 mkdir_print(struct mkdir *mkdir)
14614 {
14615 
14616 	worklist_print(&mkdir->md_list, 0);
14617 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14618 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14619 }
14620 
14621 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14622 {
14623 
14624 	if (have_addr == 0) {
14625 		db_printf("inodedep address required\n");
14626 		return;
14627 	}
14628 	inodedep_print((struct inodedep*)addr, 1);
14629 }
14630 
14631 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14632 {
14633 	struct inodedep_hashhead *inodedephd;
14634 	struct inodedep *inodedep;
14635 	struct ufsmount *ump;
14636 	int cnt;
14637 
14638 	if (have_addr == 0) {
14639 		db_printf("ufsmount address required\n");
14640 		return;
14641 	}
14642 	ump = (struct ufsmount *)addr;
14643 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14644 		inodedephd = &ump->inodedep_hashtbl[cnt];
14645 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14646 			inodedep_print(inodedep, 0);
14647 		}
14648 	}
14649 }
14650 
14651 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14652 {
14653 
14654 	if (have_addr == 0) {
14655 		db_printf("worklist address required\n");
14656 		return;
14657 	}
14658 	worklist_print((struct worklist *)addr, 1);
14659 }
14660 
14661 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14662 {
14663 	struct worklist *wk;
14664 	struct workhead *wkhd;
14665 
14666 	if (have_addr == 0) {
14667 		db_printf("worklist address required "
14668 		    "(for example value in bp->b_dep)\n");
14669 		return;
14670 	}
14671 	/*
14672 	 * We often do not have the address of the worklist head but
14673 	 * instead a pointer to its first entry (e.g., we have the
14674 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
14675 	 * pointer of bp->b_dep will point at the head of the list, so
14676 	 * we cheat and use that instead. If we are in the middle of
14677 	 * a list we will still get the same result, so nothing
14678 	 * unexpected will result.
14679 	 */
14680 	wk = (struct worklist *)addr;
14681 	if (wk == NULL)
14682 		return;
14683 	wkhd = (struct workhead *)wk->wk_list.le_prev;
14684 	LIST_FOREACH(wk, wkhd, wk_list) {
14685 		switch(wk->wk_type) {
14686 		case D_INODEDEP:
14687 			inodedep_print(WK_INODEDEP(wk), 0);
14688 			continue;
14689 		case D_ALLOCDIRECT:
14690 			allocdirect_print(WK_ALLOCDIRECT(wk));
14691 			continue;
14692 		case D_ALLOCINDIR:
14693 			allocindir_print(WK_ALLOCINDIR(wk));
14694 			continue;
14695 		case D_MKDIR:
14696 			mkdir_print(WK_MKDIR(wk));
14697 			continue;
14698 		default:
14699 			worklist_print(wk, 0);
14700 			continue;
14701 		}
14702 	}
14703 }
14704 
14705 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14706 {
14707 	if (have_addr == 0) {
14708 		db_printf("mkdir address required\n");
14709 		return;
14710 	}
14711 	mkdir_print((struct mkdir *)addr);
14712 }
14713 
14714 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14715 {
14716 	struct mkdirlist *mkdirlisthd;
14717 	struct mkdir *mkdir;
14718 
14719 	if (have_addr == 0) {
14720 		db_printf("mkdir listhead address required\n");
14721 		return;
14722 	}
14723 	mkdirlisthd = (struct mkdirlist *)addr;
14724 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14725 		mkdir_print(mkdir);
14726 		if (mkdir->md_diradd != NULL) {
14727 			db_printf("    ");
14728 			worklist_print(&mkdir->md_diradd->da_list, 0);
14729 		}
14730 		if (mkdir->md_jaddref != NULL) {
14731 			db_printf("    ");
14732 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
14733 		}
14734 	}
14735 }
14736 
14737 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
14738 {
14739 	if (have_addr == 0) {
14740 		db_printf("allocdirect address required\n");
14741 		return;
14742 	}
14743 	allocdirect_print((struct allocdirect *)addr);
14744 }
14745 
14746 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
14747 {
14748 	if (have_addr == 0) {
14749 		db_printf("allocindir address required\n");
14750 		return;
14751 	}
14752 	allocindir_print((struct allocindir *)addr);
14753 }
14754 
14755 #endif /* DDB */
14756 
14757 #endif /* SOFTUPDATES */
14758