xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 0bd5d367989b3d2de0e8d8ceaa2e31d3f0d96536)
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 
91 #include <ddb/ddb.h>
92 
93 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
94 
95 #ifndef SOFTUPDATES
96 
97 int
98 softdep_flushfiles(oldmnt, flags, td)
99 	struct mount *oldmnt;
100 	int flags;
101 	struct thread *td;
102 {
103 
104 	panic("softdep_flushfiles called");
105 }
106 
107 int
108 softdep_mount(devvp, mp, fs, cred)
109 	struct vnode *devvp;
110 	struct mount *mp;
111 	struct fs *fs;
112 	struct ucred *cred;
113 {
114 
115 	return (0);
116 }
117 
118 void
119 softdep_initialize()
120 {
121 
122 	return;
123 }
124 
125 void
126 softdep_uninitialize()
127 {
128 
129 	return;
130 }
131 
132 void
133 softdep_unmount(mp)
134 	struct mount *mp;
135 {
136 
137 	panic("softdep_unmount called");
138 }
139 
140 void
141 softdep_setup_sbupdate(ump, fs, bp)
142 	struct ufsmount *ump;
143 	struct fs *fs;
144 	struct buf *bp;
145 {
146 
147 	panic("softdep_setup_sbupdate called");
148 }
149 
150 void
151 softdep_setup_inomapdep(bp, ip, newinum, mode)
152 	struct buf *bp;
153 	struct inode *ip;
154 	ino_t newinum;
155 	int mode;
156 {
157 
158 	panic("softdep_setup_inomapdep called");
159 }
160 
161 void
162 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
163 	struct buf *bp;
164 	struct mount *mp;
165 	ufs2_daddr_t newblkno;
166 	int frags;
167 	int oldfrags;
168 {
169 
170 	panic("softdep_setup_blkmapdep called");
171 }
172 
173 void
174 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
175 	struct inode *ip;
176 	ufs_lbn_t lbn;
177 	ufs2_daddr_t newblkno;
178 	ufs2_daddr_t oldblkno;
179 	long newsize;
180 	long oldsize;
181 	struct buf *bp;
182 {
183 
184 	panic("softdep_setup_allocdirect called");
185 }
186 
187 void
188 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
189 	struct inode *ip;
190 	ufs_lbn_t lbn;
191 	ufs2_daddr_t newblkno;
192 	ufs2_daddr_t oldblkno;
193 	long newsize;
194 	long oldsize;
195 	struct buf *bp;
196 {
197 
198 	panic("softdep_setup_allocext called");
199 }
200 
201 void
202 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
203 	struct inode *ip;
204 	ufs_lbn_t lbn;
205 	struct buf *bp;
206 	int ptrno;
207 	ufs2_daddr_t newblkno;
208 	ufs2_daddr_t oldblkno;
209 	struct buf *nbp;
210 {
211 
212 	panic("softdep_setup_allocindir_page called");
213 }
214 
215 void
216 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
217 	struct buf *nbp;
218 	struct inode *ip;
219 	struct buf *bp;
220 	int ptrno;
221 	ufs2_daddr_t newblkno;
222 {
223 
224 	panic("softdep_setup_allocindir_meta called");
225 }
226 
227 void
228 softdep_journal_freeblocks(ip, cred, length, flags)
229 	struct inode *ip;
230 	struct ucred *cred;
231 	off_t length;
232 	int flags;
233 {
234 
235 	panic("softdep_journal_freeblocks called");
236 }
237 
238 void
239 softdep_journal_fsync(ip)
240 	struct inode *ip;
241 {
242 
243 	panic("softdep_journal_fsync called");
244 }
245 
246 void
247 softdep_setup_freeblocks(ip, length, flags)
248 	struct inode *ip;
249 	off_t length;
250 	int flags;
251 {
252 
253 	panic("softdep_setup_freeblocks called");
254 }
255 
256 void
257 softdep_freefile(pvp, ino, mode)
258 		struct vnode *pvp;
259 		ino_t ino;
260 		int mode;
261 {
262 
263 	panic("softdep_freefile called");
264 }
265 
266 int
267 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
268 	struct buf *bp;
269 	struct inode *dp;
270 	off_t diroffset;
271 	ino_t newinum;
272 	struct buf *newdirbp;
273 	int isnewblk;
274 {
275 
276 	panic("softdep_setup_directory_add called");
277 }
278 
279 void
280 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
281 	struct buf *bp;
282 	struct inode *dp;
283 	caddr_t base;
284 	caddr_t oldloc;
285 	caddr_t newloc;
286 	int entrysize;
287 {
288 
289 	panic("softdep_change_directoryentry_offset called");
290 }
291 
292 void
293 softdep_setup_remove(bp, dp, ip, isrmdir)
294 	struct buf *bp;
295 	struct inode *dp;
296 	struct inode *ip;
297 	int isrmdir;
298 {
299 
300 	panic("softdep_setup_remove called");
301 }
302 
303 void
304 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
305 	struct buf *bp;
306 	struct inode *dp;
307 	struct inode *ip;
308 	ino_t newinum;
309 	int isrmdir;
310 {
311 
312 	panic("softdep_setup_directory_change called");
313 }
314 
315 void
316 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
317 	struct mount *mp;
318 	struct buf *bp;
319 	ufs2_daddr_t blkno;
320 	int frags;
321 	struct workhead *wkhd;
322 {
323 
324 	panic("%s called", __FUNCTION__);
325 }
326 
327 void
328 softdep_setup_inofree(mp, bp, ino, wkhd)
329 	struct mount *mp;
330 	struct buf *bp;
331 	ino_t ino;
332 	struct workhead *wkhd;
333 {
334 
335 	panic("%s called", __FUNCTION__);
336 }
337 
338 void
339 softdep_setup_unlink(dp, ip)
340 	struct inode *dp;
341 	struct inode *ip;
342 {
343 
344 	panic("%s called", __FUNCTION__);
345 }
346 
347 void
348 softdep_setup_link(dp, ip)
349 	struct inode *dp;
350 	struct inode *ip;
351 {
352 
353 	panic("%s called", __FUNCTION__);
354 }
355 
356 void
357 softdep_revert_link(dp, ip)
358 	struct inode *dp;
359 	struct inode *ip;
360 {
361 
362 	panic("%s called", __FUNCTION__);
363 }
364 
365 void
366 softdep_setup_rmdir(dp, ip)
367 	struct inode *dp;
368 	struct inode *ip;
369 {
370 
371 	panic("%s called", __FUNCTION__);
372 }
373 
374 void
375 softdep_revert_rmdir(dp, ip)
376 	struct inode *dp;
377 	struct inode *ip;
378 {
379 
380 	panic("%s called", __FUNCTION__);
381 }
382 
383 void
384 softdep_setup_create(dp, ip)
385 	struct inode *dp;
386 	struct inode *ip;
387 {
388 
389 	panic("%s called", __FUNCTION__);
390 }
391 
392 void
393 softdep_revert_create(dp, ip)
394 	struct inode *dp;
395 	struct inode *ip;
396 {
397 
398 	panic("%s called", __FUNCTION__);
399 }
400 
401 void
402 softdep_setup_mkdir(dp, ip)
403 	struct inode *dp;
404 	struct inode *ip;
405 {
406 
407 	panic("%s called", __FUNCTION__);
408 }
409 
410 void
411 softdep_revert_mkdir(dp, ip)
412 	struct inode *dp;
413 	struct inode *ip;
414 {
415 
416 	panic("%s called", __FUNCTION__);
417 }
418 
419 void
420 softdep_setup_dotdot_link(dp, ip)
421 	struct inode *dp;
422 	struct inode *ip;
423 {
424 
425 	panic("%s called", __FUNCTION__);
426 }
427 
428 int
429 softdep_prealloc(vp, waitok)
430 	struct vnode *vp;
431 	int waitok;
432 {
433 
434 	panic("%s called", __FUNCTION__);
435 }
436 
437 int
438 softdep_journal_lookup(mp, vpp)
439 	struct mount *mp;
440 	struct vnode **vpp;
441 {
442 
443 	return (ENOENT);
444 }
445 
446 void
447 softdep_change_linkcnt(ip)
448 	struct inode *ip;
449 {
450 
451 	panic("softdep_change_linkcnt called");
452 }
453 
454 void
455 softdep_load_inodeblock(ip)
456 	struct inode *ip;
457 {
458 
459 	panic("softdep_load_inodeblock called");
460 }
461 
462 void
463 softdep_update_inodeblock(ip, bp, waitfor)
464 	struct inode *ip;
465 	struct buf *bp;
466 	int waitfor;
467 {
468 
469 	panic("softdep_update_inodeblock called");
470 }
471 
472 int
473 softdep_fsync(vp)
474 	struct vnode *vp;	/* the "in_core" copy of the inode */
475 {
476 
477 	return (0);
478 }
479 
480 void
481 softdep_fsync_mountdev(vp)
482 	struct vnode *vp;
483 {
484 
485 	return;
486 }
487 
488 int
489 softdep_flushworklist(oldmnt, countp, td)
490 	struct mount *oldmnt;
491 	int *countp;
492 	struct thread *td;
493 {
494 
495 	*countp = 0;
496 	return (0);
497 }
498 
499 int
500 softdep_sync_metadata(struct vnode *vp)
501 {
502 
503 	panic("softdep_sync_metadata called");
504 }
505 
506 int
507 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
508 {
509 
510 	panic("softdep_sync_buf called");
511 }
512 
513 int
514 softdep_slowdown(vp)
515 	struct vnode *vp;
516 {
517 
518 	panic("softdep_slowdown called");
519 }
520 
521 int
522 softdep_request_cleanup(fs, vp, cred, resource)
523 	struct fs *fs;
524 	struct vnode *vp;
525 	struct ucred *cred;
526 	int resource;
527 {
528 
529 	return (0);
530 }
531 
532 int
533 softdep_check_suspend(struct mount *mp,
534 		      struct vnode *devvp,
535 		      int softdep_depcnt,
536 		      int softdep_accdepcnt,
537 		      int secondary_writes,
538 		      int secondary_accwrites)
539 {
540 	struct bufobj *bo;
541 	int error;
542 
543 	(void) softdep_depcnt,
544 	(void) softdep_accdepcnt;
545 
546 	bo = &devvp->v_bufobj;
547 	ASSERT_BO_WLOCKED(bo);
548 
549 	MNT_ILOCK(mp);
550 	while (mp->mnt_secondary_writes != 0) {
551 		BO_UNLOCK(bo);
552 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
553 		    (PUSER - 1) | PDROP, "secwr", 0);
554 		BO_LOCK(bo);
555 		MNT_ILOCK(mp);
556 	}
557 
558 	/*
559 	 * Reasons for needing more work before suspend:
560 	 * - Dirty buffers on devvp.
561 	 * - Secondary writes occurred after start of vnode sync loop
562 	 */
563 	error = 0;
564 	if (bo->bo_numoutput > 0 ||
565 	    bo->bo_dirty.bv_cnt > 0 ||
566 	    secondary_writes != 0 ||
567 	    mp->mnt_secondary_writes != 0 ||
568 	    secondary_accwrites != mp->mnt_secondary_accwrites)
569 		error = EAGAIN;
570 	BO_UNLOCK(bo);
571 	return (error);
572 }
573 
574 void
575 softdep_get_depcounts(struct mount *mp,
576 		      int *softdepactivep,
577 		      int *softdepactiveaccp)
578 {
579 	(void) mp;
580 	*softdepactivep = 0;
581 	*softdepactiveaccp = 0;
582 }
583 
584 void
585 softdep_buf_append(bp, wkhd)
586 	struct buf *bp;
587 	struct workhead *wkhd;
588 {
589 
590 	panic("softdep_buf_appendwork called");
591 }
592 
593 void
594 softdep_inode_append(ip, cred, wkhd)
595 	struct inode *ip;
596 	struct ucred *cred;
597 	struct workhead *wkhd;
598 {
599 
600 	panic("softdep_inode_appendwork called");
601 }
602 
603 void
604 softdep_freework(wkhd)
605 	struct workhead *wkhd;
606 {
607 
608 	panic("softdep_freework called");
609 }
610 
611 #else
612 
613 FEATURE(softupdates, "FFS soft-updates support");
614 
615 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
616     "soft updates stats");
617 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
618     "total dependencies allocated");
619 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
620     "high use dependencies allocated");
621 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
622     "current dependencies allocated");
623 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
624     "current dependencies written");
625 
626 unsigned long dep_current[D_LAST + 1];
627 unsigned long dep_highuse[D_LAST + 1];
628 unsigned long dep_total[D_LAST + 1];
629 unsigned long dep_write[D_LAST + 1];
630 
631 #define	SOFTDEP_TYPE(type, str, long)					\
632     static MALLOC_DEFINE(M_ ## type, #str, long);			\
633     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
634 	&dep_total[D_ ## type], 0, "");					\
635     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
636 	&dep_current[D_ ## type], 0, "");				\
637     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
638 	&dep_highuse[D_ ## type], 0, "");				\
639     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
640 	&dep_write[D_ ## type], 0, "");
641 
642 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
643 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
644 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
645     "Block or frag allocated from cyl group map");
646 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
647 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
648 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
649 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
650 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
651 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
652 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
653 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
654 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
655 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
656 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
657 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
658 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
659 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
660 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
661 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
662 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
663 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
664 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
665 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
666 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
667 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
668 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
669 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
670 
671 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
672 
673 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
674 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
675 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
676 
677 #define M_SOFTDEP_FLAGS	(M_WAITOK)
678 
679 /*
680  * translate from workitem type to memory type
681  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
682  */
683 static struct malloc_type *memtype[] = {
684 	NULL,
685 	M_PAGEDEP,
686 	M_INODEDEP,
687 	M_BMSAFEMAP,
688 	M_NEWBLK,
689 	M_ALLOCDIRECT,
690 	M_INDIRDEP,
691 	M_ALLOCINDIR,
692 	M_FREEFRAG,
693 	M_FREEBLKS,
694 	M_FREEFILE,
695 	M_DIRADD,
696 	M_MKDIR,
697 	M_DIRREM,
698 	M_NEWDIRBLK,
699 	M_FREEWORK,
700 	M_FREEDEP,
701 	M_JADDREF,
702 	M_JREMREF,
703 	M_JMVREF,
704 	M_JNEWBLK,
705 	M_JFREEBLK,
706 	M_JFREEFRAG,
707 	M_JSEG,
708 	M_JSEGDEP,
709 	M_SBDEP,
710 	M_JTRUNC,
711 	M_JFSYNC,
712 	M_SENTINEL
713 };
714 
715 #define DtoM(type) (memtype[type])
716 
717 /*
718  * Names of malloc types.
719  */
720 #define TYPENAME(type)  \
721 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
722 	memtype[type]->ks_shortdesc : "???")
723 /*
724  * End system adaptation definitions.
725  */
726 
727 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
728 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
729 
730 /*
731  * Internal function prototypes.
732  */
733 static	void check_clear_deps(struct mount *);
734 static	void softdep_error(char *, int);
735 static	int softdep_process_worklist(struct mount *, int);
736 static	int softdep_waitidle(struct mount *, int);
737 static	void drain_output(struct vnode *);
738 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
739 static	int check_inodedep_free(struct inodedep *);
740 static	void clear_remove(struct mount *);
741 static	void clear_inodedeps(struct mount *);
742 static	void unlinked_inodedep(struct mount *, struct inodedep *);
743 static	void clear_unlinked_inodedep(struct inodedep *);
744 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
745 static	int flush_pagedep_deps(struct vnode *, struct mount *,
746 	    struct diraddhd *);
747 static	int free_pagedep(struct pagedep *);
748 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
749 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
750 static	int flush_deplist(struct allocdirectlst *, int, int *);
751 static	int sync_cgs(struct mount *, int);
752 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
753 static	int handle_written_sbdep(struct sbdep *, struct buf *);
754 static	void initiate_write_sbdep(struct sbdep *);
755 static	void diradd_inode_written(struct diradd *, struct inodedep *);
756 static	int handle_written_indirdep(struct indirdep *, struct buf *,
757 	    struct buf**, int);
758 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
759 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
760 	    uint8_t *);
761 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
762 static	void handle_written_jaddref(struct jaddref *);
763 static	void handle_written_jremref(struct jremref *);
764 static	void handle_written_jseg(struct jseg *, struct buf *);
765 static	void handle_written_jnewblk(struct jnewblk *);
766 static	void handle_written_jblkdep(struct jblkdep *);
767 static	void handle_written_jfreefrag(struct jfreefrag *);
768 static	void complete_jseg(struct jseg *);
769 static	void complete_jsegs(struct jseg *);
770 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
771 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
772 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
773 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
774 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
775 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
776 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
777 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
778 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
779 static	inline void inoref_write(struct inoref *, struct jseg *,
780 	    struct jrefrec *);
781 static	void handle_allocdirect_partdone(struct allocdirect *,
782 	    struct workhead *);
783 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
784 	    struct workhead *);
785 static	void indirdep_complete(struct indirdep *);
786 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
787 static	void indirblk_insert(struct freework *);
788 static	void indirblk_remove(struct freework *);
789 static	void handle_allocindir_partdone(struct allocindir *);
790 static	void initiate_write_filepage(struct pagedep *, struct buf *);
791 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
792 static	void handle_written_mkdir(struct mkdir *, int);
793 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
794 	    uint8_t *);
795 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
796 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
797 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
798 static	void handle_workitem_freefile(struct freefile *);
799 static	int handle_workitem_remove(struct dirrem *, int);
800 static	struct dirrem *newdirrem(struct buf *, struct inode *,
801 	    struct inode *, int, struct dirrem **);
802 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
803 	    struct buf *);
804 static	void cancel_indirdep(struct indirdep *, struct buf *,
805 	    struct freeblks *);
806 static	void free_indirdep(struct indirdep *);
807 static	void free_diradd(struct diradd *, struct workhead *);
808 static	void merge_diradd(struct inodedep *, struct diradd *);
809 static	void complete_diradd(struct diradd *);
810 static	struct diradd *diradd_lookup(struct pagedep *, int);
811 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
812 	    struct jremref *);
813 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
814 	    struct jremref *);
815 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
816 	    struct jremref *, struct jremref *);
817 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
818 	    struct jremref *);
819 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
820 	    struct freeblks *, int);
821 static	int setup_trunc_indir(struct freeblks *, struct inode *,
822 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
823 static	void complete_trunc_indir(struct freework *);
824 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
825 	    int);
826 static	void complete_mkdir(struct mkdir *);
827 static	void free_newdirblk(struct newdirblk *);
828 static	void free_jremref(struct jremref *);
829 static	void free_jaddref(struct jaddref *);
830 static	void free_jsegdep(struct jsegdep *);
831 static	void free_jsegs(struct jblocks *);
832 static	void rele_jseg(struct jseg *);
833 static	void free_jseg(struct jseg *, struct jblocks *);
834 static	void free_jnewblk(struct jnewblk *);
835 static	void free_jblkdep(struct jblkdep *);
836 static	void free_jfreefrag(struct jfreefrag *);
837 static	void free_freedep(struct freedep *);
838 static	void journal_jremref(struct dirrem *, struct jremref *,
839 	    struct inodedep *);
840 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
841 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
842 	    struct workhead *);
843 static	void cancel_jfreefrag(struct jfreefrag *);
844 static	inline void setup_freedirect(struct freeblks *, struct inode *,
845 	    int, int);
846 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
847 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
848 	    ufs_lbn_t, int);
849 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
850 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
851 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
852 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
853 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
854 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
855 	    int, int);
856 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
857 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
858 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
859 static	void newblk_freefrag(struct newblk*);
860 static	void free_newblk(struct newblk *);
861 static	void cancel_allocdirect(struct allocdirectlst *,
862 	    struct allocdirect *, struct freeblks *);
863 static	int check_inode_unwritten(struct inodedep *);
864 static	int free_inodedep(struct inodedep *);
865 static	void freework_freeblock(struct freework *, u_long);
866 static	void freework_enqueue(struct freework *);
867 static	int handle_workitem_freeblocks(struct freeblks *, int);
868 static	int handle_complete_freeblocks(struct freeblks *, int);
869 static	void handle_workitem_indirblk(struct freework *);
870 static	void handle_written_freework(struct freework *);
871 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
872 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
873 	    struct workhead *);
874 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
875 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
876 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
877 	    ufs2_daddr_t, ufs_lbn_t);
878 static	void handle_workitem_freefrag(struct freefrag *);
879 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
880 	    ufs_lbn_t, u_long);
881 static	void allocdirect_merge(struct allocdirectlst *,
882 	    struct allocdirect *, struct allocdirect *);
883 static	struct freefrag *allocindir_merge(struct allocindir *,
884 	    struct allocindir *);
885 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
886 	    struct bmsafemap **);
887 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
888 	    int cg, struct bmsafemap *);
889 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
890 	    struct newblk **);
891 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
892 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
893 	    struct inodedep **);
894 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
895 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
896 	    int, struct pagedep **);
897 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
898 	    struct pagedep **);
899 static	void pause_timer(void *);
900 static	int request_cleanup(struct mount *, int);
901 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
902 static	void schedule_cleanup(struct mount *);
903 static void softdep_ast_cleanup_proc(struct thread *);
904 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
905 static	int process_worklist_item(struct mount *, int, int);
906 static	void process_removes(struct vnode *);
907 static	void process_truncates(struct vnode *);
908 static	void jwork_move(struct workhead *, struct workhead *);
909 static	void jwork_insert(struct workhead *, struct jsegdep *);
910 static	void add_to_worklist(struct worklist *, int);
911 static	void wake_worklist(struct worklist *);
912 static	void wait_worklist(struct worklist *, char *);
913 static	void remove_from_worklist(struct worklist *);
914 static	void softdep_flush(void *);
915 static	void softdep_flushjournal(struct mount *);
916 static	int softdep_speedup(struct ufsmount *);
917 static	void worklist_speedup(struct mount *);
918 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
919 static	void journal_unmount(struct ufsmount *);
920 static	int journal_space(struct ufsmount *, int);
921 static	void journal_suspend(struct ufsmount *);
922 static	int journal_unsuspend(struct ufsmount *ump);
923 static	void softdep_prelink(struct vnode *, struct vnode *);
924 static	void add_to_journal(struct worklist *);
925 static	void remove_from_journal(struct worklist *);
926 static	bool softdep_excess_items(struct ufsmount *, int);
927 static	void softdep_process_journal(struct mount *, struct worklist *, int);
928 static	struct jremref *newjremref(struct dirrem *, struct inode *,
929 	    struct inode *ip, off_t, nlink_t);
930 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
931 	    uint16_t);
932 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
933 	    uint16_t);
934 static	inline struct jsegdep *inoref_jseg(struct inoref *);
935 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
936 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
937 	    ufs2_daddr_t, int);
938 static	void adjust_newfreework(struct freeblks *, int);
939 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
940 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
941 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
942 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
943 	    ufs2_daddr_t, long, ufs_lbn_t);
944 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
945 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
946 static	int jwait(struct worklist *, int);
947 static	struct inodedep *inodedep_lookup_ip(struct inode *);
948 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
949 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
950 static	void handle_jwork(struct workhead *);
951 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
952 	    struct mkdir **);
953 static	struct jblocks *jblocks_create(void);
954 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
955 static	void jblocks_free(struct jblocks *, struct mount *, int);
956 static	void jblocks_destroy(struct jblocks *);
957 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
958 
959 /*
960  * Exported softdep operations.
961  */
962 static	void softdep_disk_io_initiation(struct buf *);
963 static	void softdep_disk_write_complete(struct buf *);
964 static	void softdep_deallocate_dependencies(struct buf *);
965 static	int softdep_count_dependencies(struct buf *bp, int);
966 
967 /*
968  * Global lock over all of soft updates.
969  */
970 static struct mtx lk;
971 MTX_SYSINIT(softdep_lock, &lk, "Global Softdep Lock", MTX_DEF);
972 
973 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
974 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
975 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
976 
977 /*
978  * Per-filesystem soft-updates locking.
979  */
980 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
981 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
982 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
983 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
984 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
985 				    RA_WLOCKED)
986 
987 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
988 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
989 
990 /*
991  * Worklist queue management.
992  * These routines require that the lock be held.
993  */
994 #ifndef /* NOT */ INVARIANTS
995 #define WORKLIST_INSERT(head, item) do {	\
996 	(item)->wk_state |= ONWORKLIST;		\
997 	LIST_INSERT_HEAD(head, item, wk_list);	\
998 } while (0)
999 #define WORKLIST_REMOVE(item) do {		\
1000 	(item)->wk_state &= ~ONWORKLIST;	\
1001 	LIST_REMOVE(item, wk_list);		\
1002 } while (0)
1003 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1004 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1005 
1006 #else /* INVARIANTS */
1007 static	void worklist_insert(struct workhead *, struct worklist *, int,
1008 	const char *, int);
1009 static	void worklist_remove(struct worklist *, int, const char *, int);
1010 
1011 #define WORKLIST_INSERT(head, item) \
1012 	worklist_insert(head, item, 1, __func__, __LINE__)
1013 #define WORKLIST_INSERT_UNLOCKED(head, item)\
1014 	worklist_insert(head, item, 0, __func__, __LINE__)
1015 #define WORKLIST_REMOVE(item)\
1016 	worklist_remove(item, 1, __func__, __LINE__)
1017 #define WORKLIST_REMOVE_UNLOCKED(item)\
1018 	worklist_remove(item, 0, __func__, __LINE__)
1019 
1020 static void
1021 worklist_insert(head, item, locked, func, line)
1022 	struct workhead *head;
1023 	struct worklist *item;
1024 	int locked;
1025 	const char *func;
1026 	int line;
1027 {
1028 
1029 	if (locked)
1030 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1031 	if (item->wk_state & ONWORKLIST)
1032 		panic("worklist_insert: %p %s(0x%X) already on list, "
1033 		    "added in function %s at line %d",
1034 		    item, TYPENAME(item->wk_type), item->wk_state,
1035 		    item->wk_func, item->wk_line);
1036 	item->wk_state |= ONWORKLIST;
1037 	item->wk_func = func;
1038 	item->wk_line = line;
1039 	LIST_INSERT_HEAD(head, item, wk_list);
1040 }
1041 
1042 static void
1043 worklist_remove(item, locked, func, line)
1044 	struct worklist *item;
1045 	int locked;
1046 	const char *func;
1047 	int line;
1048 {
1049 
1050 	if (locked)
1051 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1052 	if ((item->wk_state & ONWORKLIST) == 0)
1053 		panic("worklist_remove: %p %s(0x%X) not on list, "
1054 		    "removed in function %s at line %d",
1055 		    item, TYPENAME(item->wk_type), item->wk_state,
1056 		    item->wk_func, item->wk_line);
1057 	item->wk_state &= ~ONWORKLIST;
1058 	item->wk_func = func;
1059 	item->wk_line = line;
1060 	LIST_REMOVE(item, wk_list);
1061 }
1062 #endif /* INVARIANTS */
1063 
1064 /*
1065  * Merge two jsegdeps keeping only the oldest one as newer references
1066  * can't be discarded until after older references.
1067  */
1068 static inline struct jsegdep *
1069 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1070 {
1071 	struct jsegdep *swp;
1072 
1073 	if (two == NULL)
1074 		return (one);
1075 
1076 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1077 		swp = one;
1078 		one = two;
1079 		two = swp;
1080 	}
1081 	WORKLIST_REMOVE(&two->jd_list);
1082 	free_jsegdep(two);
1083 
1084 	return (one);
1085 }
1086 
1087 /*
1088  * If two freedeps are compatible free one to reduce list size.
1089  */
1090 static inline struct freedep *
1091 freedep_merge(struct freedep *one, struct freedep *two)
1092 {
1093 	if (two == NULL)
1094 		return (one);
1095 
1096 	if (one->fd_freework == two->fd_freework) {
1097 		WORKLIST_REMOVE(&two->fd_list);
1098 		free_freedep(two);
1099 	}
1100 	return (one);
1101 }
1102 
1103 /*
1104  * Move journal work from one list to another.  Duplicate freedeps and
1105  * jsegdeps are coalesced to keep the lists as small as possible.
1106  */
1107 static void
1108 jwork_move(dst, src)
1109 	struct workhead *dst;
1110 	struct workhead *src;
1111 {
1112 	struct freedep *freedep;
1113 	struct jsegdep *jsegdep;
1114 	struct worklist *wkn;
1115 	struct worklist *wk;
1116 
1117 	KASSERT(dst != src,
1118 	    ("jwork_move: dst == src"));
1119 	freedep = NULL;
1120 	jsegdep = NULL;
1121 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1122 		if (wk->wk_type == D_JSEGDEP)
1123 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1124 		else if (wk->wk_type == D_FREEDEP)
1125 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1126 	}
1127 
1128 	while ((wk = LIST_FIRST(src)) != NULL) {
1129 		WORKLIST_REMOVE(wk);
1130 		WORKLIST_INSERT(dst, wk);
1131 		if (wk->wk_type == D_JSEGDEP) {
1132 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1133 			continue;
1134 		}
1135 		if (wk->wk_type == D_FREEDEP)
1136 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1137 	}
1138 }
1139 
1140 static void
1141 jwork_insert(dst, jsegdep)
1142 	struct workhead *dst;
1143 	struct jsegdep *jsegdep;
1144 {
1145 	struct jsegdep *jsegdepn;
1146 	struct worklist *wk;
1147 
1148 	LIST_FOREACH(wk, dst, wk_list)
1149 		if (wk->wk_type == D_JSEGDEP)
1150 			break;
1151 	if (wk == NULL) {
1152 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1153 		return;
1154 	}
1155 	jsegdepn = WK_JSEGDEP(wk);
1156 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1157 		WORKLIST_REMOVE(wk);
1158 		free_jsegdep(jsegdepn);
1159 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1160 	} else
1161 		free_jsegdep(jsegdep);
1162 }
1163 
1164 /*
1165  * Routines for tracking and managing workitems.
1166  */
1167 static	void workitem_free(struct worklist *, int);
1168 static	void workitem_alloc(struct worklist *, int, struct mount *);
1169 static	void workitem_reassign(struct worklist *, int);
1170 
1171 #define	WORKITEM_FREE(item, type) \
1172 	workitem_free((struct worklist *)(item), (type))
1173 #define	WORKITEM_REASSIGN(item, type) \
1174 	workitem_reassign((struct worklist *)(item), (type))
1175 
1176 static void
1177 workitem_free(item, type)
1178 	struct worklist *item;
1179 	int type;
1180 {
1181 	struct ufsmount *ump;
1182 
1183 #ifdef INVARIANTS
1184 	if (item->wk_state & ONWORKLIST)
1185 		panic("workitem_free: %s(0x%X) still on list, "
1186 		    "added in function %s at line %d",
1187 		    TYPENAME(item->wk_type), item->wk_state,
1188 		    item->wk_func, item->wk_line);
1189 	if (item->wk_type != type && type != D_NEWBLK)
1190 		panic("workitem_free: type mismatch %s != %s",
1191 		    TYPENAME(item->wk_type), TYPENAME(type));
1192 #endif
1193 	if (item->wk_state & IOWAITING)
1194 		wakeup(item);
1195 	ump = VFSTOUFS(item->wk_mp);
1196 	LOCK_OWNED(ump);
1197 	KASSERT(ump->softdep_deps > 0,
1198 	    ("workitem_free: %s: softdep_deps going negative",
1199 	    ump->um_fs->fs_fsmnt));
1200 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1201 		wakeup(&ump->softdep_deps);
1202 	KASSERT(dep_current[item->wk_type] > 0,
1203 	    ("workitem_free: %s: dep_current[%s] going negative",
1204 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1205 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1206 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1207 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1208 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1209 	ump->softdep_curdeps[item->wk_type] -= 1;
1210 	free(item, DtoM(type));
1211 }
1212 
1213 static void
1214 workitem_alloc(item, type, mp)
1215 	struct worklist *item;
1216 	int type;
1217 	struct mount *mp;
1218 {
1219 	struct ufsmount *ump;
1220 
1221 	item->wk_type = type;
1222 	item->wk_mp = mp;
1223 	item->wk_state = 0;
1224 
1225 	ump = VFSTOUFS(mp);
1226 	ACQUIRE_GBLLOCK(&lk);
1227 	dep_current[type]++;
1228 	if (dep_current[type] > dep_highuse[type])
1229 		dep_highuse[type] = dep_current[type];
1230 	dep_total[type]++;
1231 	FREE_GBLLOCK(&lk);
1232 	ACQUIRE_LOCK(ump);
1233 	ump->softdep_curdeps[type] += 1;
1234 	ump->softdep_deps++;
1235 	ump->softdep_accdeps++;
1236 	FREE_LOCK(ump);
1237 }
1238 
1239 static void
1240 workitem_reassign(item, newtype)
1241 	struct worklist *item;
1242 	int newtype;
1243 {
1244 	struct ufsmount *ump;
1245 
1246 	ump = VFSTOUFS(item->wk_mp);
1247 	LOCK_OWNED(ump);
1248 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1249 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1250 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1251 	ump->softdep_curdeps[item->wk_type] -= 1;
1252 	ump->softdep_curdeps[newtype] += 1;
1253 	KASSERT(dep_current[item->wk_type] > 0,
1254 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1255 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1256 	ACQUIRE_GBLLOCK(&lk);
1257 	dep_current[newtype]++;
1258 	dep_current[item->wk_type]--;
1259 	if (dep_current[newtype] > dep_highuse[newtype])
1260 		dep_highuse[newtype] = dep_current[newtype];
1261 	dep_total[newtype]++;
1262 	FREE_GBLLOCK(&lk);
1263 	item->wk_type = newtype;
1264 }
1265 
1266 /*
1267  * Workitem queue management
1268  */
1269 static int max_softdeps;	/* maximum number of structs before slowdown */
1270 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1271 static int proc_waiting;	/* tracks whether we have a timeout posted */
1272 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1273 static struct callout softdep_callout;
1274 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1275 static int req_clear_remove;	/* syncer process flush some freeblks */
1276 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1277 
1278 /*
1279  * runtime statistics
1280  */
1281 static int stat_flush_threads;	/* number of softdep flushing threads */
1282 static int stat_worklist_push;	/* number of worklist cleanups */
1283 static int stat_blk_limit_push;	/* number of times block limit neared */
1284 static int stat_ino_limit_push;	/* number of times inode limit neared */
1285 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1286 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1287 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1288 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1289 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1290 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1291 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1292 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1293 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1294 static int stat_journal_min;	/* Times hit journal min threshold */
1295 static int stat_journal_low;	/* Times hit journal low threshold */
1296 static int stat_journal_wait;	/* Times blocked in jwait(). */
1297 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1298 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1299 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1300 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1301 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1302 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1303 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1304 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1305 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1306 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1307 
1308 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1309     &max_softdeps, 0, "");
1310 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1311     &tickdelay, 0, "");
1312 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1313     &stat_flush_threads, 0, "");
1314 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1315     &stat_worklist_push, 0,"");
1316 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1317     &stat_blk_limit_push, 0,"");
1318 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1319     &stat_ino_limit_push, 0,"");
1320 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1321     &stat_blk_limit_hit, 0, "");
1322 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1323     &stat_ino_limit_hit, 0, "");
1324 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1325     &stat_sync_limit_hit, 0, "");
1326 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1327     &stat_indir_blk_ptrs, 0, "");
1328 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1329     &stat_inode_bitmap, 0, "");
1330 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1331     &stat_direct_blk_ptrs, 0, "");
1332 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1333     &stat_dir_entry, 0, "");
1334 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1335     &stat_jaddref, 0, "");
1336 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1337     &stat_jnewblk, 0, "");
1338 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1339     &stat_journal_low, 0, "");
1340 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1341     &stat_journal_min, 0, "");
1342 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1343     &stat_journal_wait, 0, "");
1344 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1345     &stat_jwait_filepage, 0, "");
1346 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1347     &stat_jwait_freeblks, 0, "");
1348 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1349     &stat_jwait_inode, 0, "");
1350 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1351     &stat_jwait_newblk, 0, "");
1352 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1353     &stat_cleanup_blkrequests, 0, "");
1354 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1355     &stat_cleanup_inorequests, 0, "");
1356 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1357     &stat_cleanup_high_delay, 0, "");
1358 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1359     &stat_cleanup_retries, 0, "");
1360 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1361     &stat_cleanup_failures, 0, "");
1362 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1363     &softdep_flushcache, 0, "");
1364 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1365     &stat_emptyjblocks, 0, "");
1366 
1367 SYSCTL_DECL(_vfs_ffs);
1368 
1369 /* Whether to recompute the summary at mount time */
1370 static int compute_summary_at_mount = 0;
1371 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1372 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1373 static int print_threads = 0;
1374 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1375     &print_threads, 0, "Notify flusher thread start/stop");
1376 
1377 /* List of all filesystems mounted with soft updates */
1378 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1379 
1380 /*
1381  * This function cleans the worklist for a filesystem.
1382  * Each filesystem running with soft dependencies gets its own
1383  * thread to run in this function. The thread is started up in
1384  * softdep_mount and shutdown in softdep_unmount. They show up
1385  * as part of the kernel "bufdaemon" process whose process
1386  * entry is available in bufdaemonproc.
1387  */
1388 static int searchfailed;
1389 extern struct proc *bufdaemonproc;
1390 static void
1391 softdep_flush(addr)
1392 	void *addr;
1393 {
1394 	struct mount *mp;
1395 	struct thread *td;
1396 	struct ufsmount *ump;
1397 
1398 	td = curthread;
1399 	td->td_pflags |= TDP_NORUNNINGBUF;
1400 	mp = (struct mount *)addr;
1401 	ump = VFSTOUFS(mp);
1402 	atomic_add_int(&stat_flush_threads, 1);
1403 	ACQUIRE_LOCK(ump);
1404 	ump->softdep_flags &= ~FLUSH_STARTING;
1405 	wakeup(&ump->softdep_flushtd);
1406 	FREE_LOCK(ump);
1407 	if (print_threads) {
1408 		if (stat_flush_threads == 1)
1409 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1410 			    bufdaemonproc->p_pid);
1411 		printf("Start thread %s\n", td->td_name);
1412 	}
1413 	for (;;) {
1414 		while (softdep_process_worklist(mp, 0) > 0 ||
1415 		    (MOUNTEDSUJ(mp) &&
1416 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1417 			kthread_suspend_check();
1418 		ACQUIRE_LOCK(ump);
1419 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1420 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1421 			    "sdflush", hz / 2);
1422 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1423 		/*
1424 		 * Check to see if we are done and need to exit.
1425 		 */
1426 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1427 			FREE_LOCK(ump);
1428 			continue;
1429 		}
1430 		ump->softdep_flags &= ~FLUSH_EXIT;
1431 		FREE_LOCK(ump);
1432 		wakeup(&ump->softdep_flags);
1433 		if (print_threads)
1434 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1435 		atomic_subtract_int(&stat_flush_threads, 1);
1436 		kthread_exit();
1437 		panic("kthread_exit failed\n");
1438 	}
1439 }
1440 
1441 static void
1442 worklist_speedup(mp)
1443 	struct mount *mp;
1444 {
1445 	struct ufsmount *ump;
1446 
1447 	ump = VFSTOUFS(mp);
1448 	LOCK_OWNED(ump);
1449 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1450 		ump->softdep_flags |= FLUSH_CLEANUP;
1451 	wakeup(&ump->softdep_flushtd);
1452 }
1453 
1454 static int
1455 softdep_speedup(ump)
1456 	struct ufsmount *ump;
1457 {
1458 	struct ufsmount *altump;
1459 	struct mount_softdeps *sdp;
1460 
1461 	LOCK_OWNED(ump);
1462 	worklist_speedup(ump->um_mountp);
1463 	bd_speedup();
1464 	/*
1465 	 * If we have global shortages, then we need other
1466 	 * filesystems to help with the cleanup. Here we wakeup a
1467 	 * flusher thread for a filesystem that is over its fair
1468 	 * share of resources.
1469 	 */
1470 	if (req_clear_inodedeps || req_clear_remove) {
1471 		ACQUIRE_GBLLOCK(&lk);
1472 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1473 			if ((altump = sdp->sd_ump) == ump)
1474 				continue;
1475 			if (((req_clear_inodedeps &&
1476 			    altump->softdep_curdeps[D_INODEDEP] >
1477 			    max_softdeps / stat_flush_threads) ||
1478 			    (req_clear_remove &&
1479 			    altump->softdep_curdeps[D_DIRREM] >
1480 			    (max_softdeps / 2) / stat_flush_threads)) &&
1481 			    TRY_ACQUIRE_LOCK(altump))
1482 				break;
1483 		}
1484 		if (sdp == NULL) {
1485 			searchfailed++;
1486 			FREE_GBLLOCK(&lk);
1487 		} else {
1488 			/*
1489 			 * Move to the end of the list so we pick a
1490 			 * different one on out next try.
1491 			 */
1492 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1493 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1494 			FREE_GBLLOCK(&lk);
1495 			if ((altump->softdep_flags &
1496 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1497 				altump->softdep_flags |= FLUSH_CLEANUP;
1498 			altump->um_softdep->sd_cleanups++;
1499 			wakeup(&altump->softdep_flushtd);
1500 			FREE_LOCK(altump);
1501 		}
1502 	}
1503 	return (speedup_syncer());
1504 }
1505 
1506 /*
1507  * Add an item to the end of the work queue.
1508  * This routine requires that the lock be held.
1509  * This is the only routine that adds items to the list.
1510  * The following routine is the only one that removes items
1511  * and does so in order from first to last.
1512  */
1513 
1514 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1515 #define	WK_NODELAY	0x0002	/* Process immediately. */
1516 
1517 static void
1518 add_to_worklist(wk, flags)
1519 	struct worklist *wk;
1520 	int flags;
1521 {
1522 	struct ufsmount *ump;
1523 
1524 	ump = VFSTOUFS(wk->wk_mp);
1525 	LOCK_OWNED(ump);
1526 	if (wk->wk_state & ONWORKLIST)
1527 		panic("add_to_worklist: %s(0x%X) already on list",
1528 		    TYPENAME(wk->wk_type), wk->wk_state);
1529 	wk->wk_state |= ONWORKLIST;
1530 	if (ump->softdep_on_worklist == 0) {
1531 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1532 		ump->softdep_worklist_tail = wk;
1533 	} else if (flags & WK_HEAD) {
1534 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1535 	} else {
1536 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1537 		ump->softdep_worklist_tail = wk;
1538 	}
1539 	ump->softdep_on_worklist += 1;
1540 	if (flags & WK_NODELAY)
1541 		worklist_speedup(wk->wk_mp);
1542 }
1543 
1544 /*
1545  * Remove the item to be processed. If we are removing the last
1546  * item on the list, we need to recalculate the tail pointer.
1547  */
1548 static void
1549 remove_from_worklist(wk)
1550 	struct worklist *wk;
1551 {
1552 	struct ufsmount *ump;
1553 
1554 	ump = VFSTOUFS(wk->wk_mp);
1555 	if (ump->softdep_worklist_tail == wk)
1556 		ump->softdep_worklist_tail =
1557 		    (struct worklist *)wk->wk_list.le_prev;
1558 	WORKLIST_REMOVE(wk);
1559 	ump->softdep_on_worklist -= 1;
1560 }
1561 
1562 static void
1563 wake_worklist(wk)
1564 	struct worklist *wk;
1565 {
1566 	if (wk->wk_state & IOWAITING) {
1567 		wk->wk_state &= ~IOWAITING;
1568 		wakeup(wk);
1569 	}
1570 }
1571 
1572 static void
1573 wait_worklist(wk, wmesg)
1574 	struct worklist *wk;
1575 	char *wmesg;
1576 {
1577 	struct ufsmount *ump;
1578 
1579 	ump = VFSTOUFS(wk->wk_mp);
1580 	wk->wk_state |= IOWAITING;
1581 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1582 }
1583 
1584 /*
1585  * Process that runs once per second to handle items in the background queue.
1586  *
1587  * Note that we ensure that everything is done in the order in which they
1588  * appear in the queue. The code below depends on this property to ensure
1589  * that blocks of a file are freed before the inode itself is freed. This
1590  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1591  * until all the old ones have been purged from the dependency lists.
1592  */
1593 static int
1594 softdep_process_worklist(mp, full)
1595 	struct mount *mp;
1596 	int full;
1597 {
1598 	int cnt, matchcnt;
1599 	struct ufsmount *ump;
1600 	long starttime;
1601 
1602 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1603 	if (MOUNTEDSOFTDEP(mp) == 0)
1604 		return (0);
1605 	matchcnt = 0;
1606 	ump = VFSTOUFS(mp);
1607 	ACQUIRE_LOCK(ump);
1608 	starttime = time_second;
1609 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1610 	check_clear_deps(mp);
1611 	while (ump->softdep_on_worklist > 0) {
1612 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1613 			break;
1614 		else
1615 			matchcnt += cnt;
1616 		check_clear_deps(mp);
1617 		/*
1618 		 * We do not generally want to stop for buffer space, but if
1619 		 * we are really being a buffer hog, we will stop and wait.
1620 		 */
1621 		if (should_yield()) {
1622 			FREE_LOCK(ump);
1623 			kern_yield(PRI_USER);
1624 			bwillwrite();
1625 			ACQUIRE_LOCK(ump);
1626 		}
1627 		/*
1628 		 * Never allow processing to run for more than one
1629 		 * second. This gives the syncer thread the opportunity
1630 		 * to pause if appropriate.
1631 		 */
1632 		if (!full && starttime != time_second)
1633 			break;
1634 	}
1635 	if (full == 0)
1636 		journal_unsuspend(ump);
1637 	FREE_LOCK(ump);
1638 	return (matchcnt);
1639 }
1640 
1641 /*
1642  * Process all removes associated with a vnode if we are running out of
1643  * journal space.  Any other process which attempts to flush these will
1644  * be unable as we have the vnodes locked.
1645  */
1646 static void
1647 process_removes(vp)
1648 	struct vnode *vp;
1649 {
1650 	struct inodedep *inodedep;
1651 	struct dirrem *dirrem;
1652 	struct ufsmount *ump;
1653 	struct mount *mp;
1654 	ino_t inum;
1655 
1656 	mp = vp->v_mount;
1657 	ump = VFSTOUFS(mp);
1658 	LOCK_OWNED(ump);
1659 	inum = VTOI(vp)->i_number;
1660 	for (;;) {
1661 top:
1662 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1663 			return;
1664 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1665 			/*
1666 			 * If another thread is trying to lock this vnode
1667 			 * it will fail but we must wait for it to do so
1668 			 * before we can proceed.
1669 			 */
1670 			if (dirrem->dm_state & INPROGRESS) {
1671 				wait_worklist(&dirrem->dm_list, "pwrwait");
1672 				goto top;
1673 			}
1674 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1675 			    (COMPLETE | ONWORKLIST))
1676 				break;
1677 		}
1678 		if (dirrem == NULL)
1679 			return;
1680 		remove_from_worklist(&dirrem->dm_list);
1681 		FREE_LOCK(ump);
1682 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1683 			panic("process_removes: suspended filesystem");
1684 		handle_workitem_remove(dirrem, 0);
1685 		vn_finished_secondary_write(mp);
1686 		ACQUIRE_LOCK(ump);
1687 	}
1688 }
1689 
1690 /*
1691  * Process all truncations associated with a vnode if we are running out
1692  * of journal space.  This is called when the vnode lock is already held
1693  * and no other process can clear the truncation.  This function returns
1694  * a value greater than zero if it did any work.
1695  */
1696 static void
1697 process_truncates(vp)
1698 	struct vnode *vp;
1699 {
1700 	struct inodedep *inodedep;
1701 	struct freeblks *freeblks;
1702 	struct ufsmount *ump;
1703 	struct mount *mp;
1704 	ino_t inum;
1705 	int cgwait;
1706 
1707 	mp = vp->v_mount;
1708 	ump = VFSTOUFS(mp);
1709 	LOCK_OWNED(ump);
1710 	inum = VTOI(vp)->i_number;
1711 	for (;;) {
1712 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1713 			return;
1714 		cgwait = 0;
1715 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1716 			/* Journal entries not yet written.  */
1717 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1718 				jwait(&LIST_FIRST(
1719 				    &freeblks->fb_jblkdephd)->jb_list,
1720 				    MNT_WAIT);
1721 				break;
1722 			}
1723 			/* Another thread is executing this item. */
1724 			if (freeblks->fb_state & INPROGRESS) {
1725 				wait_worklist(&freeblks->fb_list, "ptrwait");
1726 				break;
1727 			}
1728 			/* Freeblks is waiting on a inode write. */
1729 			if ((freeblks->fb_state & COMPLETE) == 0) {
1730 				FREE_LOCK(ump);
1731 				ffs_update(vp, 1);
1732 				ACQUIRE_LOCK(ump);
1733 				break;
1734 			}
1735 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1736 			    (ALLCOMPLETE | ONWORKLIST)) {
1737 				remove_from_worklist(&freeblks->fb_list);
1738 				freeblks->fb_state |= INPROGRESS;
1739 				FREE_LOCK(ump);
1740 				if (vn_start_secondary_write(NULL, &mp,
1741 				    V_NOWAIT))
1742 					panic("process_truncates: "
1743 					    "suspended filesystem");
1744 				handle_workitem_freeblocks(freeblks, 0);
1745 				vn_finished_secondary_write(mp);
1746 				ACQUIRE_LOCK(ump);
1747 				break;
1748 			}
1749 			if (freeblks->fb_cgwait)
1750 				cgwait++;
1751 		}
1752 		if (cgwait) {
1753 			FREE_LOCK(ump);
1754 			sync_cgs(mp, MNT_WAIT);
1755 			ffs_sync_snap(mp, MNT_WAIT);
1756 			ACQUIRE_LOCK(ump);
1757 			continue;
1758 		}
1759 		if (freeblks == NULL)
1760 			break;
1761 	}
1762 	return;
1763 }
1764 
1765 /*
1766  * Process one item on the worklist.
1767  */
1768 static int
1769 process_worklist_item(mp, target, flags)
1770 	struct mount *mp;
1771 	int target;
1772 	int flags;
1773 {
1774 	struct worklist sentinel;
1775 	struct worklist *wk;
1776 	struct ufsmount *ump;
1777 	int matchcnt;
1778 	int error;
1779 
1780 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1781 	/*
1782 	 * If we are being called because of a process doing a
1783 	 * copy-on-write, then it is not safe to write as we may
1784 	 * recurse into the copy-on-write routine.
1785 	 */
1786 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1787 		return (-1);
1788 	PHOLD(curproc);	/* Don't let the stack go away. */
1789 	ump = VFSTOUFS(mp);
1790 	LOCK_OWNED(ump);
1791 	matchcnt = 0;
1792 	sentinel.wk_mp = NULL;
1793 	sentinel.wk_type = D_SENTINEL;
1794 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1795 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1796 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1797 		if (wk->wk_type == D_SENTINEL) {
1798 			LIST_REMOVE(&sentinel, wk_list);
1799 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1800 			continue;
1801 		}
1802 		if (wk->wk_state & INPROGRESS)
1803 			panic("process_worklist_item: %p already in progress.",
1804 			    wk);
1805 		wk->wk_state |= INPROGRESS;
1806 		remove_from_worklist(wk);
1807 		FREE_LOCK(ump);
1808 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1809 			panic("process_worklist_item: suspended filesystem");
1810 		switch (wk->wk_type) {
1811 		case D_DIRREM:
1812 			/* removal of a directory entry */
1813 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1814 			break;
1815 
1816 		case D_FREEBLKS:
1817 			/* releasing blocks and/or fragments from a file */
1818 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1819 			    flags);
1820 			break;
1821 
1822 		case D_FREEFRAG:
1823 			/* releasing a fragment when replaced as a file grows */
1824 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1825 			error = 0;
1826 			break;
1827 
1828 		case D_FREEFILE:
1829 			/* releasing an inode when its link count drops to 0 */
1830 			handle_workitem_freefile(WK_FREEFILE(wk));
1831 			error = 0;
1832 			break;
1833 
1834 		default:
1835 			panic("%s_process_worklist: Unknown type %s",
1836 			    "softdep", TYPENAME(wk->wk_type));
1837 			/* NOTREACHED */
1838 		}
1839 		vn_finished_secondary_write(mp);
1840 		ACQUIRE_LOCK(ump);
1841 		if (error == 0) {
1842 			if (++matchcnt == target)
1843 				break;
1844 			continue;
1845 		}
1846 		/*
1847 		 * We have to retry the worklist item later.  Wake up any
1848 		 * waiters who may be able to complete it immediately and
1849 		 * add the item back to the head so we don't try to execute
1850 		 * it again.
1851 		 */
1852 		wk->wk_state &= ~INPROGRESS;
1853 		wake_worklist(wk);
1854 		add_to_worklist(wk, WK_HEAD);
1855 	}
1856 	/* Sentinal could've become the tail from remove_from_worklist. */
1857 	if (ump->softdep_worklist_tail == &sentinel)
1858 		ump->softdep_worklist_tail =
1859 		    (struct worklist *)sentinel.wk_list.le_prev;
1860 	LIST_REMOVE(&sentinel, wk_list);
1861 	PRELE(curproc);
1862 	return (matchcnt);
1863 }
1864 
1865 /*
1866  * Move dependencies from one buffer to another.
1867  */
1868 int
1869 softdep_move_dependencies(oldbp, newbp)
1870 	struct buf *oldbp;
1871 	struct buf *newbp;
1872 {
1873 	struct worklist *wk, *wktail;
1874 	struct ufsmount *ump;
1875 	int dirty;
1876 
1877 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1878 		return (0);
1879 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1880 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1881 	dirty = 0;
1882 	wktail = NULL;
1883 	ump = VFSTOUFS(wk->wk_mp);
1884 	ACQUIRE_LOCK(ump);
1885 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1886 		LIST_REMOVE(wk, wk_list);
1887 		if (wk->wk_type == D_BMSAFEMAP &&
1888 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1889 			dirty = 1;
1890 		if (wktail == NULL)
1891 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1892 		else
1893 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1894 		wktail = wk;
1895 	}
1896 	FREE_LOCK(ump);
1897 
1898 	return (dirty);
1899 }
1900 
1901 /*
1902  * Purge the work list of all items associated with a particular mount point.
1903  */
1904 int
1905 softdep_flushworklist(oldmnt, countp, td)
1906 	struct mount *oldmnt;
1907 	int *countp;
1908 	struct thread *td;
1909 {
1910 	struct vnode *devvp;
1911 	struct ufsmount *ump;
1912 	int count, error;
1913 
1914 	/*
1915 	 * Alternately flush the block device associated with the mount
1916 	 * point and process any dependencies that the flushing
1917 	 * creates. We continue until no more worklist dependencies
1918 	 * are found.
1919 	 */
1920 	*countp = 0;
1921 	error = 0;
1922 	ump = VFSTOUFS(oldmnt);
1923 	devvp = ump->um_devvp;
1924 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1925 		*countp += count;
1926 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1927 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1928 		VOP_UNLOCK(devvp, 0);
1929 		if (error != 0)
1930 			break;
1931 	}
1932 	return (error);
1933 }
1934 
1935 #define	SU_WAITIDLE_RETRIES	20
1936 static int
1937 softdep_waitidle(struct mount *mp, int flags __unused)
1938 {
1939 	struct ufsmount *ump;
1940 	struct vnode *devvp;
1941 	struct thread *td;
1942 	int error, i;
1943 
1944 	ump = VFSTOUFS(mp);
1945 	devvp = ump->um_devvp;
1946 	td = curthread;
1947 	error = 0;
1948 	ACQUIRE_LOCK(ump);
1949 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1950 		ump->softdep_req = 1;
1951 		KASSERT((flags & FORCECLOSE) == 0 ||
1952 		    ump->softdep_on_worklist == 0,
1953 		    ("softdep_waitidle: work added after flush"));
1954 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1955 		    "softdeps", 10 * hz);
1956 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1957 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1958 		VOP_UNLOCK(devvp, 0);
1959 		ACQUIRE_LOCK(ump);
1960 		if (error != 0)
1961 			break;
1962 	}
1963 	ump->softdep_req = 0;
1964 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1965 		error = EBUSY;
1966 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1967 		    mp);
1968 	}
1969 	FREE_LOCK(ump);
1970 	return (error);
1971 }
1972 
1973 /*
1974  * Flush all vnodes and worklist items associated with a specified mount point.
1975  */
1976 int
1977 softdep_flushfiles(oldmnt, flags, td)
1978 	struct mount *oldmnt;
1979 	int flags;
1980 	struct thread *td;
1981 {
1982 #ifdef QUOTA
1983 	struct ufsmount *ump;
1984 	int i;
1985 #endif
1986 	int error, early, depcount, loopcnt, retry_flush_count, retry;
1987 	int morework;
1988 
1989 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1990 	    ("softdep_flushfiles called on non-softdep filesystem"));
1991 	loopcnt = 10;
1992 	retry_flush_count = 3;
1993 retry_flush:
1994 	error = 0;
1995 
1996 	/*
1997 	 * Alternately flush the vnodes associated with the mount
1998 	 * point and process any dependencies that the flushing
1999 	 * creates. In theory, this loop can happen at most twice,
2000 	 * but we give it a few extra just to be sure.
2001 	 */
2002 	for (; loopcnt > 0; loopcnt--) {
2003 		/*
2004 		 * Do another flush in case any vnodes were brought in
2005 		 * as part of the cleanup operations.
2006 		 */
2007 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2008 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2009 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2010 			break;
2011 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2012 		    depcount == 0)
2013 			break;
2014 	}
2015 	/*
2016 	 * If we are unmounting then it is an error to fail. If we
2017 	 * are simply trying to downgrade to read-only, then filesystem
2018 	 * activity can keep us busy forever, so we just fail with EBUSY.
2019 	 */
2020 	if (loopcnt == 0) {
2021 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2022 			panic("softdep_flushfiles: looping");
2023 		error = EBUSY;
2024 	}
2025 	if (!error)
2026 		error = softdep_waitidle(oldmnt, flags);
2027 	if (!error) {
2028 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2029 			retry = 0;
2030 			MNT_ILOCK(oldmnt);
2031 			morework = oldmnt->mnt_nvnodelistsize > 0;
2032 #ifdef QUOTA
2033 			ump = VFSTOUFS(oldmnt);
2034 			UFS_LOCK(ump);
2035 			for (i = 0; i < MAXQUOTAS; i++) {
2036 				if (ump->um_quotas[i] != NULLVP)
2037 					morework = 1;
2038 			}
2039 			UFS_UNLOCK(ump);
2040 #endif
2041 			if (morework) {
2042 				if (--retry_flush_count > 0) {
2043 					retry = 1;
2044 					loopcnt = 3;
2045 				} else
2046 					error = EBUSY;
2047 			}
2048 			MNT_IUNLOCK(oldmnt);
2049 			if (retry)
2050 				goto retry_flush;
2051 		}
2052 	}
2053 	return (error);
2054 }
2055 
2056 /*
2057  * Structure hashing.
2058  *
2059  * There are four types of structures that can be looked up:
2060  *	1) pagedep structures identified by mount point, inode number,
2061  *	   and logical block.
2062  *	2) inodedep structures identified by mount point and inode number.
2063  *	3) newblk structures identified by mount point and
2064  *	   physical block number.
2065  *	4) bmsafemap structures identified by mount point and
2066  *	   cylinder group number.
2067  *
2068  * The "pagedep" and "inodedep" dependency structures are hashed
2069  * separately from the file blocks and inodes to which they correspond.
2070  * This separation helps when the in-memory copy of an inode or
2071  * file block must be replaced. It also obviates the need to access
2072  * an inode or file page when simply updating (or de-allocating)
2073  * dependency structures. Lookup of newblk structures is needed to
2074  * find newly allocated blocks when trying to associate them with
2075  * their allocdirect or allocindir structure.
2076  *
2077  * The lookup routines optionally create and hash a new instance when
2078  * an existing entry is not found. The bmsafemap lookup routine always
2079  * allocates a new structure if an existing one is not found.
2080  */
2081 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2082 
2083 /*
2084  * Structures and routines associated with pagedep caching.
2085  */
2086 #define	PAGEDEP_HASH(ump, inum, lbn) \
2087 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2088 
2089 static int
2090 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2091 	struct pagedep_hashhead *pagedephd;
2092 	ino_t ino;
2093 	ufs_lbn_t lbn;
2094 	struct pagedep **pagedeppp;
2095 {
2096 	struct pagedep *pagedep;
2097 
2098 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2099 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2100 			*pagedeppp = pagedep;
2101 			return (1);
2102 		}
2103 	}
2104 	*pagedeppp = NULL;
2105 	return (0);
2106 }
2107 /*
2108  * Look up a pagedep. Return 1 if found, 0 otherwise.
2109  * If not found, allocate if DEPALLOC flag is passed.
2110  * Found or allocated entry is returned in pagedeppp.
2111  */
2112 static int
2113 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2114 	struct mount *mp;
2115 	struct buf *bp;
2116 	ino_t ino;
2117 	ufs_lbn_t lbn;
2118 	int flags;
2119 	struct pagedep **pagedeppp;
2120 {
2121 	struct pagedep *pagedep;
2122 	struct pagedep_hashhead *pagedephd;
2123 	struct worklist *wk;
2124 	struct ufsmount *ump;
2125 	int ret;
2126 	int i;
2127 
2128 	ump = VFSTOUFS(mp);
2129 	LOCK_OWNED(ump);
2130 	if (bp) {
2131 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2132 			if (wk->wk_type == D_PAGEDEP) {
2133 				*pagedeppp = WK_PAGEDEP(wk);
2134 				return (1);
2135 			}
2136 		}
2137 	}
2138 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2139 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2140 	if (ret) {
2141 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2142 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2143 		return (1);
2144 	}
2145 	if ((flags & DEPALLOC) == 0)
2146 		return (0);
2147 	FREE_LOCK(ump);
2148 	pagedep = malloc(sizeof(struct pagedep),
2149 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2150 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2151 	ACQUIRE_LOCK(ump);
2152 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2153 	if (*pagedeppp) {
2154 		/*
2155 		 * This should never happen since we only create pagedeps
2156 		 * with the vnode lock held.  Could be an assert.
2157 		 */
2158 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2159 		return (ret);
2160 	}
2161 	pagedep->pd_ino = ino;
2162 	pagedep->pd_lbn = lbn;
2163 	LIST_INIT(&pagedep->pd_dirremhd);
2164 	LIST_INIT(&pagedep->pd_pendinghd);
2165 	for (i = 0; i < DAHASHSZ; i++)
2166 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2167 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2168 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2169 	*pagedeppp = pagedep;
2170 	return (0);
2171 }
2172 
2173 /*
2174  * Structures and routines associated with inodedep caching.
2175  */
2176 #define	INODEDEP_HASH(ump, inum) \
2177       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2178 
2179 static int
2180 inodedep_find(inodedephd, inum, inodedeppp)
2181 	struct inodedep_hashhead *inodedephd;
2182 	ino_t inum;
2183 	struct inodedep **inodedeppp;
2184 {
2185 	struct inodedep *inodedep;
2186 
2187 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2188 		if (inum == inodedep->id_ino)
2189 			break;
2190 	if (inodedep) {
2191 		*inodedeppp = inodedep;
2192 		return (1);
2193 	}
2194 	*inodedeppp = NULL;
2195 
2196 	return (0);
2197 }
2198 /*
2199  * Look up an inodedep. Return 1 if found, 0 if not found.
2200  * If not found, allocate if DEPALLOC flag is passed.
2201  * Found or allocated entry is returned in inodedeppp.
2202  */
2203 static int
2204 inodedep_lookup(mp, inum, flags, inodedeppp)
2205 	struct mount *mp;
2206 	ino_t inum;
2207 	int flags;
2208 	struct inodedep **inodedeppp;
2209 {
2210 	struct inodedep *inodedep;
2211 	struct inodedep_hashhead *inodedephd;
2212 	struct ufsmount *ump;
2213 	struct fs *fs;
2214 
2215 	ump = VFSTOUFS(mp);
2216 	LOCK_OWNED(ump);
2217 	fs = ump->um_fs;
2218 	inodedephd = INODEDEP_HASH(ump, inum);
2219 
2220 	if (inodedep_find(inodedephd, inum, inodedeppp))
2221 		return (1);
2222 	if ((flags & DEPALLOC) == 0)
2223 		return (0);
2224 	/*
2225 	 * If the system is over its limit and our filesystem is
2226 	 * responsible for more than our share of that usage and
2227 	 * we are not in a rush, request some inodedep cleanup.
2228 	 */
2229 	if (softdep_excess_items(ump, D_INODEDEP))
2230 		schedule_cleanup(mp);
2231 	else
2232 		FREE_LOCK(ump);
2233 	inodedep = malloc(sizeof(struct inodedep),
2234 		M_INODEDEP, M_SOFTDEP_FLAGS);
2235 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2236 	ACQUIRE_LOCK(ump);
2237 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2238 		WORKITEM_FREE(inodedep, D_INODEDEP);
2239 		return (1);
2240 	}
2241 	inodedep->id_fs = fs;
2242 	inodedep->id_ino = inum;
2243 	inodedep->id_state = ALLCOMPLETE;
2244 	inodedep->id_nlinkdelta = 0;
2245 	inodedep->id_savedino1 = NULL;
2246 	inodedep->id_savedsize = -1;
2247 	inodedep->id_savedextsize = -1;
2248 	inodedep->id_savednlink = -1;
2249 	inodedep->id_bmsafemap = NULL;
2250 	inodedep->id_mkdiradd = NULL;
2251 	LIST_INIT(&inodedep->id_dirremhd);
2252 	LIST_INIT(&inodedep->id_pendinghd);
2253 	LIST_INIT(&inodedep->id_inowait);
2254 	LIST_INIT(&inodedep->id_bufwait);
2255 	TAILQ_INIT(&inodedep->id_inoreflst);
2256 	TAILQ_INIT(&inodedep->id_inoupdt);
2257 	TAILQ_INIT(&inodedep->id_newinoupdt);
2258 	TAILQ_INIT(&inodedep->id_extupdt);
2259 	TAILQ_INIT(&inodedep->id_newextupdt);
2260 	TAILQ_INIT(&inodedep->id_freeblklst);
2261 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2262 	*inodedeppp = inodedep;
2263 	return (0);
2264 }
2265 
2266 /*
2267  * Structures and routines associated with newblk caching.
2268  */
2269 #define	NEWBLK_HASH(ump, inum) \
2270 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2271 
2272 static int
2273 newblk_find(newblkhd, newblkno, flags, newblkpp)
2274 	struct newblk_hashhead *newblkhd;
2275 	ufs2_daddr_t newblkno;
2276 	int flags;
2277 	struct newblk **newblkpp;
2278 {
2279 	struct newblk *newblk;
2280 
2281 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2282 		if (newblkno != newblk->nb_newblkno)
2283 			continue;
2284 		/*
2285 		 * If we're creating a new dependency don't match those that
2286 		 * have already been converted to allocdirects.  This is for
2287 		 * a frag extend.
2288 		 */
2289 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2290 			continue;
2291 		break;
2292 	}
2293 	if (newblk) {
2294 		*newblkpp = newblk;
2295 		return (1);
2296 	}
2297 	*newblkpp = NULL;
2298 	return (0);
2299 }
2300 
2301 /*
2302  * Look up a newblk. Return 1 if found, 0 if not found.
2303  * If not found, allocate if DEPALLOC flag is passed.
2304  * Found or allocated entry is returned in newblkpp.
2305  */
2306 static int
2307 newblk_lookup(mp, newblkno, flags, newblkpp)
2308 	struct mount *mp;
2309 	ufs2_daddr_t newblkno;
2310 	int flags;
2311 	struct newblk **newblkpp;
2312 {
2313 	struct newblk *newblk;
2314 	struct newblk_hashhead *newblkhd;
2315 	struct ufsmount *ump;
2316 
2317 	ump = VFSTOUFS(mp);
2318 	LOCK_OWNED(ump);
2319 	newblkhd = NEWBLK_HASH(ump, newblkno);
2320 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2321 		return (1);
2322 	if ((flags & DEPALLOC) == 0)
2323 		return (0);
2324 	if (softdep_excess_items(ump, D_NEWBLK) ||
2325 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2326 	    softdep_excess_items(ump, D_ALLOCINDIR))
2327 		schedule_cleanup(mp);
2328 	else
2329 		FREE_LOCK(ump);
2330 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2331 	    M_SOFTDEP_FLAGS | M_ZERO);
2332 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2333 	ACQUIRE_LOCK(ump);
2334 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2335 		WORKITEM_FREE(newblk, D_NEWBLK);
2336 		return (1);
2337 	}
2338 	newblk->nb_freefrag = NULL;
2339 	LIST_INIT(&newblk->nb_indirdeps);
2340 	LIST_INIT(&newblk->nb_newdirblk);
2341 	LIST_INIT(&newblk->nb_jwork);
2342 	newblk->nb_state = ATTACHED;
2343 	newblk->nb_newblkno = newblkno;
2344 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2345 	*newblkpp = newblk;
2346 	return (0);
2347 }
2348 
2349 /*
2350  * Structures and routines associated with freed indirect block caching.
2351  */
2352 #define	INDIR_HASH(ump, blkno) \
2353 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2354 
2355 /*
2356  * Lookup an indirect block in the indir hash table.  The freework is
2357  * removed and potentially freed.  The caller must do a blocking journal
2358  * write before writing to the blkno.
2359  */
2360 static int
2361 indirblk_lookup(mp, blkno)
2362 	struct mount *mp;
2363 	ufs2_daddr_t blkno;
2364 {
2365 	struct freework *freework;
2366 	struct indir_hashhead *wkhd;
2367 	struct ufsmount *ump;
2368 
2369 	ump = VFSTOUFS(mp);
2370 	wkhd = INDIR_HASH(ump, blkno);
2371 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2372 		if (freework->fw_blkno != blkno)
2373 			continue;
2374 		indirblk_remove(freework);
2375 		return (1);
2376 	}
2377 	return (0);
2378 }
2379 
2380 /*
2381  * Insert an indirect block represented by freework into the indirblk
2382  * hash table so that it may prevent the block from being re-used prior
2383  * to the journal being written.
2384  */
2385 static void
2386 indirblk_insert(freework)
2387 	struct freework *freework;
2388 {
2389 	struct jblocks *jblocks;
2390 	struct jseg *jseg;
2391 	struct ufsmount *ump;
2392 
2393 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2394 	jblocks = ump->softdep_jblocks;
2395 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2396 	if (jseg == NULL)
2397 		return;
2398 
2399 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2400 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2401 	    fw_next);
2402 	freework->fw_state &= ~DEPCOMPLETE;
2403 }
2404 
2405 static void
2406 indirblk_remove(freework)
2407 	struct freework *freework;
2408 {
2409 	struct ufsmount *ump;
2410 
2411 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2412 	LIST_REMOVE(freework, fw_segs);
2413 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2414 	freework->fw_state |= DEPCOMPLETE;
2415 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2416 		WORKITEM_FREE(freework, D_FREEWORK);
2417 }
2418 
2419 /*
2420  * Executed during filesystem system initialization before
2421  * mounting any filesystems.
2422  */
2423 void
2424 softdep_initialize()
2425 {
2426 
2427 	TAILQ_INIT(&softdepmounts);
2428 #ifdef __LP64__
2429 	max_softdeps = desiredvnodes * 4;
2430 #else
2431 	max_softdeps = desiredvnodes * 2;
2432 #endif
2433 
2434 	/* initialise bioops hack */
2435 	bioops.io_start = softdep_disk_io_initiation;
2436 	bioops.io_complete = softdep_disk_write_complete;
2437 	bioops.io_deallocate = softdep_deallocate_dependencies;
2438 	bioops.io_countdeps = softdep_count_dependencies;
2439 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2440 
2441 	/* Initialize the callout with an mtx. */
2442 	callout_init_mtx(&softdep_callout, &lk, 0);
2443 }
2444 
2445 /*
2446  * Executed after all filesystems have been unmounted during
2447  * filesystem module unload.
2448  */
2449 void
2450 softdep_uninitialize()
2451 {
2452 
2453 	/* clear bioops hack */
2454 	bioops.io_start = NULL;
2455 	bioops.io_complete = NULL;
2456 	bioops.io_deallocate = NULL;
2457 	bioops.io_countdeps = NULL;
2458 	softdep_ast_cleanup = NULL;
2459 
2460 	callout_drain(&softdep_callout);
2461 }
2462 
2463 /*
2464  * Called at mount time to notify the dependency code that a
2465  * filesystem wishes to use it.
2466  */
2467 int
2468 softdep_mount(devvp, mp, fs, cred)
2469 	struct vnode *devvp;
2470 	struct mount *mp;
2471 	struct fs *fs;
2472 	struct ucred *cred;
2473 {
2474 	struct csum_total cstotal;
2475 	struct mount_softdeps *sdp;
2476 	struct ufsmount *ump;
2477 	struct cg *cgp;
2478 	struct buf *bp;
2479 	u_int cyl, i;
2480 	int error;
2481 
2482 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2483 	    M_WAITOK | M_ZERO);
2484 	MNT_ILOCK(mp);
2485 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2486 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2487 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2488 			MNTK_SOFTDEP | MNTK_NOASYNC;
2489 	}
2490 	ump = VFSTOUFS(mp);
2491 	ump->um_softdep = sdp;
2492 	MNT_IUNLOCK(mp);
2493 	rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2494 	sdp->sd_ump = ump;
2495 	LIST_INIT(&ump->softdep_workitem_pending);
2496 	LIST_INIT(&ump->softdep_journal_pending);
2497 	TAILQ_INIT(&ump->softdep_unlinked);
2498 	LIST_INIT(&ump->softdep_dirtycg);
2499 	ump->softdep_worklist_tail = NULL;
2500 	ump->softdep_on_worklist = 0;
2501 	ump->softdep_deps = 0;
2502 	LIST_INIT(&ump->softdep_mkdirlisthd);
2503 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2504 	    &ump->pagedep_hash_size);
2505 	ump->pagedep_nextclean = 0;
2506 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2507 	    &ump->inodedep_hash_size);
2508 	ump->inodedep_nextclean = 0;
2509 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2510 	    &ump->newblk_hash_size);
2511 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2512 	    &ump->bmsafemap_hash_size);
2513 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2514 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2515 	    M_FREEWORK, M_WAITOK);
2516 	ump->indir_hash_size = i - 1;
2517 	for (i = 0; i <= ump->indir_hash_size; i++)
2518 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2519 	ACQUIRE_GBLLOCK(&lk);
2520 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2521 	FREE_GBLLOCK(&lk);
2522 	if ((fs->fs_flags & FS_SUJ) &&
2523 	    (error = journal_mount(mp, fs, cred)) != 0) {
2524 		printf("Failed to start journal: %d\n", error);
2525 		softdep_unmount(mp);
2526 		return (error);
2527 	}
2528 	/*
2529 	 * Start our flushing thread in the bufdaemon process.
2530 	 */
2531 	ACQUIRE_LOCK(ump);
2532 	ump->softdep_flags |= FLUSH_STARTING;
2533 	FREE_LOCK(ump);
2534 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2535 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2536 	    mp->mnt_stat.f_mntonname);
2537 	ACQUIRE_LOCK(ump);
2538 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2539 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2540 		    hz / 2);
2541 	}
2542 	FREE_LOCK(ump);
2543 	/*
2544 	 * When doing soft updates, the counters in the
2545 	 * superblock may have gotten out of sync. Recomputation
2546 	 * can take a long time and can be deferred for background
2547 	 * fsck.  However, the old behavior of scanning the cylinder
2548 	 * groups and recalculating them at mount time is available
2549 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2550 	 */
2551 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2552 		return (0);
2553 	bzero(&cstotal, sizeof cstotal);
2554 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2555 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2556 		    fs->fs_cgsize, cred, &bp)) != 0) {
2557 			brelse(bp);
2558 			softdep_unmount(mp);
2559 			return (error);
2560 		}
2561 		cgp = (struct cg *)bp->b_data;
2562 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2563 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2564 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2565 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2566 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2567 		brelse(bp);
2568 	}
2569 #ifdef INVARIANTS
2570 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2571 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2572 #endif
2573 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2574 	return (0);
2575 }
2576 
2577 void
2578 softdep_unmount(mp)
2579 	struct mount *mp;
2580 {
2581 	struct ufsmount *ump;
2582 #ifdef INVARIANTS
2583 	int i;
2584 #endif
2585 
2586 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2587 	    ("softdep_unmount called on non-softdep filesystem"));
2588 	ump = VFSTOUFS(mp);
2589 	MNT_ILOCK(mp);
2590 	mp->mnt_flag &= ~MNT_SOFTDEP;
2591 	if (MOUNTEDSUJ(mp) == 0) {
2592 		MNT_IUNLOCK(mp);
2593 	} else {
2594 		mp->mnt_flag &= ~MNT_SUJ;
2595 		MNT_IUNLOCK(mp);
2596 		journal_unmount(ump);
2597 	}
2598 	/*
2599 	 * Shut down our flushing thread. Check for NULL is if
2600 	 * softdep_mount errors out before the thread has been created.
2601 	 */
2602 	if (ump->softdep_flushtd != NULL) {
2603 		ACQUIRE_LOCK(ump);
2604 		ump->softdep_flags |= FLUSH_EXIT;
2605 		wakeup(&ump->softdep_flushtd);
2606 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2607 		    "sdwait", 0);
2608 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2609 		    ("Thread shutdown failed"));
2610 	}
2611 	/*
2612 	 * Free up our resources.
2613 	 */
2614 	ACQUIRE_GBLLOCK(&lk);
2615 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2616 	FREE_GBLLOCK(&lk);
2617 	rw_destroy(LOCK_PTR(ump));
2618 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2619 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2620 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2621 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2622 	    ump->bmsafemap_hash_size);
2623 	free(ump->indir_hashtbl, M_FREEWORK);
2624 #ifdef INVARIANTS
2625 	for (i = 0; i <= D_LAST; i++)
2626 		KASSERT(ump->softdep_curdeps[i] == 0,
2627 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2628 		    TYPENAME(i), ump->softdep_curdeps[i]));
2629 #endif
2630 	free(ump->um_softdep, M_MOUNTDATA);
2631 }
2632 
2633 static struct jblocks *
2634 jblocks_create(void)
2635 {
2636 	struct jblocks *jblocks;
2637 
2638 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2639 	TAILQ_INIT(&jblocks->jb_segs);
2640 	jblocks->jb_avail = 10;
2641 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2642 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2643 
2644 	return (jblocks);
2645 }
2646 
2647 static ufs2_daddr_t
2648 jblocks_alloc(jblocks, bytes, actual)
2649 	struct jblocks *jblocks;
2650 	int bytes;
2651 	int *actual;
2652 {
2653 	ufs2_daddr_t daddr;
2654 	struct jextent *jext;
2655 	int freecnt;
2656 	int blocks;
2657 
2658 	blocks = bytes / DEV_BSIZE;
2659 	jext = &jblocks->jb_extent[jblocks->jb_head];
2660 	freecnt = jext->je_blocks - jblocks->jb_off;
2661 	if (freecnt == 0) {
2662 		jblocks->jb_off = 0;
2663 		if (++jblocks->jb_head > jblocks->jb_used)
2664 			jblocks->jb_head = 0;
2665 		jext = &jblocks->jb_extent[jblocks->jb_head];
2666 		freecnt = jext->je_blocks;
2667 	}
2668 	if (freecnt > blocks)
2669 		freecnt = blocks;
2670 	*actual = freecnt * DEV_BSIZE;
2671 	daddr = jext->je_daddr + jblocks->jb_off;
2672 	jblocks->jb_off += freecnt;
2673 	jblocks->jb_free -= freecnt;
2674 
2675 	return (daddr);
2676 }
2677 
2678 static void
2679 jblocks_free(jblocks, mp, bytes)
2680 	struct jblocks *jblocks;
2681 	struct mount *mp;
2682 	int bytes;
2683 {
2684 
2685 	LOCK_OWNED(VFSTOUFS(mp));
2686 	jblocks->jb_free += bytes / DEV_BSIZE;
2687 	if (jblocks->jb_suspended)
2688 		worklist_speedup(mp);
2689 	wakeup(jblocks);
2690 }
2691 
2692 static void
2693 jblocks_destroy(jblocks)
2694 	struct jblocks *jblocks;
2695 {
2696 
2697 	if (jblocks->jb_extent)
2698 		free(jblocks->jb_extent, M_JBLOCKS);
2699 	free(jblocks, M_JBLOCKS);
2700 }
2701 
2702 static void
2703 jblocks_add(jblocks, daddr, blocks)
2704 	struct jblocks *jblocks;
2705 	ufs2_daddr_t daddr;
2706 	int blocks;
2707 {
2708 	struct jextent *jext;
2709 
2710 	jblocks->jb_blocks += blocks;
2711 	jblocks->jb_free += blocks;
2712 	jext = &jblocks->jb_extent[jblocks->jb_used];
2713 	/* Adding the first block. */
2714 	if (jext->je_daddr == 0) {
2715 		jext->je_daddr = daddr;
2716 		jext->je_blocks = blocks;
2717 		return;
2718 	}
2719 	/* Extending the last extent. */
2720 	if (jext->je_daddr + jext->je_blocks == daddr) {
2721 		jext->je_blocks += blocks;
2722 		return;
2723 	}
2724 	/* Adding a new extent. */
2725 	if (++jblocks->jb_used == jblocks->jb_avail) {
2726 		jblocks->jb_avail *= 2;
2727 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2728 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2729 		memcpy(jext, jblocks->jb_extent,
2730 		    sizeof(struct jextent) * jblocks->jb_used);
2731 		free(jblocks->jb_extent, M_JBLOCKS);
2732 		jblocks->jb_extent = jext;
2733 	}
2734 	jext = &jblocks->jb_extent[jblocks->jb_used];
2735 	jext->je_daddr = daddr;
2736 	jext->je_blocks = blocks;
2737 	return;
2738 }
2739 
2740 int
2741 softdep_journal_lookup(mp, vpp)
2742 	struct mount *mp;
2743 	struct vnode **vpp;
2744 {
2745 	struct componentname cnp;
2746 	struct vnode *dvp;
2747 	ino_t sujournal;
2748 	int error;
2749 
2750 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2751 	if (error)
2752 		return (error);
2753 	bzero(&cnp, sizeof(cnp));
2754 	cnp.cn_nameiop = LOOKUP;
2755 	cnp.cn_flags = ISLASTCN;
2756 	cnp.cn_thread = curthread;
2757 	cnp.cn_cred = curthread->td_ucred;
2758 	cnp.cn_pnbuf = SUJ_FILE;
2759 	cnp.cn_nameptr = SUJ_FILE;
2760 	cnp.cn_namelen = strlen(SUJ_FILE);
2761 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2762 	vput(dvp);
2763 	if (error != 0)
2764 		return (error);
2765 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2766 	return (error);
2767 }
2768 
2769 /*
2770  * Open and verify the journal file.
2771  */
2772 static int
2773 journal_mount(mp, fs, cred)
2774 	struct mount *mp;
2775 	struct fs *fs;
2776 	struct ucred *cred;
2777 {
2778 	struct jblocks *jblocks;
2779 	struct ufsmount *ump;
2780 	struct vnode *vp;
2781 	struct inode *ip;
2782 	ufs2_daddr_t blkno;
2783 	int bcount;
2784 	int error;
2785 	int i;
2786 
2787 	ump = VFSTOUFS(mp);
2788 	ump->softdep_journal_tail = NULL;
2789 	ump->softdep_on_journal = 0;
2790 	ump->softdep_accdeps = 0;
2791 	ump->softdep_req = 0;
2792 	ump->softdep_jblocks = NULL;
2793 	error = softdep_journal_lookup(mp, &vp);
2794 	if (error != 0) {
2795 		printf("Failed to find journal.  Use tunefs to create one\n");
2796 		return (error);
2797 	}
2798 	ip = VTOI(vp);
2799 	if (ip->i_size < SUJ_MIN) {
2800 		error = ENOSPC;
2801 		goto out;
2802 	}
2803 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2804 	jblocks = jblocks_create();
2805 	for (i = 0; i < bcount; i++) {
2806 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2807 		if (error)
2808 			break;
2809 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2810 	}
2811 	if (error) {
2812 		jblocks_destroy(jblocks);
2813 		goto out;
2814 	}
2815 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2816 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2817 	ump->softdep_jblocks = jblocks;
2818 out:
2819 	if (error == 0) {
2820 		MNT_ILOCK(mp);
2821 		mp->mnt_flag |= MNT_SUJ;
2822 		mp->mnt_flag &= ~MNT_SOFTDEP;
2823 		MNT_IUNLOCK(mp);
2824 		/*
2825 		 * Only validate the journal contents if the
2826 		 * filesystem is clean, otherwise we write the logs
2827 		 * but they'll never be used.  If the filesystem was
2828 		 * still dirty when we mounted it the journal is
2829 		 * invalid and a new journal can only be valid if it
2830 		 * starts from a clean mount.
2831 		 */
2832 		if (fs->fs_clean) {
2833 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2834 			ip->i_flags |= IN_MODIFIED;
2835 			ffs_update(vp, 1);
2836 		}
2837 	}
2838 	vput(vp);
2839 	return (error);
2840 }
2841 
2842 static void
2843 journal_unmount(ump)
2844 	struct ufsmount *ump;
2845 {
2846 
2847 	if (ump->softdep_jblocks)
2848 		jblocks_destroy(ump->softdep_jblocks);
2849 	ump->softdep_jblocks = NULL;
2850 }
2851 
2852 /*
2853  * Called when a journal record is ready to be written.  Space is allocated
2854  * and the journal entry is created when the journal is flushed to stable
2855  * store.
2856  */
2857 static void
2858 add_to_journal(wk)
2859 	struct worklist *wk;
2860 {
2861 	struct ufsmount *ump;
2862 
2863 	ump = VFSTOUFS(wk->wk_mp);
2864 	LOCK_OWNED(ump);
2865 	if (wk->wk_state & ONWORKLIST)
2866 		panic("add_to_journal: %s(0x%X) already on list",
2867 		    TYPENAME(wk->wk_type), wk->wk_state);
2868 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2869 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2870 		ump->softdep_jblocks->jb_age = ticks;
2871 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2872 	} else
2873 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2874 	ump->softdep_journal_tail = wk;
2875 	ump->softdep_on_journal += 1;
2876 }
2877 
2878 /*
2879  * Remove an arbitrary item for the journal worklist maintain the tail
2880  * pointer.  This happens when a new operation obviates the need to
2881  * journal an old operation.
2882  */
2883 static void
2884 remove_from_journal(wk)
2885 	struct worklist *wk;
2886 {
2887 	struct ufsmount *ump;
2888 
2889 	ump = VFSTOUFS(wk->wk_mp);
2890 	LOCK_OWNED(ump);
2891 #ifdef INVARIANTS
2892 	{
2893 		struct worklist *wkn;
2894 
2895 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2896 			if (wkn == wk)
2897 				break;
2898 		if (wkn == NULL)
2899 			panic("remove_from_journal: %p is not in journal", wk);
2900 	}
2901 #endif
2902 	/*
2903 	 * We emulate a TAILQ to save space in most structures which do not
2904 	 * require TAILQ semantics.  Here we must update the tail position
2905 	 * when removing the tail which is not the final entry. This works
2906 	 * only if the worklist linkage are at the beginning of the structure.
2907 	 */
2908 	if (ump->softdep_journal_tail == wk)
2909 		ump->softdep_journal_tail =
2910 		    (struct worklist *)wk->wk_list.le_prev;
2911 	WORKLIST_REMOVE(wk);
2912 	ump->softdep_on_journal -= 1;
2913 }
2914 
2915 /*
2916  * Check for journal space as well as dependency limits so the prelink
2917  * code can throttle both journaled and non-journaled filesystems.
2918  * Threshold is 0 for low and 1 for min.
2919  */
2920 static int
2921 journal_space(ump, thresh)
2922 	struct ufsmount *ump;
2923 	int thresh;
2924 {
2925 	struct jblocks *jblocks;
2926 	int limit, avail;
2927 
2928 	jblocks = ump->softdep_jblocks;
2929 	if (jblocks == NULL)
2930 		return (1);
2931 	/*
2932 	 * We use a tighter restriction here to prevent request_cleanup()
2933 	 * running in threads from running into locks we currently hold.
2934 	 * We have to be over the limit and our filesystem has to be
2935 	 * responsible for more than our share of that usage.
2936 	 */
2937 	limit = (max_softdeps / 10) * 9;
2938 	if (dep_current[D_INODEDEP] > limit &&
2939 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2940 		return (0);
2941 	if (thresh)
2942 		thresh = jblocks->jb_min;
2943 	else
2944 		thresh = jblocks->jb_low;
2945 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2946 	avail = jblocks->jb_free - avail;
2947 
2948 	return (avail > thresh);
2949 }
2950 
2951 static void
2952 journal_suspend(ump)
2953 	struct ufsmount *ump;
2954 {
2955 	struct jblocks *jblocks;
2956 	struct mount *mp;
2957 
2958 	mp = UFSTOVFS(ump);
2959 	jblocks = ump->softdep_jblocks;
2960 	MNT_ILOCK(mp);
2961 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2962 		stat_journal_min++;
2963 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2964 		mp->mnt_susp_owner = ump->softdep_flushtd;
2965 	}
2966 	jblocks->jb_suspended = 1;
2967 	MNT_IUNLOCK(mp);
2968 }
2969 
2970 static int
2971 journal_unsuspend(struct ufsmount *ump)
2972 {
2973 	struct jblocks *jblocks;
2974 	struct mount *mp;
2975 
2976 	mp = UFSTOVFS(ump);
2977 	jblocks = ump->softdep_jblocks;
2978 
2979 	if (jblocks != NULL && jblocks->jb_suspended &&
2980 	    journal_space(ump, jblocks->jb_min)) {
2981 		jblocks->jb_suspended = 0;
2982 		FREE_LOCK(ump);
2983 		mp->mnt_susp_owner = curthread;
2984 		vfs_write_resume(mp, 0);
2985 		ACQUIRE_LOCK(ump);
2986 		return (1);
2987 	}
2988 	return (0);
2989 }
2990 
2991 /*
2992  * Called before any allocation function to be certain that there is
2993  * sufficient space in the journal prior to creating any new records.
2994  * Since in the case of block allocation we may have multiple locked
2995  * buffers at the time of the actual allocation we can not block
2996  * when the journal records are created.  Doing so would create a deadlock
2997  * if any of these buffers needed to be flushed to reclaim space.  Instead
2998  * we require a sufficiently large amount of available space such that
2999  * each thread in the system could have passed this allocation check and
3000  * still have sufficient free space.  With 20% of a minimum journal size
3001  * of 1MB we have 6553 records available.
3002  */
3003 int
3004 softdep_prealloc(vp, waitok)
3005 	struct vnode *vp;
3006 	int waitok;
3007 {
3008 	struct ufsmount *ump;
3009 
3010 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3011 	    ("softdep_prealloc called on non-softdep filesystem"));
3012 	/*
3013 	 * Nothing to do if we are not running journaled soft updates.
3014 	 * If we currently hold the snapshot lock, we must avoid
3015 	 * handling other resources that could cause deadlock.  Do not
3016 	 * touch quotas vnode since it is typically recursed with
3017 	 * other vnode locks held.
3018 	 */
3019 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3020 	    (vp->v_vflag & VV_SYSTEM) != 0)
3021 		return (0);
3022 	ump = VFSTOUFS(vp->v_mount);
3023 	ACQUIRE_LOCK(ump);
3024 	if (journal_space(ump, 0)) {
3025 		FREE_LOCK(ump);
3026 		return (0);
3027 	}
3028 	stat_journal_low++;
3029 	FREE_LOCK(ump);
3030 	if (waitok == MNT_NOWAIT)
3031 		return (ENOSPC);
3032 	/*
3033 	 * Attempt to sync this vnode once to flush any journal
3034 	 * work attached to it.
3035 	 */
3036 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3037 		ffs_syncvnode(vp, waitok, 0);
3038 	ACQUIRE_LOCK(ump);
3039 	process_removes(vp);
3040 	process_truncates(vp);
3041 	if (journal_space(ump, 0) == 0) {
3042 		softdep_speedup(ump);
3043 		if (journal_space(ump, 1) == 0)
3044 			journal_suspend(ump);
3045 	}
3046 	FREE_LOCK(ump);
3047 
3048 	return (0);
3049 }
3050 
3051 /*
3052  * Before adjusting a link count on a vnode verify that we have sufficient
3053  * journal space.  If not, process operations that depend on the currently
3054  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3055  * and softdep flush threads can not acquire these locks to reclaim space.
3056  */
3057 static void
3058 softdep_prelink(dvp, vp)
3059 	struct vnode *dvp;
3060 	struct vnode *vp;
3061 {
3062 	struct ufsmount *ump;
3063 
3064 	ump = VFSTOUFS(dvp->v_mount);
3065 	LOCK_OWNED(ump);
3066 	/*
3067 	 * Nothing to do if we have sufficient journal space.
3068 	 * If we currently hold the snapshot lock, we must avoid
3069 	 * handling other resources that could cause deadlock.
3070 	 */
3071 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3072 		return;
3073 	stat_journal_low++;
3074 	FREE_LOCK(ump);
3075 	if (vp)
3076 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3077 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3078 	ACQUIRE_LOCK(ump);
3079 	/* Process vp before dvp as it may create .. removes. */
3080 	if (vp) {
3081 		process_removes(vp);
3082 		process_truncates(vp);
3083 	}
3084 	process_removes(dvp);
3085 	process_truncates(dvp);
3086 	softdep_speedup(ump);
3087 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3088 	if (journal_space(ump, 0) == 0) {
3089 		softdep_speedup(ump);
3090 		if (journal_space(ump, 1) == 0)
3091 			journal_suspend(ump);
3092 	}
3093 }
3094 
3095 static void
3096 jseg_write(ump, jseg, data)
3097 	struct ufsmount *ump;
3098 	struct jseg *jseg;
3099 	uint8_t *data;
3100 {
3101 	struct jsegrec *rec;
3102 
3103 	rec = (struct jsegrec *)data;
3104 	rec->jsr_seq = jseg->js_seq;
3105 	rec->jsr_oldest = jseg->js_oldseq;
3106 	rec->jsr_cnt = jseg->js_cnt;
3107 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3108 	rec->jsr_crc = 0;
3109 	rec->jsr_time = ump->um_fs->fs_mtime;
3110 }
3111 
3112 static inline void
3113 inoref_write(inoref, jseg, rec)
3114 	struct inoref *inoref;
3115 	struct jseg *jseg;
3116 	struct jrefrec *rec;
3117 {
3118 
3119 	inoref->if_jsegdep->jd_seg = jseg;
3120 	rec->jr_ino = inoref->if_ino;
3121 	rec->jr_parent = inoref->if_parent;
3122 	rec->jr_nlink = inoref->if_nlink;
3123 	rec->jr_mode = inoref->if_mode;
3124 	rec->jr_diroff = inoref->if_diroff;
3125 }
3126 
3127 static void
3128 jaddref_write(jaddref, jseg, data)
3129 	struct jaddref *jaddref;
3130 	struct jseg *jseg;
3131 	uint8_t *data;
3132 {
3133 	struct jrefrec *rec;
3134 
3135 	rec = (struct jrefrec *)data;
3136 	rec->jr_op = JOP_ADDREF;
3137 	inoref_write(&jaddref->ja_ref, jseg, rec);
3138 }
3139 
3140 static void
3141 jremref_write(jremref, jseg, data)
3142 	struct jremref *jremref;
3143 	struct jseg *jseg;
3144 	uint8_t *data;
3145 {
3146 	struct jrefrec *rec;
3147 
3148 	rec = (struct jrefrec *)data;
3149 	rec->jr_op = JOP_REMREF;
3150 	inoref_write(&jremref->jr_ref, jseg, rec);
3151 }
3152 
3153 static void
3154 jmvref_write(jmvref, jseg, data)
3155 	struct jmvref *jmvref;
3156 	struct jseg *jseg;
3157 	uint8_t *data;
3158 {
3159 	struct jmvrec *rec;
3160 
3161 	rec = (struct jmvrec *)data;
3162 	rec->jm_op = JOP_MVREF;
3163 	rec->jm_ino = jmvref->jm_ino;
3164 	rec->jm_parent = jmvref->jm_parent;
3165 	rec->jm_oldoff = jmvref->jm_oldoff;
3166 	rec->jm_newoff = jmvref->jm_newoff;
3167 }
3168 
3169 static void
3170 jnewblk_write(jnewblk, jseg, data)
3171 	struct jnewblk *jnewblk;
3172 	struct jseg *jseg;
3173 	uint8_t *data;
3174 {
3175 	struct jblkrec *rec;
3176 
3177 	jnewblk->jn_jsegdep->jd_seg = jseg;
3178 	rec = (struct jblkrec *)data;
3179 	rec->jb_op = JOP_NEWBLK;
3180 	rec->jb_ino = jnewblk->jn_ino;
3181 	rec->jb_blkno = jnewblk->jn_blkno;
3182 	rec->jb_lbn = jnewblk->jn_lbn;
3183 	rec->jb_frags = jnewblk->jn_frags;
3184 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3185 }
3186 
3187 static void
3188 jfreeblk_write(jfreeblk, jseg, data)
3189 	struct jfreeblk *jfreeblk;
3190 	struct jseg *jseg;
3191 	uint8_t *data;
3192 {
3193 	struct jblkrec *rec;
3194 
3195 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3196 	rec = (struct jblkrec *)data;
3197 	rec->jb_op = JOP_FREEBLK;
3198 	rec->jb_ino = jfreeblk->jf_ino;
3199 	rec->jb_blkno = jfreeblk->jf_blkno;
3200 	rec->jb_lbn = jfreeblk->jf_lbn;
3201 	rec->jb_frags = jfreeblk->jf_frags;
3202 	rec->jb_oldfrags = 0;
3203 }
3204 
3205 static void
3206 jfreefrag_write(jfreefrag, jseg, data)
3207 	struct jfreefrag *jfreefrag;
3208 	struct jseg *jseg;
3209 	uint8_t *data;
3210 {
3211 	struct jblkrec *rec;
3212 
3213 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3214 	rec = (struct jblkrec *)data;
3215 	rec->jb_op = JOP_FREEBLK;
3216 	rec->jb_ino = jfreefrag->fr_ino;
3217 	rec->jb_blkno = jfreefrag->fr_blkno;
3218 	rec->jb_lbn = jfreefrag->fr_lbn;
3219 	rec->jb_frags = jfreefrag->fr_frags;
3220 	rec->jb_oldfrags = 0;
3221 }
3222 
3223 static void
3224 jtrunc_write(jtrunc, jseg, data)
3225 	struct jtrunc *jtrunc;
3226 	struct jseg *jseg;
3227 	uint8_t *data;
3228 {
3229 	struct jtrncrec *rec;
3230 
3231 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3232 	rec = (struct jtrncrec *)data;
3233 	rec->jt_op = JOP_TRUNC;
3234 	rec->jt_ino = jtrunc->jt_ino;
3235 	rec->jt_size = jtrunc->jt_size;
3236 	rec->jt_extsize = jtrunc->jt_extsize;
3237 }
3238 
3239 static void
3240 jfsync_write(jfsync, jseg, data)
3241 	struct jfsync *jfsync;
3242 	struct jseg *jseg;
3243 	uint8_t *data;
3244 {
3245 	struct jtrncrec *rec;
3246 
3247 	rec = (struct jtrncrec *)data;
3248 	rec->jt_op = JOP_SYNC;
3249 	rec->jt_ino = jfsync->jfs_ino;
3250 	rec->jt_size = jfsync->jfs_size;
3251 	rec->jt_extsize = jfsync->jfs_extsize;
3252 }
3253 
3254 static void
3255 softdep_flushjournal(mp)
3256 	struct mount *mp;
3257 {
3258 	struct jblocks *jblocks;
3259 	struct ufsmount *ump;
3260 
3261 	if (MOUNTEDSUJ(mp) == 0)
3262 		return;
3263 	ump = VFSTOUFS(mp);
3264 	jblocks = ump->softdep_jblocks;
3265 	ACQUIRE_LOCK(ump);
3266 	while (ump->softdep_on_journal) {
3267 		jblocks->jb_needseg = 1;
3268 		softdep_process_journal(mp, NULL, MNT_WAIT);
3269 	}
3270 	FREE_LOCK(ump);
3271 }
3272 
3273 static void softdep_synchronize_completed(struct bio *);
3274 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3275 
3276 static void
3277 softdep_synchronize_completed(bp)
3278         struct bio *bp;
3279 {
3280 	struct jseg *oldest;
3281 	struct jseg *jseg;
3282 	struct ufsmount *ump;
3283 
3284 	/*
3285 	 * caller1 marks the last segment written before we issued the
3286 	 * synchronize cache.
3287 	 */
3288 	jseg = bp->bio_caller1;
3289 	if (jseg == NULL) {
3290 		g_destroy_bio(bp);
3291 		return;
3292 	}
3293 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3294 	ACQUIRE_LOCK(ump);
3295 	oldest = NULL;
3296 	/*
3297 	 * Mark all the journal entries waiting on the synchronize cache
3298 	 * as completed so they may continue on.
3299 	 */
3300 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3301 		jseg->js_state |= COMPLETE;
3302 		oldest = jseg;
3303 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3304 	}
3305 	/*
3306 	 * Restart deferred journal entry processing from the oldest
3307 	 * completed jseg.
3308 	 */
3309 	if (oldest)
3310 		complete_jsegs(oldest);
3311 
3312 	FREE_LOCK(ump);
3313 	g_destroy_bio(bp);
3314 }
3315 
3316 /*
3317  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3318  * barriers.  The journal must be written prior to any blocks that depend
3319  * on it and the journal can not be released until the blocks have be
3320  * written.  This code handles both barriers simultaneously.
3321  */
3322 static void
3323 softdep_synchronize(bp, ump, caller1)
3324 	struct bio *bp;
3325 	struct ufsmount *ump;
3326 	void *caller1;
3327 {
3328 
3329 	bp->bio_cmd = BIO_FLUSH;
3330 	bp->bio_flags |= BIO_ORDERED;
3331 	bp->bio_data = NULL;
3332 	bp->bio_offset = ump->um_cp->provider->mediasize;
3333 	bp->bio_length = 0;
3334 	bp->bio_done = softdep_synchronize_completed;
3335 	bp->bio_caller1 = caller1;
3336 	g_io_request(bp,
3337 	    (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3338 }
3339 
3340 /*
3341  * Flush some journal records to disk.
3342  */
3343 static void
3344 softdep_process_journal(mp, needwk, flags)
3345 	struct mount *mp;
3346 	struct worklist *needwk;
3347 	int flags;
3348 {
3349 	struct jblocks *jblocks;
3350 	struct ufsmount *ump;
3351 	struct worklist *wk;
3352 	struct jseg *jseg;
3353 	struct buf *bp;
3354 	struct bio *bio;
3355 	uint8_t *data;
3356 	struct fs *fs;
3357 	int shouldflush;
3358 	int segwritten;
3359 	int jrecmin;	/* Minimum records per block. */
3360 	int jrecmax;	/* Maximum records per block. */
3361 	int size;
3362 	int cnt;
3363 	int off;
3364 	int devbsize;
3365 
3366 	if (MOUNTEDSUJ(mp) == 0)
3367 		return;
3368 	shouldflush = softdep_flushcache;
3369 	bio = NULL;
3370 	jseg = NULL;
3371 	ump = VFSTOUFS(mp);
3372 	LOCK_OWNED(ump);
3373 	fs = ump->um_fs;
3374 	jblocks = ump->softdep_jblocks;
3375 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3376 	/*
3377 	 * We write anywhere between a disk block and fs block.  The upper
3378 	 * bound is picked to prevent buffer cache fragmentation and limit
3379 	 * processing time per I/O.
3380 	 */
3381 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3382 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3383 	segwritten = 0;
3384 	for (;;) {
3385 		cnt = ump->softdep_on_journal;
3386 		/*
3387 		 * Criteria for writing a segment:
3388 		 * 1) We have a full block.
3389 		 * 2) We're called from jwait() and haven't found the
3390 		 *    journal item yet.
3391 		 * 3) Always write if needseg is set.
3392 		 * 4) If we are called from process_worklist and have
3393 		 *    not yet written anything we write a partial block
3394 		 *    to enforce a 1 second maximum latency on journal
3395 		 *    entries.
3396 		 */
3397 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3398 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3399 			break;
3400 		cnt++;
3401 		/*
3402 		 * Verify some free journal space.  softdep_prealloc() should
3403 		 * guarantee that we don't run out so this is indicative of
3404 		 * a problem with the flow control.  Try to recover
3405 		 * gracefully in any event.
3406 		 */
3407 		while (jblocks->jb_free == 0) {
3408 			if (flags != MNT_WAIT)
3409 				break;
3410 			printf("softdep: Out of journal space!\n");
3411 			softdep_speedup(ump);
3412 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3413 		}
3414 		FREE_LOCK(ump);
3415 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3416 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3417 		LIST_INIT(&jseg->js_entries);
3418 		LIST_INIT(&jseg->js_indirs);
3419 		jseg->js_state = ATTACHED;
3420 		if (shouldflush == 0)
3421 			jseg->js_state |= COMPLETE;
3422 		else if (bio == NULL)
3423 			bio = g_alloc_bio();
3424 		jseg->js_jblocks = jblocks;
3425 		bp = geteblk(fs->fs_bsize, 0);
3426 		ACQUIRE_LOCK(ump);
3427 		/*
3428 		 * If there was a race while we were allocating the block
3429 		 * and jseg the entry we care about was likely written.
3430 		 * We bail out in both the WAIT and NOWAIT case and assume
3431 		 * the caller will loop if the entry it cares about is
3432 		 * not written.
3433 		 */
3434 		cnt = ump->softdep_on_journal;
3435 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3436 			bp->b_flags |= B_INVAL | B_NOCACHE;
3437 			WORKITEM_FREE(jseg, D_JSEG);
3438 			FREE_LOCK(ump);
3439 			brelse(bp);
3440 			ACQUIRE_LOCK(ump);
3441 			break;
3442 		}
3443 		/*
3444 		 * Calculate the disk block size required for the available
3445 		 * records rounded to the min size.
3446 		 */
3447 		if (cnt == 0)
3448 			size = devbsize;
3449 		else if (cnt < jrecmax)
3450 			size = howmany(cnt, jrecmin) * devbsize;
3451 		else
3452 			size = fs->fs_bsize;
3453 		/*
3454 		 * Allocate a disk block for this journal data and account
3455 		 * for truncation of the requested size if enough contiguous
3456 		 * space was not available.
3457 		 */
3458 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3459 		bp->b_lblkno = bp->b_blkno;
3460 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3461 		bp->b_bcount = size;
3462 		bp->b_flags &= ~B_INVAL;
3463 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3464 		/*
3465 		 * Initialize our jseg with cnt records.  Assign the next
3466 		 * sequence number to it and link it in-order.
3467 		 */
3468 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3469 		jseg->js_buf = bp;
3470 		jseg->js_cnt = cnt;
3471 		jseg->js_refs = cnt + 1;	/* Self ref. */
3472 		jseg->js_size = size;
3473 		jseg->js_seq = jblocks->jb_nextseq++;
3474 		if (jblocks->jb_oldestseg == NULL)
3475 			jblocks->jb_oldestseg = jseg;
3476 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3477 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3478 		if (jblocks->jb_writeseg == NULL)
3479 			jblocks->jb_writeseg = jseg;
3480 		/*
3481 		 * Start filling in records from the pending list.
3482 		 */
3483 		data = bp->b_data;
3484 		off = 0;
3485 
3486 		/*
3487 		 * Always put a header on the first block.
3488 		 * XXX As with below, there might not be a chance to get
3489 		 * into the loop.  Ensure that something valid is written.
3490 		 */
3491 		jseg_write(ump, jseg, data);
3492 		off += JREC_SIZE;
3493 		data = bp->b_data + off;
3494 
3495 		/*
3496 		 * XXX Something is wrong here.  There's no work to do,
3497 		 * but we need to perform and I/O and allow it to complete
3498 		 * anyways.
3499 		 */
3500 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3501 			stat_emptyjblocks++;
3502 
3503 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3504 		    != NULL) {
3505 			if (cnt == 0)
3506 				break;
3507 			/* Place a segment header on every device block. */
3508 			if ((off % devbsize) == 0) {
3509 				jseg_write(ump, jseg, data);
3510 				off += JREC_SIZE;
3511 				data = bp->b_data + off;
3512 			}
3513 			if (wk == needwk)
3514 				needwk = NULL;
3515 			remove_from_journal(wk);
3516 			wk->wk_state |= INPROGRESS;
3517 			WORKLIST_INSERT(&jseg->js_entries, wk);
3518 			switch (wk->wk_type) {
3519 			case D_JADDREF:
3520 				jaddref_write(WK_JADDREF(wk), jseg, data);
3521 				break;
3522 			case D_JREMREF:
3523 				jremref_write(WK_JREMREF(wk), jseg, data);
3524 				break;
3525 			case D_JMVREF:
3526 				jmvref_write(WK_JMVREF(wk), jseg, data);
3527 				break;
3528 			case D_JNEWBLK:
3529 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3530 				break;
3531 			case D_JFREEBLK:
3532 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3533 				break;
3534 			case D_JFREEFRAG:
3535 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3536 				break;
3537 			case D_JTRUNC:
3538 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3539 				break;
3540 			case D_JFSYNC:
3541 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3542 				break;
3543 			default:
3544 				panic("process_journal: Unknown type %s",
3545 				    TYPENAME(wk->wk_type));
3546 				/* NOTREACHED */
3547 			}
3548 			off += JREC_SIZE;
3549 			data = bp->b_data + off;
3550 			cnt--;
3551 		}
3552 
3553 		/* Clear any remaining space so we don't leak kernel data */
3554 		if (size > off)
3555 			bzero(data, size - off);
3556 
3557 		/*
3558 		 * Write this one buffer and continue.
3559 		 */
3560 		segwritten = 1;
3561 		jblocks->jb_needseg = 0;
3562 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3563 		FREE_LOCK(ump);
3564 		pbgetvp(ump->um_devvp, bp);
3565 		/*
3566 		 * We only do the blocking wait once we find the journal
3567 		 * entry we're looking for.
3568 		 */
3569 		if (needwk == NULL && flags == MNT_WAIT)
3570 			bwrite(bp);
3571 		else
3572 			bawrite(bp);
3573 		ACQUIRE_LOCK(ump);
3574 	}
3575 	/*
3576 	 * If we wrote a segment issue a synchronize cache so the journal
3577 	 * is reflected on disk before the data is written.  Since reclaiming
3578 	 * journal space also requires writing a journal record this
3579 	 * process also enforces a barrier before reclamation.
3580 	 */
3581 	if (segwritten && shouldflush) {
3582 		softdep_synchronize(bio, ump,
3583 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3584 	} else if (bio)
3585 		g_destroy_bio(bio);
3586 	/*
3587 	 * If we've suspended the filesystem because we ran out of journal
3588 	 * space either try to sync it here to make some progress or
3589 	 * unsuspend it if we already have.
3590 	 */
3591 	if (flags == 0 && jblocks->jb_suspended) {
3592 		if (journal_unsuspend(ump))
3593 			return;
3594 		FREE_LOCK(ump);
3595 		VFS_SYNC(mp, MNT_NOWAIT);
3596 		ffs_sbupdate(ump, MNT_WAIT, 0);
3597 		ACQUIRE_LOCK(ump);
3598 	}
3599 }
3600 
3601 /*
3602  * Complete a jseg, allowing all dependencies awaiting journal writes
3603  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3604  * structures so that the journal segment can be freed to reclaim space.
3605  */
3606 static void
3607 complete_jseg(jseg)
3608 	struct jseg *jseg;
3609 {
3610 	struct worklist *wk;
3611 	struct jmvref *jmvref;
3612 #ifdef INVARIANTS
3613 	int i = 0;
3614 #endif
3615 
3616 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3617 		WORKLIST_REMOVE(wk);
3618 		wk->wk_state &= ~INPROGRESS;
3619 		wk->wk_state |= COMPLETE;
3620 		KASSERT(i++ < jseg->js_cnt,
3621 		    ("handle_written_jseg: overflow %d >= %d",
3622 		    i - 1, jseg->js_cnt));
3623 		switch (wk->wk_type) {
3624 		case D_JADDREF:
3625 			handle_written_jaddref(WK_JADDREF(wk));
3626 			break;
3627 		case D_JREMREF:
3628 			handle_written_jremref(WK_JREMREF(wk));
3629 			break;
3630 		case D_JMVREF:
3631 			rele_jseg(jseg);	/* No jsegdep. */
3632 			jmvref = WK_JMVREF(wk);
3633 			LIST_REMOVE(jmvref, jm_deps);
3634 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3635 				free_pagedep(jmvref->jm_pagedep);
3636 			WORKITEM_FREE(jmvref, D_JMVREF);
3637 			break;
3638 		case D_JNEWBLK:
3639 			handle_written_jnewblk(WK_JNEWBLK(wk));
3640 			break;
3641 		case D_JFREEBLK:
3642 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3643 			break;
3644 		case D_JTRUNC:
3645 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3646 			break;
3647 		case D_JFSYNC:
3648 			rele_jseg(jseg);	/* No jsegdep. */
3649 			WORKITEM_FREE(wk, D_JFSYNC);
3650 			break;
3651 		case D_JFREEFRAG:
3652 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3653 			break;
3654 		default:
3655 			panic("handle_written_jseg: Unknown type %s",
3656 			    TYPENAME(wk->wk_type));
3657 			/* NOTREACHED */
3658 		}
3659 	}
3660 	/* Release the self reference so the structure may be freed. */
3661 	rele_jseg(jseg);
3662 }
3663 
3664 /*
3665  * Determine which jsegs are ready for completion processing.  Waits for
3666  * synchronize cache to complete as well as forcing in-order completion
3667  * of journal entries.
3668  */
3669 static void
3670 complete_jsegs(jseg)
3671 	struct jseg *jseg;
3672 {
3673 	struct jblocks *jblocks;
3674 	struct jseg *jsegn;
3675 
3676 	jblocks = jseg->js_jblocks;
3677 	/*
3678 	 * Don't allow out of order completions.  If this isn't the first
3679 	 * block wait for it to write before we're done.
3680 	 */
3681 	if (jseg != jblocks->jb_writeseg)
3682 		return;
3683 	/* Iterate through available jsegs processing their entries. */
3684 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3685 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3686 		jsegn = TAILQ_NEXT(jseg, js_next);
3687 		complete_jseg(jseg);
3688 		jseg = jsegn;
3689 	}
3690 	jblocks->jb_writeseg = jseg;
3691 	/*
3692 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3693 	 */
3694 	free_jsegs(jblocks);
3695 }
3696 
3697 /*
3698  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3699  * the final completions.
3700  */
3701 static void
3702 handle_written_jseg(jseg, bp)
3703 	struct jseg *jseg;
3704 	struct buf *bp;
3705 {
3706 
3707 	if (jseg->js_refs == 0)
3708 		panic("handle_written_jseg: No self-reference on %p", jseg);
3709 	jseg->js_state |= DEPCOMPLETE;
3710 	/*
3711 	 * We'll never need this buffer again, set flags so it will be
3712 	 * discarded.
3713 	 */
3714 	bp->b_flags |= B_INVAL | B_NOCACHE;
3715 	pbrelvp(bp);
3716 	complete_jsegs(jseg);
3717 }
3718 
3719 static inline struct jsegdep *
3720 inoref_jseg(inoref)
3721 	struct inoref *inoref;
3722 {
3723 	struct jsegdep *jsegdep;
3724 
3725 	jsegdep = inoref->if_jsegdep;
3726 	inoref->if_jsegdep = NULL;
3727 
3728 	return (jsegdep);
3729 }
3730 
3731 /*
3732  * Called once a jremref has made it to stable store.  The jremref is marked
3733  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3734  * for the jremref to complete will be awoken by free_jremref.
3735  */
3736 static void
3737 handle_written_jremref(jremref)
3738 	struct jremref *jremref;
3739 {
3740 	struct inodedep *inodedep;
3741 	struct jsegdep *jsegdep;
3742 	struct dirrem *dirrem;
3743 
3744 	/* Grab the jsegdep. */
3745 	jsegdep = inoref_jseg(&jremref->jr_ref);
3746 	/*
3747 	 * Remove us from the inoref list.
3748 	 */
3749 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3750 	    0, &inodedep) == 0)
3751 		panic("handle_written_jremref: Lost inodedep");
3752 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3753 	/*
3754 	 * Complete the dirrem.
3755 	 */
3756 	dirrem = jremref->jr_dirrem;
3757 	jremref->jr_dirrem = NULL;
3758 	LIST_REMOVE(jremref, jr_deps);
3759 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3760 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3761 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3762 	    (dirrem->dm_state & COMPLETE) != 0)
3763 		add_to_worklist(&dirrem->dm_list, 0);
3764 	free_jremref(jremref);
3765 }
3766 
3767 /*
3768  * Called once a jaddref has made it to stable store.  The dependency is
3769  * marked complete and any dependent structures are added to the inode
3770  * bufwait list to be completed as soon as it is written.  If a bitmap write
3771  * depends on this entry we move the inode into the inodedephd of the
3772  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3773  */
3774 static void
3775 handle_written_jaddref(jaddref)
3776 	struct jaddref *jaddref;
3777 {
3778 	struct jsegdep *jsegdep;
3779 	struct inodedep *inodedep;
3780 	struct diradd *diradd;
3781 	struct mkdir *mkdir;
3782 
3783 	/* Grab the jsegdep. */
3784 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3785 	mkdir = NULL;
3786 	diradd = NULL;
3787 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3788 	    0, &inodedep) == 0)
3789 		panic("handle_written_jaddref: Lost inodedep.");
3790 	if (jaddref->ja_diradd == NULL)
3791 		panic("handle_written_jaddref: No dependency");
3792 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3793 		diradd = jaddref->ja_diradd;
3794 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3795 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3796 		mkdir = jaddref->ja_mkdir;
3797 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3798 	} else if (jaddref->ja_state & MKDIR_BODY)
3799 		mkdir = jaddref->ja_mkdir;
3800 	else
3801 		panic("handle_written_jaddref: Unknown dependency %p",
3802 		    jaddref->ja_diradd);
3803 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3804 	/*
3805 	 * Remove us from the inode list.
3806 	 */
3807 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3808 	/*
3809 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3810 	 */
3811 	if (mkdir) {
3812 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3813 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3814 		    TYPENAME(mkdir->md_list.wk_type)));
3815 		mkdir->md_jaddref = NULL;
3816 		diradd = mkdir->md_diradd;
3817 		mkdir->md_state |= DEPCOMPLETE;
3818 		complete_mkdir(mkdir);
3819 	}
3820 	jwork_insert(&diradd->da_jwork, jsegdep);
3821 	if (jaddref->ja_state & NEWBLOCK) {
3822 		inodedep->id_state |= ONDEPLIST;
3823 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3824 		    inodedep, id_deps);
3825 	}
3826 	free_jaddref(jaddref);
3827 }
3828 
3829 /*
3830  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3831  * is placed in the bmsafemap to await notification of a written bitmap.  If
3832  * the operation was canceled we add the segdep to the appropriate
3833  * dependency to free the journal space once the canceling operation
3834  * completes.
3835  */
3836 static void
3837 handle_written_jnewblk(jnewblk)
3838 	struct jnewblk *jnewblk;
3839 {
3840 	struct bmsafemap *bmsafemap;
3841 	struct freefrag *freefrag;
3842 	struct freework *freework;
3843 	struct jsegdep *jsegdep;
3844 	struct newblk *newblk;
3845 
3846 	/* Grab the jsegdep. */
3847 	jsegdep = jnewblk->jn_jsegdep;
3848 	jnewblk->jn_jsegdep = NULL;
3849 	if (jnewblk->jn_dep == NULL)
3850 		panic("handle_written_jnewblk: No dependency for the segdep.");
3851 	switch (jnewblk->jn_dep->wk_type) {
3852 	case D_NEWBLK:
3853 	case D_ALLOCDIRECT:
3854 	case D_ALLOCINDIR:
3855 		/*
3856 		 * Add the written block to the bmsafemap so it can
3857 		 * be notified when the bitmap is on disk.
3858 		 */
3859 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3860 		newblk->nb_jnewblk = NULL;
3861 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3862 			bmsafemap = newblk->nb_bmsafemap;
3863 			newblk->nb_state |= ONDEPLIST;
3864 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3865 			    nb_deps);
3866 		}
3867 		jwork_insert(&newblk->nb_jwork, jsegdep);
3868 		break;
3869 	case D_FREEFRAG:
3870 		/*
3871 		 * A newblock being removed by a freefrag when replaced by
3872 		 * frag extension.
3873 		 */
3874 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3875 		freefrag->ff_jdep = NULL;
3876 		jwork_insert(&freefrag->ff_jwork, jsegdep);
3877 		break;
3878 	case D_FREEWORK:
3879 		/*
3880 		 * A direct block was removed by truncate.
3881 		 */
3882 		freework = WK_FREEWORK(jnewblk->jn_dep);
3883 		freework->fw_jnewblk = NULL;
3884 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3885 		break;
3886 	default:
3887 		panic("handle_written_jnewblk: Unknown type %d.",
3888 		    jnewblk->jn_dep->wk_type);
3889 	}
3890 	jnewblk->jn_dep = NULL;
3891 	free_jnewblk(jnewblk);
3892 }
3893 
3894 /*
3895  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3896  * an in-flight allocation that has not yet been committed.  Divorce us
3897  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3898  * to the worklist.
3899  */
3900 static void
3901 cancel_jfreefrag(jfreefrag)
3902 	struct jfreefrag *jfreefrag;
3903 {
3904 	struct freefrag *freefrag;
3905 
3906 	if (jfreefrag->fr_jsegdep) {
3907 		free_jsegdep(jfreefrag->fr_jsegdep);
3908 		jfreefrag->fr_jsegdep = NULL;
3909 	}
3910 	freefrag = jfreefrag->fr_freefrag;
3911 	jfreefrag->fr_freefrag = NULL;
3912 	free_jfreefrag(jfreefrag);
3913 	freefrag->ff_state |= DEPCOMPLETE;
3914 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3915 }
3916 
3917 /*
3918  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3919  */
3920 static void
3921 free_jfreefrag(jfreefrag)
3922 	struct jfreefrag *jfreefrag;
3923 {
3924 
3925 	if (jfreefrag->fr_state & INPROGRESS)
3926 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3927 	else if (jfreefrag->fr_state & ONWORKLIST)
3928 		remove_from_journal(&jfreefrag->fr_list);
3929 	if (jfreefrag->fr_freefrag != NULL)
3930 		panic("free_jfreefrag:  Still attached to a freefrag.");
3931 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3932 }
3933 
3934 /*
3935  * Called when the journal write for a jfreefrag completes.  The parent
3936  * freefrag is added to the worklist if this completes its dependencies.
3937  */
3938 static void
3939 handle_written_jfreefrag(jfreefrag)
3940 	struct jfreefrag *jfreefrag;
3941 {
3942 	struct jsegdep *jsegdep;
3943 	struct freefrag *freefrag;
3944 
3945 	/* Grab the jsegdep. */
3946 	jsegdep = jfreefrag->fr_jsegdep;
3947 	jfreefrag->fr_jsegdep = NULL;
3948 	freefrag = jfreefrag->fr_freefrag;
3949 	if (freefrag == NULL)
3950 		panic("handle_written_jfreefrag: No freefrag.");
3951 	freefrag->ff_state |= DEPCOMPLETE;
3952 	freefrag->ff_jdep = NULL;
3953 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3954 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3955 		add_to_worklist(&freefrag->ff_list, 0);
3956 	jfreefrag->fr_freefrag = NULL;
3957 	free_jfreefrag(jfreefrag);
3958 }
3959 
3960 /*
3961  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3962  * is removed from the freeblks list of pending journal writes and the
3963  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3964  * have been reclaimed.
3965  */
3966 static void
3967 handle_written_jblkdep(jblkdep)
3968 	struct jblkdep *jblkdep;
3969 {
3970 	struct freeblks *freeblks;
3971 	struct jsegdep *jsegdep;
3972 
3973 	/* Grab the jsegdep. */
3974 	jsegdep = jblkdep->jb_jsegdep;
3975 	jblkdep->jb_jsegdep = NULL;
3976 	freeblks = jblkdep->jb_freeblks;
3977 	LIST_REMOVE(jblkdep, jb_deps);
3978 	jwork_insert(&freeblks->fb_jwork, jsegdep);
3979 	/*
3980 	 * If the freeblks is all journaled, we can add it to the worklist.
3981 	 */
3982 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3983 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3984 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3985 
3986 	free_jblkdep(jblkdep);
3987 }
3988 
3989 static struct jsegdep *
3990 newjsegdep(struct worklist *wk)
3991 {
3992 	struct jsegdep *jsegdep;
3993 
3994 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3995 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3996 	jsegdep->jd_seg = NULL;
3997 
3998 	return (jsegdep);
3999 }
4000 
4001 static struct jmvref *
4002 newjmvref(dp, ino, oldoff, newoff)
4003 	struct inode *dp;
4004 	ino_t ino;
4005 	off_t oldoff;
4006 	off_t newoff;
4007 {
4008 	struct jmvref *jmvref;
4009 
4010 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4011 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4012 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4013 	jmvref->jm_parent = dp->i_number;
4014 	jmvref->jm_ino = ino;
4015 	jmvref->jm_oldoff = oldoff;
4016 	jmvref->jm_newoff = newoff;
4017 
4018 	return (jmvref);
4019 }
4020 
4021 /*
4022  * Allocate a new jremref that tracks the removal of ip from dp with the
4023  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4024  * DEPCOMPLETE as we have all the information required for the journal write
4025  * and the directory has already been removed from the buffer.  The caller
4026  * is responsible for linking the jremref into the pagedep and adding it
4027  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4028  * a DOTDOT addition so handle_workitem_remove() can properly assign
4029  * the jsegdep when we're done.
4030  */
4031 static struct jremref *
4032 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4033     off_t diroff, nlink_t nlink)
4034 {
4035 	struct jremref *jremref;
4036 
4037 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4038 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4039 	jremref->jr_state = ATTACHED;
4040 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4041 	   nlink, ip->i_mode);
4042 	jremref->jr_dirrem = dirrem;
4043 
4044 	return (jremref);
4045 }
4046 
4047 static inline void
4048 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4049     nlink_t nlink, uint16_t mode)
4050 {
4051 
4052 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4053 	inoref->if_diroff = diroff;
4054 	inoref->if_ino = ino;
4055 	inoref->if_parent = parent;
4056 	inoref->if_nlink = nlink;
4057 	inoref->if_mode = mode;
4058 }
4059 
4060 /*
4061  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4062  * directory offset may not be known until later.  The caller is responsible
4063  * adding the entry to the journal when this information is available.  nlink
4064  * should be the link count prior to the addition and mode is only required
4065  * to have the correct FMT.
4066  */
4067 static struct jaddref *
4068 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4069     uint16_t mode)
4070 {
4071 	struct jaddref *jaddref;
4072 
4073 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4074 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4075 	jaddref->ja_state = ATTACHED;
4076 	jaddref->ja_mkdir = NULL;
4077 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4078 
4079 	return (jaddref);
4080 }
4081 
4082 /*
4083  * Create a new free dependency for a freework.  The caller is responsible
4084  * for adjusting the reference count when it has the lock held.  The freedep
4085  * will track an outstanding bitmap write that will ultimately clear the
4086  * freework to continue.
4087  */
4088 static struct freedep *
4089 newfreedep(struct freework *freework)
4090 {
4091 	struct freedep *freedep;
4092 
4093 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4094 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4095 	freedep->fd_freework = freework;
4096 
4097 	return (freedep);
4098 }
4099 
4100 /*
4101  * Free a freedep structure once the buffer it is linked to is written.  If
4102  * this is the last reference to the freework schedule it for completion.
4103  */
4104 static void
4105 free_freedep(freedep)
4106 	struct freedep *freedep;
4107 {
4108 	struct freework *freework;
4109 
4110 	freework = freedep->fd_freework;
4111 	freework->fw_freeblks->fb_cgwait--;
4112 	if (--freework->fw_ref == 0)
4113 		freework_enqueue(freework);
4114 	WORKITEM_FREE(freedep, D_FREEDEP);
4115 }
4116 
4117 /*
4118  * Allocate a new freework structure that may be a level in an indirect
4119  * when parent is not NULL or a top level block when it is.  The top level
4120  * freework structures are allocated without the per-filesystem lock held
4121  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4122  */
4123 static struct freework *
4124 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4125 	struct ufsmount *ump;
4126 	struct freeblks *freeblks;
4127 	struct freework *parent;
4128 	ufs_lbn_t lbn;
4129 	ufs2_daddr_t nb;
4130 	int frags;
4131 	int off;
4132 	int journal;
4133 {
4134 	struct freework *freework;
4135 
4136 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4137 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4138 	freework->fw_state = ATTACHED;
4139 	freework->fw_jnewblk = NULL;
4140 	freework->fw_freeblks = freeblks;
4141 	freework->fw_parent = parent;
4142 	freework->fw_lbn = lbn;
4143 	freework->fw_blkno = nb;
4144 	freework->fw_frags = frags;
4145 	freework->fw_indir = NULL;
4146 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4147 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4148 	freework->fw_start = freework->fw_off = off;
4149 	if (journal)
4150 		newjfreeblk(freeblks, lbn, nb, frags);
4151 	if (parent == NULL) {
4152 		ACQUIRE_LOCK(ump);
4153 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4154 		freeblks->fb_ref++;
4155 		FREE_LOCK(ump);
4156 	}
4157 
4158 	return (freework);
4159 }
4160 
4161 /*
4162  * Eliminate a jfreeblk for a block that does not need journaling.
4163  */
4164 static void
4165 cancel_jfreeblk(freeblks, blkno)
4166 	struct freeblks *freeblks;
4167 	ufs2_daddr_t blkno;
4168 {
4169 	struct jfreeblk *jfreeblk;
4170 	struct jblkdep *jblkdep;
4171 
4172 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4173 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4174 			continue;
4175 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4176 		if (jfreeblk->jf_blkno == blkno)
4177 			break;
4178 	}
4179 	if (jblkdep == NULL)
4180 		return;
4181 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4182 	free_jsegdep(jblkdep->jb_jsegdep);
4183 	LIST_REMOVE(jblkdep, jb_deps);
4184 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4185 }
4186 
4187 /*
4188  * Allocate a new jfreeblk to journal top level block pointer when truncating
4189  * a file.  The caller must add this to the worklist when the per-filesystem
4190  * lock is held.
4191  */
4192 static struct jfreeblk *
4193 newjfreeblk(freeblks, lbn, blkno, frags)
4194 	struct freeblks *freeblks;
4195 	ufs_lbn_t lbn;
4196 	ufs2_daddr_t blkno;
4197 	int frags;
4198 {
4199 	struct jfreeblk *jfreeblk;
4200 
4201 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4202 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4203 	    freeblks->fb_list.wk_mp);
4204 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4205 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4206 	jfreeblk->jf_ino = freeblks->fb_inum;
4207 	jfreeblk->jf_lbn = lbn;
4208 	jfreeblk->jf_blkno = blkno;
4209 	jfreeblk->jf_frags = frags;
4210 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4211 
4212 	return (jfreeblk);
4213 }
4214 
4215 /*
4216  * The journal is only prepared to handle full-size block numbers, so we
4217  * have to adjust the record to reflect the change to a full-size block.
4218  * For example, suppose we have a block made up of fragments 8-15 and
4219  * want to free its last two fragments. We are given a request that says:
4220  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4221  * where frags are the number of fragments to free and oldfrags are the
4222  * number of fragments to keep. To block align it, we have to change it to
4223  * have a valid full-size blkno, so it becomes:
4224  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4225  */
4226 static void
4227 adjust_newfreework(freeblks, frag_offset)
4228 	struct freeblks *freeblks;
4229 	int frag_offset;
4230 {
4231 	struct jfreeblk *jfreeblk;
4232 
4233 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4234 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4235 	    ("adjust_newfreework: Missing freeblks dependency"));
4236 
4237 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4238 	jfreeblk->jf_blkno -= frag_offset;
4239 	jfreeblk->jf_frags += frag_offset;
4240 }
4241 
4242 /*
4243  * Allocate a new jtrunc to track a partial truncation.
4244  */
4245 static struct jtrunc *
4246 newjtrunc(freeblks, size, extsize)
4247 	struct freeblks *freeblks;
4248 	off_t size;
4249 	int extsize;
4250 {
4251 	struct jtrunc *jtrunc;
4252 
4253 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4254 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4255 	    freeblks->fb_list.wk_mp);
4256 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4257 	jtrunc->jt_dep.jb_freeblks = freeblks;
4258 	jtrunc->jt_ino = freeblks->fb_inum;
4259 	jtrunc->jt_size = size;
4260 	jtrunc->jt_extsize = extsize;
4261 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4262 
4263 	return (jtrunc);
4264 }
4265 
4266 /*
4267  * If we're canceling a new bitmap we have to search for another ref
4268  * to move into the bmsafemap dep.  This might be better expressed
4269  * with another structure.
4270  */
4271 static void
4272 move_newblock_dep(jaddref, inodedep)
4273 	struct jaddref *jaddref;
4274 	struct inodedep *inodedep;
4275 {
4276 	struct inoref *inoref;
4277 	struct jaddref *jaddrefn;
4278 
4279 	jaddrefn = NULL;
4280 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4281 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4282 		if ((jaddref->ja_state & NEWBLOCK) &&
4283 		    inoref->if_list.wk_type == D_JADDREF) {
4284 			jaddrefn = (struct jaddref *)inoref;
4285 			break;
4286 		}
4287 	}
4288 	if (jaddrefn == NULL)
4289 		return;
4290 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4291 	jaddrefn->ja_state |= jaddref->ja_state &
4292 	    (ATTACHED | UNDONE | NEWBLOCK);
4293 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4294 	jaddref->ja_state |= ATTACHED;
4295 	LIST_REMOVE(jaddref, ja_bmdeps);
4296 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4297 	    ja_bmdeps);
4298 }
4299 
4300 /*
4301  * Cancel a jaddref either before it has been written or while it is being
4302  * written.  This happens when a link is removed before the add reaches
4303  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4304  * and inode to prevent the link count or bitmap from reaching the disk
4305  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4306  * required.
4307  *
4308  * Returns 1 if the canceled addref requires journaling of the remove and
4309  * 0 otherwise.
4310  */
4311 static int
4312 cancel_jaddref(jaddref, inodedep, wkhd)
4313 	struct jaddref *jaddref;
4314 	struct inodedep *inodedep;
4315 	struct workhead *wkhd;
4316 {
4317 	struct inoref *inoref;
4318 	struct jsegdep *jsegdep;
4319 	int needsj;
4320 
4321 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4322 	    ("cancel_jaddref: Canceling complete jaddref"));
4323 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4324 		needsj = 1;
4325 	else
4326 		needsj = 0;
4327 	if (inodedep == NULL)
4328 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4329 		    0, &inodedep) == 0)
4330 			panic("cancel_jaddref: Lost inodedep");
4331 	/*
4332 	 * We must adjust the nlink of any reference operation that follows
4333 	 * us so that it is consistent with the in-memory reference.  This
4334 	 * ensures that inode nlink rollbacks always have the correct link.
4335 	 */
4336 	if (needsj == 0) {
4337 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4338 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4339 			if (inoref->if_state & GOINGAWAY)
4340 				break;
4341 			inoref->if_nlink--;
4342 		}
4343 	}
4344 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4345 	if (jaddref->ja_state & NEWBLOCK)
4346 		move_newblock_dep(jaddref, inodedep);
4347 	wake_worklist(&jaddref->ja_list);
4348 	jaddref->ja_mkdir = NULL;
4349 	if (jaddref->ja_state & INPROGRESS) {
4350 		jaddref->ja_state &= ~INPROGRESS;
4351 		WORKLIST_REMOVE(&jaddref->ja_list);
4352 		jwork_insert(wkhd, jsegdep);
4353 	} else {
4354 		free_jsegdep(jsegdep);
4355 		if (jaddref->ja_state & DEPCOMPLETE)
4356 			remove_from_journal(&jaddref->ja_list);
4357 	}
4358 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4359 	/*
4360 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4361 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4362 	 * no longer need this addref attached to the inoreflst and it
4363 	 * will incorrectly adjust nlink if we leave it.
4364 	 */
4365 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4366 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4367 		    if_deps);
4368 		jaddref->ja_state |= COMPLETE;
4369 		free_jaddref(jaddref);
4370 		return (needsj);
4371 	}
4372 	/*
4373 	 * Leave the head of the list for jsegdeps for fast merging.
4374 	 */
4375 	if (LIST_FIRST(wkhd) != NULL) {
4376 		jaddref->ja_state |= ONWORKLIST;
4377 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4378 	} else
4379 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4380 
4381 	return (needsj);
4382 }
4383 
4384 /*
4385  * Attempt to free a jaddref structure when some work completes.  This
4386  * should only succeed once the entry is written and all dependencies have
4387  * been notified.
4388  */
4389 static void
4390 free_jaddref(jaddref)
4391 	struct jaddref *jaddref;
4392 {
4393 
4394 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4395 		return;
4396 	if (jaddref->ja_ref.if_jsegdep)
4397 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4398 		    jaddref, jaddref->ja_state);
4399 	if (jaddref->ja_state & NEWBLOCK)
4400 		LIST_REMOVE(jaddref, ja_bmdeps);
4401 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4402 		panic("free_jaddref: Bad state %p(0x%X)",
4403 		    jaddref, jaddref->ja_state);
4404 	if (jaddref->ja_mkdir != NULL)
4405 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4406 	WORKITEM_FREE(jaddref, D_JADDREF);
4407 }
4408 
4409 /*
4410  * Free a jremref structure once it has been written or discarded.
4411  */
4412 static void
4413 free_jremref(jremref)
4414 	struct jremref *jremref;
4415 {
4416 
4417 	if (jremref->jr_ref.if_jsegdep)
4418 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4419 	if (jremref->jr_state & INPROGRESS)
4420 		panic("free_jremref: IO still pending");
4421 	WORKITEM_FREE(jremref, D_JREMREF);
4422 }
4423 
4424 /*
4425  * Free a jnewblk structure.
4426  */
4427 static void
4428 free_jnewblk(jnewblk)
4429 	struct jnewblk *jnewblk;
4430 {
4431 
4432 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4433 		return;
4434 	LIST_REMOVE(jnewblk, jn_deps);
4435 	if (jnewblk->jn_dep != NULL)
4436 		panic("free_jnewblk: Dependency still attached.");
4437 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4438 }
4439 
4440 /*
4441  * Cancel a jnewblk which has been been made redundant by frag extension.
4442  */
4443 static void
4444 cancel_jnewblk(jnewblk, wkhd)
4445 	struct jnewblk *jnewblk;
4446 	struct workhead *wkhd;
4447 {
4448 	struct jsegdep *jsegdep;
4449 
4450 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4451 	jsegdep = jnewblk->jn_jsegdep;
4452 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4453 		panic("cancel_jnewblk: Invalid state");
4454 	jnewblk->jn_jsegdep  = NULL;
4455 	jnewblk->jn_dep = NULL;
4456 	jnewblk->jn_state |= GOINGAWAY;
4457 	if (jnewblk->jn_state & INPROGRESS) {
4458 		jnewblk->jn_state &= ~INPROGRESS;
4459 		WORKLIST_REMOVE(&jnewblk->jn_list);
4460 		jwork_insert(wkhd, jsegdep);
4461 	} else {
4462 		free_jsegdep(jsegdep);
4463 		remove_from_journal(&jnewblk->jn_list);
4464 	}
4465 	wake_worklist(&jnewblk->jn_list);
4466 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4467 }
4468 
4469 static void
4470 free_jblkdep(jblkdep)
4471 	struct jblkdep *jblkdep;
4472 {
4473 
4474 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4475 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4476 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4477 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4478 	else
4479 		panic("free_jblkdep: Unexpected type %s",
4480 		    TYPENAME(jblkdep->jb_list.wk_type));
4481 }
4482 
4483 /*
4484  * Free a single jseg once it is no longer referenced in memory or on
4485  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4486  * to disappear.
4487  */
4488 static void
4489 free_jseg(jseg, jblocks)
4490 	struct jseg *jseg;
4491 	struct jblocks *jblocks;
4492 {
4493 	struct freework *freework;
4494 
4495 	/*
4496 	 * Free freework structures that were lingering to indicate freed
4497 	 * indirect blocks that forced journal write ordering on reallocate.
4498 	 */
4499 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4500 		indirblk_remove(freework);
4501 	if (jblocks->jb_oldestseg == jseg)
4502 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4503 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4504 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4505 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4506 	    ("free_jseg: Freed jseg has valid entries."));
4507 	WORKITEM_FREE(jseg, D_JSEG);
4508 }
4509 
4510 /*
4511  * Free all jsegs that meet the criteria for being reclaimed and update
4512  * oldestseg.
4513  */
4514 static void
4515 free_jsegs(jblocks)
4516 	struct jblocks *jblocks;
4517 {
4518 	struct jseg *jseg;
4519 
4520 	/*
4521 	 * Free only those jsegs which have none allocated before them to
4522 	 * preserve the journal space ordering.
4523 	 */
4524 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4525 		/*
4526 		 * Only reclaim space when nothing depends on this journal
4527 		 * set and another set has written that it is no longer
4528 		 * valid.
4529 		 */
4530 		if (jseg->js_refs != 0) {
4531 			jblocks->jb_oldestseg = jseg;
4532 			return;
4533 		}
4534 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4535 			break;
4536 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4537 			break;
4538 		/*
4539 		 * We can free jsegs that didn't write entries when
4540 		 * oldestwrseq == js_seq.
4541 		 */
4542 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4543 		    jseg->js_cnt != 0)
4544 			break;
4545 		free_jseg(jseg, jblocks);
4546 	}
4547 	/*
4548 	 * If we exited the loop above we still must discover the
4549 	 * oldest valid segment.
4550 	 */
4551 	if (jseg)
4552 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4553 		     jseg = TAILQ_NEXT(jseg, js_next))
4554 			if (jseg->js_refs != 0)
4555 				break;
4556 	jblocks->jb_oldestseg = jseg;
4557 	/*
4558 	 * The journal has no valid records but some jsegs may still be
4559 	 * waiting on oldestwrseq to advance.  We force a small record
4560 	 * out to permit these lingering records to be reclaimed.
4561 	 */
4562 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4563 		jblocks->jb_needseg = 1;
4564 }
4565 
4566 /*
4567  * Release one reference to a jseg and free it if the count reaches 0.  This
4568  * should eventually reclaim journal space as well.
4569  */
4570 static void
4571 rele_jseg(jseg)
4572 	struct jseg *jseg;
4573 {
4574 
4575 	KASSERT(jseg->js_refs > 0,
4576 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4577 	if (--jseg->js_refs != 0)
4578 		return;
4579 	free_jsegs(jseg->js_jblocks);
4580 }
4581 
4582 /*
4583  * Release a jsegdep and decrement the jseg count.
4584  */
4585 static void
4586 free_jsegdep(jsegdep)
4587 	struct jsegdep *jsegdep;
4588 {
4589 
4590 	if (jsegdep->jd_seg)
4591 		rele_jseg(jsegdep->jd_seg);
4592 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4593 }
4594 
4595 /*
4596  * Wait for a journal item to make it to disk.  Initiate journal processing
4597  * if required.
4598  */
4599 static int
4600 jwait(wk, waitfor)
4601 	struct worklist *wk;
4602 	int waitfor;
4603 {
4604 
4605 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4606 	/*
4607 	 * Blocking journal waits cause slow synchronous behavior.  Record
4608 	 * stats on the frequency of these blocking operations.
4609 	 */
4610 	if (waitfor == MNT_WAIT) {
4611 		stat_journal_wait++;
4612 		switch (wk->wk_type) {
4613 		case D_JREMREF:
4614 		case D_JMVREF:
4615 			stat_jwait_filepage++;
4616 			break;
4617 		case D_JTRUNC:
4618 		case D_JFREEBLK:
4619 			stat_jwait_freeblks++;
4620 			break;
4621 		case D_JNEWBLK:
4622 			stat_jwait_newblk++;
4623 			break;
4624 		case D_JADDREF:
4625 			stat_jwait_inode++;
4626 			break;
4627 		default:
4628 			break;
4629 		}
4630 	}
4631 	/*
4632 	 * If IO has not started we process the journal.  We can't mark the
4633 	 * worklist item as IOWAITING because we drop the lock while
4634 	 * processing the journal and the worklist entry may be freed after
4635 	 * this point.  The caller may call back in and re-issue the request.
4636 	 */
4637 	if ((wk->wk_state & INPROGRESS) == 0) {
4638 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4639 		if (waitfor != MNT_WAIT)
4640 			return (EBUSY);
4641 		return (0);
4642 	}
4643 	if (waitfor != MNT_WAIT)
4644 		return (EBUSY);
4645 	wait_worklist(wk, "jwait");
4646 	return (0);
4647 }
4648 
4649 /*
4650  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4651  * appropriate.  This is a convenience function to reduce duplicate code
4652  * for the setup and revert functions below.
4653  */
4654 static struct inodedep *
4655 inodedep_lookup_ip(ip)
4656 	struct inode *ip;
4657 {
4658 	struct inodedep *inodedep;
4659 
4660 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4661 	    ("inodedep_lookup_ip: bad delta"));
4662 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4663 	    &inodedep);
4664 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4665 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4666 
4667 	return (inodedep);
4668 }
4669 
4670 /*
4671  * Called prior to creating a new inode and linking it to a directory.  The
4672  * jaddref structure must already be allocated by softdep_setup_inomapdep
4673  * and it is discovered here so we can initialize the mode and update
4674  * nlinkdelta.
4675  */
4676 void
4677 softdep_setup_create(dp, ip)
4678 	struct inode *dp;
4679 	struct inode *ip;
4680 {
4681 	struct inodedep *inodedep;
4682 	struct jaddref *jaddref;
4683 	struct vnode *dvp;
4684 
4685 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4686 	    ("softdep_setup_create called on non-softdep filesystem"));
4687 	KASSERT(ip->i_nlink == 1,
4688 	    ("softdep_setup_create: Invalid link count."));
4689 	dvp = ITOV(dp);
4690 	ACQUIRE_LOCK(ITOUMP(dp));
4691 	inodedep = inodedep_lookup_ip(ip);
4692 	if (DOINGSUJ(dvp)) {
4693 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4694 		    inoreflst);
4695 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4696 		    ("softdep_setup_create: No addref structure present."));
4697 	}
4698 	softdep_prelink(dvp, NULL);
4699 	FREE_LOCK(ITOUMP(dp));
4700 }
4701 
4702 /*
4703  * Create a jaddref structure to track the addition of a DOTDOT link when
4704  * we are reparenting an inode as part of a rename.  This jaddref will be
4705  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4706  * non-journaling softdep.
4707  */
4708 void
4709 softdep_setup_dotdot_link(dp, ip)
4710 	struct inode *dp;
4711 	struct inode *ip;
4712 {
4713 	struct inodedep *inodedep;
4714 	struct jaddref *jaddref;
4715 	struct vnode *dvp;
4716 
4717 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4718 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4719 	dvp = ITOV(dp);
4720 	jaddref = NULL;
4721 	/*
4722 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4723 	 * is used as a normal link would be.
4724 	 */
4725 	if (DOINGSUJ(dvp))
4726 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4727 		    dp->i_effnlink - 1, dp->i_mode);
4728 	ACQUIRE_LOCK(ITOUMP(dp));
4729 	inodedep = inodedep_lookup_ip(dp);
4730 	if (jaddref)
4731 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4732 		    if_deps);
4733 	softdep_prelink(dvp, ITOV(ip));
4734 	FREE_LOCK(ITOUMP(dp));
4735 }
4736 
4737 /*
4738  * Create a jaddref structure to track a new link to an inode.  The directory
4739  * offset is not known until softdep_setup_directory_add or
4740  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4741  * softdep.
4742  */
4743 void
4744 softdep_setup_link(dp, ip)
4745 	struct inode *dp;
4746 	struct inode *ip;
4747 {
4748 	struct inodedep *inodedep;
4749 	struct jaddref *jaddref;
4750 	struct vnode *dvp;
4751 
4752 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4753 	    ("softdep_setup_link called on non-softdep filesystem"));
4754 	dvp = ITOV(dp);
4755 	jaddref = NULL;
4756 	if (DOINGSUJ(dvp))
4757 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4758 		    ip->i_mode);
4759 	ACQUIRE_LOCK(ITOUMP(dp));
4760 	inodedep = inodedep_lookup_ip(ip);
4761 	if (jaddref)
4762 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4763 		    if_deps);
4764 	softdep_prelink(dvp, ITOV(ip));
4765 	FREE_LOCK(ITOUMP(dp));
4766 }
4767 
4768 /*
4769  * Called to create the jaddref structures to track . and .. references as
4770  * well as lookup and further initialize the incomplete jaddref created
4771  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4772  * nlinkdelta for non-journaling softdep.
4773  */
4774 void
4775 softdep_setup_mkdir(dp, ip)
4776 	struct inode *dp;
4777 	struct inode *ip;
4778 {
4779 	struct inodedep *inodedep;
4780 	struct jaddref *dotdotaddref;
4781 	struct jaddref *dotaddref;
4782 	struct jaddref *jaddref;
4783 	struct vnode *dvp;
4784 
4785 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4786 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
4787 	dvp = ITOV(dp);
4788 	dotaddref = dotdotaddref = NULL;
4789 	if (DOINGSUJ(dvp)) {
4790 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4791 		    ip->i_mode);
4792 		dotaddref->ja_state |= MKDIR_BODY;
4793 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4794 		    dp->i_effnlink - 1, dp->i_mode);
4795 		dotdotaddref->ja_state |= MKDIR_PARENT;
4796 	}
4797 	ACQUIRE_LOCK(ITOUMP(dp));
4798 	inodedep = inodedep_lookup_ip(ip);
4799 	if (DOINGSUJ(dvp)) {
4800 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4801 		    inoreflst);
4802 		KASSERT(jaddref != NULL,
4803 		    ("softdep_setup_mkdir: No addref structure present."));
4804 		KASSERT(jaddref->ja_parent == dp->i_number,
4805 		    ("softdep_setup_mkdir: bad parent %ju",
4806 		    (uintmax_t)jaddref->ja_parent));
4807 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4808 		    if_deps);
4809 	}
4810 	inodedep = inodedep_lookup_ip(dp);
4811 	if (DOINGSUJ(dvp))
4812 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4813 		    &dotdotaddref->ja_ref, if_deps);
4814 	softdep_prelink(ITOV(dp), NULL);
4815 	FREE_LOCK(ITOUMP(dp));
4816 }
4817 
4818 /*
4819  * Called to track nlinkdelta of the inode and parent directories prior to
4820  * unlinking a directory.
4821  */
4822 void
4823 softdep_setup_rmdir(dp, ip)
4824 	struct inode *dp;
4825 	struct inode *ip;
4826 {
4827 	struct vnode *dvp;
4828 
4829 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4830 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4831 	dvp = ITOV(dp);
4832 	ACQUIRE_LOCK(ITOUMP(dp));
4833 	(void) inodedep_lookup_ip(ip);
4834 	(void) inodedep_lookup_ip(dp);
4835 	softdep_prelink(dvp, ITOV(ip));
4836 	FREE_LOCK(ITOUMP(dp));
4837 }
4838 
4839 /*
4840  * Called to track nlinkdelta of the inode and parent directories prior to
4841  * unlink.
4842  */
4843 void
4844 softdep_setup_unlink(dp, ip)
4845 	struct inode *dp;
4846 	struct inode *ip;
4847 {
4848 	struct vnode *dvp;
4849 
4850 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4851 	    ("softdep_setup_unlink called on non-softdep filesystem"));
4852 	dvp = ITOV(dp);
4853 	ACQUIRE_LOCK(ITOUMP(dp));
4854 	(void) inodedep_lookup_ip(ip);
4855 	(void) inodedep_lookup_ip(dp);
4856 	softdep_prelink(dvp, ITOV(ip));
4857 	FREE_LOCK(ITOUMP(dp));
4858 }
4859 
4860 /*
4861  * Called to release the journal structures created by a failed non-directory
4862  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4863  */
4864 void
4865 softdep_revert_create(dp, ip)
4866 	struct inode *dp;
4867 	struct inode *ip;
4868 {
4869 	struct inodedep *inodedep;
4870 	struct jaddref *jaddref;
4871 	struct vnode *dvp;
4872 
4873 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4874 	    ("softdep_revert_create called on non-softdep filesystem"));
4875 	dvp = ITOV(dp);
4876 	ACQUIRE_LOCK(ITOUMP(dp));
4877 	inodedep = inodedep_lookup_ip(ip);
4878 	if (DOINGSUJ(dvp)) {
4879 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4880 		    inoreflst);
4881 		KASSERT(jaddref->ja_parent == dp->i_number,
4882 		    ("softdep_revert_create: addref parent mismatch"));
4883 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4884 	}
4885 	FREE_LOCK(ITOUMP(dp));
4886 }
4887 
4888 /*
4889  * Called to release the journal structures created by a failed link
4890  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4891  */
4892 void
4893 softdep_revert_link(dp, ip)
4894 	struct inode *dp;
4895 	struct inode *ip;
4896 {
4897 	struct inodedep *inodedep;
4898 	struct jaddref *jaddref;
4899 	struct vnode *dvp;
4900 
4901 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4902 	    ("softdep_revert_link called on non-softdep filesystem"));
4903 	dvp = ITOV(dp);
4904 	ACQUIRE_LOCK(ITOUMP(dp));
4905 	inodedep = inodedep_lookup_ip(ip);
4906 	if (DOINGSUJ(dvp)) {
4907 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4908 		    inoreflst);
4909 		KASSERT(jaddref->ja_parent == dp->i_number,
4910 		    ("softdep_revert_link: addref parent mismatch"));
4911 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4912 	}
4913 	FREE_LOCK(ITOUMP(dp));
4914 }
4915 
4916 /*
4917  * Called to release the journal structures created by a failed mkdir
4918  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4919  */
4920 void
4921 softdep_revert_mkdir(dp, ip)
4922 	struct inode *dp;
4923 	struct inode *ip;
4924 {
4925 	struct inodedep *inodedep;
4926 	struct jaddref *jaddref;
4927 	struct jaddref *dotaddref;
4928 	struct vnode *dvp;
4929 
4930 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4931 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4932 	dvp = ITOV(dp);
4933 
4934 	ACQUIRE_LOCK(ITOUMP(dp));
4935 	inodedep = inodedep_lookup_ip(dp);
4936 	if (DOINGSUJ(dvp)) {
4937 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4938 		    inoreflst);
4939 		KASSERT(jaddref->ja_parent == ip->i_number,
4940 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4941 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4942 	}
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_mkdir: addref parent mismatch"));
4949 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4950 		    inoreflst, if_deps);
4951 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4952 		KASSERT(dotaddref->ja_parent == ip->i_number,
4953 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4954 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4955 	}
4956 	FREE_LOCK(ITOUMP(dp));
4957 }
4958 
4959 /*
4960  * Called to correct nlinkdelta after a failed rmdir.
4961  */
4962 void
4963 softdep_revert_rmdir(dp, ip)
4964 	struct inode *dp;
4965 	struct inode *ip;
4966 {
4967 
4968 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4969 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
4970 	ACQUIRE_LOCK(ITOUMP(dp));
4971 	(void) inodedep_lookup_ip(ip);
4972 	(void) inodedep_lookup_ip(dp);
4973 	FREE_LOCK(ITOUMP(dp));
4974 }
4975 
4976 /*
4977  * Protecting the freemaps (or bitmaps).
4978  *
4979  * To eliminate the need to execute fsck before mounting a filesystem
4980  * after a power failure, one must (conservatively) guarantee that the
4981  * on-disk copy of the bitmaps never indicate that a live inode or block is
4982  * free.  So, when a block or inode is allocated, the bitmap should be
4983  * updated (on disk) before any new pointers.  When a block or inode is
4984  * freed, the bitmap should not be updated until all pointers have been
4985  * reset.  The latter dependency is handled by the delayed de-allocation
4986  * approach described below for block and inode de-allocation.  The former
4987  * dependency is handled by calling the following procedure when a block or
4988  * inode is allocated. When an inode is allocated an "inodedep" is created
4989  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4990  * Each "inodedep" is also inserted into the hash indexing structure so
4991  * that any additional link additions can be made dependent on the inode
4992  * allocation.
4993  *
4994  * The ufs filesystem maintains a number of free block counts (e.g., per
4995  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4996  * in addition to the bitmaps.  These counts are used to improve efficiency
4997  * during allocation and therefore must be consistent with the bitmaps.
4998  * There is no convenient way to guarantee post-crash consistency of these
4999  * counts with simple update ordering, for two main reasons: (1) The counts
5000  * and bitmaps for a single cylinder group block are not in the same disk
5001  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5002  * be written and the other not.  (2) Some of the counts are located in the
5003  * superblock rather than the cylinder group block. So, we focus our soft
5004  * updates implementation on protecting the bitmaps. When mounting a
5005  * filesystem, we recompute the auxiliary counts from the bitmaps.
5006  */
5007 
5008 /*
5009  * Called just after updating the cylinder group block to allocate an inode.
5010  */
5011 void
5012 softdep_setup_inomapdep(bp, ip, newinum, mode)
5013 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5014 	struct inode *ip;	/* inode related to allocation */
5015 	ino_t newinum;		/* new inode number being allocated */
5016 	int mode;
5017 {
5018 	struct inodedep *inodedep;
5019 	struct bmsafemap *bmsafemap;
5020 	struct jaddref *jaddref;
5021 	struct mount *mp;
5022 	struct fs *fs;
5023 
5024 	mp = ITOVFS(ip);
5025 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5026 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5027 	fs = VFSTOUFS(mp)->um_fs;
5028 	jaddref = NULL;
5029 
5030 	/*
5031 	 * Allocate the journal reference add structure so that the bitmap
5032 	 * can be dependent on it.
5033 	 */
5034 	if (MOUNTEDSUJ(mp)) {
5035 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5036 		jaddref->ja_state |= NEWBLOCK;
5037 	}
5038 
5039 	/*
5040 	 * Create a dependency for the newly allocated inode.
5041 	 * Panic if it already exists as something is seriously wrong.
5042 	 * Otherwise add it to the dependency list for the buffer holding
5043 	 * the cylinder group map from which it was allocated.
5044 	 *
5045 	 * We have to preallocate a bmsafemap entry in case it is needed
5046 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5047 	 * have to finish initializing it before we can FREE_LOCK().
5048 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5049 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5050 	 * creating the inodedep as it can be freed during the time
5051 	 * that we FREE_LOCK() while allocating the inodedep. We must
5052 	 * call workitem_alloc() before entering the locked section as
5053 	 * it also acquires the lock and we must avoid trying doing so
5054 	 * recursively.
5055 	 */
5056 	bmsafemap = malloc(sizeof(struct bmsafemap),
5057 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5058 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5059 	ACQUIRE_LOCK(ITOUMP(ip));
5060 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5061 		panic("softdep_setup_inomapdep: dependency %p for new"
5062 		    "inode already exists", inodedep);
5063 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5064 	if (jaddref) {
5065 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5066 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5067 		    if_deps);
5068 	} else {
5069 		inodedep->id_state |= ONDEPLIST;
5070 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5071 	}
5072 	inodedep->id_bmsafemap = bmsafemap;
5073 	inodedep->id_state &= ~DEPCOMPLETE;
5074 	FREE_LOCK(ITOUMP(ip));
5075 }
5076 
5077 /*
5078  * Called just after updating the cylinder group block to
5079  * allocate block or fragment.
5080  */
5081 void
5082 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5083 	struct buf *bp;		/* buffer for cylgroup block with block map */
5084 	struct mount *mp;	/* filesystem doing allocation */
5085 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5086 	int frags;		/* Number of fragments. */
5087 	int oldfrags;		/* Previous number of fragments for extend. */
5088 {
5089 	struct newblk *newblk;
5090 	struct bmsafemap *bmsafemap;
5091 	struct jnewblk *jnewblk;
5092 	struct ufsmount *ump;
5093 	struct fs *fs;
5094 
5095 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5096 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5097 	ump = VFSTOUFS(mp);
5098 	fs = ump->um_fs;
5099 	jnewblk = NULL;
5100 	/*
5101 	 * Create a dependency for the newly allocated block.
5102 	 * Add it to the dependency list for the buffer holding
5103 	 * the cylinder group map from which it was allocated.
5104 	 */
5105 	if (MOUNTEDSUJ(mp)) {
5106 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5107 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5108 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5109 		jnewblk->jn_state = ATTACHED;
5110 		jnewblk->jn_blkno = newblkno;
5111 		jnewblk->jn_frags = frags;
5112 		jnewblk->jn_oldfrags = oldfrags;
5113 #ifdef INVARIANTS
5114 		{
5115 			struct cg *cgp;
5116 			uint8_t *blksfree;
5117 			long bno;
5118 			int i;
5119 
5120 			cgp = (struct cg *)bp->b_data;
5121 			blksfree = cg_blksfree(cgp);
5122 			bno = dtogd(fs, jnewblk->jn_blkno);
5123 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5124 			    i++) {
5125 				if (isset(blksfree, bno + i))
5126 					panic("softdep_setup_blkmapdep: "
5127 					    "free fragment %d from %d-%d "
5128 					    "state 0x%X dep %p", i,
5129 					    jnewblk->jn_oldfrags,
5130 					    jnewblk->jn_frags,
5131 					    jnewblk->jn_state,
5132 					    jnewblk->jn_dep);
5133 			}
5134 		}
5135 #endif
5136 	}
5137 
5138 	CTR3(KTR_SUJ,
5139 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5140 	    newblkno, frags, oldfrags);
5141 	ACQUIRE_LOCK(ump);
5142 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5143 		panic("softdep_setup_blkmapdep: found block");
5144 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5145 	    dtog(fs, newblkno), NULL);
5146 	if (jnewblk) {
5147 		jnewblk->jn_dep = (struct worklist *)newblk;
5148 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5149 	} else {
5150 		newblk->nb_state |= ONDEPLIST;
5151 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5152 	}
5153 	newblk->nb_bmsafemap = bmsafemap;
5154 	newblk->nb_jnewblk = jnewblk;
5155 	FREE_LOCK(ump);
5156 }
5157 
5158 #define	BMSAFEMAP_HASH(ump, cg) \
5159       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5160 
5161 static int
5162 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5163 	struct bmsafemap_hashhead *bmsafemaphd;
5164 	int cg;
5165 	struct bmsafemap **bmsafemapp;
5166 {
5167 	struct bmsafemap *bmsafemap;
5168 
5169 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5170 		if (bmsafemap->sm_cg == cg)
5171 			break;
5172 	if (bmsafemap) {
5173 		*bmsafemapp = bmsafemap;
5174 		return (1);
5175 	}
5176 	*bmsafemapp = NULL;
5177 
5178 	return (0);
5179 }
5180 
5181 /*
5182  * Find the bmsafemap associated with a cylinder group buffer.
5183  * If none exists, create one. The buffer must be locked when
5184  * this routine is called and this routine must be called with
5185  * the softdep lock held. To avoid giving up the lock while
5186  * allocating a new bmsafemap, a preallocated bmsafemap may be
5187  * provided. If it is provided but not needed, it is freed.
5188  */
5189 static struct bmsafemap *
5190 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5191 	struct mount *mp;
5192 	struct buf *bp;
5193 	int cg;
5194 	struct bmsafemap *newbmsafemap;
5195 {
5196 	struct bmsafemap_hashhead *bmsafemaphd;
5197 	struct bmsafemap *bmsafemap, *collision;
5198 	struct worklist *wk;
5199 	struct ufsmount *ump;
5200 
5201 	ump = VFSTOUFS(mp);
5202 	LOCK_OWNED(ump);
5203 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5204 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5205 		if (wk->wk_type == D_BMSAFEMAP) {
5206 			if (newbmsafemap)
5207 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5208 			return (WK_BMSAFEMAP(wk));
5209 		}
5210 	}
5211 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5212 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5213 		if (newbmsafemap)
5214 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5215 		return (bmsafemap);
5216 	}
5217 	if (newbmsafemap) {
5218 		bmsafemap = newbmsafemap;
5219 	} else {
5220 		FREE_LOCK(ump);
5221 		bmsafemap = malloc(sizeof(struct bmsafemap),
5222 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5223 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5224 		ACQUIRE_LOCK(ump);
5225 	}
5226 	bmsafemap->sm_buf = bp;
5227 	LIST_INIT(&bmsafemap->sm_inodedephd);
5228 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5229 	LIST_INIT(&bmsafemap->sm_newblkhd);
5230 	LIST_INIT(&bmsafemap->sm_newblkwr);
5231 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5232 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5233 	LIST_INIT(&bmsafemap->sm_freehd);
5234 	LIST_INIT(&bmsafemap->sm_freewr);
5235 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5236 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5237 		return (collision);
5238 	}
5239 	bmsafemap->sm_cg = cg;
5240 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5241 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5242 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5243 	return (bmsafemap);
5244 }
5245 
5246 /*
5247  * Direct block allocation dependencies.
5248  *
5249  * When a new block is allocated, the corresponding disk locations must be
5250  * initialized (with zeros or new data) before the on-disk inode points to
5251  * them.  Also, the freemap from which the block was allocated must be
5252  * updated (on disk) before the inode's pointer. These two dependencies are
5253  * independent of each other and are needed for all file blocks and indirect
5254  * blocks that are pointed to directly by the inode.  Just before the
5255  * "in-core" version of the inode is updated with a newly allocated block
5256  * number, a procedure (below) is called to setup allocation dependency
5257  * structures.  These structures are removed when the corresponding
5258  * dependencies are satisfied or when the block allocation becomes obsolete
5259  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5260  * fragment that gets upgraded).  All of these cases are handled in
5261  * procedures described later.
5262  *
5263  * When a file extension causes a fragment to be upgraded, either to a larger
5264  * fragment or to a full block, the on-disk location may change (if the
5265  * previous fragment could not simply be extended). In this case, the old
5266  * fragment must be de-allocated, but not until after the inode's pointer has
5267  * been updated. In most cases, this is handled by later procedures, which
5268  * will construct a "freefrag" structure to be added to the workitem queue
5269  * when the inode update is complete (or obsolete).  The main exception to
5270  * this is when an allocation occurs while a pending allocation dependency
5271  * (for the same block pointer) remains.  This case is handled in the main
5272  * allocation dependency setup procedure by immediately freeing the
5273  * unreferenced fragments.
5274  */
5275 void
5276 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5277 	struct inode *ip;	/* inode to which block is being added */
5278 	ufs_lbn_t off;		/* block pointer within inode */
5279 	ufs2_daddr_t newblkno;	/* disk block number being added */
5280 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5281 	long newsize;		/* size of new block */
5282 	long oldsize;		/* size of new block */
5283 	struct buf *bp;		/* bp for allocated block */
5284 {
5285 	struct allocdirect *adp, *oldadp;
5286 	struct allocdirectlst *adphead;
5287 	struct freefrag *freefrag;
5288 	struct inodedep *inodedep;
5289 	struct pagedep *pagedep;
5290 	struct jnewblk *jnewblk;
5291 	struct newblk *newblk;
5292 	struct mount *mp;
5293 	ufs_lbn_t lbn;
5294 
5295 	lbn = bp->b_lblkno;
5296 	mp = ITOVFS(ip);
5297 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5298 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5299 	if (oldblkno && oldblkno != newblkno)
5300 		/*
5301 		 * The usual case is that a smaller fragment that
5302 		 * was just allocated has been replaced with a bigger
5303 		 * fragment or a full-size block. If it is marked as
5304 		 * B_DELWRI, the current contents have not been written
5305 		 * to disk. It is possible that the block was written
5306 		 * earlier, but very uncommon. If the block has never
5307 		 * been written, there is no need to send a BIO_DELETE
5308 		 * for it when it is freed. The gain from avoiding the
5309 		 * TRIMs for the common case of unwritten blocks far
5310 		 * exceeds the cost of the write amplification for the
5311 		 * uncommon case of failing to send a TRIM for a block
5312 		 * that had been written.
5313 		 */
5314 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5315 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5316 	else
5317 		freefrag = NULL;
5318 
5319 	CTR6(KTR_SUJ,
5320 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5321 	    "off %jd newsize %ld oldsize %d",
5322 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5323 	ACQUIRE_LOCK(ITOUMP(ip));
5324 	if (off >= UFS_NDADDR) {
5325 		if (lbn > 0)
5326 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5327 			    lbn, off);
5328 		/* allocating an indirect block */
5329 		if (oldblkno != 0)
5330 			panic("softdep_setup_allocdirect: non-zero indir");
5331 	} else {
5332 		if (off != lbn)
5333 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5334 			    lbn, off);
5335 		/*
5336 		 * Allocating a direct block.
5337 		 *
5338 		 * If we are allocating a directory block, then we must
5339 		 * allocate an associated pagedep to track additions and
5340 		 * deletions.
5341 		 */
5342 		if ((ip->i_mode & IFMT) == IFDIR)
5343 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5344 			    &pagedep);
5345 	}
5346 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5347 		panic("softdep_setup_allocdirect: lost block");
5348 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5349 	    ("softdep_setup_allocdirect: newblk already initialized"));
5350 	/*
5351 	 * Convert the newblk to an allocdirect.
5352 	 */
5353 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5354 	adp = (struct allocdirect *)newblk;
5355 	newblk->nb_freefrag = freefrag;
5356 	adp->ad_offset = off;
5357 	adp->ad_oldblkno = oldblkno;
5358 	adp->ad_newsize = newsize;
5359 	adp->ad_oldsize = oldsize;
5360 
5361 	/*
5362 	 * Finish initializing the journal.
5363 	 */
5364 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5365 		jnewblk->jn_ino = ip->i_number;
5366 		jnewblk->jn_lbn = lbn;
5367 		add_to_journal(&jnewblk->jn_list);
5368 	}
5369 	if (freefrag && freefrag->ff_jdep != NULL &&
5370 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5371 		add_to_journal(freefrag->ff_jdep);
5372 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5373 	adp->ad_inodedep = inodedep;
5374 
5375 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5376 	/*
5377 	 * The list of allocdirects must be kept in sorted and ascending
5378 	 * order so that the rollback routines can quickly determine the
5379 	 * first uncommitted block (the size of the file stored on disk
5380 	 * ends at the end of the lowest committed fragment, or if there
5381 	 * are no fragments, at the end of the highest committed block).
5382 	 * Since files generally grow, the typical case is that the new
5383 	 * block is to be added at the end of the list. We speed this
5384 	 * special case by checking against the last allocdirect in the
5385 	 * list before laboriously traversing the list looking for the
5386 	 * insertion point.
5387 	 */
5388 	adphead = &inodedep->id_newinoupdt;
5389 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5390 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5391 		/* insert at end of list */
5392 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5393 		if (oldadp != NULL && oldadp->ad_offset == off)
5394 			allocdirect_merge(adphead, adp, oldadp);
5395 		FREE_LOCK(ITOUMP(ip));
5396 		return;
5397 	}
5398 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5399 		if (oldadp->ad_offset >= off)
5400 			break;
5401 	}
5402 	if (oldadp == NULL)
5403 		panic("softdep_setup_allocdirect: lost entry");
5404 	/* insert in middle of list */
5405 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5406 	if (oldadp->ad_offset == off)
5407 		allocdirect_merge(adphead, adp, oldadp);
5408 
5409 	FREE_LOCK(ITOUMP(ip));
5410 }
5411 
5412 /*
5413  * Merge a newer and older journal record to be stored either in a
5414  * newblock or freefrag.  This handles aggregating journal records for
5415  * fragment allocation into a second record as well as replacing a
5416  * journal free with an aborted journal allocation.  A segment for the
5417  * oldest record will be placed on wkhd if it has been written.  If not
5418  * the segment for the newer record will suffice.
5419  */
5420 static struct worklist *
5421 jnewblk_merge(new, old, wkhd)
5422 	struct worklist *new;
5423 	struct worklist *old;
5424 	struct workhead *wkhd;
5425 {
5426 	struct jnewblk *njnewblk;
5427 	struct jnewblk *jnewblk;
5428 
5429 	/* Handle NULLs to simplify callers. */
5430 	if (new == NULL)
5431 		return (old);
5432 	if (old == NULL)
5433 		return (new);
5434 	/* Replace a jfreefrag with a jnewblk. */
5435 	if (new->wk_type == D_JFREEFRAG) {
5436 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5437 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5438 			    old, new);
5439 		cancel_jfreefrag(WK_JFREEFRAG(new));
5440 		return (old);
5441 	}
5442 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5443 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5444 		    old->wk_type, new->wk_type);
5445 	/*
5446 	 * Handle merging of two jnewblk records that describe
5447 	 * different sets of fragments in the same block.
5448 	 */
5449 	jnewblk = WK_JNEWBLK(old);
5450 	njnewblk = WK_JNEWBLK(new);
5451 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5452 		panic("jnewblk_merge: Merging disparate blocks.");
5453 	/*
5454 	 * The record may be rolled back in the cg.
5455 	 */
5456 	if (jnewblk->jn_state & UNDONE) {
5457 		jnewblk->jn_state &= ~UNDONE;
5458 		njnewblk->jn_state |= UNDONE;
5459 		njnewblk->jn_state &= ~ATTACHED;
5460 	}
5461 	/*
5462 	 * We modify the newer addref and free the older so that if neither
5463 	 * has been written the most up-to-date copy will be on disk.  If
5464 	 * both have been written but rolled back we only temporarily need
5465 	 * one of them to fix the bits when the cg write completes.
5466 	 */
5467 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5468 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5469 	cancel_jnewblk(jnewblk, wkhd);
5470 	WORKLIST_REMOVE(&jnewblk->jn_list);
5471 	free_jnewblk(jnewblk);
5472 	return (new);
5473 }
5474 
5475 /*
5476  * Replace an old allocdirect dependency with a newer one.
5477  */
5478 static void
5479 allocdirect_merge(adphead, newadp, oldadp)
5480 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5481 	struct allocdirect *newadp;	/* allocdirect being added */
5482 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5483 {
5484 	struct worklist *wk;
5485 	struct freefrag *freefrag;
5486 
5487 	freefrag = NULL;
5488 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5489 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5490 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5491 	    newadp->ad_offset >= UFS_NDADDR)
5492 		panic("%s %jd != new %jd || old size %ld != new %ld",
5493 		    "allocdirect_merge: old blkno",
5494 		    (intmax_t)newadp->ad_oldblkno,
5495 		    (intmax_t)oldadp->ad_newblkno,
5496 		    newadp->ad_oldsize, oldadp->ad_newsize);
5497 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5498 	newadp->ad_oldsize = oldadp->ad_oldsize;
5499 	/*
5500 	 * If the old dependency had a fragment to free or had never
5501 	 * previously had a block allocated, then the new dependency
5502 	 * can immediately post its freefrag and adopt the old freefrag.
5503 	 * This action is done by swapping the freefrag dependencies.
5504 	 * The new dependency gains the old one's freefrag, and the
5505 	 * old one gets the new one and then immediately puts it on
5506 	 * the worklist when it is freed by free_newblk. It is
5507 	 * not possible to do this swap when the old dependency had a
5508 	 * non-zero size but no previous fragment to free. This condition
5509 	 * arises when the new block is an extension of the old block.
5510 	 * Here, the first part of the fragment allocated to the new
5511 	 * dependency is part of the block currently claimed on disk by
5512 	 * the old dependency, so cannot legitimately be freed until the
5513 	 * conditions for the new dependency are fulfilled.
5514 	 */
5515 	freefrag = newadp->ad_freefrag;
5516 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5517 		newadp->ad_freefrag = oldadp->ad_freefrag;
5518 		oldadp->ad_freefrag = freefrag;
5519 	}
5520 	/*
5521 	 * If we are tracking a new directory-block allocation,
5522 	 * move it from the old allocdirect to the new allocdirect.
5523 	 */
5524 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5525 		WORKLIST_REMOVE(wk);
5526 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5527 			panic("allocdirect_merge: extra newdirblk");
5528 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5529 	}
5530 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5531 	/*
5532 	 * We need to move any journal dependencies over to the freefrag
5533 	 * that releases this block if it exists.  Otherwise we are
5534 	 * extending an existing block and we'll wait until that is
5535 	 * complete to release the journal space and extend the
5536 	 * new journal to cover this old space as well.
5537 	 */
5538 	if (freefrag == NULL) {
5539 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5540 			panic("allocdirect_merge: %jd != %jd",
5541 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5542 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5543 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5544 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5545 		    &newadp->ad_block.nb_jwork);
5546 		oldadp->ad_block.nb_jnewblk = NULL;
5547 		cancel_newblk(&oldadp->ad_block, NULL,
5548 		    &newadp->ad_block.nb_jwork);
5549 	} else {
5550 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5551 		    &freefrag->ff_list, &freefrag->ff_jwork);
5552 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5553 		    &freefrag->ff_jwork);
5554 	}
5555 	free_newblk(&oldadp->ad_block);
5556 }
5557 
5558 /*
5559  * Allocate a jfreefrag structure to journal a single block free.
5560  */
5561 static struct jfreefrag *
5562 newjfreefrag(freefrag, ip, blkno, size, lbn)
5563 	struct freefrag *freefrag;
5564 	struct inode *ip;
5565 	ufs2_daddr_t blkno;
5566 	long size;
5567 	ufs_lbn_t lbn;
5568 {
5569 	struct jfreefrag *jfreefrag;
5570 	struct fs *fs;
5571 
5572 	fs = ITOFS(ip);
5573 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5574 	    M_SOFTDEP_FLAGS);
5575 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5576 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5577 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5578 	jfreefrag->fr_ino = ip->i_number;
5579 	jfreefrag->fr_lbn = lbn;
5580 	jfreefrag->fr_blkno = blkno;
5581 	jfreefrag->fr_frags = numfrags(fs, size);
5582 	jfreefrag->fr_freefrag = freefrag;
5583 
5584 	return (jfreefrag);
5585 }
5586 
5587 /*
5588  * Allocate a new freefrag structure.
5589  */
5590 static struct freefrag *
5591 newfreefrag(ip, blkno, size, lbn, key)
5592 	struct inode *ip;
5593 	ufs2_daddr_t blkno;
5594 	long size;
5595 	ufs_lbn_t lbn;
5596 	u_long key;
5597 {
5598 	struct freefrag *freefrag;
5599 	struct ufsmount *ump;
5600 	struct fs *fs;
5601 
5602 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5603 	    ip->i_number, blkno, size, lbn);
5604 	ump = ITOUMP(ip);
5605 	fs = ump->um_fs;
5606 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5607 		panic("newfreefrag: frag size");
5608 	freefrag = malloc(sizeof(struct freefrag),
5609 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5610 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5611 	freefrag->ff_state = ATTACHED;
5612 	LIST_INIT(&freefrag->ff_jwork);
5613 	freefrag->ff_inum = ip->i_number;
5614 	freefrag->ff_vtype = ITOV(ip)->v_type;
5615 	freefrag->ff_blkno = blkno;
5616 	freefrag->ff_fragsize = size;
5617 	freefrag->ff_key = key;
5618 
5619 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5620 		freefrag->ff_jdep = (struct worklist *)
5621 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5622 	} else {
5623 		freefrag->ff_state |= DEPCOMPLETE;
5624 		freefrag->ff_jdep = NULL;
5625 	}
5626 
5627 	return (freefrag);
5628 }
5629 
5630 /*
5631  * This workitem de-allocates fragments that were replaced during
5632  * file block allocation.
5633  */
5634 static void
5635 handle_workitem_freefrag(freefrag)
5636 	struct freefrag *freefrag;
5637 {
5638 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5639 	struct workhead wkhd;
5640 
5641 	CTR3(KTR_SUJ,
5642 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5643 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5644 	/*
5645 	 * It would be illegal to add new completion items to the
5646 	 * freefrag after it was schedule to be done so it must be
5647 	 * safe to modify the list head here.
5648 	 */
5649 	LIST_INIT(&wkhd);
5650 	ACQUIRE_LOCK(ump);
5651 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5652 	/*
5653 	 * If the journal has not been written we must cancel it here.
5654 	 */
5655 	if (freefrag->ff_jdep) {
5656 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5657 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5658 			    freefrag->ff_jdep->wk_type);
5659 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5660 	}
5661 	FREE_LOCK(ump);
5662 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5663 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5664 	   &wkhd, freefrag->ff_key);
5665 	ACQUIRE_LOCK(ump);
5666 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5667 	FREE_LOCK(ump);
5668 }
5669 
5670 /*
5671  * Set up a dependency structure for an external attributes data block.
5672  * This routine follows much of the structure of softdep_setup_allocdirect.
5673  * See the description of softdep_setup_allocdirect above for details.
5674  */
5675 void
5676 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5677 	struct inode *ip;
5678 	ufs_lbn_t off;
5679 	ufs2_daddr_t newblkno;
5680 	ufs2_daddr_t oldblkno;
5681 	long newsize;
5682 	long oldsize;
5683 	struct buf *bp;
5684 {
5685 	struct allocdirect *adp, *oldadp;
5686 	struct allocdirectlst *adphead;
5687 	struct freefrag *freefrag;
5688 	struct inodedep *inodedep;
5689 	struct jnewblk *jnewblk;
5690 	struct newblk *newblk;
5691 	struct mount *mp;
5692 	struct ufsmount *ump;
5693 	ufs_lbn_t lbn;
5694 
5695 	mp = ITOVFS(ip);
5696 	ump = VFSTOUFS(mp);
5697 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5698 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5699 	KASSERT(off < UFS_NXADDR,
5700 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5701 
5702 	lbn = bp->b_lblkno;
5703 	if (oldblkno && oldblkno != newblkno)
5704 		/*
5705 		 * The usual case is that a smaller fragment that
5706 		 * was just allocated has been replaced with a bigger
5707 		 * fragment or a full-size block. If it is marked as
5708 		 * B_DELWRI, the current contents have not been written
5709 		 * to disk. It is possible that the block was written
5710 		 * earlier, but very uncommon. If the block has never
5711 		 * been written, there is no need to send a BIO_DELETE
5712 		 * for it when it is freed. The gain from avoiding the
5713 		 * TRIMs for the common case of unwritten blocks far
5714 		 * exceeds the cost of the write amplification for the
5715 		 * uncommon case of failing to send a TRIM for a block
5716 		 * that had been written.
5717 		 */
5718 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5719 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5720 	else
5721 		freefrag = NULL;
5722 
5723 	ACQUIRE_LOCK(ump);
5724 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5725 		panic("softdep_setup_allocext: lost block");
5726 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5727 	    ("softdep_setup_allocext: newblk already initialized"));
5728 	/*
5729 	 * Convert the newblk to an allocdirect.
5730 	 */
5731 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5732 	adp = (struct allocdirect *)newblk;
5733 	newblk->nb_freefrag = freefrag;
5734 	adp->ad_offset = off;
5735 	adp->ad_oldblkno = oldblkno;
5736 	adp->ad_newsize = newsize;
5737 	adp->ad_oldsize = oldsize;
5738 	adp->ad_state |=  EXTDATA;
5739 
5740 	/*
5741 	 * Finish initializing the journal.
5742 	 */
5743 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5744 		jnewblk->jn_ino = ip->i_number;
5745 		jnewblk->jn_lbn = lbn;
5746 		add_to_journal(&jnewblk->jn_list);
5747 	}
5748 	if (freefrag && freefrag->ff_jdep != NULL &&
5749 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5750 		add_to_journal(freefrag->ff_jdep);
5751 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5752 	adp->ad_inodedep = inodedep;
5753 
5754 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5755 	/*
5756 	 * The list of allocdirects must be kept in sorted and ascending
5757 	 * order so that the rollback routines can quickly determine the
5758 	 * first uncommitted block (the size of the file stored on disk
5759 	 * ends at the end of the lowest committed fragment, or if there
5760 	 * are no fragments, at the end of the highest committed block).
5761 	 * Since files generally grow, the typical case is that the new
5762 	 * block is to be added at the end of the list. We speed this
5763 	 * special case by checking against the last allocdirect in the
5764 	 * list before laboriously traversing the list looking for the
5765 	 * insertion point.
5766 	 */
5767 	adphead = &inodedep->id_newextupdt;
5768 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5769 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5770 		/* insert at end of list */
5771 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5772 		if (oldadp != NULL && oldadp->ad_offset == off)
5773 			allocdirect_merge(adphead, adp, oldadp);
5774 		FREE_LOCK(ump);
5775 		return;
5776 	}
5777 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5778 		if (oldadp->ad_offset >= off)
5779 			break;
5780 	}
5781 	if (oldadp == NULL)
5782 		panic("softdep_setup_allocext: lost entry");
5783 	/* insert in middle of list */
5784 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5785 	if (oldadp->ad_offset == off)
5786 		allocdirect_merge(adphead, adp, oldadp);
5787 	FREE_LOCK(ump);
5788 }
5789 
5790 /*
5791  * Indirect block allocation dependencies.
5792  *
5793  * The same dependencies that exist for a direct block also exist when
5794  * a new block is allocated and pointed to by an entry in a block of
5795  * indirect pointers. The undo/redo states described above are also
5796  * used here. Because an indirect block contains many pointers that
5797  * may have dependencies, a second copy of the entire in-memory indirect
5798  * block is kept. The buffer cache copy is always completely up-to-date.
5799  * The second copy, which is used only as a source for disk writes,
5800  * contains only the safe pointers (i.e., those that have no remaining
5801  * update dependencies). The second copy is freed when all pointers
5802  * are safe. The cache is not allowed to replace indirect blocks with
5803  * pending update dependencies. If a buffer containing an indirect
5804  * block with dependencies is written, these routines will mark it
5805  * dirty again. It can only be successfully written once all the
5806  * dependencies are removed. The ffs_fsync routine in conjunction with
5807  * softdep_sync_metadata work together to get all the dependencies
5808  * removed so that a file can be successfully written to disk. Three
5809  * procedures are used when setting up indirect block pointer
5810  * dependencies. The division is necessary because of the organization
5811  * of the "balloc" routine and because of the distinction between file
5812  * pages and file metadata blocks.
5813  */
5814 
5815 /*
5816  * Allocate a new allocindir structure.
5817  */
5818 static struct allocindir *
5819 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5820 	struct inode *ip;	/* inode for file being extended */
5821 	int ptrno;		/* offset of pointer in indirect block */
5822 	ufs2_daddr_t newblkno;	/* disk block number being added */
5823 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5824 	ufs_lbn_t lbn;
5825 {
5826 	struct newblk *newblk;
5827 	struct allocindir *aip;
5828 	struct freefrag *freefrag;
5829 	struct jnewblk *jnewblk;
5830 
5831 	if (oldblkno)
5832 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
5833 		    SINGLETON_KEY);
5834 	else
5835 		freefrag = NULL;
5836 	ACQUIRE_LOCK(ITOUMP(ip));
5837 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5838 		panic("new_allocindir: lost block");
5839 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5840 	    ("newallocindir: newblk already initialized"));
5841 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5842 	newblk->nb_freefrag = freefrag;
5843 	aip = (struct allocindir *)newblk;
5844 	aip->ai_offset = ptrno;
5845 	aip->ai_oldblkno = oldblkno;
5846 	aip->ai_lbn = lbn;
5847 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5848 		jnewblk->jn_ino = ip->i_number;
5849 		jnewblk->jn_lbn = lbn;
5850 		add_to_journal(&jnewblk->jn_list);
5851 	}
5852 	if (freefrag && freefrag->ff_jdep != NULL &&
5853 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5854 		add_to_journal(freefrag->ff_jdep);
5855 	return (aip);
5856 }
5857 
5858 /*
5859  * Called just before setting an indirect block pointer
5860  * to a newly allocated file page.
5861  */
5862 void
5863 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5864 	struct inode *ip;	/* inode for file being extended */
5865 	ufs_lbn_t lbn;		/* allocated block number within file */
5866 	struct buf *bp;		/* buffer with indirect blk referencing page */
5867 	int ptrno;		/* offset of pointer in indirect block */
5868 	ufs2_daddr_t newblkno;	/* disk block number being added */
5869 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5870 	struct buf *nbp;	/* buffer holding allocated page */
5871 {
5872 	struct inodedep *inodedep;
5873 	struct freefrag *freefrag;
5874 	struct allocindir *aip;
5875 	struct pagedep *pagedep;
5876 	struct mount *mp;
5877 	struct ufsmount *ump;
5878 
5879 	mp = ITOVFS(ip);
5880 	ump = VFSTOUFS(mp);
5881 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5882 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5883 	KASSERT(lbn == nbp->b_lblkno,
5884 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5885 	    lbn, bp->b_lblkno));
5886 	CTR4(KTR_SUJ,
5887 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5888 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5889 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5890 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5891 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5892 	/*
5893 	 * If we are allocating a directory page, then we must
5894 	 * allocate an associated pagedep to track additions and
5895 	 * deletions.
5896 	 */
5897 	if ((ip->i_mode & IFMT) == IFDIR)
5898 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5899 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5900 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5901 	FREE_LOCK(ump);
5902 	if (freefrag)
5903 		handle_workitem_freefrag(freefrag);
5904 }
5905 
5906 /*
5907  * Called just before setting an indirect block pointer to a
5908  * newly allocated indirect block.
5909  */
5910 void
5911 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5912 	struct buf *nbp;	/* newly allocated indirect block */
5913 	struct inode *ip;	/* inode for file being extended */
5914 	struct buf *bp;		/* indirect block referencing allocated block */
5915 	int ptrno;		/* offset of pointer in indirect block */
5916 	ufs2_daddr_t newblkno;	/* disk block number being added */
5917 {
5918 	struct inodedep *inodedep;
5919 	struct allocindir *aip;
5920 	struct ufsmount *ump;
5921 	ufs_lbn_t lbn;
5922 
5923 	ump = ITOUMP(ip);
5924 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5925 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5926 	CTR3(KTR_SUJ,
5927 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5928 	    ip->i_number, newblkno, ptrno);
5929 	lbn = nbp->b_lblkno;
5930 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5931 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5932 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5933 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5934 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5935 		panic("softdep_setup_allocindir_meta: Block already existed");
5936 	FREE_LOCK(ump);
5937 }
5938 
5939 static void
5940 indirdep_complete(indirdep)
5941 	struct indirdep *indirdep;
5942 {
5943 	struct allocindir *aip;
5944 
5945 	LIST_REMOVE(indirdep, ir_next);
5946 	indirdep->ir_state |= DEPCOMPLETE;
5947 
5948 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5949 		LIST_REMOVE(aip, ai_next);
5950 		free_newblk(&aip->ai_block);
5951 	}
5952 	/*
5953 	 * If this indirdep is not attached to a buf it was simply waiting
5954 	 * on completion to clear completehd.  free_indirdep() asserts
5955 	 * that nothing is dangling.
5956 	 */
5957 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5958 		free_indirdep(indirdep);
5959 }
5960 
5961 static struct indirdep *
5962 indirdep_lookup(mp, ip, bp)
5963 	struct mount *mp;
5964 	struct inode *ip;
5965 	struct buf *bp;
5966 {
5967 	struct indirdep *indirdep, *newindirdep;
5968 	struct newblk *newblk;
5969 	struct ufsmount *ump;
5970 	struct worklist *wk;
5971 	struct fs *fs;
5972 	ufs2_daddr_t blkno;
5973 
5974 	ump = VFSTOUFS(mp);
5975 	LOCK_OWNED(ump);
5976 	indirdep = NULL;
5977 	newindirdep = NULL;
5978 	fs = ump->um_fs;
5979 	for (;;) {
5980 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5981 			if (wk->wk_type != D_INDIRDEP)
5982 				continue;
5983 			indirdep = WK_INDIRDEP(wk);
5984 			break;
5985 		}
5986 		/* Found on the buffer worklist, no new structure to free. */
5987 		if (indirdep != NULL && newindirdep == NULL)
5988 			return (indirdep);
5989 		if (indirdep != NULL && newindirdep != NULL)
5990 			panic("indirdep_lookup: simultaneous create");
5991 		/* None found on the buffer and a new structure is ready. */
5992 		if (indirdep == NULL && newindirdep != NULL)
5993 			break;
5994 		/* None found and no new structure available. */
5995 		FREE_LOCK(ump);
5996 		newindirdep = malloc(sizeof(struct indirdep),
5997 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
5998 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5999 		newindirdep->ir_state = ATTACHED;
6000 		if (I_IS_UFS1(ip))
6001 			newindirdep->ir_state |= UFS1FMT;
6002 		TAILQ_INIT(&newindirdep->ir_trunc);
6003 		newindirdep->ir_saveddata = NULL;
6004 		LIST_INIT(&newindirdep->ir_deplisthd);
6005 		LIST_INIT(&newindirdep->ir_donehd);
6006 		LIST_INIT(&newindirdep->ir_writehd);
6007 		LIST_INIT(&newindirdep->ir_completehd);
6008 		if (bp->b_blkno == bp->b_lblkno) {
6009 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6010 			    NULL, NULL);
6011 			bp->b_blkno = blkno;
6012 		}
6013 		newindirdep->ir_freeblks = NULL;
6014 		newindirdep->ir_savebp =
6015 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6016 		newindirdep->ir_bp = bp;
6017 		BUF_KERNPROC(newindirdep->ir_savebp);
6018 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6019 		ACQUIRE_LOCK(ump);
6020 	}
6021 	indirdep = newindirdep;
6022 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6023 	/*
6024 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6025 	 * that we don't free dependencies until the pointers are valid.
6026 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6027 	 * than using the hash.
6028 	 */
6029 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6030 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6031 	else
6032 		indirdep->ir_state |= DEPCOMPLETE;
6033 	return (indirdep);
6034 }
6035 
6036 /*
6037  * Called to finish the allocation of the "aip" allocated
6038  * by one of the two routines above.
6039  */
6040 static struct freefrag *
6041 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6042 	struct buf *bp;		/* in-memory copy of the indirect block */
6043 	struct inode *ip;	/* inode for file being extended */
6044 	struct inodedep *inodedep; /* Inodedep for ip */
6045 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6046 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6047 {
6048 	struct fs *fs;
6049 	struct indirdep *indirdep;
6050 	struct allocindir *oldaip;
6051 	struct freefrag *freefrag;
6052 	struct mount *mp;
6053 	struct ufsmount *ump;
6054 
6055 	mp = ITOVFS(ip);
6056 	ump = VFSTOUFS(mp);
6057 	LOCK_OWNED(ump);
6058 	fs = ump->um_fs;
6059 	if (bp->b_lblkno >= 0)
6060 		panic("setup_allocindir_phase2: not indir blk");
6061 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6062 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6063 	indirdep = indirdep_lookup(mp, ip, bp);
6064 	KASSERT(indirdep->ir_savebp != NULL,
6065 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6066 	aip->ai_indirdep = indirdep;
6067 	/*
6068 	 * Check for an unwritten dependency for this indirect offset.  If
6069 	 * there is, merge the old dependency into the new one.  This happens
6070 	 * as a result of reallocblk only.
6071 	 */
6072 	freefrag = NULL;
6073 	if (aip->ai_oldblkno != 0) {
6074 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6075 			if (oldaip->ai_offset == aip->ai_offset) {
6076 				freefrag = allocindir_merge(aip, oldaip);
6077 				goto done;
6078 			}
6079 		}
6080 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6081 			if (oldaip->ai_offset == aip->ai_offset) {
6082 				freefrag = allocindir_merge(aip, oldaip);
6083 				goto done;
6084 			}
6085 		}
6086 	}
6087 done:
6088 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6089 	return (freefrag);
6090 }
6091 
6092 /*
6093  * Merge two allocindirs which refer to the same block.  Move newblock
6094  * dependencies and setup the freefrags appropriately.
6095  */
6096 static struct freefrag *
6097 allocindir_merge(aip, oldaip)
6098 	struct allocindir *aip;
6099 	struct allocindir *oldaip;
6100 {
6101 	struct freefrag *freefrag;
6102 	struct worklist *wk;
6103 
6104 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6105 		panic("allocindir_merge: blkno");
6106 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6107 	freefrag = aip->ai_freefrag;
6108 	aip->ai_freefrag = oldaip->ai_freefrag;
6109 	oldaip->ai_freefrag = NULL;
6110 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6111 	/*
6112 	 * If we are tracking a new directory-block allocation,
6113 	 * move it from the old allocindir to the new allocindir.
6114 	 */
6115 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6116 		WORKLIST_REMOVE(wk);
6117 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6118 			panic("allocindir_merge: extra newdirblk");
6119 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6120 	}
6121 	/*
6122 	 * We can skip journaling for this freefrag and just complete
6123 	 * any pending journal work for the allocindir that is being
6124 	 * removed after the freefrag completes.
6125 	 */
6126 	if (freefrag->ff_jdep)
6127 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6128 	LIST_REMOVE(oldaip, ai_next);
6129 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6130 	    &freefrag->ff_list, &freefrag->ff_jwork);
6131 	free_newblk(&oldaip->ai_block);
6132 
6133 	return (freefrag);
6134 }
6135 
6136 static inline void
6137 setup_freedirect(freeblks, ip, i, needj)
6138 	struct freeblks *freeblks;
6139 	struct inode *ip;
6140 	int i;
6141 	int needj;
6142 {
6143 	struct ufsmount *ump;
6144 	ufs2_daddr_t blkno;
6145 	int frags;
6146 
6147 	blkno = DIP(ip, i_db[i]);
6148 	if (blkno == 0)
6149 		return;
6150 	DIP_SET(ip, i_db[i], 0);
6151 	ump = ITOUMP(ip);
6152 	frags = sblksize(ump->um_fs, ip->i_size, i);
6153 	frags = numfrags(ump->um_fs, frags);
6154 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6155 }
6156 
6157 static inline void
6158 setup_freeext(freeblks, ip, i, needj)
6159 	struct freeblks *freeblks;
6160 	struct inode *ip;
6161 	int i;
6162 	int needj;
6163 {
6164 	struct ufsmount *ump;
6165 	ufs2_daddr_t blkno;
6166 	int frags;
6167 
6168 	blkno = ip->i_din2->di_extb[i];
6169 	if (blkno == 0)
6170 		return;
6171 	ip->i_din2->di_extb[i] = 0;
6172 	ump = ITOUMP(ip);
6173 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6174 	frags = numfrags(ump->um_fs, frags);
6175 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6176 }
6177 
6178 static inline void
6179 setup_freeindir(freeblks, ip, i, lbn, needj)
6180 	struct freeblks *freeblks;
6181 	struct inode *ip;
6182 	int i;
6183 	ufs_lbn_t lbn;
6184 	int needj;
6185 {
6186 	struct ufsmount *ump;
6187 	ufs2_daddr_t blkno;
6188 
6189 	blkno = DIP(ip, i_ib[i]);
6190 	if (blkno == 0)
6191 		return;
6192 	DIP_SET(ip, i_ib[i], 0);
6193 	ump = ITOUMP(ip);
6194 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6195 	    0, needj);
6196 }
6197 
6198 static inline struct freeblks *
6199 newfreeblks(mp, ip)
6200 	struct mount *mp;
6201 	struct inode *ip;
6202 {
6203 	struct freeblks *freeblks;
6204 
6205 	freeblks = malloc(sizeof(struct freeblks),
6206 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6207 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6208 	LIST_INIT(&freeblks->fb_jblkdephd);
6209 	LIST_INIT(&freeblks->fb_jwork);
6210 	freeblks->fb_ref = 0;
6211 	freeblks->fb_cgwait = 0;
6212 	freeblks->fb_state = ATTACHED;
6213 	freeblks->fb_uid = ip->i_uid;
6214 	freeblks->fb_inum = ip->i_number;
6215 	freeblks->fb_vtype = ITOV(ip)->v_type;
6216 	freeblks->fb_modrev = DIP(ip, i_modrev);
6217 	freeblks->fb_devvp = ITODEVVP(ip);
6218 	freeblks->fb_chkcnt = 0;
6219 	freeblks->fb_len = 0;
6220 
6221 	return (freeblks);
6222 }
6223 
6224 static void
6225 trunc_indirdep(indirdep, freeblks, bp, off)
6226 	struct indirdep *indirdep;
6227 	struct freeblks *freeblks;
6228 	struct buf *bp;
6229 	int off;
6230 {
6231 	struct allocindir *aip, *aipn;
6232 
6233 	/*
6234 	 * The first set of allocindirs won't be in savedbp.
6235 	 */
6236 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6237 		if (aip->ai_offset > off)
6238 			cancel_allocindir(aip, bp, freeblks, 1);
6239 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6240 		if (aip->ai_offset > off)
6241 			cancel_allocindir(aip, bp, freeblks, 1);
6242 	/*
6243 	 * These will exist in savedbp.
6244 	 */
6245 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6246 		if (aip->ai_offset > off)
6247 			cancel_allocindir(aip, NULL, freeblks, 0);
6248 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6249 		if (aip->ai_offset > off)
6250 			cancel_allocindir(aip, NULL, freeblks, 0);
6251 }
6252 
6253 /*
6254  * Follow the chain of indirects down to lastlbn creating a freework
6255  * structure for each.  This will be used to start indir_trunc() at
6256  * the right offset and create the journal records for the parrtial
6257  * truncation.  A second step will handle the truncated dependencies.
6258  */
6259 static int
6260 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6261 	struct freeblks *freeblks;
6262 	struct inode *ip;
6263 	ufs_lbn_t lbn;
6264 	ufs_lbn_t lastlbn;
6265 	ufs2_daddr_t blkno;
6266 {
6267 	struct indirdep *indirdep;
6268 	struct indirdep *indirn;
6269 	struct freework *freework;
6270 	struct newblk *newblk;
6271 	struct mount *mp;
6272 	struct ufsmount *ump;
6273 	struct buf *bp;
6274 	uint8_t *start;
6275 	uint8_t *end;
6276 	ufs_lbn_t lbnadd;
6277 	int level;
6278 	int error;
6279 	int off;
6280 
6281 
6282 	freework = NULL;
6283 	if (blkno == 0)
6284 		return (0);
6285 	mp = freeblks->fb_list.wk_mp;
6286 	ump = VFSTOUFS(mp);
6287 	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6288 	if ((bp->b_flags & B_CACHE) == 0) {
6289 		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6290 		bp->b_iocmd = BIO_READ;
6291 		bp->b_flags &= ~B_INVAL;
6292 		bp->b_ioflags &= ~BIO_ERROR;
6293 		vfs_busy_pages(bp, 0);
6294 		bp->b_iooffset = dbtob(bp->b_blkno);
6295 		bstrategy(bp);
6296 #ifdef RACCT
6297 		if (racct_enable) {
6298 			PROC_LOCK(curproc);
6299 			racct_add_buf(curproc, bp, 0);
6300 			PROC_UNLOCK(curproc);
6301 		}
6302 #endif /* RACCT */
6303 		curthread->td_ru.ru_inblock++;
6304 		error = bufwait(bp);
6305 		if (error) {
6306 			brelse(bp);
6307 			return (error);
6308 		}
6309 	}
6310 	level = lbn_level(lbn);
6311 	lbnadd = lbn_offset(ump->um_fs, level);
6312 	/*
6313 	 * Compute the offset of the last block we want to keep.  Store
6314 	 * in the freework the first block we want to completely free.
6315 	 */
6316 	off = (lastlbn - -(lbn + level)) / lbnadd;
6317 	if (off + 1 == NINDIR(ump->um_fs))
6318 		goto nowork;
6319 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6320 	/*
6321 	 * Link the freework into the indirdep.  This will prevent any new
6322 	 * allocations from proceeding until we are finished with the
6323 	 * truncate and the block is written.
6324 	 */
6325 	ACQUIRE_LOCK(ump);
6326 	indirdep = indirdep_lookup(mp, ip, bp);
6327 	if (indirdep->ir_freeblks)
6328 		panic("setup_trunc_indir: indirdep already truncated.");
6329 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6330 	freework->fw_indir = indirdep;
6331 	/*
6332 	 * Cancel any allocindirs that will not make it to disk.
6333 	 * We have to do this for all copies of the indirdep that
6334 	 * live on this newblk.
6335 	 */
6336 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6337 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6338 		    &newblk) == 0)
6339 			panic("setup_trunc_indir: lost block");
6340 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6341 			trunc_indirdep(indirn, freeblks, bp, off);
6342 	} else
6343 		trunc_indirdep(indirdep, freeblks, bp, off);
6344 	FREE_LOCK(ump);
6345 	/*
6346 	 * Creation is protected by the buf lock. The saveddata is only
6347 	 * needed if a full truncation follows a partial truncation but it
6348 	 * is difficult to allocate in that case so we fetch it anyway.
6349 	 */
6350 	if (indirdep->ir_saveddata == NULL)
6351 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6352 		    M_SOFTDEP_FLAGS);
6353 nowork:
6354 	/* Fetch the blkno of the child and the zero start offset. */
6355 	if (I_IS_UFS1(ip)) {
6356 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6357 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6358 	} else {
6359 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6360 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6361 	}
6362 	if (freework) {
6363 		/* Zero the truncated pointers. */
6364 		end = bp->b_data + bp->b_bcount;
6365 		bzero(start, end - start);
6366 		bdwrite(bp);
6367 	} else
6368 		bqrelse(bp);
6369 	if (level == 0)
6370 		return (0);
6371 	lbn++; /* adjust level */
6372 	lbn -= (off * lbnadd);
6373 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6374 }
6375 
6376 /*
6377  * Complete the partial truncation of an indirect block setup by
6378  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6379  * copy and writes them to disk before the freeblks is allowed to complete.
6380  */
6381 static void
6382 complete_trunc_indir(freework)
6383 	struct freework *freework;
6384 {
6385 	struct freework *fwn;
6386 	struct indirdep *indirdep;
6387 	struct ufsmount *ump;
6388 	struct buf *bp;
6389 	uintptr_t start;
6390 	int count;
6391 
6392 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6393 	LOCK_OWNED(ump);
6394 	indirdep = freework->fw_indir;
6395 	for (;;) {
6396 		bp = indirdep->ir_bp;
6397 		/* See if the block was discarded. */
6398 		if (bp == NULL)
6399 			break;
6400 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6401 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6402 			break;
6403 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6404 		    LOCK_PTR(ump)) == 0)
6405 			BUF_UNLOCK(bp);
6406 		ACQUIRE_LOCK(ump);
6407 	}
6408 	freework->fw_state |= DEPCOMPLETE;
6409 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6410 	/*
6411 	 * Zero the pointers in the saved copy.
6412 	 */
6413 	if (indirdep->ir_state & UFS1FMT)
6414 		start = sizeof(ufs1_daddr_t);
6415 	else
6416 		start = sizeof(ufs2_daddr_t);
6417 	start *= freework->fw_start;
6418 	count = indirdep->ir_savebp->b_bcount - start;
6419 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6420 	bzero((char *)start, count);
6421 	/*
6422 	 * We need to start the next truncation in the list if it has not
6423 	 * been started yet.
6424 	 */
6425 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6426 	if (fwn != NULL) {
6427 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6428 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6429 		if ((fwn->fw_state & ONWORKLIST) == 0)
6430 			freework_enqueue(fwn);
6431 	}
6432 	/*
6433 	 * If bp is NULL the block was fully truncated, restore
6434 	 * the saved block list otherwise free it if it is no
6435 	 * longer needed.
6436 	 */
6437 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6438 		if (bp == NULL)
6439 			bcopy(indirdep->ir_saveddata,
6440 			    indirdep->ir_savebp->b_data,
6441 			    indirdep->ir_savebp->b_bcount);
6442 		free(indirdep->ir_saveddata, M_INDIRDEP);
6443 		indirdep->ir_saveddata = NULL;
6444 	}
6445 	/*
6446 	 * When bp is NULL there is a full truncation pending.  We
6447 	 * must wait for this full truncation to be journaled before
6448 	 * we can release this freework because the disk pointers will
6449 	 * never be written as zero.
6450 	 */
6451 	if (bp == NULL)  {
6452 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6453 			handle_written_freework(freework);
6454 		else
6455 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6456 			   &freework->fw_list);
6457 	} else {
6458 		/* Complete when the real copy is written. */
6459 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6460 		BUF_UNLOCK(bp);
6461 	}
6462 }
6463 
6464 /*
6465  * Calculate the number of blocks we are going to release where datablocks
6466  * is the current total and length is the new file size.
6467  */
6468 static ufs2_daddr_t
6469 blkcount(fs, datablocks, length)
6470 	struct fs *fs;
6471 	ufs2_daddr_t datablocks;
6472 	off_t length;
6473 {
6474 	off_t totblks, numblks;
6475 
6476 	totblks = 0;
6477 	numblks = howmany(length, fs->fs_bsize);
6478 	if (numblks <= UFS_NDADDR) {
6479 		totblks = howmany(length, fs->fs_fsize);
6480 		goto out;
6481 	}
6482         totblks = blkstofrags(fs, numblks);
6483 	numblks -= UFS_NDADDR;
6484 	/*
6485 	 * Count all single, then double, then triple indirects required.
6486 	 * Subtracting one indirects worth of blocks for each pass
6487 	 * acknowledges one of each pointed to by the inode.
6488 	 */
6489 	for (;;) {
6490 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6491 		numblks -= NINDIR(fs);
6492 		if (numblks <= 0)
6493 			break;
6494 		numblks = howmany(numblks, NINDIR(fs));
6495 	}
6496 out:
6497 	totblks = fsbtodb(fs, totblks);
6498 	/*
6499 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6500 	 * references.  We will correct it later in handle_complete_freeblks()
6501 	 * when we know the real count.
6502 	 */
6503 	if (totblks > datablocks)
6504 		return (0);
6505 	return (datablocks - totblks);
6506 }
6507 
6508 /*
6509  * Handle freeblocks for journaled softupdate filesystems.
6510  *
6511  * Contrary to normal softupdates, we must preserve the block pointers in
6512  * indirects until their subordinates are free.  This is to avoid journaling
6513  * every block that is freed which may consume more space than the journal
6514  * itself.  The recovery program will see the free block journals at the
6515  * base of the truncated area and traverse them to reclaim space.  The
6516  * pointers in the inode may be cleared immediately after the journal
6517  * records are written because each direct and indirect pointer in the
6518  * inode is recorded in a journal.  This permits full truncation to proceed
6519  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6520  *
6521  * The algorithm is as follows:
6522  * 1) Traverse the in-memory state and create journal entries to release
6523  *    the relevant blocks and full indirect trees.
6524  * 2) Traverse the indirect block chain adding partial truncation freework
6525  *    records to indirects in the path to lastlbn.  The freework will
6526  *    prevent new allocation dependencies from being satisfied in this
6527  *    indirect until the truncation completes.
6528  * 3) Read and lock the inode block, performing an update with the new size
6529  *    and pointers.  This prevents truncated data from becoming valid on
6530  *    disk through step 4.
6531  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6532  *    eliminate journal work for those records that do not require it.
6533  * 5) Schedule the journal records to be written followed by the inode block.
6534  * 6) Allocate any necessary frags for the end of file.
6535  * 7) Zero any partially truncated blocks.
6536  *
6537  * From this truncation proceeds asynchronously using the freework and
6538  * indir_trunc machinery.  The file will not be extended again into a
6539  * partially truncated indirect block until all work is completed but
6540  * the normal dependency mechanism ensures that it is rolled back/forward
6541  * as appropriate.  Further truncation may occur without delay and is
6542  * serialized in indir_trunc().
6543  */
6544 void
6545 softdep_journal_freeblocks(ip, cred, length, flags)
6546 	struct inode *ip;	/* The inode whose length is to be reduced */
6547 	struct ucred *cred;
6548 	off_t length;		/* The new length for the file */
6549 	int flags;		/* IO_EXT and/or IO_NORMAL */
6550 {
6551 	struct freeblks *freeblks, *fbn;
6552 	struct worklist *wk, *wkn;
6553 	struct inodedep *inodedep;
6554 	struct jblkdep *jblkdep;
6555 	struct allocdirect *adp, *adpn;
6556 	struct ufsmount *ump;
6557 	struct fs *fs;
6558 	struct buf *bp;
6559 	struct vnode *vp;
6560 	struct mount *mp;
6561 	ufs2_daddr_t extblocks, datablocks;
6562 	ufs_lbn_t tmpval, lbn, lastlbn;
6563 	int frags, lastoff, iboff, allocblock, needj, error, i;
6564 
6565 	ump = ITOUMP(ip);
6566 	mp = UFSTOVFS(ump);
6567 	fs = ump->um_fs;
6568 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6569 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6570 	vp = ITOV(ip);
6571 	needj = 1;
6572 	iboff = -1;
6573 	allocblock = 0;
6574 	extblocks = 0;
6575 	datablocks = 0;
6576 	frags = 0;
6577 	freeblks = newfreeblks(mp, ip);
6578 	ACQUIRE_LOCK(ump);
6579 	/*
6580 	 * If we're truncating a removed file that will never be written
6581 	 * we don't need to journal the block frees.  The canceled journals
6582 	 * for the allocations will suffice.
6583 	 */
6584 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6585 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6586 	    length == 0)
6587 		needj = 0;
6588 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6589 	    ip->i_number, length, needj);
6590 	FREE_LOCK(ump);
6591 	/*
6592 	 * Calculate the lbn that we are truncating to.  This results in -1
6593 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6594 	 * to keep, not the first lbn we want to truncate.
6595 	 */
6596 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6597 	lastoff = blkoff(fs, length);
6598 	/*
6599 	 * Compute frags we are keeping in lastlbn.  0 means all.
6600 	 */
6601 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6602 		frags = fragroundup(fs, lastoff);
6603 		/* adp offset of last valid allocdirect. */
6604 		iboff = lastlbn;
6605 	} else if (lastlbn > 0)
6606 		iboff = UFS_NDADDR;
6607 	if (fs->fs_magic == FS_UFS2_MAGIC)
6608 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6609 	/*
6610 	 * Handle normal data blocks and indirects.  This section saves
6611 	 * values used after the inode update to complete frag and indirect
6612 	 * truncation.
6613 	 */
6614 	if ((flags & IO_NORMAL) != 0) {
6615 		/*
6616 		 * Handle truncation of whole direct and indirect blocks.
6617 		 */
6618 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6619 			setup_freedirect(freeblks, ip, i, needj);
6620 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6621 		    i < UFS_NIADDR;
6622 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6623 			/* Release a whole indirect tree. */
6624 			if (lbn > lastlbn) {
6625 				setup_freeindir(freeblks, ip, i, -lbn -i,
6626 				    needj);
6627 				continue;
6628 			}
6629 			iboff = i + UFS_NDADDR;
6630 			/*
6631 			 * Traverse partially truncated indirect tree.
6632 			 */
6633 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6634 				setup_trunc_indir(freeblks, ip, -lbn - i,
6635 				    lastlbn, DIP(ip, i_ib[i]));
6636 		}
6637 		/*
6638 		 * Handle partial truncation to a frag boundary.
6639 		 */
6640 		if (frags) {
6641 			ufs2_daddr_t blkno;
6642 			long oldfrags;
6643 
6644 			oldfrags = blksize(fs, ip, lastlbn);
6645 			blkno = DIP(ip, i_db[lastlbn]);
6646 			if (blkno && oldfrags != frags) {
6647 				oldfrags -= frags;
6648 				oldfrags = numfrags(fs, oldfrags);
6649 				blkno += numfrags(fs, frags);
6650 				newfreework(ump, freeblks, NULL, lastlbn,
6651 				    blkno, oldfrags, 0, needj);
6652 				if (needj)
6653 					adjust_newfreework(freeblks,
6654 					    numfrags(fs, frags));
6655 			} else if (blkno == 0)
6656 				allocblock = 1;
6657 		}
6658 		/*
6659 		 * Add a journal record for partial truncate if we are
6660 		 * handling indirect blocks.  Non-indirects need no extra
6661 		 * journaling.
6662 		 */
6663 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6664 			ip->i_flag |= IN_TRUNCATED;
6665 			newjtrunc(freeblks, length, 0);
6666 		}
6667 		ip->i_size = length;
6668 		DIP_SET(ip, i_size, ip->i_size);
6669 		datablocks = DIP(ip, i_blocks) - extblocks;
6670 		if (length != 0)
6671 			datablocks = blkcount(fs, datablocks, length);
6672 		freeblks->fb_len = length;
6673 	}
6674 	if ((flags & IO_EXT) != 0) {
6675 		for (i = 0; i < UFS_NXADDR; i++)
6676 			setup_freeext(freeblks, ip, i, needj);
6677 		ip->i_din2->di_extsize = 0;
6678 		datablocks += extblocks;
6679 	}
6680 #ifdef QUOTA
6681 	/* Reference the quotas in case the block count is wrong in the end. */
6682 	quotaref(vp, freeblks->fb_quota);
6683 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6684 #endif
6685 	freeblks->fb_chkcnt = -datablocks;
6686 	UFS_LOCK(ump);
6687 	fs->fs_pendingblocks += datablocks;
6688 	UFS_UNLOCK(ump);
6689 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6690 	/*
6691 	 * Handle truncation of incomplete alloc direct dependencies.  We
6692 	 * hold the inode block locked to prevent incomplete dependencies
6693 	 * from reaching the disk while we are eliminating those that
6694 	 * have been truncated.  This is a partially inlined ffs_update().
6695 	 */
6696 	ufs_itimes(vp);
6697 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6698 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6699 	    (int)fs->fs_bsize, cred, &bp);
6700 	if (error) {
6701 		brelse(bp);
6702 		softdep_error("softdep_journal_freeblocks", error);
6703 		return;
6704 	}
6705 	if (bp->b_bufsize == fs->fs_bsize)
6706 		bp->b_flags |= B_CLUSTEROK;
6707 	softdep_update_inodeblock(ip, bp, 0);
6708 	if (ump->um_fstype == UFS1) {
6709 		*((struct ufs1_dinode *)bp->b_data +
6710 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6711 	} else {
6712 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6713 		*((struct ufs2_dinode *)bp->b_data +
6714 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6715 	}
6716 	ACQUIRE_LOCK(ump);
6717 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6718 	if ((inodedep->id_state & IOSTARTED) != 0)
6719 		panic("softdep_setup_freeblocks: inode busy");
6720 	/*
6721 	 * Add the freeblks structure to the list of operations that
6722 	 * must await the zero'ed inode being written to disk. If we
6723 	 * still have a bitmap dependency (needj), then the inode
6724 	 * has never been written to disk, so we can process the
6725 	 * freeblks below once we have deleted the dependencies.
6726 	 */
6727 	if (needj)
6728 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6729 	else
6730 		freeblks->fb_state |= COMPLETE;
6731 	if ((flags & IO_NORMAL) != 0) {
6732 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6733 			if (adp->ad_offset > iboff)
6734 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6735 				    freeblks);
6736 			/*
6737 			 * Truncate the allocdirect.  We could eliminate
6738 			 * or modify journal records as well.
6739 			 */
6740 			else if (adp->ad_offset == iboff && frags)
6741 				adp->ad_newsize = frags;
6742 		}
6743 	}
6744 	if ((flags & IO_EXT) != 0)
6745 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6746 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6747 			    freeblks);
6748 	/*
6749 	 * Scan the bufwait list for newblock dependencies that will never
6750 	 * make it to disk.
6751 	 */
6752 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6753 		if (wk->wk_type != D_ALLOCDIRECT)
6754 			continue;
6755 		adp = WK_ALLOCDIRECT(wk);
6756 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6757 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6758 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6759 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6760 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6761 		}
6762 	}
6763 	/*
6764 	 * Add journal work.
6765 	 */
6766 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6767 		add_to_journal(&jblkdep->jb_list);
6768 	FREE_LOCK(ump);
6769 	bdwrite(bp);
6770 	/*
6771 	 * Truncate dependency structures beyond length.
6772 	 */
6773 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6774 	/*
6775 	 * This is only set when we need to allocate a fragment because
6776 	 * none existed at the end of a frag-sized file.  It handles only
6777 	 * allocating a new, zero filled block.
6778 	 */
6779 	if (allocblock) {
6780 		ip->i_size = length - lastoff;
6781 		DIP_SET(ip, i_size, ip->i_size);
6782 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6783 		if (error != 0) {
6784 			softdep_error("softdep_journal_freeblks", error);
6785 			return;
6786 		}
6787 		ip->i_size = length;
6788 		DIP_SET(ip, i_size, length);
6789 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6790 		allocbuf(bp, frags);
6791 		ffs_update(vp, 0);
6792 		bawrite(bp);
6793 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6794 		int size;
6795 
6796 		/*
6797 		 * Zero the end of a truncated frag or block.
6798 		 */
6799 		size = sblksize(fs, length, lastlbn);
6800 		error = bread(vp, lastlbn, size, cred, &bp);
6801 		if (error) {
6802 			softdep_error("softdep_journal_freeblks", error);
6803 			return;
6804 		}
6805 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6806 		bawrite(bp);
6807 
6808 	}
6809 	ACQUIRE_LOCK(ump);
6810 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6811 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6812 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6813 	/*
6814 	 * We zero earlier truncations so they don't erroneously
6815 	 * update i_blocks.
6816 	 */
6817 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6818 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6819 			fbn->fb_len = 0;
6820 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6821 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6822 		freeblks->fb_state |= INPROGRESS;
6823 	else
6824 		freeblks = NULL;
6825 	FREE_LOCK(ump);
6826 	if (freeblks)
6827 		handle_workitem_freeblocks(freeblks, 0);
6828 	trunc_pages(ip, length, extblocks, flags);
6829 
6830 }
6831 
6832 /*
6833  * Flush a JOP_SYNC to the journal.
6834  */
6835 void
6836 softdep_journal_fsync(ip)
6837 	struct inode *ip;
6838 {
6839 	struct jfsync *jfsync;
6840 	struct ufsmount *ump;
6841 
6842 	ump = ITOUMP(ip);
6843 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6844 	    ("softdep_journal_fsync called on non-softdep filesystem"));
6845 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6846 		return;
6847 	ip->i_flag &= ~IN_TRUNCATED;
6848 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6849 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6850 	jfsync->jfs_size = ip->i_size;
6851 	jfsync->jfs_ino = ip->i_number;
6852 	ACQUIRE_LOCK(ump);
6853 	add_to_journal(&jfsync->jfs_list);
6854 	jwait(&jfsync->jfs_list, MNT_WAIT);
6855 	FREE_LOCK(ump);
6856 }
6857 
6858 /*
6859  * Block de-allocation dependencies.
6860  *
6861  * When blocks are de-allocated, the on-disk pointers must be nullified before
6862  * the blocks are made available for use by other files.  (The true
6863  * requirement is that old pointers must be nullified before new on-disk
6864  * pointers are set.  We chose this slightly more stringent requirement to
6865  * reduce complexity.) Our implementation handles this dependency by updating
6866  * the inode (or indirect block) appropriately but delaying the actual block
6867  * de-allocation (i.e., freemap and free space count manipulation) until
6868  * after the updated versions reach stable storage.  After the disk is
6869  * updated, the blocks can be safely de-allocated whenever it is convenient.
6870  * This implementation handles only the common case of reducing a file's
6871  * length to zero. Other cases are handled by the conventional synchronous
6872  * write approach.
6873  *
6874  * The ffs implementation with which we worked double-checks
6875  * the state of the block pointers and file size as it reduces
6876  * a file's length.  Some of this code is replicated here in our
6877  * soft updates implementation.  The freeblks->fb_chkcnt field is
6878  * used to transfer a part of this information to the procedure
6879  * that eventually de-allocates the blocks.
6880  *
6881  * This routine should be called from the routine that shortens
6882  * a file's length, before the inode's size or block pointers
6883  * are modified. It will save the block pointer information for
6884  * later release and zero the inode so that the calling routine
6885  * can release it.
6886  */
6887 void
6888 softdep_setup_freeblocks(ip, length, flags)
6889 	struct inode *ip;	/* The inode whose length is to be reduced */
6890 	off_t length;		/* The new length for the file */
6891 	int flags;		/* IO_EXT and/or IO_NORMAL */
6892 {
6893 	struct ufs1_dinode *dp1;
6894 	struct ufs2_dinode *dp2;
6895 	struct freeblks *freeblks;
6896 	struct inodedep *inodedep;
6897 	struct allocdirect *adp;
6898 	struct ufsmount *ump;
6899 	struct buf *bp;
6900 	struct fs *fs;
6901 	ufs2_daddr_t extblocks, datablocks;
6902 	struct mount *mp;
6903 	int i, delay, error;
6904 	ufs_lbn_t tmpval;
6905 	ufs_lbn_t lbn;
6906 
6907 	ump = ITOUMP(ip);
6908 	mp = UFSTOVFS(ump);
6909 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6910 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6911 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6912 	    ip->i_number, length);
6913 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6914 	fs = ump->um_fs;
6915 	if ((error = bread(ump->um_devvp,
6916 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6917 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6918 		brelse(bp);
6919 		softdep_error("softdep_setup_freeblocks", error);
6920 		return;
6921 	}
6922 	freeblks = newfreeblks(mp, ip);
6923 	extblocks = 0;
6924 	datablocks = 0;
6925 	if (fs->fs_magic == FS_UFS2_MAGIC)
6926 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6927 	if ((flags & IO_NORMAL) != 0) {
6928 		for (i = 0; i < UFS_NDADDR; i++)
6929 			setup_freedirect(freeblks, ip, i, 0);
6930 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6931 		    i < UFS_NIADDR;
6932 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6933 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6934 		ip->i_size = 0;
6935 		DIP_SET(ip, i_size, 0);
6936 		datablocks = DIP(ip, i_blocks) - extblocks;
6937 	}
6938 	if ((flags & IO_EXT) != 0) {
6939 		for (i = 0; i < UFS_NXADDR; i++)
6940 			setup_freeext(freeblks, ip, i, 0);
6941 		ip->i_din2->di_extsize = 0;
6942 		datablocks += extblocks;
6943 	}
6944 #ifdef QUOTA
6945 	/* Reference the quotas in case the block count is wrong in the end. */
6946 	quotaref(ITOV(ip), freeblks->fb_quota);
6947 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6948 #endif
6949 	freeblks->fb_chkcnt = -datablocks;
6950 	UFS_LOCK(ump);
6951 	fs->fs_pendingblocks += datablocks;
6952 	UFS_UNLOCK(ump);
6953 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6954 	/*
6955 	 * Push the zero'ed inode to its disk buffer so that we are free
6956 	 * to delete its dependencies below. Once the dependencies are gone
6957 	 * the buffer can be safely released.
6958 	 */
6959 	if (ump->um_fstype == UFS1) {
6960 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6961 		    ino_to_fsbo(fs, ip->i_number));
6962 		ip->i_din1->di_freelink = dp1->di_freelink;
6963 		*dp1 = *ip->i_din1;
6964 	} else {
6965 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6966 		    ino_to_fsbo(fs, ip->i_number));
6967 		ip->i_din2->di_freelink = dp2->di_freelink;
6968 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6969 		*dp2 = *ip->i_din2;
6970 	}
6971 	/*
6972 	 * Find and eliminate any inode dependencies.
6973 	 */
6974 	ACQUIRE_LOCK(ump);
6975 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6976 	if ((inodedep->id_state & IOSTARTED) != 0)
6977 		panic("softdep_setup_freeblocks: inode busy");
6978 	/*
6979 	 * Add the freeblks structure to the list of operations that
6980 	 * must await the zero'ed inode being written to disk. If we
6981 	 * still have a bitmap dependency (delay == 0), then the inode
6982 	 * has never been written to disk, so we can process the
6983 	 * freeblks below once we have deleted the dependencies.
6984 	 */
6985 	delay = (inodedep->id_state & DEPCOMPLETE);
6986 	if (delay)
6987 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6988 	else
6989 		freeblks->fb_state |= COMPLETE;
6990 	/*
6991 	 * Because the file length has been truncated to zero, any
6992 	 * pending block allocation dependency structures associated
6993 	 * with this inode are obsolete and can simply be de-allocated.
6994 	 * We must first merge the two dependency lists to get rid of
6995 	 * any duplicate freefrag structures, then purge the merged list.
6996 	 * If we still have a bitmap dependency, then the inode has never
6997 	 * been written to disk, so we can free any fragments without delay.
6998 	 */
6999 	if (flags & IO_NORMAL) {
7000 		merge_inode_lists(&inodedep->id_newinoupdt,
7001 		    &inodedep->id_inoupdt);
7002 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7003 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7004 			    freeblks);
7005 	}
7006 	if (flags & IO_EXT) {
7007 		merge_inode_lists(&inodedep->id_newextupdt,
7008 		    &inodedep->id_extupdt);
7009 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7010 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7011 			    freeblks);
7012 	}
7013 	FREE_LOCK(ump);
7014 	bdwrite(bp);
7015 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7016 	ACQUIRE_LOCK(ump);
7017 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7018 		(void) free_inodedep(inodedep);
7019 	freeblks->fb_state |= DEPCOMPLETE;
7020 	/*
7021 	 * If the inode with zeroed block pointers is now on disk
7022 	 * we can start freeing blocks.
7023 	 */
7024 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7025 		freeblks->fb_state |= INPROGRESS;
7026 	else
7027 		freeblks = NULL;
7028 	FREE_LOCK(ump);
7029 	if (freeblks)
7030 		handle_workitem_freeblocks(freeblks, 0);
7031 	trunc_pages(ip, length, extblocks, flags);
7032 }
7033 
7034 /*
7035  * Eliminate pages from the page cache that back parts of this inode and
7036  * adjust the vnode pager's idea of our size.  This prevents stale data
7037  * from hanging around in the page cache.
7038  */
7039 static void
7040 trunc_pages(ip, length, extblocks, flags)
7041 	struct inode *ip;
7042 	off_t length;
7043 	ufs2_daddr_t extblocks;
7044 	int flags;
7045 {
7046 	struct vnode *vp;
7047 	struct fs *fs;
7048 	ufs_lbn_t lbn;
7049 	off_t end, extend;
7050 
7051 	vp = ITOV(ip);
7052 	fs = ITOFS(ip);
7053 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7054 	if ((flags & IO_EXT) != 0)
7055 		vn_pages_remove(vp, extend, 0);
7056 	if ((flags & IO_NORMAL) == 0)
7057 		return;
7058 	BO_LOCK(&vp->v_bufobj);
7059 	drain_output(vp);
7060 	BO_UNLOCK(&vp->v_bufobj);
7061 	/*
7062 	 * The vnode pager eliminates file pages we eliminate indirects
7063 	 * below.
7064 	 */
7065 	vnode_pager_setsize(vp, length);
7066 	/*
7067 	 * Calculate the end based on the last indirect we want to keep.  If
7068 	 * the block extends into indirects we can just use the negative of
7069 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7070 	 * be careful not to remove those, if they exist.  double and triple
7071 	 * indirect lbns do not overlap with others so it is not important
7072 	 * to verify how many levels are required.
7073 	 */
7074 	lbn = lblkno(fs, length);
7075 	if (lbn >= UFS_NDADDR) {
7076 		/* Calculate the virtual lbn of the triple indirect. */
7077 		lbn = -lbn - (UFS_NIADDR - 1);
7078 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7079 	} else
7080 		end = extend;
7081 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7082 }
7083 
7084 /*
7085  * See if the buf bp is in the range eliminated by truncation.
7086  */
7087 static int
7088 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7089 	struct buf *bp;
7090 	int *blkoffp;
7091 	ufs_lbn_t lastlbn;
7092 	int lastoff;
7093 	int flags;
7094 {
7095 	ufs_lbn_t lbn;
7096 
7097 	*blkoffp = 0;
7098 	/* Only match ext/normal blocks as appropriate. */
7099 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7100 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7101 		return (0);
7102 	/* ALTDATA is always a full truncation. */
7103 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7104 		return (1);
7105 	/* -1 is full truncation. */
7106 	if (lastlbn == -1)
7107 		return (1);
7108 	/*
7109 	 * If this is a partial truncate we only want those
7110 	 * blocks and indirect blocks that cover the range
7111 	 * we're after.
7112 	 */
7113 	lbn = bp->b_lblkno;
7114 	if (lbn < 0)
7115 		lbn = -(lbn + lbn_level(lbn));
7116 	if (lbn < lastlbn)
7117 		return (0);
7118 	/* Here we only truncate lblkno if it's partial. */
7119 	if (lbn == lastlbn) {
7120 		if (lastoff == 0)
7121 			return (0);
7122 		*blkoffp = lastoff;
7123 	}
7124 	return (1);
7125 }
7126 
7127 /*
7128  * Eliminate any dependencies that exist in memory beyond lblkno:off
7129  */
7130 static void
7131 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7132 	struct inode *ip;
7133 	struct freeblks *freeblks;
7134 	ufs_lbn_t lastlbn;
7135 	int lastoff;
7136 	int flags;
7137 {
7138 	struct bufobj *bo;
7139 	struct vnode *vp;
7140 	struct buf *bp;
7141 	int blkoff;
7142 
7143 	/*
7144 	 * We must wait for any I/O in progress to finish so that
7145 	 * all potential buffers on the dirty list will be visible.
7146 	 * Once they are all there, walk the list and get rid of
7147 	 * any dependencies.
7148 	 */
7149 	vp = ITOV(ip);
7150 	bo = &vp->v_bufobj;
7151 	BO_LOCK(bo);
7152 	drain_output(vp);
7153 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7154 		bp->b_vflags &= ~BV_SCANNED;
7155 restart:
7156 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7157 		if (bp->b_vflags & BV_SCANNED)
7158 			continue;
7159 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7160 			bp->b_vflags |= BV_SCANNED;
7161 			continue;
7162 		}
7163 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7164 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7165 			goto restart;
7166 		BO_UNLOCK(bo);
7167 		if (deallocate_dependencies(bp, freeblks, blkoff))
7168 			bqrelse(bp);
7169 		else
7170 			brelse(bp);
7171 		BO_LOCK(bo);
7172 		goto restart;
7173 	}
7174 	/*
7175 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7176 	 */
7177 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7178 		bp->b_vflags &= ~BV_SCANNED;
7179 cleanrestart:
7180 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7181 		if (bp->b_vflags & BV_SCANNED)
7182 			continue;
7183 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7184 			bp->b_vflags |= BV_SCANNED;
7185 			continue;
7186 		}
7187 		if (BUF_LOCK(bp,
7188 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7189 		    BO_LOCKPTR(bo)) == ENOLCK) {
7190 			BO_LOCK(bo);
7191 			goto cleanrestart;
7192 		}
7193 		bp->b_vflags |= BV_SCANNED;
7194 		bremfree(bp);
7195 		if (blkoff != 0) {
7196 			allocbuf(bp, blkoff);
7197 			bqrelse(bp);
7198 		} else {
7199 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7200 			brelse(bp);
7201 		}
7202 		BO_LOCK(bo);
7203 		goto cleanrestart;
7204 	}
7205 	drain_output(vp);
7206 	BO_UNLOCK(bo);
7207 }
7208 
7209 static int
7210 cancel_pagedep(pagedep, freeblks, blkoff)
7211 	struct pagedep *pagedep;
7212 	struct freeblks *freeblks;
7213 	int blkoff;
7214 {
7215 	struct jremref *jremref;
7216 	struct jmvref *jmvref;
7217 	struct dirrem *dirrem, *tmp;
7218 	int i;
7219 
7220 	/*
7221 	 * Copy any directory remove dependencies to the list
7222 	 * to be processed after the freeblks proceeds.  If
7223 	 * directory entry never made it to disk they
7224 	 * can be dumped directly onto the work list.
7225 	 */
7226 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7227 		/* Skip this directory removal if it is intended to remain. */
7228 		if (dirrem->dm_offset < blkoff)
7229 			continue;
7230 		/*
7231 		 * If there are any dirrems we wait for the journal write
7232 		 * to complete and then restart the buf scan as the lock
7233 		 * has been dropped.
7234 		 */
7235 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7236 			jwait(&jremref->jr_list, MNT_WAIT);
7237 			return (ERESTART);
7238 		}
7239 		LIST_REMOVE(dirrem, dm_next);
7240 		dirrem->dm_dirinum = pagedep->pd_ino;
7241 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7242 	}
7243 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7244 		jwait(&jmvref->jm_list, MNT_WAIT);
7245 		return (ERESTART);
7246 	}
7247 	/*
7248 	 * When we're partially truncating a pagedep we just want to flush
7249 	 * journal entries and return.  There can not be any adds in the
7250 	 * truncated portion of the directory and newblk must remain if
7251 	 * part of the block remains.
7252 	 */
7253 	if (blkoff != 0) {
7254 		struct diradd *dap;
7255 
7256 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7257 			if (dap->da_offset > blkoff)
7258 				panic("cancel_pagedep: diradd %p off %d > %d",
7259 				    dap, dap->da_offset, blkoff);
7260 		for (i = 0; i < DAHASHSZ; i++)
7261 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7262 				if (dap->da_offset > blkoff)
7263 					panic("cancel_pagedep: diradd %p off %d > %d",
7264 					    dap, dap->da_offset, blkoff);
7265 		return (0);
7266 	}
7267 	/*
7268 	 * There should be no directory add dependencies present
7269 	 * as the directory could not be truncated until all
7270 	 * children were removed.
7271 	 */
7272 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7273 	    ("deallocate_dependencies: pendinghd != NULL"));
7274 	for (i = 0; i < DAHASHSZ; i++)
7275 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7276 		    ("deallocate_dependencies: diraddhd != NULL"));
7277 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7278 		free_newdirblk(pagedep->pd_newdirblk);
7279 	if (free_pagedep(pagedep) == 0)
7280 		panic("Failed to free pagedep %p", pagedep);
7281 	return (0);
7282 }
7283 
7284 /*
7285  * Reclaim any dependency structures from a buffer that is about to
7286  * be reallocated to a new vnode. The buffer must be locked, thus,
7287  * no I/O completion operations can occur while we are manipulating
7288  * its associated dependencies. The mutex is held so that other I/O's
7289  * associated with related dependencies do not occur.
7290  */
7291 static int
7292 deallocate_dependencies(bp, freeblks, off)
7293 	struct buf *bp;
7294 	struct freeblks *freeblks;
7295 	int off;
7296 {
7297 	struct indirdep *indirdep;
7298 	struct pagedep *pagedep;
7299 	struct worklist *wk, *wkn;
7300 	struct ufsmount *ump;
7301 
7302 	ump = softdep_bp_to_mp(bp);
7303 	if (ump == NULL)
7304 		goto done;
7305 	ACQUIRE_LOCK(ump);
7306 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7307 		switch (wk->wk_type) {
7308 		case D_INDIRDEP:
7309 			indirdep = WK_INDIRDEP(wk);
7310 			if (bp->b_lblkno >= 0 ||
7311 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7312 				panic("deallocate_dependencies: not indir");
7313 			cancel_indirdep(indirdep, bp, freeblks);
7314 			continue;
7315 
7316 		case D_PAGEDEP:
7317 			pagedep = WK_PAGEDEP(wk);
7318 			if (cancel_pagedep(pagedep, freeblks, off)) {
7319 				FREE_LOCK(ump);
7320 				return (ERESTART);
7321 			}
7322 			continue;
7323 
7324 		case D_ALLOCINDIR:
7325 			/*
7326 			 * Simply remove the allocindir, we'll find it via
7327 			 * the indirdep where we can clear pointers if
7328 			 * needed.
7329 			 */
7330 			WORKLIST_REMOVE(wk);
7331 			continue;
7332 
7333 		case D_FREEWORK:
7334 			/*
7335 			 * A truncation is waiting for the zero'd pointers
7336 			 * to be written.  It can be freed when the freeblks
7337 			 * is journaled.
7338 			 */
7339 			WORKLIST_REMOVE(wk);
7340 			wk->wk_state |= ONDEPLIST;
7341 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7342 			break;
7343 
7344 		case D_ALLOCDIRECT:
7345 			if (off != 0)
7346 				continue;
7347 			/* FALLTHROUGH */
7348 		default:
7349 			panic("deallocate_dependencies: Unexpected type %s",
7350 			    TYPENAME(wk->wk_type));
7351 			/* NOTREACHED */
7352 		}
7353 	}
7354 	FREE_LOCK(ump);
7355 done:
7356 	/*
7357 	 * Don't throw away this buf, we were partially truncating and
7358 	 * some deps may always remain.
7359 	 */
7360 	if (off) {
7361 		allocbuf(bp, off);
7362 		bp->b_vflags |= BV_SCANNED;
7363 		return (EBUSY);
7364 	}
7365 	bp->b_flags |= B_INVAL | B_NOCACHE;
7366 
7367 	return (0);
7368 }
7369 
7370 /*
7371  * An allocdirect is being canceled due to a truncate.  We must make sure
7372  * the journal entry is released in concert with the blkfree that releases
7373  * the storage.  Completed journal entries must not be released until the
7374  * space is no longer pointed to by the inode or in the bitmap.
7375  */
7376 static void
7377 cancel_allocdirect(adphead, adp, freeblks)
7378 	struct allocdirectlst *adphead;
7379 	struct allocdirect *adp;
7380 	struct freeblks *freeblks;
7381 {
7382 	struct freework *freework;
7383 	struct newblk *newblk;
7384 	struct worklist *wk;
7385 
7386 	TAILQ_REMOVE(adphead, adp, ad_next);
7387 	newblk = (struct newblk *)adp;
7388 	freework = NULL;
7389 	/*
7390 	 * Find the correct freework structure.
7391 	 */
7392 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7393 		if (wk->wk_type != D_FREEWORK)
7394 			continue;
7395 		freework = WK_FREEWORK(wk);
7396 		if (freework->fw_blkno == newblk->nb_newblkno)
7397 			break;
7398 	}
7399 	if (freework == NULL)
7400 		panic("cancel_allocdirect: Freework not found");
7401 	/*
7402 	 * If a newblk exists at all we still have the journal entry that
7403 	 * initiated the allocation so we do not need to journal the free.
7404 	 */
7405 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7406 	/*
7407 	 * If the journal hasn't been written the jnewblk must be passed
7408 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7409 	 * this by linking the journal dependency into the freework to be
7410 	 * freed when freework_freeblock() is called.  If the journal has
7411 	 * been written we can simply reclaim the journal space when the
7412 	 * freeblks work is complete.
7413 	 */
7414 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7415 	    &freeblks->fb_jwork);
7416 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7417 }
7418 
7419 
7420 /*
7421  * Cancel a new block allocation.  May be an indirect or direct block.  We
7422  * remove it from various lists and return any journal record that needs to
7423  * be resolved by the caller.
7424  *
7425  * A special consideration is made for indirects which were never pointed
7426  * at on disk and will never be found once this block is released.
7427  */
7428 static struct jnewblk *
7429 cancel_newblk(newblk, wk, wkhd)
7430 	struct newblk *newblk;
7431 	struct worklist *wk;
7432 	struct workhead *wkhd;
7433 {
7434 	struct jnewblk *jnewblk;
7435 
7436 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7437 
7438 	newblk->nb_state |= GOINGAWAY;
7439 	/*
7440 	 * Previously we traversed the completedhd on each indirdep
7441 	 * attached to this newblk to cancel them and gather journal
7442 	 * work.  Since we need only the oldest journal segment and
7443 	 * the lowest point on the tree will always have the oldest
7444 	 * journal segment we are free to release the segments
7445 	 * of any subordinates and may leave the indirdep list to
7446 	 * indirdep_complete() when this newblk is freed.
7447 	 */
7448 	if (newblk->nb_state & ONDEPLIST) {
7449 		newblk->nb_state &= ~ONDEPLIST;
7450 		LIST_REMOVE(newblk, nb_deps);
7451 	}
7452 	if (newblk->nb_state & ONWORKLIST)
7453 		WORKLIST_REMOVE(&newblk->nb_list);
7454 	/*
7455 	 * If the journal entry hasn't been written we save a pointer to
7456 	 * the dependency that frees it until it is written or the
7457 	 * superseding operation completes.
7458 	 */
7459 	jnewblk = newblk->nb_jnewblk;
7460 	if (jnewblk != NULL && wk != NULL) {
7461 		newblk->nb_jnewblk = NULL;
7462 		jnewblk->jn_dep = wk;
7463 	}
7464 	if (!LIST_EMPTY(&newblk->nb_jwork))
7465 		jwork_move(wkhd, &newblk->nb_jwork);
7466 	/*
7467 	 * When truncating we must free the newdirblk early to remove
7468 	 * the pagedep from the hash before returning.
7469 	 */
7470 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7471 		free_newdirblk(WK_NEWDIRBLK(wk));
7472 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7473 		panic("cancel_newblk: extra newdirblk");
7474 
7475 	return (jnewblk);
7476 }
7477 
7478 /*
7479  * Schedule the freefrag associated with a newblk to be released once
7480  * the pointers are written and the previous block is no longer needed.
7481  */
7482 static void
7483 newblk_freefrag(newblk)
7484 	struct newblk *newblk;
7485 {
7486 	struct freefrag *freefrag;
7487 
7488 	if (newblk->nb_freefrag == NULL)
7489 		return;
7490 	freefrag = newblk->nb_freefrag;
7491 	newblk->nb_freefrag = NULL;
7492 	freefrag->ff_state |= COMPLETE;
7493 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7494 		add_to_worklist(&freefrag->ff_list, 0);
7495 }
7496 
7497 /*
7498  * Free a newblk. Generate a new freefrag work request if appropriate.
7499  * This must be called after the inode pointer and any direct block pointers
7500  * are valid or fully removed via truncate or frag extension.
7501  */
7502 static void
7503 free_newblk(newblk)
7504 	struct newblk *newblk;
7505 {
7506 	struct indirdep *indirdep;
7507 	struct worklist *wk;
7508 
7509 	KASSERT(newblk->nb_jnewblk == NULL,
7510 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7511 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7512 	    ("free_newblk: unclaimed newblk"));
7513 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7514 	newblk_freefrag(newblk);
7515 	if (newblk->nb_state & ONDEPLIST)
7516 		LIST_REMOVE(newblk, nb_deps);
7517 	if (newblk->nb_state & ONWORKLIST)
7518 		WORKLIST_REMOVE(&newblk->nb_list);
7519 	LIST_REMOVE(newblk, nb_hash);
7520 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7521 		free_newdirblk(WK_NEWDIRBLK(wk));
7522 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7523 		panic("free_newblk: extra newdirblk");
7524 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7525 		indirdep_complete(indirdep);
7526 	handle_jwork(&newblk->nb_jwork);
7527 	WORKITEM_FREE(newblk, D_NEWBLK);
7528 }
7529 
7530 /*
7531  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7532  */
7533 static void
7534 free_newdirblk(newdirblk)
7535 	struct newdirblk *newdirblk;
7536 {
7537 	struct pagedep *pagedep;
7538 	struct diradd *dap;
7539 	struct worklist *wk;
7540 
7541 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7542 	WORKLIST_REMOVE(&newdirblk->db_list);
7543 	/*
7544 	 * If the pagedep is still linked onto the directory buffer
7545 	 * dependency chain, then some of the entries on the
7546 	 * pd_pendinghd list may not be committed to disk yet. In
7547 	 * this case, we will simply clear the NEWBLOCK flag and
7548 	 * let the pd_pendinghd list be processed when the pagedep
7549 	 * is next written. If the pagedep is no longer on the buffer
7550 	 * dependency chain, then all the entries on the pd_pending
7551 	 * list are committed to disk and we can free them here.
7552 	 */
7553 	pagedep = newdirblk->db_pagedep;
7554 	pagedep->pd_state &= ~NEWBLOCK;
7555 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7556 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7557 			free_diradd(dap, NULL);
7558 		/*
7559 		 * If no dependencies remain, the pagedep will be freed.
7560 		 */
7561 		free_pagedep(pagedep);
7562 	}
7563 	/* Should only ever be one item in the list. */
7564 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7565 		WORKLIST_REMOVE(wk);
7566 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7567 	}
7568 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7569 }
7570 
7571 /*
7572  * Prepare an inode to be freed. The actual free operation is not
7573  * done until the zero'ed inode has been written to disk.
7574  */
7575 void
7576 softdep_freefile(pvp, ino, mode)
7577 	struct vnode *pvp;
7578 	ino_t ino;
7579 	int mode;
7580 {
7581 	struct inode *ip = VTOI(pvp);
7582 	struct inodedep *inodedep;
7583 	struct freefile *freefile;
7584 	struct freeblks *freeblks;
7585 	struct ufsmount *ump;
7586 
7587 	ump = ITOUMP(ip);
7588 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7589 	    ("softdep_freefile called on non-softdep filesystem"));
7590 	/*
7591 	 * This sets up the inode de-allocation dependency.
7592 	 */
7593 	freefile = malloc(sizeof(struct freefile),
7594 		M_FREEFILE, M_SOFTDEP_FLAGS);
7595 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7596 	freefile->fx_mode = mode;
7597 	freefile->fx_oldinum = ino;
7598 	freefile->fx_devvp = ump->um_devvp;
7599 	LIST_INIT(&freefile->fx_jwork);
7600 	UFS_LOCK(ump);
7601 	ump->um_fs->fs_pendinginodes += 1;
7602 	UFS_UNLOCK(ump);
7603 
7604 	/*
7605 	 * If the inodedep does not exist, then the zero'ed inode has
7606 	 * been written to disk. If the allocated inode has never been
7607 	 * written to disk, then the on-disk inode is zero'ed. In either
7608 	 * case we can free the file immediately.  If the journal was
7609 	 * canceled before being written the inode will never make it to
7610 	 * disk and we must send the canceled journal entrys to
7611 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7612 	 * Any blocks waiting on the inode to write can be safely freed
7613 	 * here as it will never been written.
7614 	 */
7615 	ACQUIRE_LOCK(ump);
7616 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7617 	if (inodedep) {
7618 		/*
7619 		 * Clear out freeblks that no longer need to reference
7620 		 * this inode.
7621 		 */
7622 		while ((freeblks =
7623 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7624 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7625 			    fb_next);
7626 			freeblks->fb_state &= ~ONDEPLIST;
7627 		}
7628 		/*
7629 		 * Remove this inode from the unlinked list.
7630 		 */
7631 		if (inodedep->id_state & UNLINKED) {
7632 			/*
7633 			 * Save the journal work to be freed with the bitmap
7634 			 * before we clear UNLINKED.  Otherwise it can be lost
7635 			 * if the inode block is written.
7636 			 */
7637 			handle_bufwait(inodedep, &freefile->fx_jwork);
7638 			clear_unlinked_inodedep(inodedep);
7639 			/*
7640 			 * Re-acquire inodedep as we've dropped the
7641 			 * per-filesystem lock in clear_unlinked_inodedep().
7642 			 */
7643 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7644 		}
7645 	}
7646 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7647 		FREE_LOCK(ump);
7648 		handle_workitem_freefile(freefile);
7649 		return;
7650 	}
7651 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7652 		inodedep->id_state |= GOINGAWAY;
7653 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7654 	FREE_LOCK(ump);
7655 	if (ip->i_number == ino)
7656 		ip->i_flag |= IN_MODIFIED;
7657 }
7658 
7659 /*
7660  * Check to see if an inode has never been written to disk. If
7661  * so free the inodedep and return success, otherwise return failure.
7662  *
7663  * If we still have a bitmap dependency, then the inode has never
7664  * been written to disk. Drop the dependency as it is no longer
7665  * necessary since the inode is being deallocated. We set the
7666  * ALLCOMPLETE flags since the bitmap now properly shows that the
7667  * inode is not allocated. Even if the inode is actively being
7668  * written, it has been rolled back to its zero'ed state, so we
7669  * are ensured that a zero inode is what is on the disk. For short
7670  * lived files, this change will usually result in removing all the
7671  * dependencies from the inode so that it can be freed immediately.
7672  */
7673 static int
7674 check_inode_unwritten(inodedep)
7675 	struct inodedep *inodedep;
7676 {
7677 
7678 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7679 
7680 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7681 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7682 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7683 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7684 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7685 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7686 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7687 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7688 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7689 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7690 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7691 	    inodedep->id_mkdiradd != NULL ||
7692 	    inodedep->id_nlinkdelta != 0)
7693 		return (0);
7694 	/*
7695 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7696 	 * trying to allocate memory without holding "Softdep Lock".
7697 	 */
7698 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7699 	    inodedep->id_savedino1 == NULL)
7700 		return (0);
7701 
7702 	if (inodedep->id_state & ONDEPLIST)
7703 		LIST_REMOVE(inodedep, id_deps);
7704 	inodedep->id_state &= ~ONDEPLIST;
7705 	inodedep->id_state |= ALLCOMPLETE;
7706 	inodedep->id_bmsafemap = NULL;
7707 	if (inodedep->id_state & ONWORKLIST)
7708 		WORKLIST_REMOVE(&inodedep->id_list);
7709 	if (inodedep->id_savedino1 != NULL) {
7710 		free(inodedep->id_savedino1, M_SAVEDINO);
7711 		inodedep->id_savedino1 = NULL;
7712 	}
7713 	if (free_inodedep(inodedep) == 0)
7714 		panic("check_inode_unwritten: busy inode");
7715 	return (1);
7716 }
7717 
7718 static int
7719 check_inodedep_free(inodedep)
7720 	struct inodedep *inodedep;
7721 {
7722 
7723 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7724 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7725 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7726 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7727 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7728 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7729 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7730 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7731 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7732 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7733 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7734 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7735 	    inodedep->id_mkdiradd != NULL ||
7736 	    inodedep->id_nlinkdelta != 0 ||
7737 	    inodedep->id_savedino1 != NULL)
7738 		return (0);
7739 	return (1);
7740 }
7741 
7742 /*
7743  * Try to free an inodedep structure. Return 1 if it could be freed.
7744  */
7745 static int
7746 free_inodedep(inodedep)
7747 	struct inodedep *inodedep;
7748 {
7749 
7750 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7751 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7752 	    !check_inodedep_free(inodedep))
7753 		return (0);
7754 	if (inodedep->id_state & ONDEPLIST)
7755 		LIST_REMOVE(inodedep, id_deps);
7756 	LIST_REMOVE(inodedep, id_hash);
7757 	WORKITEM_FREE(inodedep, D_INODEDEP);
7758 	return (1);
7759 }
7760 
7761 /*
7762  * Free the block referenced by a freework structure.  The parent freeblks
7763  * structure is released and completed when the final cg bitmap reaches
7764  * the disk.  This routine may be freeing a jnewblk which never made it to
7765  * disk in which case we do not have to wait as the operation is undone
7766  * in memory immediately.
7767  */
7768 static void
7769 freework_freeblock(freework, key)
7770 	struct freework *freework;
7771 	u_long key;
7772 {
7773 	struct freeblks *freeblks;
7774 	struct jnewblk *jnewblk;
7775 	struct ufsmount *ump;
7776 	struct workhead wkhd;
7777 	struct fs *fs;
7778 	int bsize;
7779 	int needj;
7780 
7781 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7782 	LOCK_OWNED(ump);
7783 	/*
7784 	 * Handle partial truncate separately.
7785 	 */
7786 	if (freework->fw_indir) {
7787 		complete_trunc_indir(freework);
7788 		return;
7789 	}
7790 	freeblks = freework->fw_freeblks;
7791 	fs = ump->um_fs;
7792 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7793 	bsize = lfragtosize(fs, freework->fw_frags);
7794 	LIST_INIT(&wkhd);
7795 	/*
7796 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7797 	 * on the indirblk hashtable and prevents premature freeing.
7798 	 */
7799 	freework->fw_state |= DEPCOMPLETE;
7800 	/*
7801 	 * SUJ needs to wait for the segment referencing freed indirect
7802 	 * blocks to expire so that we know the checker will not confuse
7803 	 * a re-allocated indirect block with its old contents.
7804 	 */
7805 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7806 		indirblk_insert(freework);
7807 	/*
7808 	 * If we are canceling an existing jnewblk pass it to the free
7809 	 * routine, otherwise pass the freeblk which will ultimately
7810 	 * release the freeblks.  If we're not journaling, we can just
7811 	 * free the freeblks immediately.
7812 	 */
7813 	jnewblk = freework->fw_jnewblk;
7814 	if (jnewblk != NULL) {
7815 		cancel_jnewblk(jnewblk, &wkhd);
7816 		needj = 0;
7817 	} else if (needj) {
7818 		freework->fw_state |= DELAYEDFREE;
7819 		freeblks->fb_cgwait++;
7820 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7821 	}
7822 	FREE_LOCK(ump);
7823 	freeblks_free(ump, freeblks, btodb(bsize));
7824 	CTR4(KTR_SUJ,
7825 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
7826 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7827 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7828 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
7829 	ACQUIRE_LOCK(ump);
7830 	/*
7831 	 * The jnewblk will be discarded and the bits in the map never
7832 	 * made it to disk.  We can immediately free the freeblk.
7833 	 */
7834 	if (needj == 0)
7835 		handle_written_freework(freework);
7836 }
7837 
7838 /*
7839  * We enqueue freework items that need processing back on the freeblks and
7840  * add the freeblks to the worklist.  This makes it easier to find all work
7841  * required to flush a truncation in process_truncates().
7842  */
7843 static void
7844 freework_enqueue(freework)
7845 	struct freework *freework;
7846 {
7847 	struct freeblks *freeblks;
7848 
7849 	freeblks = freework->fw_freeblks;
7850 	if ((freework->fw_state & INPROGRESS) == 0)
7851 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7852 	if ((freeblks->fb_state &
7853 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7854 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7855 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7856 }
7857 
7858 /*
7859  * Start, continue, or finish the process of freeing an indirect block tree.
7860  * The free operation may be paused at any point with fw_off containing the
7861  * offset to restart from.  This enables us to implement some flow control
7862  * for large truncates which may fan out and generate a huge number of
7863  * dependencies.
7864  */
7865 static void
7866 handle_workitem_indirblk(freework)
7867 	struct freework *freework;
7868 {
7869 	struct freeblks *freeblks;
7870 	struct ufsmount *ump;
7871 	struct fs *fs;
7872 
7873 	freeblks = freework->fw_freeblks;
7874 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7875 	fs = ump->um_fs;
7876 	if (freework->fw_state & DEPCOMPLETE) {
7877 		handle_written_freework(freework);
7878 		return;
7879 	}
7880 	if (freework->fw_off == NINDIR(fs)) {
7881 		freework_freeblock(freework, SINGLETON_KEY);
7882 		return;
7883 	}
7884 	freework->fw_state |= INPROGRESS;
7885 	FREE_LOCK(ump);
7886 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7887 	    freework->fw_lbn);
7888 	ACQUIRE_LOCK(ump);
7889 }
7890 
7891 /*
7892  * Called when a freework structure attached to a cg buf is written.  The
7893  * ref on either the parent or the freeblks structure is released and
7894  * the freeblks is added back to the worklist if there is more work to do.
7895  */
7896 static void
7897 handle_written_freework(freework)
7898 	struct freework *freework;
7899 {
7900 	struct freeblks *freeblks;
7901 	struct freework *parent;
7902 
7903 	freeblks = freework->fw_freeblks;
7904 	parent = freework->fw_parent;
7905 	if (freework->fw_state & DELAYEDFREE)
7906 		freeblks->fb_cgwait--;
7907 	freework->fw_state |= COMPLETE;
7908 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7909 		WORKITEM_FREE(freework, D_FREEWORK);
7910 	if (parent) {
7911 		if (--parent->fw_ref == 0)
7912 			freework_enqueue(parent);
7913 		return;
7914 	}
7915 	if (--freeblks->fb_ref != 0)
7916 		return;
7917 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7918 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7919 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7920 }
7921 
7922 /*
7923  * This workitem routine performs the block de-allocation.
7924  * The workitem is added to the pending list after the updated
7925  * inode block has been written to disk.  As mentioned above,
7926  * checks regarding the number of blocks de-allocated (compared
7927  * to the number of blocks allocated for the file) are also
7928  * performed in this function.
7929  */
7930 static int
7931 handle_workitem_freeblocks(freeblks, flags)
7932 	struct freeblks *freeblks;
7933 	int flags;
7934 {
7935 	struct freework *freework;
7936 	struct newblk *newblk;
7937 	struct allocindir *aip;
7938 	struct ufsmount *ump;
7939 	struct worklist *wk;
7940 	u_long key;
7941 
7942 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7943 	    ("handle_workitem_freeblocks: Journal entries not written."));
7944 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7945 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
7946 	ACQUIRE_LOCK(ump);
7947 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7948 		WORKLIST_REMOVE(wk);
7949 		switch (wk->wk_type) {
7950 		case D_DIRREM:
7951 			wk->wk_state |= COMPLETE;
7952 			add_to_worklist(wk, 0);
7953 			continue;
7954 
7955 		case D_ALLOCDIRECT:
7956 			free_newblk(WK_NEWBLK(wk));
7957 			continue;
7958 
7959 		case D_ALLOCINDIR:
7960 			aip = WK_ALLOCINDIR(wk);
7961 			freework = NULL;
7962 			if (aip->ai_state & DELAYEDFREE) {
7963 				FREE_LOCK(ump);
7964 				freework = newfreework(ump, freeblks, NULL,
7965 				    aip->ai_lbn, aip->ai_newblkno,
7966 				    ump->um_fs->fs_frag, 0, 0);
7967 				ACQUIRE_LOCK(ump);
7968 			}
7969 			newblk = WK_NEWBLK(wk);
7970 			if (newblk->nb_jnewblk) {
7971 				freework->fw_jnewblk = newblk->nb_jnewblk;
7972 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7973 				newblk->nb_jnewblk = NULL;
7974 			}
7975 			free_newblk(newblk);
7976 			continue;
7977 
7978 		case D_FREEWORK:
7979 			freework = WK_FREEWORK(wk);
7980 			if (freework->fw_lbn <= -UFS_NDADDR)
7981 				handle_workitem_indirblk(freework);
7982 			else
7983 				freework_freeblock(freework, key);
7984 			continue;
7985 		default:
7986 			panic("handle_workitem_freeblocks: Unknown type %s",
7987 			    TYPENAME(wk->wk_type));
7988 		}
7989 	}
7990 	if (freeblks->fb_ref != 0) {
7991 		freeblks->fb_state &= ~INPROGRESS;
7992 		wake_worklist(&freeblks->fb_list);
7993 		freeblks = NULL;
7994 	}
7995 	FREE_LOCK(ump);
7996 	ffs_blkrelease_finish(ump, key);
7997 	if (freeblks)
7998 		return handle_complete_freeblocks(freeblks, flags);
7999 	return (0);
8000 }
8001 
8002 /*
8003  * Handle completion of block free via truncate.  This allows fs_pending
8004  * to track the actual free block count more closely than if we only updated
8005  * it at the end.  We must be careful to handle cases where the block count
8006  * on free was incorrect.
8007  */
8008 static void
8009 freeblks_free(ump, freeblks, blocks)
8010 	struct ufsmount *ump;
8011 	struct freeblks *freeblks;
8012 	int blocks;
8013 {
8014 	struct fs *fs;
8015 	ufs2_daddr_t remain;
8016 
8017 	UFS_LOCK(ump);
8018 	remain = -freeblks->fb_chkcnt;
8019 	freeblks->fb_chkcnt += blocks;
8020 	if (remain > 0) {
8021 		if (remain < blocks)
8022 			blocks = remain;
8023 		fs = ump->um_fs;
8024 		fs->fs_pendingblocks -= blocks;
8025 	}
8026 	UFS_UNLOCK(ump);
8027 }
8028 
8029 /*
8030  * Once all of the freework workitems are complete we can retire the
8031  * freeblocks dependency and any journal work awaiting completion.  This
8032  * can not be called until all other dependencies are stable on disk.
8033  */
8034 static int
8035 handle_complete_freeblocks(freeblks, flags)
8036 	struct freeblks *freeblks;
8037 	int flags;
8038 {
8039 	struct inodedep *inodedep;
8040 	struct inode *ip;
8041 	struct vnode *vp;
8042 	struct fs *fs;
8043 	struct ufsmount *ump;
8044 	ufs2_daddr_t spare;
8045 
8046 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8047 	fs = ump->um_fs;
8048 	flags = LK_EXCLUSIVE | flags;
8049 	spare = freeblks->fb_chkcnt;
8050 
8051 	/*
8052 	 * If we did not release the expected number of blocks we may have
8053 	 * to adjust the inode block count here.  Only do so if it wasn't
8054 	 * a truncation to zero and the modrev still matches.
8055 	 */
8056 	if (spare && freeblks->fb_len != 0) {
8057 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8058 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8059 			return (EBUSY);
8060 		ip = VTOI(vp);
8061 		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8062 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8063 			ip->i_flag |= IN_CHANGE;
8064 			/*
8065 			 * We must wait so this happens before the
8066 			 * journal is reclaimed.
8067 			 */
8068 			ffs_update(vp, 1);
8069 		}
8070 		vput(vp);
8071 	}
8072 	if (spare < 0) {
8073 		UFS_LOCK(ump);
8074 		fs->fs_pendingblocks += spare;
8075 		UFS_UNLOCK(ump);
8076 	}
8077 #ifdef QUOTA
8078 	/* Handle spare. */
8079 	if (spare)
8080 		quotaadj(freeblks->fb_quota, ump, -spare);
8081 	quotarele(freeblks->fb_quota);
8082 #endif
8083 	ACQUIRE_LOCK(ump);
8084 	if (freeblks->fb_state & ONDEPLIST) {
8085 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8086 		    0, &inodedep);
8087 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8088 		freeblks->fb_state &= ~ONDEPLIST;
8089 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8090 			free_inodedep(inodedep);
8091 	}
8092 	/*
8093 	 * All of the freeblock deps must be complete prior to this call
8094 	 * so it's now safe to complete earlier outstanding journal entries.
8095 	 */
8096 	handle_jwork(&freeblks->fb_jwork);
8097 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8098 	FREE_LOCK(ump);
8099 	return (0);
8100 }
8101 
8102 /*
8103  * Release blocks associated with the freeblks and stored in the indirect
8104  * block dbn. If level is greater than SINGLE, the block is an indirect block
8105  * and recursive calls to indirtrunc must be used to cleanse other indirect
8106  * blocks.
8107  *
8108  * This handles partial and complete truncation of blocks.  Partial is noted
8109  * with goingaway == 0.  In this case the freework is completed after the
8110  * zero'd indirects are written to disk.  For full truncation the freework
8111  * is completed after the block is freed.
8112  */
8113 static void
8114 indir_trunc(freework, dbn, lbn)
8115 	struct freework *freework;
8116 	ufs2_daddr_t dbn;
8117 	ufs_lbn_t lbn;
8118 {
8119 	struct freework *nfreework;
8120 	struct workhead wkhd;
8121 	struct freeblks *freeblks;
8122 	struct buf *bp;
8123 	struct fs *fs;
8124 	struct indirdep *indirdep;
8125 	struct mount *mp;
8126 	struct ufsmount *ump;
8127 	ufs1_daddr_t *bap1;
8128 	ufs2_daddr_t nb, nnb, *bap2;
8129 	ufs_lbn_t lbnadd, nlbn;
8130 	u_long key;
8131 	int nblocks, ufs1fmt, freedblocks;
8132 	int goingaway, freedeps, needj, level, cnt, i;
8133 
8134 	freeblks = freework->fw_freeblks;
8135 	mp = freeblks->fb_list.wk_mp;
8136 	ump = VFSTOUFS(mp);
8137 	fs = ump->um_fs;
8138 	/*
8139 	 * Get buffer of block pointers to be freed.  There are three cases:
8140 	 *
8141 	 * 1) Partial truncate caches the indirdep pointer in the freework
8142 	 *    which provides us a back copy to the save bp which holds the
8143 	 *    pointers we want to clear.  When this completes the zero
8144 	 *    pointers are written to the real copy.
8145 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8146 	 *    eliminated the real copy and placed the indirdep on the saved
8147 	 *    copy.  The indirdep and buf are discarded when this completes.
8148 	 * 3) The indirect was not in memory, we read a copy off of the disk
8149 	 *    using the devvp and drop and invalidate the buffer when we're
8150 	 *    done.
8151 	 */
8152 	goingaway = 1;
8153 	indirdep = NULL;
8154 	if (freework->fw_indir != NULL) {
8155 		goingaway = 0;
8156 		indirdep = freework->fw_indir;
8157 		bp = indirdep->ir_savebp;
8158 		if (bp == NULL || bp->b_blkno != dbn)
8159 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8160 			    bp, (intmax_t)dbn);
8161 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8162 		/*
8163 		 * The lock prevents the buf dep list from changing and
8164 	 	 * indirects on devvp should only ever have one dependency.
8165 		 */
8166 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8167 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8168 			panic("indir_trunc: Bad indirdep %p from buf %p",
8169 			    indirdep, bp);
8170 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8171 	    NOCRED, &bp) != 0) {
8172 		brelse(bp);
8173 		return;
8174 	}
8175 	ACQUIRE_LOCK(ump);
8176 	/* Protects against a race with complete_trunc_indir(). */
8177 	freework->fw_state &= ~INPROGRESS;
8178 	/*
8179 	 * If we have an indirdep we need to enforce the truncation order
8180 	 * and discard it when it is complete.
8181 	 */
8182 	if (indirdep) {
8183 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8184 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8185 			/*
8186 			 * Add the complete truncate to the list on the
8187 			 * indirdep to enforce in-order processing.
8188 			 */
8189 			if (freework->fw_indir == NULL)
8190 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8191 				    freework, fw_next);
8192 			FREE_LOCK(ump);
8193 			return;
8194 		}
8195 		/*
8196 		 * If we're goingaway, free the indirdep.  Otherwise it will
8197 		 * linger until the write completes.
8198 		 */
8199 		if (goingaway)
8200 			free_indirdep(indirdep);
8201 	}
8202 	FREE_LOCK(ump);
8203 	/* Initialize pointers depending on block size. */
8204 	if (ump->um_fstype == UFS1) {
8205 		bap1 = (ufs1_daddr_t *)bp->b_data;
8206 		nb = bap1[freework->fw_off];
8207 		ufs1fmt = 1;
8208 		bap2 = NULL;
8209 	} else {
8210 		bap2 = (ufs2_daddr_t *)bp->b_data;
8211 		nb = bap2[freework->fw_off];
8212 		ufs1fmt = 0;
8213 		bap1 = NULL;
8214 	}
8215 	level = lbn_level(lbn);
8216 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8217 	lbnadd = lbn_offset(fs, level);
8218 	nblocks = btodb(fs->fs_bsize);
8219 	nfreework = freework;
8220 	freedeps = 0;
8221 	cnt = 0;
8222 	/*
8223 	 * Reclaim blocks.  Traverses into nested indirect levels and
8224 	 * arranges for the current level to be freed when subordinates
8225 	 * are free when journaling.
8226 	 */
8227 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8228 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8229 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8230 		    fs->fs_bsize) != 0)
8231 			nb = 0;
8232 		if (i != NINDIR(fs) - 1) {
8233 			if (ufs1fmt)
8234 				nnb = bap1[i+1];
8235 			else
8236 				nnb = bap2[i+1];
8237 		} else
8238 			nnb = 0;
8239 		if (nb == 0)
8240 			continue;
8241 		cnt++;
8242 		if (level != 0) {
8243 			nlbn = (lbn + 1) - (i * lbnadd);
8244 			if (needj != 0) {
8245 				nfreework = newfreework(ump, freeblks, freework,
8246 				    nlbn, nb, fs->fs_frag, 0, 0);
8247 				freedeps++;
8248 			}
8249 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8250 		} else {
8251 			struct freedep *freedep;
8252 
8253 			/*
8254 			 * Attempt to aggregate freedep dependencies for
8255 			 * all blocks being released to the same CG.
8256 			 */
8257 			LIST_INIT(&wkhd);
8258 			if (needj != 0 &&
8259 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8260 				freedep = newfreedep(freework);
8261 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8262 				    &freedep->fd_list);
8263 				freedeps++;
8264 			}
8265 			CTR3(KTR_SUJ,
8266 			    "indir_trunc: ino %jd blkno %jd size %d",
8267 			    freeblks->fb_inum, nb, fs->fs_bsize);
8268 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8269 			    fs->fs_bsize, freeblks->fb_inum,
8270 			    freeblks->fb_vtype, &wkhd, key);
8271 		}
8272 	}
8273 	ffs_blkrelease_finish(ump, key);
8274 	if (goingaway) {
8275 		bp->b_flags |= B_INVAL | B_NOCACHE;
8276 		brelse(bp);
8277 	}
8278 	freedblocks = 0;
8279 	if (level == 0)
8280 		freedblocks = (nblocks * cnt);
8281 	if (needj == 0)
8282 		freedblocks += nblocks;
8283 	freeblks_free(ump, freeblks, freedblocks);
8284 	/*
8285 	 * If we are journaling set up the ref counts and offset so this
8286 	 * indirect can be completed when its children are free.
8287 	 */
8288 	if (needj) {
8289 		ACQUIRE_LOCK(ump);
8290 		freework->fw_off = i;
8291 		freework->fw_ref += freedeps;
8292 		freework->fw_ref -= NINDIR(fs) + 1;
8293 		if (level == 0)
8294 			freeblks->fb_cgwait += freedeps;
8295 		if (freework->fw_ref == 0)
8296 			freework_freeblock(freework, SINGLETON_KEY);
8297 		FREE_LOCK(ump);
8298 		return;
8299 	}
8300 	/*
8301 	 * If we're not journaling we can free the indirect now.
8302 	 */
8303 	dbn = dbtofsb(fs, dbn);
8304 	CTR3(KTR_SUJ,
8305 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8306 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8307 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8308 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8309 	/* Non SUJ softdep does single-threaded truncations. */
8310 	if (freework->fw_blkno == dbn) {
8311 		freework->fw_state |= ALLCOMPLETE;
8312 		ACQUIRE_LOCK(ump);
8313 		handle_written_freework(freework);
8314 		FREE_LOCK(ump);
8315 	}
8316 	return;
8317 }
8318 
8319 /*
8320  * Cancel an allocindir when it is removed via truncation.  When bp is not
8321  * NULL the indirect never appeared on disk and is scheduled to be freed
8322  * independently of the indir so we can more easily track journal work.
8323  */
8324 static void
8325 cancel_allocindir(aip, bp, freeblks, trunc)
8326 	struct allocindir *aip;
8327 	struct buf *bp;
8328 	struct freeblks *freeblks;
8329 	int trunc;
8330 {
8331 	struct indirdep *indirdep;
8332 	struct freefrag *freefrag;
8333 	struct newblk *newblk;
8334 
8335 	newblk = (struct newblk *)aip;
8336 	LIST_REMOVE(aip, ai_next);
8337 	/*
8338 	 * We must eliminate the pointer in bp if it must be freed on its
8339 	 * own due to partial truncate or pending journal work.
8340 	 */
8341 	if (bp && (trunc || newblk->nb_jnewblk)) {
8342 		/*
8343 		 * Clear the pointer and mark the aip to be freed
8344 		 * directly if it never existed on disk.
8345 		 */
8346 		aip->ai_state |= DELAYEDFREE;
8347 		indirdep = aip->ai_indirdep;
8348 		if (indirdep->ir_state & UFS1FMT)
8349 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8350 		else
8351 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8352 	}
8353 	/*
8354 	 * When truncating the previous pointer will be freed via
8355 	 * savedbp.  Eliminate the freefrag which would dup free.
8356 	 */
8357 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8358 		newblk->nb_freefrag = NULL;
8359 		if (freefrag->ff_jdep)
8360 			cancel_jfreefrag(
8361 			    WK_JFREEFRAG(freefrag->ff_jdep));
8362 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8363 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8364 	}
8365 	/*
8366 	 * If the journal hasn't been written the jnewblk must be passed
8367 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8368 	 * this by leaving the journal dependency on the newblk to be freed
8369 	 * when a freework is created in handle_workitem_freeblocks().
8370 	 */
8371 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8372 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8373 }
8374 
8375 /*
8376  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8377  * in to a newdirblk so any subsequent additions are tracked properly.  The
8378  * caller is responsible for adding the mkdir1 dependency to the journal
8379  * and updating id_mkdiradd.  This function returns with the per-filesystem
8380  * lock held.
8381  */
8382 static struct mkdir *
8383 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8384 	struct diradd *dap;
8385 	ino_t newinum;
8386 	ino_t dinum;
8387 	struct buf *newdirbp;
8388 	struct mkdir **mkdirp;
8389 {
8390 	struct newblk *newblk;
8391 	struct pagedep *pagedep;
8392 	struct inodedep *inodedep;
8393 	struct newdirblk *newdirblk;
8394 	struct mkdir *mkdir1, *mkdir2;
8395 	struct worklist *wk;
8396 	struct jaddref *jaddref;
8397 	struct ufsmount *ump;
8398 	struct mount *mp;
8399 
8400 	mp = dap->da_list.wk_mp;
8401 	ump = VFSTOUFS(mp);
8402 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8403 	    M_SOFTDEP_FLAGS);
8404 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8405 	LIST_INIT(&newdirblk->db_mkdir);
8406 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8407 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8408 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8409 	mkdir1->md_diradd = dap;
8410 	mkdir1->md_jaddref = NULL;
8411 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8412 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8413 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8414 	mkdir2->md_diradd = dap;
8415 	mkdir2->md_jaddref = NULL;
8416 	if (MOUNTEDSUJ(mp) == 0) {
8417 		mkdir1->md_state |= DEPCOMPLETE;
8418 		mkdir2->md_state |= DEPCOMPLETE;
8419 	}
8420 	/*
8421 	 * Dependency on "." and ".." being written to disk.
8422 	 */
8423 	mkdir1->md_buf = newdirbp;
8424 	ACQUIRE_LOCK(VFSTOUFS(mp));
8425 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8426 	/*
8427 	 * We must link the pagedep, allocdirect, and newdirblk for
8428 	 * the initial file page so the pointer to the new directory
8429 	 * is not written until the directory contents are live and
8430 	 * any subsequent additions are not marked live until the
8431 	 * block is reachable via the inode.
8432 	 */
8433 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8434 		panic("setup_newdir: lost pagedep");
8435 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8436 		if (wk->wk_type == D_ALLOCDIRECT)
8437 			break;
8438 	if (wk == NULL)
8439 		panic("setup_newdir: lost allocdirect");
8440 	if (pagedep->pd_state & NEWBLOCK)
8441 		panic("setup_newdir: NEWBLOCK already set");
8442 	newblk = WK_NEWBLK(wk);
8443 	pagedep->pd_state |= NEWBLOCK;
8444 	pagedep->pd_newdirblk = newdirblk;
8445 	newdirblk->db_pagedep = pagedep;
8446 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8447 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8448 	/*
8449 	 * Look up the inodedep for the parent directory so that we
8450 	 * can link mkdir2 into the pending dotdot jaddref or
8451 	 * the inode write if there is none.  If the inode is
8452 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8453 	 * been satisfied and mkdir2 can be freed.
8454 	 */
8455 	inodedep_lookup(mp, dinum, 0, &inodedep);
8456 	if (MOUNTEDSUJ(mp)) {
8457 		if (inodedep == NULL)
8458 			panic("setup_newdir: Lost parent.");
8459 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8460 		    inoreflst);
8461 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8462 		    (jaddref->ja_state & MKDIR_PARENT),
8463 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8464 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8465 		mkdir2->md_jaddref = jaddref;
8466 		jaddref->ja_mkdir = mkdir2;
8467 	} else if (inodedep == NULL ||
8468 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8469 		dap->da_state &= ~MKDIR_PARENT;
8470 		WORKITEM_FREE(mkdir2, D_MKDIR);
8471 		mkdir2 = NULL;
8472 	} else {
8473 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8474 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8475 	}
8476 	*mkdirp = mkdir2;
8477 
8478 	return (mkdir1);
8479 }
8480 
8481 /*
8482  * Directory entry addition dependencies.
8483  *
8484  * When adding a new directory entry, the inode (with its incremented link
8485  * count) must be written to disk before the directory entry's pointer to it.
8486  * Also, if the inode is newly allocated, the corresponding freemap must be
8487  * updated (on disk) before the directory entry's pointer. These requirements
8488  * are met via undo/redo on the directory entry's pointer, which consists
8489  * simply of the inode number.
8490  *
8491  * As directory entries are added and deleted, the free space within a
8492  * directory block can become fragmented.  The ufs filesystem will compact
8493  * a fragmented directory block to make space for a new entry. When this
8494  * occurs, the offsets of previously added entries change. Any "diradd"
8495  * dependency structures corresponding to these entries must be updated with
8496  * the new offsets.
8497  */
8498 
8499 /*
8500  * This routine is called after the in-memory inode's link
8501  * count has been incremented, but before the directory entry's
8502  * pointer to the inode has been set.
8503  */
8504 int
8505 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8506 	struct buf *bp;		/* buffer containing directory block */
8507 	struct inode *dp;	/* inode for directory */
8508 	off_t diroffset;	/* offset of new entry in directory */
8509 	ino_t newinum;		/* inode referenced by new directory entry */
8510 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8511 	int isnewblk;		/* entry is in a newly allocated block */
8512 {
8513 	int offset;		/* offset of new entry within directory block */
8514 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8515 	struct fs *fs;
8516 	struct diradd *dap;
8517 	struct newblk *newblk;
8518 	struct pagedep *pagedep;
8519 	struct inodedep *inodedep;
8520 	struct newdirblk *newdirblk;
8521 	struct mkdir *mkdir1, *mkdir2;
8522 	struct jaddref *jaddref;
8523 	struct ufsmount *ump;
8524 	struct mount *mp;
8525 	int isindir;
8526 
8527 	mp = ITOVFS(dp);
8528 	ump = VFSTOUFS(mp);
8529 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8530 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8531 	/*
8532 	 * Whiteouts have no dependencies.
8533 	 */
8534 	if (newinum == UFS_WINO) {
8535 		if (newdirbp != NULL)
8536 			bdwrite(newdirbp);
8537 		return (0);
8538 	}
8539 	jaddref = NULL;
8540 	mkdir1 = mkdir2 = NULL;
8541 	fs = ump->um_fs;
8542 	lbn = lblkno(fs, diroffset);
8543 	offset = blkoff(fs, diroffset);
8544 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8545 		M_SOFTDEP_FLAGS|M_ZERO);
8546 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8547 	dap->da_offset = offset;
8548 	dap->da_newinum = newinum;
8549 	dap->da_state = ATTACHED;
8550 	LIST_INIT(&dap->da_jwork);
8551 	isindir = bp->b_lblkno >= UFS_NDADDR;
8552 	newdirblk = NULL;
8553 	if (isnewblk &&
8554 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8555 		newdirblk = malloc(sizeof(struct newdirblk),
8556 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8557 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8558 		LIST_INIT(&newdirblk->db_mkdir);
8559 	}
8560 	/*
8561 	 * If we're creating a new directory setup the dependencies and set
8562 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8563 	 * we can move on.
8564 	 */
8565 	if (newdirbp == NULL) {
8566 		dap->da_state |= DEPCOMPLETE;
8567 		ACQUIRE_LOCK(ump);
8568 	} else {
8569 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8570 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8571 		    &mkdir2);
8572 	}
8573 	/*
8574 	 * Link into parent directory pagedep to await its being written.
8575 	 */
8576 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8577 #ifdef INVARIANTS
8578 	if (diradd_lookup(pagedep, offset) != NULL)
8579 		panic("softdep_setup_directory_add: %p already at off %d\n",
8580 		    diradd_lookup(pagedep, offset), offset);
8581 #endif
8582 	dap->da_pagedep = pagedep;
8583 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8584 	    da_pdlist);
8585 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8586 	/*
8587 	 * If we're journaling, link the diradd into the jaddref so it
8588 	 * may be completed after the journal entry is written.  Otherwise,
8589 	 * link the diradd into its inodedep.  If the inode is not yet
8590 	 * written place it on the bufwait list, otherwise do the post-inode
8591 	 * write processing to put it on the id_pendinghd list.
8592 	 */
8593 	if (MOUNTEDSUJ(mp)) {
8594 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8595 		    inoreflst);
8596 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8597 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8598 		jaddref->ja_diroff = diroffset;
8599 		jaddref->ja_diradd = dap;
8600 		add_to_journal(&jaddref->ja_list);
8601 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8602 		diradd_inode_written(dap, inodedep);
8603 	else
8604 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8605 	/*
8606 	 * Add the journal entries for . and .. links now that the primary
8607 	 * link is written.
8608 	 */
8609 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8610 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8611 		    inoreflst, if_deps);
8612 		KASSERT(jaddref != NULL &&
8613 		    jaddref->ja_ino == jaddref->ja_parent &&
8614 		    (jaddref->ja_state & MKDIR_BODY),
8615 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8616 		    jaddref));
8617 		mkdir1->md_jaddref = jaddref;
8618 		jaddref->ja_mkdir = mkdir1;
8619 		/*
8620 		 * It is important that the dotdot journal entry
8621 		 * is added prior to the dot entry since dot writes
8622 		 * both the dot and dotdot links.  These both must
8623 		 * be added after the primary link for the journal
8624 		 * to remain consistent.
8625 		 */
8626 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8627 		add_to_journal(&jaddref->ja_list);
8628 	}
8629 	/*
8630 	 * If we are adding a new directory remember this diradd so that if
8631 	 * we rename it we can keep the dot and dotdot dependencies.  If
8632 	 * we are adding a new name for an inode that has a mkdiradd we
8633 	 * must be in rename and we have to move the dot and dotdot
8634 	 * dependencies to this new name.  The old name is being orphaned
8635 	 * soon.
8636 	 */
8637 	if (mkdir1 != NULL) {
8638 		if (inodedep->id_mkdiradd != NULL)
8639 			panic("softdep_setup_directory_add: Existing mkdir");
8640 		inodedep->id_mkdiradd = dap;
8641 	} else if (inodedep->id_mkdiradd)
8642 		merge_diradd(inodedep, dap);
8643 	if (newdirblk != NULL) {
8644 		/*
8645 		 * There is nothing to do if we are already tracking
8646 		 * this block.
8647 		 */
8648 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8649 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8650 			FREE_LOCK(ump);
8651 			return (0);
8652 		}
8653 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8654 		    == 0)
8655 			panic("softdep_setup_directory_add: lost entry");
8656 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8657 		pagedep->pd_state |= NEWBLOCK;
8658 		pagedep->pd_newdirblk = newdirblk;
8659 		newdirblk->db_pagedep = pagedep;
8660 		FREE_LOCK(ump);
8661 		/*
8662 		 * If we extended into an indirect signal direnter to sync.
8663 		 */
8664 		if (isindir)
8665 			return (1);
8666 		return (0);
8667 	}
8668 	FREE_LOCK(ump);
8669 	return (0);
8670 }
8671 
8672 /*
8673  * This procedure is called to change the offset of a directory
8674  * entry when compacting a directory block which must be owned
8675  * exclusively by the caller. Note that the actual entry movement
8676  * must be done in this procedure to ensure that no I/O completions
8677  * occur while the move is in progress.
8678  */
8679 void
8680 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8681 	struct buf *bp;		/* Buffer holding directory block. */
8682 	struct inode *dp;	/* inode for directory */
8683 	caddr_t base;		/* address of dp->i_offset */
8684 	caddr_t oldloc;		/* address of old directory location */
8685 	caddr_t newloc;		/* address of new directory location */
8686 	int entrysize;		/* size of directory entry */
8687 {
8688 	int offset, oldoffset, newoffset;
8689 	struct pagedep *pagedep;
8690 	struct jmvref *jmvref;
8691 	struct diradd *dap;
8692 	struct direct *de;
8693 	struct mount *mp;
8694 	struct ufsmount *ump;
8695 	ufs_lbn_t lbn;
8696 	int flags;
8697 
8698 	mp = ITOVFS(dp);
8699 	ump = VFSTOUFS(mp);
8700 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8701 	    ("softdep_change_directoryentry_offset called on "
8702 	     "non-softdep filesystem"));
8703 	de = (struct direct *)oldloc;
8704 	jmvref = NULL;
8705 	flags = 0;
8706 	/*
8707 	 * Moves are always journaled as it would be too complex to
8708 	 * determine if any affected adds or removes are present in the
8709 	 * journal.
8710 	 */
8711 	if (MOUNTEDSUJ(mp)) {
8712 		flags = DEPALLOC;
8713 		jmvref = newjmvref(dp, de->d_ino,
8714 		    dp->i_offset + (oldloc - base),
8715 		    dp->i_offset + (newloc - base));
8716 	}
8717 	lbn = lblkno(ump->um_fs, dp->i_offset);
8718 	offset = blkoff(ump->um_fs, dp->i_offset);
8719 	oldoffset = offset + (oldloc - base);
8720 	newoffset = offset + (newloc - base);
8721 	ACQUIRE_LOCK(ump);
8722 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8723 		goto done;
8724 	dap = diradd_lookup(pagedep, oldoffset);
8725 	if (dap) {
8726 		dap->da_offset = newoffset;
8727 		newoffset = DIRADDHASH(newoffset);
8728 		oldoffset = DIRADDHASH(oldoffset);
8729 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8730 		    newoffset != oldoffset) {
8731 			LIST_REMOVE(dap, da_pdlist);
8732 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8733 			    dap, da_pdlist);
8734 		}
8735 	}
8736 done:
8737 	if (jmvref) {
8738 		jmvref->jm_pagedep = pagedep;
8739 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8740 		add_to_journal(&jmvref->jm_list);
8741 	}
8742 	bcopy(oldloc, newloc, entrysize);
8743 	FREE_LOCK(ump);
8744 }
8745 
8746 /*
8747  * Move the mkdir dependencies and journal work from one diradd to another
8748  * when renaming a directory.  The new name must depend on the mkdir deps
8749  * completing as the old name did.  Directories can only have one valid link
8750  * at a time so one must be canonical.
8751  */
8752 static void
8753 merge_diradd(inodedep, newdap)
8754 	struct inodedep *inodedep;
8755 	struct diradd *newdap;
8756 {
8757 	struct diradd *olddap;
8758 	struct mkdir *mkdir, *nextmd;
8759 	struct ufsmount *ump;
8760 	short state;
8761 
8762 	olddap = inodedep->id_mkdiradd;
8763 	inodedep->id_mkdiradd = newdap;
8764 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8765 		newdap->da_state &= ~DEPCOMPLETE;
8766 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8767 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8768 		     mkdir = nextmd) {
8769 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8770 			if (mkdir->md_diradd != olddap)
8771 				continue;
8772 			mkdir->md_diradd = newdap;
8773 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8774 			newdap->da_state |= state;
8775 			olddap->da_state &= ~state;
8776 			if ((olddap->da_state &
8777 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8778 				break;
8779 		}
8780 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8781 			panic("merge_diradd: unfound ref");
8782 	}
8783 	/*
8784 	 * Any mkdir related journal items are not safe to be freed until
8785 	 * the new name is stable.
8786 	 */
8787 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8788 	olddap->da_state |= DEPCOMPLETE;
8789 	complete_diradd(olddap);
8790 }
8791 
8792 /*
8793  * Move the diradd to the pending list when all diradd dependencies are
8794  * complete.
8795  */
8796 static void
8797 complete_diradd(dap)
8798 	struct diradd *dap;
8799 {
8800 	struct pagedep *pagedep;
8801 
8802 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8803 		if (dap->da_state & DIRCHG)
8804 			pagedep = dap->da_previous->dm_pagedep;
8805 		else
8806 			pagedep = dap->da_pagedep;
8807 		LIST_REMOVE(dap, da_pdlist);
8808 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8809 	}
8810 }
8811 
8812 /*
8813  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8814  * add entries and conditonally journal the remove.
8815  */
8816 static void
8817 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8818 	struct diradd *dap;
8819 	struct dirrem *dirrem;
8820 	struct jremref *jremref;
8821 	struct jremref *dotremref;
8822 	struct jremref *dotdotremref;
8823 {
8824 	struct inodedep *inodedep;
8825 	struct jaddref *jaddref;
8826 	struct inoref *inoref;
8827 	struct ufsmount *ump;
8828 	struct mkdir *mkdir;
8829 
8830 	/*
8831 	 * If no remove references were allocated we're on a non-journaled
8832 	 * filesystem and can skip the cancel step.
8833 	 */
8834 	if (jremref == NULL) {
8835 		free_diradd(dap, NULL);
8836 		return;
8837 	}
8838 	/*
8839 	 * Cancel the primary name an free it if it does not require
8840 	 * journaling.
8841 	 */
8842 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8843 	    0, &inodedep) != 0) {
8844 		/* Abort the addref that reference this diradd.  */
8845 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8846 			if (inoref->if_list.wk_type != D_JADDREF)
8847 				continue;
8848 			jaddref = (struct jaddref *)inoref;
8849 			if (jaddref->ja_diradd != dap)
8850 				continue;
8851 			if (cancel_jaddref(jaddref, inodedep,
8852 			    &dirrem->dm_jwork) == 0) {
8853 				free_jremref(jremref);
8854 				jremref = NULL;
8855 			}
8856 			break;
8857 		}
8858 	}
8859 	/*
8860 	 * Cancel subordinate names and free them if they do not require
8861 	 * journaling.
8862 	 */
8863 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8864 		ump = VFSTOUFS(dap->da_list.wk_mp);
8865 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8866 			if (mkdir->md_diradd != dap)
8867 				continue;
8868 			if ((jaddref = mkdir->md_jaddref) == NULL)
8869 				continue;
8870 			mkdir->md_jaddref = NULL;
8871 			if (mkdir->md_state & MKDIR_PARENT) {
8872 				if (cancel_jaddref(jaddref, NULL,
8873 				    &dirrem->dm_jwork) == 0) {
8874 					free_jremref(dotdotremref);
8875 					dotdotremref = NULL;
8876 				}
8877 			} else {
8878 				if (cancel_jaddref(jaddref, inodedep,
8879 				    &dirrem->dm_jwork) == 0) {
8880 					free_jremref(dotremref);
8881 					dotremref = NULL;
8882 				}
8883 			}
8884 		}
8885 	}
8886 
8887 	if (jremref)
8888 		journal_jremref(dirrem, jremref, inodedep);
8889 	if (dotremref)
8890 		journal_jremref(dirrem, dotremref, inodedep);
8891 	if (dotdotremref)
8892 		journal_jremref(dirrem, dotdotremref, NULL);
8893 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8894 	free_diradd(dap, &dirrem->dm_jwork);
8895 }
8896 
8897 /*
8898  * Free a diradd dependency structure.
8899  */
8900 static void
8901 free_diradd(dap, wkhd)
8902 	struct diradd *dap;
8903 	struct workhead *wkhd;
8904 {
8905 	struct dirrem *dirrem;
8906 	struct pagedep *pagedep;
8907 	struct inodedep *inodedep;
8908 	struct mkdir *mkdir, *nextmd;
8909 	struct ufsmount *ump;
8910 
8911 	ump = VFSTOUFS(dap->da_list.wk_mp);
8912 	LOCK_OWNED(ump);
8913 	LIST_REMOVE(dap, da_pdlist);
8914 	if (dap->da_state & ONWORKLIST)
8915 		WORKLIST_REMOVE(&dap->da_list);
8916 	if ((dap->da_state & DIRCHG) == 0) {
8917 		pagedep = dap->da_pagedep;
8918 	} else {
8919 		dirrem = dap->da_previous;
8920 		pagedep = dirrem->dm_pagedep;
8921 		dirrem->dm_dirinum = pagedep->pd_ino;
8922 		dirrem->dm_state |= COMPLETE;
8923 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8924 			add_to_worklist(&dirrem->dm_list, 0);
8925 	}
8926 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8927 	    0, &inodedep) != 0)
8928 		if (inodedep->id_mkdiradd == dap)
8929 			inodedep->id_mkdiradd = NULL;
8930 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8931 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8932 		     mkdir = nextmd) {
8933 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8934 			if (mkdir->md_diradd != dap)
8935 				continue;
8936 			dap->da_state &=
8937 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8938 			LIST_REMOVE(mkdir, md_mkdirs);
8939 			if (mkdir->md_state & ONWORKLIST)
8940 				WORKLIST_REMOVE(&mkdir->md_list);
8941 			if (mkdir->md_jaddref != NULL)
8942 				panic("free_diradd: Unexpected jaddref");
8943 			WORKITEM_FREE(mkdir, D_MKDIR);
8944 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8945 				break;
8946 		}
8947 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8948 			panic("free_diradd: unfound ref");
8949 	}
8950 	if (inodedep)
8951 		free_inodedep(inodedep);
8952 	/*
8953 	 * Free any journal segments waiting for the directory write.
8954 	 */
8955 	handle_jwork(&dap->da_jwork);
8956 	WORKITEM_FREE(dap, D_DIRADD);
8957 }
8958 
8959 /*
8960  * Directory entry removal dependencies.
8961  *
8962  * When removing a directory entry, the entry's inode pointer must be
8963  * zero'ed on disk before the corresponding inode's link count is decremented
8964  * (possibly freeing the inode for re-use). This dependency is handled by
8965  * updating the directory entry but delaying the inode count reduction until
8966  * after the directory block has been written to disk. After this point, the
8967  * inode count can be decremented whenever it is convenient.
8968  */
8969 
8970 /*
8971  * This routine should be called immediately after removing
8972  * a directory entry.  The inode's link count should not be
8973  * decremented by the calling procedure -- the soft updates
8974  * code will do this task when it is safe.
8975  */
8976 void
8977 softdep_setup_remove(bp, dp, ip, isrmdir)
8978 	struct buf *bp;		/* buffer containing directory block */
8979 	struct inode *dp;	/* inode for the directory being modified */
8980 	struct inode *ip;	/* inode for directory entry being removed */
8981 	int isrmdir;		/* indicates if doing RMDIR */
8982 {
8983 	struct dirrem *dirrem, *prevdirrem;
8984 	struct inodedep *inodedep;
8985 	struct ufsmount *ump;
8986 	int direct;
8987 
8988 	ump = ITOUMP(ip);
8989 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8990 	    ("softdep_setup_remove called on non-softdep filesystem"));
8991 	/*
8992 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8993 	 * newdirrem() to setup the full directory remove which requires
8994 	 * isrmdir > 1.
8995 	 */
8996 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8997 	/*
8998 	 * Add the dirrem to the inodedep's pending remove list for quick
8999 	 * discovery later.
9000 	 */
9001 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9002 		panic("softdep_setup_remove: Lost inodedep.");
9003 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9004 	dirrem->dm_state |= ONDEPLIST;
9005 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9006 
9007 	/*
9008 	 * If the COMPLETE flag is clear, then there were no active
9009 	 * entries and we want to roll back to a zeroed entry until
9010 	 * the new inode is committed to disk. If the COMPLETE flag is
9011 	 * set then we have deleted an entry that never made it to
9012 	 * disk. If the entry we deleted resulted from a name change,
9013 	 * then the old name still resides on disk. We cannot delete
9014 	 * its inode (returned to us in prevdirrem) until the zeroed
9015 	 * directory entry gets to disk. The new inode has never been
9016 	 * referenced on the disk, so can be deleted immediately.
9017 	 */
9018 	if ((dirrem->dm_state & COMPLETE) == 0) {
9019 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9020 		    dm_next);
9021 		FREE_LOCK(ump);
9022 	} else {
9023 		if (prevdirrem != NULL)
9024 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9025 			    prevdirrem, dm_next);
9026 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9027 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9028 		FREE_LOCK(ump);
9029 		if (direct)
9030 			handle_workitem_remove(dirrem, 0);
9031 	}
9032 }
9033 
9034 /*
9035  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9036  * pd_pendinghd list of a pagedep.
9037  */
9038 static struct diradd *
9039 diradd_lookup(pagedep, offset)
9040 	struct pagedep *pagedep;
9041 	int offset;
9042 {
9043 	struct diradd *dap;
9044 
9045 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9046 		if (dap->da_offset == offset)
9047 			return (dap);
9048 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9049 		if (dap->da_offset == offset)
9050 			return (dap);
9051 	return (NULL);
9052 }
9053 
9054 /*
9055  * Search for a .. diradd dependency in a directory that is being removed.
9056  * If the directory was renamed to a new parent we have a diradd rather
9057  * than a mkdir for the .. entry.  We need to cancel it now before
9058  * it is found in truncate().
9059  */
9060 static struct jremref *
9061 cancel_diradd_dotdot(ip, dirrem, jremref)
9062 	struct inode *ip;
9063 	struct dirrem *dirrem;
9064 	struct jremref *jremref;
9065 {
9066 	struct pagedep *pagedep;
9067 	struct diradd *dap;
9068 	struct worklist *wk;
9069 
9070 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9071 		return (jremref);
9072 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9073 	if (dap == NULL)
9074 		return (jremref);
9075 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9076 	/*
9077 	 * Mark any journal work as belonging to the parent so it is freed
9078 	 * with the .. reference.
9079 	 */
9080 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9081 		wk->wk_state |= MKDIR_PARENT;
9082 	return (NULL);
9083 }
9084 
9085 /*
9086  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9087  * replace it with a dirrem/diradd pair as a result of re-parenting a
9088  * directory.  This ensures that we don't simultaneously have a mkdir and
9089  * a diradd for the same .. entry.
9090  */
9091 static struct jremref *
9092 cancel_mkdir_dotdot(ip, dirrem, jremref)
9093 	struct inode *ip;
9094 	struct dirrem *dirrem;
9095 	struct jremref *jremref;
9096 {
9097 	struct inodedep *inodedep;
9098 	struct jaddref *jaddref;
9099 	struct ufsmount *ump;
9100 	struct mkdir *mkdir;
9101 	struct diradd *dap;
9102 	struct mount *mp;
9103 
9104 	mp = ITOVFS(ip);
9105 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9106 		return (jremref);
9107 	dap = inodedep->id_mkdiradd;
9108 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9109 		return (jremref);
9110 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9111 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9112 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9113 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9114 			break;
9115 	if (mkdir == NULL)
9116 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9117 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9118 		mkdir->md_jaddref = NULL;
9119 		jaddref->ja_state &= ~MKDIR_PARENT;
9120 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9121 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9122 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9123 			journal_jremref(dirrem, jremref, inodedep);
9124 			jremref = NULL;
9125 		}
9126 	}
9127 	if (mkdir->md_state & ONWORKLIST)
9128 		WORKLIST_REMOVE(&mkdir->md_list);
9129 	mkdir->md_state |= ALLCOMPLETE;
9130 	complete_mkdir(mkdir);
9131 	return (jremref);
9132 }
9133 
9134 static void
9135 journal_jremref(dirrem, jremref, inodedep)
9136 	struct dirrem *dirrem;
9137 	struct jremref *jremref;
9138 	struct inodedep *inodedep;
9139 {
9140 
9141 	if (inodedep == NULL)
9142 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9143 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9144 			panic("journal_jremref: Lost inodedep");
9145 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9146 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9147 	add_to_journal(&jremref->jr_list);
9148 }
9149 
9150 static void
9151 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9152 	struct dirrem *dirrem;
9153 	struct jremref *jremref;
9154 	struct jremref *dotremref;
9155 	struct jremref *dotdotremref;
9156 {
9157 	struct inodedep *inodedep;
9158 
9159 
9160 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9161 	    &inodedep) == 0)
9162 		panic("dirrem_journal: Lost inodedep");
9163 	journal_jremref(dirrem, jremref, inodedep);
9164 	if (dotremref)
9165 		journal_jremref(dirrem, dotremref, inodedep);
9166 	if (dotdotremref)
9167 		journal_jremref(dirrem, dotdotremref, NULL);
9168 }
9169 
9170 /*
9171  * Allocate a new dirrem if appropriate and return it along with
9172  * its associated pagedep. Called without a lock, returns with lock.
9173  */
9174 static struct dirrem *
9175 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9176 	struct buf *bp;		/* buffer containing directory block */
9177 	struct inode *dp;	/* inode for the directory being modified */
9178 	struct inode *ip;	/* inode for directory entry being removed */
9179 	int isrmdir;		/* indicates if doing RMDIR */
9180 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9181 {
9182 	int offset;
9183 	ufs_lbn_t lbn;
9184 	struct diradd *dap;
9185 	struct dirrem *dirrem;
9186 	struct pagedep *pagedep;
9187 	struct jremref *jremref;
9188 	struct jremref *dotremref;
9189 	struct jremref *dotdotremref;
9190 	struct vnode *dvp;
9191 	struct ufsmount *ump;
9192 
9193 	/*
9194 	 * Whiteouts have no deletion dependencies.
9195 	 */
9196 	if (ip == NULL)
9197 		panic("newdirrem: whiteout");
9198 	dvp = ITOV(dp);
9199 	ump = ITOUMP(dp);
9200 
9201 	/*
9202 	 * If the system is over its limit and our filesystem is
9203 	 * responsible for more than our share of that usage and
9204 	 * we are not a snapshot, request some inodedep cleanup.
9205 	 * Limiting the number of dirrem structures will also limit
9206 	 * the number of freefile and freeblks structures.
9207 	 */
9208 	ACQUIRE_LOCK(ump);
9209 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9210 		schedule_cleanup(UFSTOVFS(ump));
9211 	else
9212 		FREE_LOCK(ump);
9213 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9214 	    M_ZERO);
9215 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9216 	LIST_INIT(&dirrem->dm_jremrefhd);
9217 	LIST_INIT(&dirrem->dm_jwork);
9218 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9219 	dirrem->dm_oldinum = ip->i_number;
9220 	*prevdirremp = NULL;
9221 	/*
9222 	 * Allocate remove reference structures to track journal write
9223 	 * dependencies.  We will always have one for the link and
9224 	 * when doing directories we will always have one more for dot.
9225 	 * When renaming a directory we skip the dotdot link change so
9226 	 * this is not needed.
9227 	 */
9228 	jremref = dotremref = dotdotremref = NULL;
9229 	if (DOINGSUJ(dvp)) {
9230 		if (isrmdir) {
9231 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9232 			    ip->i_effnlink + 2);
9233 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9234 			    ip->i_effnlink + 1);
9235 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9236 			    dp->i_effnlink + 1);
9237 			dotdotremref->jr_state |= MKDIR_PARENT;
9238 		} else
9239 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9240 			    ip->i_effnlink + 1);
9241 	}
9242 	ACQUIRE_LOCK(ump);
9243 	lbn = lblkno(ump->um_fs, dp->i_offset);
9244 	offset = blkoff(ump->um_fs, dp->i_offset);
9245 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9246 	    &pagedep);
9247 	dirrem->dm_pagedep = pagedep;
9248 	dirrem->dm_offset = offset;
9249 	/*
9250 	 * If we're renaming a .. link to a new directory, cancel any
9251 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9252 	 * the jremref is preserved for any potential diradd in this
9253 	 * location.  This can not coincide with a rmdir.
9254 	 */
9255 	if (dp->i_offset == DOTDOT_OFFSET) {
9256 		if (isrmdir)
9257 			panic("newdirrem: .. directory change during remove?");
9258 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9259 	}
9260 	/*
9261 	 * If we're removing a directory search for the .. dependency now and
9262 	 * cancel it.  Any pending journal work will be added to the dirrem
9263 	 * to be completed when the workitem remove completes.
9264 	 */
9265 	if (isrmdir)
9266 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9267 	/*
9268 	 * Check for a diradd dependency for the same directory entry.
9269 	 * If present, then both dependencies become obsolete and can
9270 	 * be de-allocated.
9271 	 */
9272 	dap = diradd_lookup(pagedep, offset);
9273 	if (dap == NULL) {
9274 		/*
9275 		 * Link the jremref structures into the dirrem so they are
9276 		 * written prior to the pagedep.
9277 		 */
9278 		if (jremref)
9279 			dirrem_journal(dirrem, jremref, dotremref,
9280 			    dotdotremref);
9281 		return (dirrem);
9282 	}
9283 	/*
9284 	 * Must be ATTACHED at this point.
9285 	 */
9286 	if ((dap->da_state & ATTACHED) == 0)
9287 		panic("newdirrem: not ATTACHED");
9288 	if (dap->da_newinum != ip->i_number)
9289 		panic("newdirrem: inum %ju should be %ju",
9290 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9291 	/*
9292 	 * If we are deleting a changed name that never made it to disk,
9293 	 * then return the dirrem describing the previous inode (which
9294 	 * represents the inode currently referenced from this entry on disk).
9295 	 */
9296 	if ((dap->da_state & DIRCHG) != 0) {
9297 		*prevdirremp = dap->da_previous;
9298 		dap->da_state &= ~DIRCHG;
9299 		dap->da_pagedep = pagedep;
9300 	}
9301 	/*
9302 	 * We are deleting an entry that never made it to disk.
9303 	 * Mark it COMPLETE so we can delete its inode immediately.
9304 	 */
9305 	dirrem->dm_state |= COMPLETE;
9306 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9307 #ifdef INVARIANTS
9308 	if (isrmdir == 0) {
9309 		struct worklist *wk;
9310 
9311 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9312 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9313 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9314 	}
9315 #endif
9316 
9317 	return (dirrem);
9318 }
9319 
9320 /*
9321  * Directory entry change dependencies.
9322  *
9323  * Changing an existing directory entry requires that an add operation
9324  * be completed first followed by a deletion. The semantics for the addition
9325  * are identical to the description of adding a new entry above except
9326  * that the rollback is to the old inode number rather than zero. Once
9327  * the addition dependency is completed, the removal is done as described
9328  * in the removal routine above.
9329  */
9330 
9331 /*
9332  * This routine should be called immediately after changing
9333  * a directory entry.  The inode's link count should not be
9334  * decremented by the calling procedure -- the soft updates
9335  * code will perform this task when it is safe.
9336  */
9337 void
9338 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9339 	struct buf *bp;		/* buffer containing directory block */
9340 	struct inode *dp;	/* inode for the directory being modified */
9341 	struct inode *ip;	/* inode for directory entry being removed */
9342 	ino_t newinum;		/* new inode number for changed entry */
9343 	int isrmdir;		/* indicates if doing RMDIR */
9344 {
9345 	int offset;
9346 	struct diradd *dap = NULL;
9347 	struct dirrem *dirrem, *prevdirrem;
9348 	struct pagedep *pagedep;
9349 	struct inodedep *inodedep;
9350 	struct jaddref *jaddref;
9351 	struct mount *mp;
9352 	struct ufsmount *ump;
9353 
9354 	mp = ITOVFS(dp);
9355 	ump = VFSTOUFS(mp);
9356 	offset = blkoff(ump->um_fs, dp->i_offset);
9357 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9358 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9359 
9360 	/*
9361 	 * Whiteouts do not need diradd dependencies.
9362 	 */
9363 	if (newinum != UFS_WINO) {
9364 		dap = malloc(sizeof(struct diradd),
9365 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9366 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9367 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9368 		dap->da_offset = offset;
9369 		dap->da_newinum = newinum;
9370 		LIST_INIT(&dap->da_jwork);
9371 	}
9372 
9373 	/*
9374 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9375 	 */
9376 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9377 	pagedep = dirrem->dm_pagedep;
9378 	/*
9379 	 * The possible values for isrmdir:
9380 	 *	0 - non-directory file rename
9381 	 *	1 - directory rename within same directory
9382 	 *   inum - directory rename to new directory of given inode number
9383 	 * When renaming to a new directory, we are both deleting and
9384 	 * creating a new directory entry, so the link count on the new
9385 	 * directory should not change. Thus we do not need the followup
9386 	 * dirrem which is usually done in handle_workitem_remove. We set
9387 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9388 	 * followup dirrem.
9389 	 */
9390 	if (isrmdir > 1)
9391 		dirrem->dm_state |= DIRCHG;
9392 
9393 	/*
9394 	 * Whiteouts have no additional dependencies,
9395 	 * so just put the dirrem on the correct list.
9396 	 */
9397 	if (newinum == UFS_WINO) {
9398 		if ((dirrem->dm_state & COMPLETE) == 0) {
9399 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9400 			    dm_next);
9401 		} else {
9402 			dirrem->dm_dirinum = pagedep->pd_ino;
9403 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9404 				add_to_worklist(&dirrem->dm_list, 0);
9405 		}
9406 		FREE_LOCK(ump);
9407 		return;
9408 	}
9409 	/*
9410 	 * Add the dirrem to the inodedep's pending remove list for quick
9411 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9412 	 * will not fail.
9413 	 */
9414 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9415 		panic("softdep_setup_directory_change: Lost inodedep.");
9416 	dirrem->dm_state |= ONDEPLIST;
9417 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9418 
9419 	/*
9420 	 * If the COMPLETE flag is clear, then there were no active
9421 	 * entries and we want to roll back to the previous inode until
9422 	 * the new inode is committed to disk. If the COMPLETE flag is
9423 	 * set, then we have deleted an entry that never made it to disk.
9424 	 * If the entry we deleted resulted from a name change, then the old
9425 	 * inode reference still resides on disk. Any rollback that we do
9426 	 * needs to be to that old inode (returned to us in prevdirrem). If
9427 	 * the entry we deleted resulted from a create, then there is
9428 	 * no entry on the disk, so we want to roll back to zero rather
9429 	 * than the uncommitted inode. In either of the COMPLETE cases we
9430 	 * want to immediately free the unwritten and unreferenced inode.
9431 	 */
9432 	if ((dirrem->dm_state & COMPLETE) == 0) {
9433 		dap->da_previous = dirrem;
9434 	} else {
9435 		if (prevdirrem != NULL) {
9436 			dap->da_previous = prevdirrem;
9437 		} else {
9438 			dap->da_state &= ~DIRCHG;
9439 			dap->da_pagedep = pagedep;
9440 		}
9441 		dirrem->dm_dirinum = pagedep->pd_ino;
9442 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9443 			add_to_worklist(&dirrem->dm_list, 0);
9444 	}
9445 	/*
9446 	 * Lookup the jaddref for this journal entry.  We must finish
9447 	 * initializing it and make the diradd write dependent on it.
9448 	 * If we're not journaling, put it on the id_bufwait list if the
9449 	 * inode is not yet written. If it is written, do the post-inode
9450 	 * write processing to put it on the id_pendinghd list.
9451 	 */
9452 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9453 	if (MOUNTEDSUJ(mp)) {
9454 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9455 		    inoreflst);
9456 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9457 		    ("softdep_setup_directory_change: bad jaddref %p",
9458 		    jaddref));
9459 		jaddref->ja_diroff = dp->i_offset;
9460 		jaddref->ja_diradd = dap;
9461 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9462 		    dap, da_pdlist);
9463 		add_to_journal(&jaddref->ja_list);
9464 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9465 		dap->da_state |= COMPLETE;
9466 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9467 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9468 	} else {
9469 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9470 		    dap, da_pdlist);
9471 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9472 	}
9473 	/*
9474 	 * If we're making a new name for a directory that has not been
9475 	 * committed when need to move the dot and dotdot references to
9476 	 * this new name.
9477 	 */
9478 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9479 		merge_diradd(inodedep, dap);
9480 	FREE_LOCK(ump);
9481 }
9482 
9483 /*
9484  * Called whenever the link count on an inode is changed.
9485  * It creates an inode dependency so that the new reference(s)
9486  * to the inode cannot be committed to disk until the updated
9487  * inode has been written.
9488  */
9489 void
9490 softdep_change_linkcnt(ip)
9491 	struct inode *ip;	/* the inode with the increased link count */
9492 {
9493 	struct inodedep *inodedep;
9494 	struct ufsmount *ump;
9495 
9496 	ump = ITOUMP(ip);
9497 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9498 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9499 	ACQUIRE_LOCK(ump);
9500 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9501 	if (ip->i_nlink < ip->i_effnlink)
9502 		panic("softdep_change_linkcnt: bad delta");
9503 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9504 	FREE_LOCK(ump);
9505 }
9506 
9507 /*
9508  * Attach a sbdep dependency to the superblock buf so that we can keep
9509  * track of the head of the linked list of referenced but unlinked inodes.
9510  */
9511 void
9512 softdep_setup_sbupdate(ump, fs, bp)
9513 	struct ufsmount *ump;
9514 	struct fs *fs;
9515 	struct buf *bp;
9516 {
9517 	struct sbdep *sbdep;
9518 	struct worklist *wk;
9519 
9520 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9521 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9522 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9523 		if (wk->wk_type == D_SBDEP)
9524 			break;
9525 	if (wk != NULL)
9526 		return;
9527 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9528 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9529 	sbdep->sb_fs = fs;
9530 	sbdep->sb_ump = ump;
9531 	ACQUIRE_LOCK(ump);
9532 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9533 	FREE_LOCK(ump);
9534 }
9535 
9536 /*
9537  * Return the first unlinked inodedep which is ready to be the head of the
9538  * list.  The inodedep and all those after it must have valid next pointers.
9539  */
9540 static struct inodedep *
9541 first_unlinked_inodedep(ump)
9542 	struct ufsmount *ump;
9543 {
9544 	struct inodedep *inodedep;
9545 	struct inodedep *idp;
9546 
9547 	LOCK_OWNED(ump);
9548 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9549 	    inodedep; inodedep = idp) {
9550 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9551 			return (NULL);
9552 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9553 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9554 			break;
9555 		if ((inodedep->id_state & UNLINKPREV) == 0)
9556 			break;
9557 	}
9558 	return (inodedep);
9559 }
9560 
9561 /*
9562  * Set the sujfree unlinked head pointer prior to writing a superblock.
9563  */
9564 static void
9565 initiate_write_sbdep(sbdep)
9566 	struct sbdep *sbdep;
9567 {
9568 	struct inodedep *inodedep;
9569 	struct fs *bpfs;
9570 	struct fs *fs;
9571 
9572 	bpfs = sbdep->sb_fs;
9573 	fs = sbdep->sb_ump->um_fs;
9574 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9575 	if (inodedep) {
9576 		fs->fs_sujfree = inodedep->id_ino;
9577 		inodedep->id_state |= UNLINKPREV;
9578 	} else
9579 		fs->fs_sujfree = 0;
9580 	bpfs->fs_sujfree = fs->fs_sujfree;
9581 }
9582 
9583 /*
9584  * After a superblock is written determine whether it must be written again
9585  * due to a changing unlinked list head.
9586  */
9587 static int
9588 handle_written_sbdep(sbdep, bp)
9589 	struct sbdep *sbdep;
9590 	struct buf *bp;
9591 {
9592 	struct inodedep *inodedep;
9593 	struct fs *fs;
9594 
9595 	LOCK_OWNED(sbdep->sb_ump);
9596 	fs = sbdep->sb_fs;
9597 	/*
9598 	 * If the superblock doesn't match the in-memory list start over.
9599 	 */
9600 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9601 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9602 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9603 		bdirty(bp);
9604 		return (1);
9605 	}
9606 	WORKITEM_FREE(sbdep, D_SBDEP);
9607 	if (fs->fs_sujfree == 0)
9608 		return (0);
9609 	/*
9610 	 * Now that we have a record of this inode in stable store allow it
9611 	 * to be written to free up pending work.  Inodes may see a lot of
9612 	 * write activity after they are unlinked which we must not hold up.
9613 	 */
9614 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9615 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9616 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9617 			    inodedep, inodedep->id_state);
9618 		if (inodedep->id_state & UNLINKONLIST)
9619 			break;
9620 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9621 	}
9622 
9623 	return (0);
9624 }
9625 
9626 /*
9627  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9628  */
9629 static void
9630 unlinked_inodedep(mp, inodedep)
9631 	struct mount *mp;
9632 	struct inodedep *inodedep;
9633 {
9634 	struct ufsmount *ump;
9635 
9636 	ump = VFSTOUFS(mp);
9637 	LOCK_OWNED(ump);
9638 	if (MOUNTEDSUJ(mp) == 0)
9639 		return;
9640 	ump->um_fs->fs_fmod = 1;
9641 	if (inodedep->id_state & UNLINKED)
9642 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9643 	inodedep->id_state |= UNLINKED;
9644 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9645 }
9646 
9647 /*
9648  * Remove an inodedep from the unlinked inodedep list.  This may require
9649  * disk writes if the inode has made it that far.
9650  */
9651 static void
9652 clear_unlinked_inodedep(inodedep)
9653 	struct inodedep *inodedep;
9654 {
9655 	struct ufs2_dinode *dip;
9656 	struct ufsmount *ump;
9657 	struct inodedep *idp;
9658 	struct inodedep *idn;
9659 	struct fs *fs;
9660 	struct buf *bp;
9661 	ino_t ino;
9662 	ino_t nino;
9663 	ino_t pino;
9664 	int error;
9665 
9666 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9667 	fs = ump->um_fs;
9668 	ino = inodedep->id_ino;
9669 	error = 0;
9670 	for (;;) {
9671 		LOCK_OWNED(ump);
9672 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9673 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9674 		    inodedep));
9675 		/*
9676 		 * If nothing has yet been written simply remove us from
9677 		 * the in memory list and return.  This is the most common
9678 		 * case where handle_workitem_remove() loses the final
9679 		 * reference.
9680 		 */
9681 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9682 			break;
9683 		/*
9684 		 * If we have a NEXT pointer and no PREV pointer we can simply
9685 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9686 		 * careful not to clear PREV if the superblock points at
9687 		 * next as well.
9688 		 */
9689 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9690 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9691 			if (idn && fs->fs_sujfree != idn->id_ino)
9692 				idn->id_state &= ~UNLINKPREV;
9693 			break;
9694 		}
9695 		/*
9696 		 * Here we have an inodedep which is actually linked into
9697 		 * the list.  We must remove it by forcing a write to the
9698 		 * link before us, whether it be the superblock or an inode.
9699 		 * Unfortunately the list may change while we're waiting
9700 		 * on the buf lock for either resource so we must loop until
9701 		 * we lock the right one.  If both the superblock and an
9702 		 * inode point to this inode we must clear the inode first
9703 		 * followed by the superblock.
9704 		 */
9705 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9706 		pino = 0;
9707 		if (idp && (idp->id_state & UNLINKNEXT))
9708 			pino = idp->id_ino;
9709 		FREE_LOCK(ump);
9710 		if (pino == 0) {
9711 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9712 			    (int)fs->fs_sbsize, 0, 0, 0);
9713 		} else {
9714 			error = bread(ump->um_devvp,
9715 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9716 			    (int)fs->fs_bsize, NOCRED, &bp);
9717 			if (error)
9718 				brelse(bp);
9719 		}
9720 		ACQUIRE_LOCK(ump);
9721 		if (error)
9722 			break;
9723 		/* If the list has changed restart the loop. */
9724 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9725 		nino = 0;
9726 		if (idp && (idp->id_state & UNLINKNEXT))
9727 			nino = idp->id_ino;
9728 		if (nino != pino ||
9729 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9730 			FREE_LOCK(ump);
9731 			brelse(bp);
9732 			ACQUIRE_LOCK(ump);
9733 			continue;
9734 		}
9735 		nino = 0;
9736 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9737 		if (idn)
9738 			nino = idn->id_ino;
9739 		/*
9740 		 * Remove us from the in memory list.  After this we cannot
9741 		 * access the inodedep.
9742 		 */
9743 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9744 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9745 		    inodedep));
9746 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9747 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9748 		FREE_LOCK(ump);
9749 		/*
9750 		 * The predecessor's next pointer is manually updated here
9751 		 * so that the NEXT flag is never cleared for an element
9752 		 * that is in the list.
9753 		 */
9754 		if (pino == 0) {
9755 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9756 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9757 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9758 			    bp);
9759 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
9760 			((struct ufs1_dinode *)bp->b_data +
9761 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9762 		} else {
9763 			dip = (struct ufs2_dinode *)bp->b_data +
9764 			    ino_to_fsbo(fs, pino);
9765 			dip->di_freelink = nino;
9766 			ffs_update_dinode_ckhash(fs, dip);
9767 		}
9768 		/*
9769 		 * If the bwrite fails we have no recourse to recover.  The
9770 		 * filesystem is corrupted already.
9771 		 */
9772 		bwrite(bp);
9773 		ACQUIRE_LOCK(ump);
9774 		/*
9775 		 * If the superblock pointer still needs to be cleared force
9776 		 * a write here.
9777 		 */
9778 		if (fs->fs_sujfree == ino) {
9779 			FREE_LOCK(ump);
9780 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9781 			    (int)fs->fs_sbsize, 0, 0, 0);
9782 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9783 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9784 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9785 			    bp);
9786 			bwrite(bp);
9787 			ACQUIRE_LOCK(ump);
9788 		}
9789 
9790 		if (fs->fs_sujfree != ino)
9791 			return;
9792 		panic("clear_unlinked_inodedep: Failed to clear free head");
9793 	}
9794 	if (inodedep->id_ino == fs->fs_sujfree)
9795 		panic("clear_unlinked_inodedep: Freeing head of free list");
9796 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9797 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9798 	return;
9799 }
9800 
9801 /*
9802  * This workitem decrements the inode's link count.
9803  * If the link count reaches zero, the file is removed.
9804  */
9805 static int
9806 handle_workitem_remove(dirrem, flags)
9807 	struct dirrem *dirrem;
9808 	int flags;
9809 {
9810 	struct inodedep *inodedep;
9811 	struct workhead dotdotwk;
9812 	struct worklist *wk;
9813 	struct ufsmount *ump;
9814 	struct mount *mp;
9815 	struct vnode *vp;
9816 	struct inode *ip;
9817 	ino_t oldinum;
9818 
9819 	if (dirrem->dm_state & ONWORKLIST)
9820 		panic("handle_workitem_remove: dirrem %p still on worklist",
9821 		    dirrem);
9822 	oldinum = dirrem->dm_oldinum;
9823 	mp = dirrem->dm_list.wk_mp;
9824 	ump = VFSTOUFS(mp);
9825 	flags |= LK_EXCLUSIVE;
9826 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9827 		return (EBUSY);
9828 	ip = VTOI(vp);
9829 	ACQUIRE_LOCK(ump);
9830 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9831 		panic("handle_workitem_remove: lost inodedep");
9832 	if (dirrem->dm_state & ONDEPLIST)
9833 		LIST_REMOVE(dirrem, dm_inonext);
9834 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9835 	    ("handle_workitem_remove:  Journal entries not written."));
9836 
9837 	/*
9838 	 * Move all dependencies waiting on the remove to complete
9839 	 * from the dirrem to the inode inowait list to be completed
9840 	 * after the inode has been updated and written to disk.  Any
9841 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9842 	 * is removed.
9843 	 */
9844 	LIST_INIT(&dotdotwk);
9845 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9846 		WORKLIST_REMOVE(wk);
9847 		if (wk->wk_state & MKDIR_PARENT) {
9848 			wk->wk_state &= ~MKDIR_PARENT;
9849 			WORKLIST_INSERT(&dotdotwk, wk);
9850 			continue;
9851 		}
9852 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9853 	}
9854 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9855 	/*
9856 	 * Normal file deletion.
9857 	 */
9858 	if ((dirrem->dm_state & RMDIR) == 0) {
9859 		ip->i_nlink--;
9860 		DIP_SET(ip, i_nlink, ip->i_nlink);
9861 		ip->i_flag |= IN_CHANGE;
9862 		if (ip->i_nlink < ip->i_effnlink)
9863 			panic("handle_workitem_remove: bad file delta");
9864 		if (ip->i_nlink == 0)
9865 			unlinked_inodedep(mp, inodedep);
9866 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9867 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9868 		    ("handle_workitem_remove: worklist not empty. %s",
9869 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9870 		WORKITEM_FREE(dirrem, D_DIRREM);
9871 		FREE_LOCK(ump);
9872 		goto out;
9873 	}
9874 	/*
9875 	 * Directory deletion. Decrement reference count for both the
9876 	 * just deleted parent directory entry and the reference for ".".
9877 	 * Arrange to have the reference count on the parent decremented
9878 	 * to account for the loss of "..".
9879 	 */
9880 	ip->i_nlink -= 2;
9881 	DIP_SET(ip, i_nlink, ip->i_nlink);
9882 	ip->i_flag |= IN_CHANGE;
9883 	if (ip->i_nlink < ip->i_effnlink)
9884 		panic("handle_workitem_remove: bad dir delta");
9885 	if (ip->i_nlink == 0)
9886 		unlinked_inodedep(mp, inodedep);
9887 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9888 	/*
9889 	 * Rename a directory to a new parent. Since, we are both deleting
9890 	 * and creating a new directory entry, the link count on the new
9891 	 * directory should not change. Thus we skip the followup dirrem.
9892 	 */
9893 	if (dirrem->dm_state & DIRCHG) {
9894 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9895 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9896 		WORKITEM_FREE(dirrem, D_DIRREM);
9897 		FREE_LOCK(ump);
9898 		goto out;
9899 	}
9900 	dirrem->dm_state = ONDEPLIST;
9901 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9902 	/*
9903 	 * Place the dirrem on the parent's diremhd list.
9904 	 */
9905 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9906 		panic("handle_workitem_remove: lost dir inodedep");
9907 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9908 	/*
9909 	 * If the allocated inode has never been written to disk, then
9910 	 * the on-disk inode is zero'ed and we can remove the file
9911 	 * immediately.  When journaling if the inode has been marked
9912 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9913 	 */
9914 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9915 	if (inodedep == NULL ||
9916 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9917 	    check_inode_unwritten(inodedep)) {
9918 		FREE_LOCK(ump);
9919 		vput(vp);
9920 		return handle_workitem_remove(dirrem, flags);
9921 	}
9922 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9923 	FREE_LOCK(ump);
9924 	ip->i_flag |= IN_CHANGE;
9925 out:
9926 	ffs_update(vp, 0);
9927 	vput(vp);
9928 	return (0);
9929 }
9930 
9931 /*
9932  * Inode de-allocation dependencies.
9933  *
9934  * When an inode's link count is reduced to zero, it can be de-allocated. We
9935  * found it convenient to postpone de-allocation until after the inode is
9936  * written to disk with its new link count (zero).  At this point, all of the
9937  * on-disk inode's block pointers are nullified and, with careful dependency
9938  * list ordering, all dependencies related to the inode will be satisfied and
9939  * the corresponding dependency structures de-allocated.  So, if/when the
9940  * inode is reused, there will be no mixing of old dependencies with new
9941  * ones.  This artificial dependency is set up by the block de-allocation
9942  * procedure above (softdep_setup_freeblocks) and completed by the
9943  * following procedure.
9944  */
9945 static void
9946 handle_workitem_freefile(freefile)
9947 	struct freefile *freefile;
9948 {
9949 	struct workhead wkhd;
9950 	struct fs *fs;
9951 	struct ufsmount *ump;
9952 	int error;
9953 #ifdef INVARIANTS
9954 	struct inodedep *idp;
9955 #endif
9956 
9957 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9958 	fs = ump->um_fs;
9959 #ifdef INVARIANTS
9960 	ACQUIRE_LOCK(ump);
9961 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9962 	FREE_LOCK(ump);
9963 	if (error)
9964 		panic("handle_workitem_freefile: inodedep %p survived", idp);
9965 #endif
9966 	UFS_LOCK(ump);
9967 	fs->fs_pendinginodes -= 1;
9968 	UFS_UNLOCK(ump);
9969 	LIST_INIT(&wkhd);
9970 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9971 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9972 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9973 		softdep_error("handle_workitem_freefile", error);
9974 	ACQUIRE_LOCK(ump);
9975 	WORKITEM_FREE(freefile, D_FREEFILE);
9976 	FREE_LOCK(ump);
9977 }
9978 
9979 
9980 /*
9981  * Helper function which unlinks marker element from work list and returns
9982  * the next element on the list.
9983  */
9984 static __inline struct worklist *
9985 markernext(struct worklist *marker)
9986 {
9987 	struct worklist *next;
9988 
9989 	next = LIST_NEXT(marker, wk_list);
9990 	LIST_REMOVE(marker, wk_list);
9991 	return next;
9992 }
9993 
9994 /*
9995  * Disk writes.
9996  *
9997  * The dependency structures constructed above are most actively used when file
9998  * system blocks are written to disk.  No constraints are placed on when a
9999  * block can be written, but unsatisfied update dependencies are made safe by
10000  * modifying (or replacing) the source memory for the duration of the disk
10001  * write.  When the disk write completes, the memory block is again brought
10002  * up-to-date.
10003  *
10004  * In-core inode structure reclamation.
10005  *
10006  * Because there are a finite number of "in-core" inode structures, they are
10007  * reused regularly.  By transferring all inode-related dependencies to the
10008  * in-memory inode block and indexing them separately (via "inodedep"s), we
10009  * can allow "in-core" inode structures to be reused at any time and avoid
10010  * any increase in contention.
10011  *
10012  * Called just before entering the device driver to initiate a new disk I/O.
10013  * The buffer must be locked, thus, no I/O completion operations can occur
10014  * while we are manipulating its associated dependencies.
10015  */
10016 static void
10017 softdep_disk_io_initiation(bp)
10018 	struct buf *bp;		/* structure describing disk write to occur */
10019 {
10020 	struct worklist *wk;
10021 	struct worklist marker;
10022 	struct inodedep *inodedep;
10023 	struct freeblks *freeblks;
10024 	struct jblkdep *jblkdep;
10025 	struct newblk *newblk;
10026 	struct ufsmount *ump;
10027 
10028 	/*
10029 	 * We only care about write operations. There should never
10030 	 * be dependencies for reads.
10031 	 */
10032 	if (bp->b_iocmd != BIO_WRITE)
10033 		panic("softdep_disk_io_initiation: not write");
10034 
10035 	if (bp->b_vflags & BV_BKGRDINPROG)
10036 		panic("softdep_disk_io_initiation: Writing buffer with "
10037 		    "background write in progress: %p", bp);
10038 
10039 	ump = softdep_bp_to_mp(bp);
10040 	if (ump == NULL)
10041 		return;
10042 
10043 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10044 	PHOLD(curproc);			/* Don't swap out kernel stack */
10045 	ACQUIRE_LOCK(ump);
10046 	/*
10047 	 * Do any necessary pre-I/O processing.
10048 	 */
10049 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10050 	     wk = markernext(&marker)) {
10051 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10052 		switch (wk->wk_type) {
10053 
10054 		case D_PAGEDEP:
10055 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10056 			continue;
10057 
10058 		case D_INODEDEP:
10059 			inodedep = WK_INODEDEP(wk);
10060 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10061 				initiate_write_inodeblock_ufs1(inodedep, bp);
10062 			else
10063 				initiate_write_inodeblock_ufs2(inodedep, bp);
10064 			continue;
10065 
10066 		case D_INDIRDEP:
10067 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10068 			continue;
10069 
10070 		case D_BMSAFEMAP:
10071 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10072 			continue;
10073 
10074 		case D_JSEG:
10075 			WK_JSEG(wk)->js_buf = NULL;
10076 			continue;
10077 
10078 		case D_FREEBLKS:
10079 			freeblks = WK_FREEBLKS(wk);
10080 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10081 			/*
10082 			 * We have to wait for the freeblks to be journaled
10083 			 * before we can write an inodeblock with updated
10084 			 * pointers.  Be careful to arrange the marker so
10085 			 * we revisit the freeblks if it's not removed by
10086 			 * the first jwait().
10087 			 */
10088 			if (jblkdep != NULL) {
10089 				LIST_REMOVE(&marker, wk_list);
10090 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10091 				jwait(&jblkdep->jb_list, MNT_WAIT);
10092 			}
10093 			continue;
10094 		case D_ALLOCDIRECT:
10095 		case D_ALLOCINDIR:
10096 			/*
10097 			 * We have to wait for the jnewblk to be journaled
10098 			 * before we can write to a block if the contents
10099 			 * may be confused with an earlier file's indirect
10100 			 * at recovery time.  Handle the marker as described
10101 			 * above.
10102 			 */
10103 			newblk = WK_NEWBLK(wk);
10104 			if (newblk->nb_jnewblk != NULL &&
10105 			    indirblk_lookup(newblk->nb_list.wk_mp,
10106 			    newblk->nb_newblkno)) {
10107 				LIST_REMOVE(&marker, wk_list);
10108 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10109 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10110 			}
10111 			continue;
10112 
10113 		case D_SBDEP:
10114 			initiate_write_sbdep(WK_SBDEP(wk));
10115 			continue;
10116 
10117 		case D_MKDIR:
10118 		case D_FREEWORK:
10119 		case D_FREEDEP:
10120 		case D_JSEGDEP:
10121 			continue;
10122 
10123 		default:
10124 			panic("handle_disk_io_initiation: Unexpected type %s",
10125 			    TYPENAME(wk->wk_type));
10126 			/* NOTREACHED */
10127 		}
10128 	}
10129 	FREE_LOCK(ump);
10130 	PRELE(curproc);			/* Allow swapout of kernel stack */
10131 }
10132 
10133 /*
10134  * Called from within the procedure above to deal with unsatisfied
10135  * allocation dependencies in a directory. The buffer must be locked,
10136  * thus, no I/O completion operations can occur while we are
10137  * manipulating its associated dependencies.
10138  */
10139 static void
10140 initiate_write_filepage(pagedep, bp)
10141 	struct pagedep *pagedep;
10142 	struct buf *bp;
10143 {
10144 	struct jremref *jremref;
10145 	struct jmvref *jmvref;
10146 	struct dirrem *dirrem;
10147 	struct diradd *dap;
10148 	struct direct *ep;
10149 	int i;
10150 
10151 	if (pagedep->pd_state & IOSTARTED) {
10152 		/*
10153 		 * This can only happen if there is a driver that does not
10154 		 * understand chaining. Here biodone will reissue the call
10155 		 * to strategy for the incomplete buffers.
10156 		 */
10157 		printf("initiate_write_filepage: already started\n");
10158 		return;
10159 	}
10160 	pagedep->pd_state |= IOSTARTED;
10161 	/*
10162 	 * Wait for all journal remove dependencies to hit the disk.
10163 	 * We can not allow any potentially conflicting directory adds
10164 	 * to be visible before removes and rollback is too difficult.
10165 	 * The per-filesystem lock may be dropped and re-acquired, however
10166 	 * we hold the buf locked so the dependency can not go away.
10167 	 */
10168 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10169 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10170 			jwait(&jremref->jr_list, MNT_WAIT);
10171 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10172 		jwait(&jmvref->jm_list, MNT_WAIT);
10173 	for (i = 0; i < DAHASHSZ; i++) {
10174 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10175 			ep = (struct direct *)
10176 			    ((char *)bp->b_data + dap->da_offset);
10177 			if (ep->d_ino != dap->da_newinum)
10178 				panic("%s: dir inum %ju != new %ju",
10179 				    "initiate_write_filepage",
10180 				    (uintmax_t)ep->d_ino,
10181 				    (uintmax_t)dap->da_newinum);
10182 			if (dap->da_state & DIRCHG)
10183 				ep->d_ino = dap->da_previous->dm_oldinum;
10184 			else
10185 				ep->d_ino = 0;
10186 			dap->da_state &= ~ATTACHED;
10187 			dap->da_state |= UNDONE;
10188 		}
10189 	}
10190 }
10191 
10192 /*
10193  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10194  * Note that any bug fixes made to this routine must be done in the
10195  * version found below.
10196  *
10197  * Called from within the procedure above to deal with unsatisfied
10198  * allocation dependencies in an inodeblock. The buffer must be
10199  * locked, thus, no I/O completion operations can occur while we
10200  * are manipulating its associated dependencies.
10201  */
10202 static void
10203 initiate_write_inodeblock_ufs1(inodedep, bp)
10204 	struct inodedep *inodedep;
10205 	struct buf *bp;			/* The inode block */
10206 {
10207 	struct allocdirect *adp, *lastadp;
10208 	struct ufs1_dinode *dp;
10209 	struct ufs1_dinode *sip;
10210 	struct inoref *inoref;
10211 	struct ufsmount *ump;
10212 	struct fs *fs;
10213 	ufs_lbn_t i;
10214 #ifdef INVARIANTS
10215 	ufs_lbn_t prevlbn = 0;
10216 #endif
10217 	int deplist;
10218 
10219 	if (inodedep->id_state & IOSTARTED)
10220 		panic("initiate_write_inodeblock_ufs1: already started");
10221 	inodedep->id_state |= IOSTARTED;
10222 	fs = inodedep->id_fs;
10223 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10224 	LOCK_OWNED(ump);
10225 	dp = (struct ufs1_dinode *)bp->b_data +
10226 	    ino_to_fsbo(fs, inodedep->id_ino);
10227 
10228 	/*
10229 	 * If we're on the unlinked list but have not yet written our
10230 	 * next pointer initialize it here.
10231 	 */
10232 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10233 		struct inodedep *inon;
10234 
10235 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10236 		dp->di_freelink = inon ? inon->id_ino : 0;
10237 	}
10238 	/*
10239 	 * If the bitmap is not yet written, then the allocated
10240 	 * inode cannot be written to disk.
10241 	 */
10242 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10243 		if (inodedep->id_savedino1 != NULL)
10244 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10245 		FREE_LOCK(ump);
10246 		sip = malloc(sizeof(struct ufs1_dinode),
10247 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10248 		ACQUIRE_LOCK(ump);
10249 		inodedep->id_savedino1 = sip;
10250 		*inodedep->id_savedino1 = *dp;
10251 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10252 		dp->di_gen = inodedep->id_savedino1->di_gen;
10253 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10254 		return;
10255 	}
10256 	/*
10257 	 * If no dependencies, then there is nothing to roll back.
10258 	 */
10259 	inodedep->id_savedsize = dp->di_size;
10260 	inodedep->id_savedextsize = 0;
10261 	inodedep->id_savednlink = dp->di_nlink;
10262 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10263 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10264 		return;
10265 	/*
10266 	 * Revert the link count to that of the first unwritten journal entry.
10267 	 */
10268 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10269 	if (inoref)
10270 		dp->di_nlink = inoref->if_nlink;
10271 	/*
10272 	 * Set the dependencies to busy.
10273 	 */
10274 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10275 	     adp = TAILQ_NEXT(adp, ad_next)) {
10276 #ifdef INVARIANTS
10277 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10278 			panic("softdep_write_inodeblock: lbn order");
10279 		prevlbn = adp->ad_offset;
10280 		if (adp->ad_offset < UFS_NDADDR &&
10281 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10282 			panic("initiate_write_inodeblock_ufs1: "
10283 			    "direct pointer #%jd mismatch %d != %jd",
10284 			    (intmax_t)adp->ad_offset,
10285 			    dp->di_db[adp->ad_offset],
10286 			    (intmax_t)adp->ad_newblkno);
10287 		if (adp->ad_offset >= UFS_NDADDR &&
10288 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10289 			panic("initiate_write_inodeblock_ufs1: "
10290 			    "indirect pointer #%jd mismatch %d != %jd",
10291 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10292 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10293 			    (intmax_t)adp->ad_newblkno);
10294 		deplist |= 1 << adp->ad_offset;
10295 		if ((adp->ad_state & ATTACHED) == 0)
10296 			panic("initiate_write_inodeblock_ufs1: "
10297 			    "Unknown state 0x%x", adp->ad_state);
10298 #endif /* INVARIANTS */
10299 		adp->ad_state &= ~ATTACHED;
10300 		adp->ad_state |= UNDONE;
10301 	}
10302 	/*
10303 	 * The on-disk inode cannot claim to be any larger than the last
10304 	 * fragment that has been written. Otherwise, the on-disk inode
10305 	 * might have fragments that were not the last block in the file
10306 	 * which would corrupt the filesystem.
10307 	 */
10308 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10309 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10310 		if (adp->ad_offset >= UFS_NDADDR)
10311 			break;
10312 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10313 		/* keep going until hitting a rollback to a frag */
10314 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10315 			continue;
10316 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10317 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10318 #ifdef INVARIANTS
10319 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10320 				panic("initiate_write_inodeblock_ufs1: "
10321 				    "lost dep1");
10322 #endif /* INVARIANTS */
10323 			dp->di_db[i] = 0;
10324 		}
10325 		for (i = 0; i < UFS_NIADDR; i++) {
10326 #ifdef INVARIANTS
10327 			if (dp->di_ib[i] != 0 &&
10328 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10329 				panic("initiate_write_inodeblock_ufs1: "
10330 				    "lost dep2");
10331 #endif /* INVARIANTS */
10332 			dp->di_ib[i] = 0;
10333 		}
10334 		return;
10335 	}
10336 	/*
10337 	 * If we have zero'ed out the last allocated block of the file,
10338 	 * roll back the size to the last currently allocated block.
10339 	 * We know that this last allocated block is a full-sized as
10340 	 * we already checked for fragments in the loop above.
10341 	 */
10342 	if (lastadp != NULL &&
10343 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10344 		for (i = lastadp->ad_offset; i >= 0; i--)
10345 			if (dp->di_db[i] != 0)
10346 				break;
10347 		dp->di_size = (i + 1) * fs->fs_bsize;
10348 	}
10349 	/*
10350 	 * The only dependencies are for indirect blocks.
10351 	 *
10352 	 * The file size for indirect block additions is not guaranteed.
10353 	 * Such a guarantee would be non-trivial to achieve. The conventional
10354 	 * synchronous write implementation also does not make this guarantee.
10355 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10356 	 * can be over-estimated without destroying integrity when the file
10357 	 * moves into the indirect blocks (i.e., is large). If we want to
10358 	 * postpone fsck, we are stuck with this argument.
10359 	 */
10360 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10361 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10362 }
10363 
10364 /*
10365  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10366  * Note that any bug fixes made to this routine must be done in the
10367  * version found above.
10368  *
10369  * Called from within the procedure above to deal with unsatisfied
10370  * allocation dependencies in an inodeblock. The buffer must be
10371  * locked, thus, no I/O completion operations can occur while we
10372  * are manipulating its associated dependencies.
10373  */
10374 static void
10375 initiate_write_inodeblock_ufs2(inodedep, bp)
10376 	struct inodedep *inodedep;
10377 	struct buf *bp;			/* The inode block */
10378 {
10379 	struct allocdirect *adp, *lastadp;
10380 	struct ufs2_dinode *dp;
10381 	struct ufs2_dinode *sip;
10382 	struct inoref *inoref;
10383 	struct ufsmount *ump;
10384 	struct fs *fs;
10385 	ufs_lbn_t i;
10386 #ifdef INVARIANTS
10387 	ufs_lbn_t prevlbn = 0;
10388 #endif
10389 	int deplist;
10390 
10391 	if (inodedep->id_state & IOSTARTED)
10392 		panic("initiate_write_inodeblock_ufs2: already started");
10393 	inodedep->id_state |= IOSTARTED;
10394 	fs = inodedep->id_fs;
10395 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10396 	LOCK_OWNED(ump);
10397 	dp = (struct ufs2_dinode *)bp->b_data +
10398 	    ino_to_fsbo(fs, inodedep->id_ino);
10399 
10400 	/*
10401 	 * If we're on the unlinked list but have not yet written our
10402 	 * next pointer initialize it here.
10403 	 */
10404 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10405 		struct inodedep *inon;
10406 
10407 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10408 		dp->di_freelink = inon ? inon->id_ino : 0;
10409 		ffs_update_dinode_ckhash(fs, dp);
10410 	}
10411 	/*
10412 	 * If the bitmap is not yet written, then the allocated
10413 	 * inode cannot be written to disk.
10414 	 */
10415 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10416 		if (inodedep->id_savedino2 != NULL)
10417 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10418 		FREE_LOCK(ump);
10419 		sip = malloc(sizeof(struct ufs2_dinode),
10420 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10421 		ACQUIRE_LOCK(ump);
10422 		inodedep->id_savedino2 = sip;
10423 		*inodedep->id_savedino2 = *dp;
10424 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10425 		dp->di_gen = inodedep->id_savedino2->di_gen;
10426 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10427 		return;
10428 	}
10429 	/*
10430 	 * If no dependencies, then there is nothing to roll back.
10431 	 */
10432 	inodedep->id_savedsize = dp->di_size;
10433 	inodedep->id_savedextsize = dp->di_extsize;
10434 	inodedep->id_savednlink = dp->di_nlink;
10435 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10436 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10437 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10438 		return;
10439 	/*
10440 	 * Revert the link count to that of the first unwritten journal entry.
10441 	 */
10442 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10443 	if (inoref)
10444 		dp->di_nlink = inoref->if_nlink;
10445 
10446 	/*
10447 	 * Set the ext data dependencies to busy.
10448 	 */
10449 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10450 	     adp = TAILQ_NEXT(adp, ad_next)) {
10451 #ifdef INVARIANTS
10452 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10453 			panic("initiate_write_inodeblock_ufs2: lbn order");
10454 		prevlbn = adp->ad_offset;
10455 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10456 			panic("initiate_write_inodeblock_ufs2: "
10457 			    "ext pointer #%jd mismatch %jd != %jd",
10458 			    (intmax_t)adp->ad_offset,
10459 			    (intmax_t)dp->di_extb[adp->ad_offset],
10460 			    (intmax_t)adp->ad_newblkno);
10461 		deplist |= 1 << adp->ad_offset;
10462 		if ((adp->ad_state & ATTACHED) == 0)
10463 			panic("initiate_write_inodeblock_ufs2: Unknown "
10464 			    "state 0x%x", adp->ad_state);
10465 #endif /* INVARIANTS */
10466 		adp->ad_state &= ~ATTACHED;
10467 		adp->ad_state |= UNDONE;
10468 	}
10469 	/*
10470 	 * The on-disk inode cannot claim to be any larger than the last
10471 	 * fragment that has been written. Otherwise, the on-disk inode
10472 	 * might have fragments that were not the last block in the ext
10473 	 * data which would corrupt the filesystem.
10474 	 */
10475 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10476 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10477 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10478 		/* keep going until hitting a rollback to a frag */
10479 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10480 			continue;
10481 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10482 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10483 #ifdef INVARIANTS
10484 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10485 				panic("initiate_write_inodeblock_ufs2: "
10486 				    "lost dep1");
10487 #endif /* INVARIANTS */
10488 			dp->di_extb[i] = 0;
10489 		}
10490 		lastadp = NULL;
10491 		break;
10492 	}
10493 	/*
10494 	 * If we have zero'ed out the last allocated block of the ext
10495 	 * data, roll back the size to the last currently allocated block.
10496 	 * We know that this last allocated block is a full-sized as
10497 	 * we already checked for fragments in the loop above.
10498 	 */
10499 	if (lastadp != NULL &&
10500 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10501 		for (i = lastadp->ad_offset; i >= 0; i--)
10502 			if (dp->di_extb[i] != 0)
10503 				break;
10504 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10505 	}
10506 	/*
10507 	 * Set the file data dependencies to busy.
10508 	 */
10509 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10510 	     adp = TAILQ_NEXT(adp, ad_next)) {
10511 #ifdef INVARIANTS
10512 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10513 			panic("softdep_write_inodeblock: lbn order");
10514 		if ((adp->ad_state & ATTACHED) == 0)
10515 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10516 		prevlbn = adp->ad_offset;
10517 		if (adp->ad_offset < UFS_NDADDR &&
10518 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10519 			panic("initiate_write_inodeblock_ufs2: "
10520 			    "direct pointer #%jd mismatch %jd != %jd",
10521 			    (intmax_t)adp->ad_offset,
10522 			    (intmax_t)dp->di_db[adp->ad_offset],
10523 			    (intmax_t)adp->ad_newblkno);
10524 		if (adp->ad_offset >= UFS_NDADDR &&
10525 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10526 			panic("initiate_write_inodeblock_ufs2: "
10527 			    "indirect pointer #%jd mismatch %jd != %jd",
10528 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10529 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10530 			    (intmax_t)adp->ad_newblkno);
10531 		deplist |= 1 << adp->ad_offset;
10532 		if ((adp->ad_state & ATTACHED) == 0)
10533 			panic("initiate_write_inodeblock_ufs2: Unknown "
10534 			     "state 0x%x", adp->ad_state);
10535 #endif /* INVARIANTS */
10536 		adp->ad_state &= ~ATTACHED;
10537 		adp->ad_state |= UNDONE;
10538 	}
10539 	/*
10540 	 * The on-disk inode cannot claim to be any larger than the last
10541 	 * fragment that has been written. Otherwise, the on-disk inode
10542 	 * might have fragments that were not the last block in the file
10543 	 * which would corrupt the filesystem.
10544 	 */
10545 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10546 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10547 		if (adp->ad_offset >= UFS_NDADDR)
10548 			break;
10549 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10550 		/* keep going until hitting a rollback to a frag */
10551 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10552 			continue;
10553 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10554 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10555 #ifdef INVARIANTS
10556 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10557 				panic("initiate_write_inodeblock_ufs2: "
10558 				    "lost dep2");
10559 #endif /* INVARIANTS */
10560 			dp->di_db[i] = 0;
10561 		}
10562 		for (i = 0; i < UFS_NIADDR; i++) {
10563 #ifdef INVARIANTS
10564 			if (dp->di_ib[i] != 0 &&
10565 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10566 				panic("initiate_write_inodeblock_ufs2: "
10567 				    "lost dep3");
10568 #endif /* INVARIANTS */
10569 			dp->di_ib[i] = 0;
10570 		}
10571 		ffs_update_dinode_ckhash(fs, dp);
10572 		return;
10573 	}
10574 	/*
10575 	 * If we have zero'ed out the last allocated block of the file,
10576 	 * roll back the size to the last currently allocated block.
10577 	 * We know that this last allocated block is a full-sized as
10578 	 * we already checked for fragments in the loop above.
10579 	 */
10580 	if (lastadp != NULL &&
10581 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10582 		for (i = lastadp->ad_offset; i >= 0; i--)
10583 			if (dp->di_db[i] != 0)
10584 				break;
10585 		dp->di_size = (i + 1) * fs->fs_bsize;
10586 	}
10587 	/*
10588 	 * The only dependencies are for indirect blocks.
10589 	 *
10590 	 * The file size for indirect block additions is not guaranteed.
10591 	 * Such a guarantee would be non-trivial to achieve. The conventional
10592 	 * synchronous write implementation also does not make this guarantee.
10593 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10594 	 * can be over-estimated without destroying integrity when the file
10595 	 * moves into the indirect blocks (i.e., is large). If we want to
10596 	 * postpone fsck, we are stuck with this argument.
10597 	 */
10598 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10599 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10600 	ffs_update_dinode_ckhash(fs, dp);
10601 }
10602 
10603 /*
10604  * Cancel an indirdep as a result of truncation.  Release all of the
10605  * children allocindirs and place their journal work on the appropriate
10606  * list.
10607  */
10608 static void
10609 cancel_indirdep(indirdep, bp, freeblks)
10610 	struct indirdep *indirdep;
10611 	struct buf *bp;
10612 	struct freeblks *freeblks;
10613 {
10614 	struct allocindir *aip;
10615 
10616 	/*
10617 	 * None of the indirect pointers will ever be visible,
10618 	 * so they can simply be tossed. GOINGAWAY ensures
10619 	 * that allocated pointers will be saved in the buffer
10620 	 * cache until they are freed. Note that they will
10621 	 * only be able to be found by their physical address
10622 	 * since the inode mapping the logical address will
10623 	 * be gone. The save buffer used for the safe copy
10624 	 * was allocated in setup_allocindir_phase2 using
10625 	 * the physical address so it could be used for this
10626 	 * purpose. Hence we swap the safe copy with the real
10627 	 * copy, allowing the safe copy to be freed and holding
10628 	 * on to the real copy for later use in indir_trunc.
10629 	 */
10630 	if (indirdep->ir_state & GOINGAWAY)
10631 		panic("cancel_indirdep: already gone");
10632 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10633 		indirdep->ir_state |= DEPCOMPLETE;
10634 		LIST_REMOVE(indirdep, ir_next);
10635 	}
10636 	indirdep->ir_state |= GOINGAWAY;
10637 	/*
10638 	 * Pass in bp for blocks still have journal writes
10639 	 * pending so we can cancel them on their own.
10640 	 */
10641 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10642 		cancel_allocindir(aip, bp, freeblks, 0);
10643 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10644 		cancel_allocindir(aip, NULL, freeblks, 0);
10645 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10646 		cancel_allocindir(aip, NULL, freeblks, 0);
10647 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10648 		cancel_allocindir(aip, NULL, freeblks, 0);
10649 	/*
10650 	 * If there are pending partial truncations we need to keep the
10651 	 * old block copy around until they complete.  This is because
10652 	 * the current b_data is not a perfect superset of the available
10653 	 * blocks.
10654 	 */
10655 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10656 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10657 	else
10658 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10659 	WORKLIST_REMOVE(&indirdep->ir_list);
10660 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10661 	indirdep->ir_bp = NULL;
10662 	indirdep->ir_freeblks = freeblks;
10663 }
10664 
10665 /*
10666  * Free an indirdep once it no longer has new pointers to track.
10667  */
10668 static void
10669 free_indirdep(indirdep)
10670 	struct indirdep *indirdep;
10671 {
10672 
10673 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10674 	    ("free_indirdep: Indir trunc list not empty."));
10675 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10676 	    ("free_indirdep: Complete head not empty."));
10677 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10678 	    ("free_indirdep: write head not empty."));
10679 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10680 	    ("free_indirdep: done head not empty."));
10681 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10682 	    ("free_indirdep: deplist head not empty."));
10683 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10684 	    ("free_indirdep: %p still on newblk list.", indirdep));
10685 	KASSERT(indirdep->ir_saveddata == NULL,
10686 	    ("free_indirdep: %p still has saved data.", indirdep));
10687 	if (indirdep->ir_state & ONWORKLIST)
10688 		WORKLIST_REMOVE(&indirdep->ir_list);
10689 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10690 }
10691 
10692 /*
10693  * Called before a write to an indirdep.  This routine is responsible for
10694  * rolling back pointers to a safe state which includes only those
10695  * allocindirs which have been completed.
10696  */
10697 static void
10698 initiate_write_indirdep(indirdep, bp)
10699 	struct indirdep *indirdep;
10700 	struct buf *bp;
10701 {
10702 	struct ufsmount *ump;
10703 
10704 	indirdep->ir_state |= IOSTARTED;
10705 	if (indirdep->ir_state & GOINGAWAY)
10706 		panic("disk_io_initiation: indirdep gone");
10707 	/*
10708 	 * If there are no remaining dependencies, this will be writing
10709 	 * the real pointers.
10710 	 */
10711 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10712 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10713 		return;
10714 	/*
10715 	 * Replace up-to-date version with safe version.
10716 	 */
10717 	if (indirdep->ir_saveddata == NULL) {
10718 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10719 		LOCK_OWNED(ump);
10720 		FREE_LOCK(ump);
10721 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10722 		    M_SOFTDEP_FLAGS);
10723 		ACQUIRE_LOCK(ump);
10724 	}
10725 	indirdep->ir_state &= ~ATTACHED;
10726 	indirdep->ir_state |= UNDONE;
10727 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10728 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10729 	    bp->b_bcount);
10730 }
10731 
10732 /*
10733  * Called when an inode has been cleared in a cg bitmap.  This finally
10734  * eliminates any canceled jaddrefs
10735  */
10736 void
10737 softdep_setup_inofree(mp, bp, ino, wkhd)
10738 	struct mount *mp;
10739 	struct buf *bp;
10740 	ino_t ino;
10741 	struct workhead *wkhd;
10742 {
10743 	struct worklist *wk, *wkn;
10744 	struct inodedep *inodedep;
10745 	struct ufsmount *ump;
10746 	uint8_t *inosused;
10747 	struct cg *cgp;
10748 	struct fs *fs;
10749 
10750 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10751 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10752 	ump = VFSTOUFS(mp);
10753 	ACQUIRE_LOCK(ump);
10754 	fs = ump->um_fs;
10755 	cgp = (struct cg *)bp->b_data;
10756 	inosused = cg_inosused(cgp);
10757 	if (isset(inosused, ino % fs->fs_ipg))
10758 		panic("softdep_setup_inofree: inode %ju not freed.",
10759 		    (uintmax_t)ino);
10760 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10761 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10762 		    (uintmax_t)ino, inodedep);
10763 	if (wkhd) {
10764 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10765 			if (wk->wk_type != D_JADDREF)
10766 				continue;
10767 			WORKLIST_REMOVE(wk);
10768 			/*
10769 			 * We can free immediately even if the jaddref
10770 			 * isn't attached in a background write as now
10771 			 * the bitmaps are reconciled.
10772 			 */
10773 			wk->wk_state |= COMPLETE | ATTACHED;
10774 			free_jaddref(WK_JADDREF(wk));
10775 		}
10776 		jwork_move(&bp->b_dep, wkhd);
10777 	}
10778 	FREE_LOCK(ump);
10779 }
10780 
10781 
10782 /*
10783  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10784  * map.  Any dependencies waiting for the write to clear are added to the
10785  * buf's list and any jnewblks that are being canceled are discarded
10786  * immediately.
10787  */
10788 void
10789 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10790 	struct mount *mp;
10791 	struct buf *bp;
10792 	ufs2_daddr_t blkno;
10793 	int frags;
10794 	struct workhead *wkhd;
10795 {
10796 	struct bmsafemap *bmsafemap;
10797 	struct jnewblk *jnewblk;
10798 	struct ufsmount *ump;
10799 	struct worklist *wk;
10800 	struct fs *fs;
10801 #ifdef INVARIANTS
10802 	uint8_t *blksfree;
10803 	struct cg *cgp;
10804 	ufs2_daddr_t jstart;
10805 	ufs2_daddr_t jend;
10806 	ufs2_daddr_t end;
10807 	long bno;
10808 	int i;
10809 #endif
10810 
10811 	CTR3(KTR_SUJ,
10812 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10813 	    blkno, frags, wkhd);
10814 
10815 	ump = VFSTOUFS(mp);
10816 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10817 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10818 	ACQUIRE_LOCK(ump);
10819 	/* Lookup the bmsafemap so we track when it is dirty. */
10820 	fs = ump->um_fs;
10821 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10822 	/*
10823 	 * Detach any jnewblks which have been canceled.  They must linger
10824 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10825 	 * an unjournaled allocation from hitting the disk.
10826 	 */
10827 	if (wkhd) {
10828 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10829 			CTR2(KTR_SUJ,
10830 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10831 			    blkno, wk->wk_type);
10832 			WORKLIST_REMOVE(wk);
10833 			if (wk->wk_type != D_JNEWBLK) {
10834 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10835 				continue;
10836 			}
10837 			jnewblk = WK_JNEWBLK(wk);
10838 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10839 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10840 #ifdef INVARIANTS
10841 			/*
10842 			 * Assert that this block is free in the bitmap
10843 			 * before we discard the jnewblk.
10844 			 */
10845 			cgp = (struct cg *)bp->b_data;
10846 			blksfree = cg_blksfree(cgp);
10847 			bno = dtogd(fs, jnewblk->jn_blkno);
10848 			for (i = jnewblk->jn_oldfrags;
10849 			    i < jnewblk->jn_frags; i++) {
10850 				if (isset(blksfree, bno + i))
10851 					continue;
10852 				panic("softdep_setup_blkfree: not free");
10853 			}
10854 #endif
10855 			/*
10856 			 * Even if it's not attached we can free immediately
10857 			 * as the new bitmap is correct.
10858 			 */
10859 			wk->wk_state |= COMPLETE | ATTACHED;
10860 			free_jnewblk(jnewblk);
10861 		}
10862 	}
10863 
10864 #ifdef INVARIANTS
10865 	/*
10866 	 * Assert that we are not freeing a block which has an outstanding
10867 	 * allocation dependency.
10868 	 */
10869 	fs = VFSTOUFS(mp)->um_fs;
10870 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10871 	end = blkno + frags;
10872 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10873 		/*
10874 		 * Don't match against blocks that will be freed when the
10875 		 * background write is done.
10876 		 */
10877 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10878 		    (COMPLETE | DEPCOMPLETE))
10879 			continue;
10880 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10881 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10882 		if ((blkno >= jstart && blkno < jend) ||
10883 		    (end > jstart && end <= jend)) {
10884 			printf("state 0x%X %jd - %d %d dep %p\n",
10885 			    jnewblk->jn_state, jnewblk->jn_blkno,
10886 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10887 			    jnewblk->jn_dep);
10888 			panic("softdep_setup_blkfree: "
10889 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10890 			    blkno, end, frags, jstart, jend);
10891 		}
10892 	}
10893 #endif
10894 	FREE_LOCK(ump);
10895 }
10896 
10897 /*
10898  * Revert a block allocation when the journal record that describes it
10899  * is not yet written.
10900  */
10901 static int
10902 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10903 	struct jnewblk *jnewblk;
10904 	struct fs *fs;
10905 	struct cg *cgp;
10906 	uint8_t *blksfree;
10907 {
10908 	ufs1_daddr_t fragno;
10909 	long cgbno, bbase;
10910 	int frags, blk;
10911 	int i;
10912 
10913 	frags = 0;
10914 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10915 	/*
10916 	 * We have to test which frags need to be rolled back.  We may
10917 	 * be operating on a stale copy when doing background writes.
10918 	 */
10919 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10920 		if (isclr(blksfree, cgbno + i))
10921 			frags++;
10922 	if (frags == 0)
10923 		return (0);
10924 	/*
10925 	 * This is mostly ffs_blkfree() sans some validation and
10926 	 * superblock updates.
10927 	 */
10928 	if (frags == fs->fs_frag) {
10929 		fragno = fragstoblks(fs, cgbno);
10930 		ffs_setblock(fs, blksfree, fragno);
10931 		ffs_clusteracct(fs, cgp, fragno, 1);
10932 		cgp->cg_cs.cs_nbfree++;
10933 	} else {
10934 		cgbno += jnewblk->jn_oldfrags;
10935 		bbase = cgbno - fragnum(fs, cgbno);
10936 		/* Decrement the old frags.  */
10937 		blk = blkmap(fs, blksfree, bbase);
10938 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10939 		/* Deallocate the fragment */
10940 		for (i = 0; i < frags; i++)
10941 			setbit(blksfree, cgbno + i);
10942 		cgp->cg_cs.cs_nffree += frags;
10943 		/* Add back in counts associated with the new frags */
10944 		blk = blkmap(fs, blksfree, bbase);
10945 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10946 		/* If a complete block has been reassembled, account for it. */
10947 		fragno = fragstoblks(fs, bbase);
10948 		if (ffs_isblock(fs, blksfree, fragno)) {
10949 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10950 			ffs_clusteracct(fs, cgp, fragno, 1);
10951 			cgp->cg_cs.cs_nbfree++;
10952 		}
10953 	}
10954 	stat_jnewblk++;
10955 	jnewblk->jn_state &= ~ATTACHED;
10956 	jnewblk->jn_state |= UNDONE;
10957 
10958 	return (frags);
10959 }
10960 
10961 static void
10962 initiate_write_bmsafemap(bmsafemap, bp)
10963 	struct bmsafemap *bmsafemap;
10964 	struct buf *bp;			/* The cg block. */
10965 {
10966 	struct jaddref *jaddref;
10967 	struct jnewblk *jnewblk;
10968 	uint8_t *inosused;
10969 	uint8_t *blksfree;
10970 	struct cg *cgp;
10971 	struct fs *fs;
10972 	ino_t ino;
10973 
10974 	/*
10975 	 * If this is a background write, we did this at the time that
10976 	 * the copy was made, so do not need to do it again.
10977 	 */
10978 	if (bmsafemap->sm_state & IOSTARTED)
10979 		return;
10980 	bmsafemap->sm_state |= IOSTARTED;
10981 	/*
10982 	 * Clear any inode allocations which are pending journal writes.
10983 	 */
10984 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10985 		cgp = (struct cg *)bp->b_data;
10986 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10987 		inosused = cg_inosused(cgp);
10988 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10989 			ino = jaddref->ja_ino % fs->fs_ipg;
10990 			if (isset(inosused, ino)) {
10991 				if ((jaddref->ja_mode & IFMT) == IFDIR)
10992 					cgp->cg_cs.cs_ndir--;
10993 				cgp->cg_cs.cs_nifree++;
10994 				clrbit(inosused, ino);
10995 				jaddref->ja_state &= ~ATTACHED;
10996 				jaddref->ja_state |= UNDONE;
10997 				stat_jaddref++;
10998 			} else
10999 				panic("initiate_write_bmsafemap: inode %ju "
11000 				    "marked free", (uintmax_t)jaddref->ja_ino);
11001 		}
11002 	}
11003 	/*
11004 	 * Clear any block allocations which are pending journal writes.
11005 	 */
11006 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11007 		cgp = (struct cg *)bp->b_data;
11008 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11009 		blksfree = cg_blksfree(cgp);
11010 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11011 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11012 				continue;
11013 			panic("initiate_write_bmsafemap: block %jd "
11014 			    "marked free", jnewblk->jn_blkno);
11015 		}
11016 	}
11017 	/*
11018 	 * Move allocation lists to the written lists so they can be
11019 	 * cleared once the block write is complete.
11020 	 */
11021 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11022 	    inodedep, id_deps);
11023 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11024 	    newblk, nb_deps);
11025 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11026 	    wk_list);
11027 }
11028 
11029 /*
11030  * This routine is called during the completion interrupt
11031  * service routine for a disk write (from the procedure called
11032  * by the device driver to inform the filesystem caches of
11033  * a request completion).  It should be called early in this
11034  * procedure, before the block is made available to other
11035  * processes or other routines are called.
11036  *
11037  */
11038 static void
11039 softdep_disk_write_complete(bp)
11040 	struct buf *bp;		/* describes the completed disk write */
11041 {
11042 	struct worklist *wk;
11043 	struct worklist *owk;
11044 	struct ufsmount *ump;
11045 	struct workhead reattach;
11046 	struct freeblks *freeblks;
11047 	struct buf *sbp;
11048 
11049 	ump = softdep_bp_to_mp(bp);
11050 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11051 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11052 	     "with outstanding dependencies for buffer %p", bp));
11053 	if (ump == NULL)
11054 		return;
11055 	/*
11056 	 * If an error occurred while doing the write, then the data
11057 	 * has not hit the disk and the dependencies cannot be processed.
11058 	 * But we do have to go through and roll forward any dependencies
11059 	 * that were rolled back before the disk write.
11060 	 */
11061 	sbp = NULL;
11062 	ACQUIRE_LOCK(ump);
11063 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11064 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11065 			switch (wk->wk_type) {
11066 
11067 			case D_PAGEDEP:
11068 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11069 				continue;
11070 
11071 			case D_INODEDEP:
11072 				handle_written_inodeblock(WK_INODEDEP(wk),
11073 				    bp, 0);
11074 				continue;
11075 
11076 			case D_BMSAFEMAP:
11077 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11078 				    bp, 0);
11079 				continue;
11080 
11081 			case D_INDIRDEP:
11082 				handle_written_indirdep(WK_INDIRDEP(wk),
11083 				    bp, &sbp, 0);
11084 				continue;
11085 			default:
11086 				/* nothing to roll forward */
11087 				continue;
11088 			}
11089 		}
11090 		FREE_LOCK(ump);
11091 		if (sbp)
11092 			brelse(sbp);
11093 		return;
11094 	}
11095 	LIST_INIT(&reattach);
11096 
11097 	/*
11098 	 * Ump SU lock must not be released anywhere in this code segment.
11099 	 */
11100 	owk = NULL;
11101 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11102 		WORKLIST_REMOVE(wk);
11103 		atomic_add_long(&dep_write[wk->wk_type], 1);
11104 		if (wk == owk)
11105 			panic("duplicate worklist: %p\n", wk);
11106 		owk = wk;
11107 		switch (wk->wk_type) {
11108 
11109 		case D_PAGEDEP:
11110 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11111 			    WRITESUCCEEDED))
11112 				WORKLIST_INSERT(&reattach, wk);
11113 			continue;
11114 
11115 		case D_INODEDEP:
11116 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11117 			    WRITESUCCEEDED))
11118 				WORKLIST_INSERT(&reattach, wk);
11119 			continue;
11120 
11121 		case D_BMSAFEMAP:
11122 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11123 			    WRITESUCCEEDED))
11124 				WORKLIST_INSERT(&reattach, wk);
11125 			continue;
11126 
11127 		case D_MKDIR:
11128 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11129 			continue;
11130 
11131 		case D_ALLOCDIRECT:
11132 			wk->wk_state |= COMPLETE;
11133 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11134 			continue;
11135 
11136 		case D_ALLOCINDIR:
11137 			wk->wk_state |= COMPLETE;
11138 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11139 			continue;
11140 
11141 		case D_INDIRDEP:
11142 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11143 			    WRITESUCCEEDED))
11144 				WORKLIST_INSERT(&reattach, wk);
11145 			continue;
11146 
11147 		case D_FREEBLKS:
11148 			wk->wk_state |= COMPLETE;
11149 			freeblks = WK_FREEBLKS(wk);
11150 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11151 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11152 				add_to_worklist(wk, WK_NODELAY);
11153 			continue;
11154 
11155 		case D_FREEWORK:
11156 			handle_written_freework(WK_FREEWORK(wk));
11157 			break;
11158 
11159 		case D_JSEGDEP:
11160 			free_jsegdep(WK_JSEGDEP(wk));
11161 			continue;
11162 
11163 		case D_JSEG:
11164 			handle_written_jseg(WK_JSEG(wk), bp);
11165 			continue;
11166 
11167 		case D_SBDEP:
11168 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11169 				WORKLIST_INSERT(&reattach, wk);
11170 			continue;
11171 
11172 		case D_FREEDEP:
11173 			free_freedep(WK_FREEDEP(wk));
11174 			continue;
11175 
11176 		default:
11177 			panic("handle_disk_write_complete: Unknown type %s",
11178 			    TYPENAME(wk->wk_type));
11179 			/* NOTREACHED */
11180 		}
11181 	}
11182 	/*
11183 	 * Reattach any requests that must be redone.
11184 	 */
11185 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11186 		WORKLIST_REMOVE(wk);
11187 		WORKLIST_INSERT(&bp->b_dep, wk);
11188 	}
11189 	FREE_LOCK(ump);
11190 	if (sbp)
11191 		brelse(sbp);
11192 }
11193 
11194 /*
11195  * Called from within softdep_disk_write_complete above.
11196  */
11197 static void
11198 handle_allocdirect_partdone(adp, wkhd)
11199 	struct allocdirect *adp;	/* the completed allocdirect */
11200 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11201 {
11202 	struct allocdirectlst *listhead;
11203 	struct allocdirect *listadp;
11204 	struct inodedep *inodedep;
11205 	long bsize;
11206 
11207 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11208 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11209 		return;
11210 	/*
11211 	 * The on-disk inode cannot claim to be any larger than the last
11212 	 * fragment that has been written. Otherwise, the on-disk inode
11213 	 * might have fragments that were not the last block in the file
11214 	 * which would corrupt the filesystem. Thus, we cannot free any
11215 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11216 	 * these blocks must be rolled back to zero before writing the inode.
11217 	 * We check the currently active set of allocdirects in id_inoupdt
11218 	 * or id_extupdt as appropriate.
11219 	 */
11220 	inodedep = adp->ad_inodedep;
11221 	bsize = inodedep->id_fs->fs_bsize;
11222 	if (adp->ad_state & EXTDATA)
11223 		listhead = &inodedep->id_extupdt;
11224 	else
11225 		listhead = &inodedep->id_inoupdt;
11226 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11227 		/* found our block */
11228 		if (listadp == adp)
11229 			break;
11230 		/* continue if ad_oldlbn is not a fragment */
11231 		if (listadp->ad_oldsize == 0 ||
11232 		    listadp->ad_oldsize == bsize)
11233 			continue;
11234 		/* hit a fragment */
11235 		return;
11236 	}
11237 	/*
11238 	 * If we have reached the end of the current list without
11239 	 * finding the just finished dependency, then it must be
11240 	 * on the future dependency list. Future dependencies cannot
11241 	 * be freed until they are moved to the current list.
11242 	 */
11243 	if (listadp == NULL) {
11244 #ifdef INVARIANTS
11245 		if (adp->ad_state & EXTDATA)
11246 			listhead = &inodedep->id_newextupdt;
11247 		else
11248 			listhead = &inodedep->id_newinoupdt;
11249 		TAILQ_FOREACH(listadp, listhead, ad_next)
11250 			/* found our block */
11251 			if (listadp == adp)
11252 				break;
11253 		if (listadp == NULL)
11254 			panic("handle_allocdirect_partdone: lost dep");
11255 #endif /* INVARIANTS */
11256 		return;
11257 	}
11258 	/*
11259 	 * If we have found the just finished dependency, then queue
11260 	 * it along with anything that follows it that is complete.
11261 	 * Since the pointer has not yet been written in the inode
11262 	 * as the dependency prevents it, place the allocdirect on the
11263 	 * bufwait list where it will be freed once the pointer is
11264 	 * valid.
11265 	 */
11266 	if (wkhd == NULL)
11267 		wkhd = &inodedep->id_bufwait;
11268 	for (; adp; adp = listadp) {
11269 		listadp = TAILQ_NEXT(adp, ad_next);
11270 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11271 			return;
11272 		TAILQ_REMOVE(listhead, adp, ad_next);
11273 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11274 	}
11275 }
11276 
11277 /*
11278  * Called from within softdep_disk_write_complete above.  This routine
11279  * completes successfully written allocindirs.
11280  */
11281 static void
11282 handle_allocindir_partdone(aip)
11283 	struct allocindir *aip;		/* the completed allocindir */
11284 {
11285 	struct indirdep *indirdep;
11286 
11287 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11288 		return;
11289 	indirdep = aip->ai_indirdep;
11290 	LIST_REMOVE(aip, ai_next);
11291 	/*
11292 	 * Don't set a pointer while the buffer is undergoing IO or while
11293 	 * we have active truncations.
11294 	 */
11295 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11296 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11297 		return;
11298 	}
11299 	if (indirdep->ir_state & UFS1FMT)
11300 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11301 		    aip->ai_newblkno;
11302 	else
11303 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11304 		    aip->ai_newblkno;
11305 	/*
11306 	 * Await the pointer write before freeing the allocindir.
11307 	 */
11308 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11309 }
11310 
11311 /*
11312  * Release segments held on a jwork list.
11313  */
11314 static void
11315 handle_jwork(wkhd)
11316 	struct workhead *wkhd;
11317 {
11318 	struct worklist *wk;
11319 
11320 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11321 		WORKLIST_REMOVE(wk);
11322 		switch (wk->wk_type) {
11323 		case D_JSEGDEP:
11324 			free_jsegdep(WK_JSEGDEP(wk));
11325 			continue;
11326 		case D_FREEDEP:
11327 			free_freedep(WK_FREEDEP(wk));
11328 			continue;
11329 		case D_FREEFRAG:
11330 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11331 			WORKITEM_FREE(wk, D_FREEFRAG);
11332 			continue;
11333 		case D_FREEWORK:
11334 			handle_written_freework(WK_FREEWORK(wk));
11335 			continue;
11336 		default:
11337 			panic("handle_jwork: Unknown type %s\n",
11338 			    TYPENAME(wk->wk_type));
11339 		}
11340 	}
11341 }
11342 
11343 /*
11344  * Handle the bufwait list on an inode when it is safe to release items
11345  * held there.  This normally happens after an inode block is written but
11346  * may be delayed and handled later if there are pending journal items that
11347  * are not yet safe to be released.
11348  */
11349 static struct freefile *
11350 handle_bufwait(inodedep, refhd)
11351 	struct inodedep *inodedep;
11352 	struct workhead *refhd;
11353 {
11354 	struct jaddref *jaddref;
11355 	struct freefile *freefile;
11356 	struct worklist *wk;
11357 
11358 	freefile = NULL;
11359 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11360 		WORKLIST_REMOVE(wk);
11361 		switch (wk->wk_type) {
11362 		case D_FREEFILE:
11363 			/*
11364 			 * We defer adding freefile to the worklist
11365 			 * until all other additions have been made to
11366 			 * ensure that it will be done after all the
11367 			 * old blocks have been freed.
11368 			 */
11369 			if (freefile != NULL)
11370 				panic("handle_bufwait: freefile");
11371 			freefile = WK_FREEFILE(wk);
11372 			continue;
11373 
11374 		case D_MKDIR:
11375 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11376 			continue;
11377 
11378 		case D_DIRADD:
11379 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11380 			continue;
11381 
11382 		case D_FREEFRAG:
11383 			wk->wk_state |= COMPLETE;
11384 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11385 				add_to_worklist(wk, 0);
11386 			continue;
11387 
11388 		case D_DIRREM:
11389 			wk->wk_state |= COMPLETE;
11390 			add_to_worklist(wk, 0);
11391 			continue;
11392 
11393 		case D_ALLOCDIRECT:
11394 		case D_ALLOCINDIR:
11395 			free_newblk(WK_NEWBLK(wk));
11396 			continue;
11397 
11398 		case D_JNEWBLK:
11399 			wk->wk_state |= COMPLETE;
11400 			free_jnewblk(WK_JNEWBLK(wk));
11401 			continue;
11402 
11403 		/*
11404 		 * Save freed journal segments and add references on
11405 		 * the supplied list which will delay their release
11406 		 * until the cg bitmap is cleared on disk.
11407 		 */
11408 		case D_JSEGDEP:
11409 			if (refhd == NULL)
11410 				free_jsegdep(WK_JSEGDEP(wk));
11411 			else
11412 				WORKLIST_INSERT(refhd, wk);
11413 			continue;
11414 
11415 		case D_JADDREF:
11416 			jaddref = WK_JADDREF(wk);
11417 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11418 			    if_deps);
11419 			/*
11420 			 * Transfer any jaddrefs to the list to be freed with
11421 			 * the bitmap if we're handling a removed file.
11422 			 */
11423 			if (refhd == NULL) {
11424 				wk->wk_state |= COMPLETE;
11425 				free_jaddref(jaddref);
11426 			} else
11427 				WORKLIST_INSERT(refhd, wk);
11428 			continue;
11429 
11430 		default:
11431 			panic("handle_bufwait: Unknown type %p(%s)",
11432 			    wk, TYPENAME(wk->wk_type));
11433 			/* NOTREACHED */
11434 		}
11435 	}
11436 	return (freefile);
11437 }
11438 /*
11439  * Called from within softdep_disk_write_complete above to restore
11440  * in-memory inode block contents to their most up-to-date state. Note
11441  * that this routine is always called from interrupt level with further
11442  * interrupts from this device blocked.
11443  *
11444  * If the write did not succeed, we will do all the roll-forward
11445  * operations, but we will not take the actions that will allow its
11446  * dependencies to be processed.
11447  */
11448 static int
11449 handle_written_inodeblock(inodedep, bp, flags)
11450 	struct inodedep *inodedep;
11451 	struct buf *bp;		/* buffer containing the inode block */
11452 	int flags;
11453 {
11454 	struct freefile *freefile;
11455 	struct allocdirect *adp, *nextadp;
11456 	struct ufs1_dinode *dp1 = NULL;
11457 	struct ufs2_dinode *dp2 = NULL;
11458 	struct workhead wkhd;
11459 	int hadchanges, fstype;
11460 	ino_t freelink;
11461 
11462 	LIST_INIT(&wkhd);
11463 	hadchanges = 0;
11464 	freefile = NULL;
11465 	if ((inodedep->id_state & IOSTARTED) == 0)
11466 		panic("handle_written_inodeblock: not started");
11467 	inodedep->id_state &= ~IOSTARTED;
11468 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11469 		fstype = UFS1;
11470 		dp1 = (struct ufs1_dinode *)bp->b_data +
11471 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11472 		freelink = dp1->di_freelink;
11473 	} else {
11474 		fstype = UFS2;
11475 		dp2 = (struct ufs2_dinode *)bp->b_data +
11476 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11477 		freelink = dp2->di_freelink;
11478 	}
11479 	/*
11480 	 * Leave this inodeblock dirty until it's in the list.
11481 	 */
11482 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11483 	    (flags & WRITESUCCEEDED)) {
11484 		struct inodedep *inon;
11485 
11486 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11487 		if ((inon == NULL && freelink == 0) ||
11488 		    (inon && inon->id_ino == freelink)) {
11489 			if (inon)
11490 				inon->id_state |= UNLINKPREV;
11491 			inodedep->id_state |= UNLINKNEXT;
11492 		}
11493 		hadchanges = 1;
11494 	}
11495 	/*
11496 	 * If we had to rollback the inode allocation because of
11497 	 * bitmaps being incomplete, then simply restore it.
11498 	 * Keep the block dirty so that it will not be reclaimed until
11499 	 * all associated dependencies have been cleared and the
11500 	 * corresponding updates written to disk.
11501 	 */
11502 	if (inodedep->id_savedino1 != NULL) {
11503 		hadchanges = 1;
11504 		if (fstype == UFS1)
11505 			*dp1 = *inodedep->id_savedino1;
11506 		else
11507 			*dp2 = *inodedep->id_savedino2;
11508 		free(inodedep->id_savedino1, M_SAVEDINO);
11509 		inodedep->id_savedino1 = NULL;
11510 		if ((bp->b_flags & B_DELWRI) == 0)
11511 			stat_inode_bitmap++;
11512 		bdirty(bp);
11513 		/*
11514 		 * If the inode is clear here and GOINGAWAY it will never
11515 		 * be written.  Process the bufwait and clear any pending
11516 		 * work which may include the freefile.
11517 		 */
11518 		if (inodedep->id_state & GOINGAWAY)
11519 			goto bufwait;
11520 		return (1);
11521 	}
11522 	if (flags & WRITESUCCEEDED)
11523 		inodedep->id_state |= COMPLETE;
11524 	/*
11525 	 * Roll forward anything that had to be rolled back before
11526 	 * the inode could be updated.
11527 	 */
11528 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11529 		nextadp = TAILQ_NEXT(adp, ad_next);
11530 		if (adp->ad_state & ATTACHED)
11531 			panic("handle_written_inodeblock: new entry");
11532 		if (fstype == UFS1) {
11533 			if (adp->ad_offset < UFS_NDADDR) {
11534 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11535 					panic("%s %s #%jd mismatch %d != %jd",
11536 					    "handle_written_inodeblock:",
11537 					    "direct pointer",
11538 					    (intmax_t)adp->ad_offset,
11539 					    dp1->di_db[adp->ad_offset],
11540 					    (intmax_t)adp->ad_oldblkno);
11541 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11542 			} else {
11543 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11544 				    0)
11545 					panic("%s: %s #%jd allocated as %d",
11546 					    "handle_written_inodeblock",
11547 					    "indirect pointer",
11548 					    (intmax_t)adp->ad_offset -
11549 					    UFS_NDADDR,
11550 					    dp1->di_ib[adp->ad_offset -
11551 					    UFS_NDADDR]);
11552 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11553 				    adp->ad_newblkno;
11554 			}
11555 		} else {
11556 			if (adp->ad_offset < UFS_NDADDR) {
11557 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11558 					panic("%s: %s #%jd %s %jd != %jd",
11559 					    "handle_written_inodeblock",
11560 					    "direct pointer",
11561 					    (intmax_t)adp->ad_offset, "mismatch",
11562 					    (intmax_t)dp2->di_db[adp->ad_offset],
11563 					    (intmax_t)adp->ad_oldblkno);
11564 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11565 			} else {
11566 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11567 				    0)
11568 					panic("%s: %s #%jd allocated as %jd",
11569 					    "handle_written_inodeblock",
11570 					    "indirect pointer",
11571 					    (intmax_t)adp->ad_offset -
11572 					    UFS_NDADDR,
11573 					    (intmax_t)
11574 					    dp2->di_ib[adp->ad_offset -
11575 					    UFS_NDADDR]);
11576 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11577 				    adp->ad_newblkno;
11578 			}
11579 		}
11580 		adp->ad_state &= ~UNDONE;
11581 		adp->ad_state |= ATTACHED;
11582 		hadchanges = 1;
11583 	}
11584 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11585 		nextadp = TAILQ_NEXT(adp, ad_next);
11586 		if (adp->ad_state & ATTACHED)
11587 			panic("handle_written_inodeblock: new entry");
11588 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11589 			panic("%s: direct pointers #%jd %s %jd != %jd",
11590 			    "handle_written_inodeblock",
11591 			    (intmax_t)adp->ad_offset, "mismatch",
11592 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11593 			    (intmax_t)adp->ad_oldblkno);
11594 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11595 		adp->ad_state &= ~UNDONE;
11596 		adp->ad_state |= ATTACHED;
11597 		hadchanges = 1;
11598 	}
11599 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11600 		stat_direct_blk_ptrs++;
11601 	/*
11602 	 * Reset the file size to its most up-to-date value.
11603 	 */
11604 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11605 		panic("handle_written_inodeblock: bad size");
11606 	if (inodedep->id_savednlink > UFS_LINK_MAX)
11607 		panic("handle_written_inodeblock: Invalid link count "
11608 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11609 		    inodedep);
11610 	if (fstype == UFS1) {
11611 		if (dp1->di_nlink != inodedep->id_savednlink) {
11612 			dp1->di_nlink = inodedep->id_savednlink;
11613 			hadchanges = 1;
11614 		}
11615 		if (dp1->di_size != inodedep->id_savedsize) {
11616 			dp1->di_size = inodedep->id_savedsize;
11617 			hadchanges = 1;
11618 		}
11619 	} else {
11620 		if (dp2->di_nlink != inodedep->id_savednlink) {
11621 			dp2->di_nlink = inodedep->id_savednlink;
11622 			hadchanges = 1;
11623 		}
11624 		if (dp2->di_size != inodedep->id_savedsize) {
11625 			dp2->di_size = inodedep->id_savedsize;
11626 			hadchanges = 1;
11627 		}
11628 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11629 			dp2->di_extsize = inodedep->id_savedextsize;
11630 			hadchanges = 1;
11631 		}
11632 	}
11633 	inodedep->id_savedsize = -1;
11634 	inodedep->id_savedextsize = -1;
11635 	inodedep->id_savednlink = -1;
11636 	/*
11637 	 * If there were any rollbacks in the inode block, then it must be
11638 	 * marked dirty so that its will eventually get written back in
11639 	 * its correct form.
11640 	 */
11641 	if (hadchanges) {
11642 		if (fstype == UFS2)
11643 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11644 		bdirty(bp);
11645 	}
11646 bufwait:
11647 	/*
11648 	 * If the write did not succeed, we have done all the roll-forward
11649 	 * operations, but we cannot take the actions that will allow its
11650 	 * dependencies to be processed.
11651 	 */
11652 	if ((flags & WRITESUCCEEDED) == 0)
11653 		return (hadchanges);
11654 	/*
11655 	 * Process any allocdirects that completed during the update.
11656 	 */
11657 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11658 		handle_allocdirect_partdone(adp, &wkhd);
11659 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11660 		handle_allocdirect_partdone(adp, &wkhd);
11661 	/*
11662 	 * Process deallocations that were held pending until the
11663 	 * inode had been written to disk. Freeing of the inode
11664 	 * is delayed until after all blocks have been freed to
11665 	 * avoid creation of new <vfsid, inum, lbn> triples
11666 	 * before the old ones have been deleted.  Completely
11667 	 * unlinked inodes are not processed until the unlinked
11668 	 * inode list is written or the last reference is removed.
11669 	 */
11670 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11671 		freefile = handle_bufwait(inodedep, NULL);
11672 		if (freefile && !LIST_EMPTY(&wkhd)) {
11673 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11674 			freefile = NULL;
11675 		}
11676 	}
11677 	/*
11678 	 * Move rolled forward dependency completions to the bufwait list
11679 	 * now that those that were already written have been processed.
11680 	 */
11681 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11682 		panic("handle_written_inodeblock: bufwait but no changes");
11683 	jwork_move(&inodedep->id_bufwait, &wkhd);
11684 
11685 	if (freefile != NULL) {
11686 		/*
11687 		 * If the inode is goingaway it was never written.  Fake up
11688 		 * the state here so free_inodedep() can succeed.
11689 		 */
11690 		if (inodedep->id_state & GOINGAWAY)
11691 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11692 		if (free_inodedep(inodedep) == 0)
11693 			panic("handle_written_inodeblock: live inodedep %p",
11694 			    inodedep);
11695 		add_to_worklist(&freefile->fx_list, 0);
11696 		return (0);
11697 	}
11698 
11699 	/*
11700 	 * If no outstanding dependencies, free it.
11701 	 */
11702 	if (free_inodedep(inodedep) ||
11703 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11704 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11705 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11706 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11707 		return (0);
11708 	return (hadchanges);
11709 }
11710 
11711 /*
11712  * Perform needed roll-forwards and kick off any dependencies that
11713  * can now be processed.
11714  *
11715  * If the write did not succeed, we will do all the roll-forward
11716  * operations, but we will not take the actions that will allow its
11717  * dependencies to be processed.
11718  */
11719 static int
11720 handle_written_indirdep(indirdep, bp, bpp, flags)
11721 	struct indirdep *indirdep;
11722 	struct buf *bp;
11723 	struct buf **bpp;
11724 	int flags;
11725 {
11726 	struct allocindir *aip;
11727 	struct buf *sbp;
11728 	int chgs;
11729 
11730 	if (indirdep->ir_state & GOINGAWAY)
11731 		panic("handle_written_indirdep: indirdep gone");
11732 	if ((indirdep->ir_state & IOSTARTED) == 0)
11733 		panic("handle_written_indirdep: IO not started");
11734 	chgs = 0;
11735 	/*
11736 	 * If there were rollbacks revert them here.
11737 	 */
11738 	if (indirdep->ir_saveddata) {
11739 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11740 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11741 			free(indirdep->ir_saveddata, M_INDIRDEP);
11742 			indirdep->ir_saveddata = NULL;
11743 		}
11744 		chgs = 1;
11745 	}
11746 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11747 	indirdep->ir_state |= ATTACHED;
11748 	/*
11749 	 * If the write did not succeed, we have done all the roll-forward
11750 	 * operations, but we cannot take the actions that will allow its
11751 	 * dependencies to be processed.
11752 	 */
11753 	if ((flags & WRITESUCCEEDED) == 0) {
11754 		stat_indir_blk_ptrs++;
11755 		bdirty(bp);
11756 		return (1);
11757 	}
11758 	/*
11759 	 * Move allocindirs with written pointers to the completehd if
11760 	 * the indirdep's pointer is not yet written.  Otherwise
11761 	 * free them here.
11762 	 */
11763 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11764 		LIST_REMOVE(aip, ai_next);
11765 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11766 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11767 			    ai_next);
11768 			newblk_freefrag(&aip->ai_block);
11769 			continue;
11770 		}
11771 		free_newblk(&aip->ai_block);
11772 	}
11773 	/*
11774 	 * Move allocindirs that have finished dependency processing from
11775 	 * the done list to the write list after updating the pointers.
11776 	 */
11777 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11778 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11779 			handle_allocindir_partdone(aip);
11780 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11781 				panic("disk_write_complete: not gone");
11782 			chgs = 1;
11783 		}
11784 	}
11785 	/*
11786 	 * Preserve the indirdep if there were any changes or if it is not
11787 	 * yet valid on disk.
11788 	 */
11789 	if (chgs) {
11790 		stat_indir_blk_ptrs++;
11791 		bdirty(bp);
11792 		return (1);
11793 	}
11794 	/*
11795 	 * If there were no changes we can discard the savedbp and detach
11796 	 * ourselves from the buf.  We are only carrying completed pointers
11797 	 * in this case.
11798 	 */
11799 	sbp = indirdep->ir_savebp;
11800 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11801 	indirdep->ir_savebp = NULL;
11802 	indirdep->ir_bp = NULL;
11803 	if (*bpp != NULL)
11804 		panic("handle_written_indirdep: bp already exists.");
11805 	*bpp = sbp;
11806 	/*
11807 	 * The indirdep may not be freed until its parent points at it.
11808 	 */
11809 	if (indirdep->ir_state & DEPCOMPLETE)
11810 		free_indirdep(indirdep);
11811 
11812 	return (0);
11813 }
11814 
11815 /*
11816  * Process a diradd entry after its dependent inode has been written.
11817  */
11818 static void
11819 diradd_inode_written(dap, inodedep)
11820 	struct diradd *dap;
11821 	struct inodedep *inodedep;
11822 {
11823 
11824 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
11825 	dap->da_state |= COMPLETE;
11826 	complete_diradd(dap);
11827 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11828 }
11829 
11830 /*
11831  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11832  * be called with the per-filesystem lock and the buf lock on the cg held.
11833  */
11834 static int
11835 bmsafemap_backgroundwrite(bmsafemap, bp)
11836 	struct bmsafemap *bmsafemap;
11837 	struct buf *bp;
11838 {
11839 	int dirty;
11840 
11841 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11842 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11843 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11844 	/*
11845 	 * If we're initiating a background write we need to process the
11846 	 * rollbacks as they exist now, not as they exist when IO starts.
11847 	 * No other consumers will look at the contents of the shadowed
11848 	 * buf so this is safe to do here.
11849 	 */
11850 	if (bp->b_xflags & BX_BKGRDMARKER)
11851 		initiate_write_bmsafemap(bmsafemap, bp);
11852 
11853 	return (dirty);
11854 }
11855 
11856 /*
11857  * Re-apply an allocation when a cg write is complete.
11858  */
11859 static int
11860 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11861 	struct jnewblk *jnewblk;
11862 	struct fs *fs;
11863 	struct cg *cgp;
11864 	uint8_t *blksfree;
11865 {
11866 	ufs1_daddr_t fragno;
11867 	ufs2_daddr_t blkno;
11868 	long cgbno, bbase;
11869 	int frags, blk;
11870 	int i;
11871 
11872 	frags = 0;
11873 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11874 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11875 		if (isclr(blksfree, cgbno + i))
11876 			panic("jnewblk_rollforward: re-allocated fragment");
11877 		frags++;
11878 	}
11879 	if (frags == fs->fs_frag) {
11880 		blkno = fragstoblks(fs, cgbno);
11881 		ffs_clrblock(fs, blksfree, (long)blkno);
11882 		ffs_clusteracct(fs, cgp, blkno, -1);
11883 		cgp->cg_cs.cs_nbfree--;
11884 	} else {
11885 		bbase = cgbno - fragnum(fs, cgbno);
11886 		cgbno += jnewblk->jn_oldfrags;
11887                 /* If a complete block had been reassembled, account for it. */
11888 		fragno = fragstoblks(fs, bbase);
11889 		if (ffs_isblock(fs, blksfree, fragno)) {
11890 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11891 			ffs_clusteracct(fs, cgp, fragno, -1);
11892 			cgp->cg_cs.cs_nbfree--;
11893 		}
11894 		/* Decrement the old frags.  */
11895 		blk = blkmap(fs, blksfree, bbase);
11896 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11897 		/* Allocate the fragment */
11898 		for (i = 0; i < frags; i++)
11899 			clrbit(blksfree, cgbno + i);
11900 		cgp->cg_cs.cs_nffree -= frags;
11901 		/* Add back in counts associated with the new frags */
11902 		blk = blkmap(fs, blksfree, bbase);
11903 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11904 	}
11905 	return (frags);
11906 }
11907 
11908 /*
11909  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11910  * changes if it's not a background write.  Set all written dependencies
11911  * to DEPCOMPLETE and free the structure if possible.
11912  *
11913  * If the write did not succeed, we will do all the roll-forward
11914  * operations, but we will not take the actions that will allow its
11915  * dependencies to be processed.
11916  */
11917 static int
11918 handle_written_bmsafemap(bmsafemap, bp, flags)
11919 	struct bmsafemap *bmsafemap;
11920 	struct buf *bp;
11921 	int flags;
11922 {
11923 	struct newblk *newblk;
11924 	struct inodedep *inodedep;
11925 	struct jaddref *jaddref, *jatmp;
11926 	struct jnewblk *jnewblk, *jntmp;
11927 	struct ufsmount *ump;
11928 	uint8_t *inosused;
11929 	uint8_t *blksfree;
11930 	struct cg *cgp;
11931 	struct fs *fs;
11932 	ino_t ino;
11933 	int foreground;
11934 	int chgs;
11935 
11936 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11937 		panic("handle_written_bmsafemap: Not started\n");
11938 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11939 	chgs = 0;
11940 	bmsafemap->sm_state &= ~IOSTARTED;
11941 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11942 	/*
11943 	 * If write was successful, release journal work that was waiting
11944 	 * on the write. Otherwise move the work back.
11945 	 */
11946 	if (flags & WRITESUCCEEDED)
11947 		handle_jwork(&bmsafemap->sm_freewr);
11948 	else
11949 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11950 		    worklist, wk_list);
11951 
11952 	/*
11953 	 * Restore unwritten inode allocation pending jaddref writes.
11954 	 */
11955 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11956 		cgp = (struct cg *)bp->b_data;
11957 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11958 		inosused = cg_inosused(cgp);
11959 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11960 		    ja_bmdeps, jatmp) {
11961 			if ((jaddref->ja_state & UNDONE) == 0)
11962 				continue;
11963 			ino = jaddref->ja_ino % fs->fs_ipg;
11964 			if (isset(inosused, ino))
11965 				panic("handle_written_bmsafemap: "
11966 				    "re-allocated inode");
11967 			/* Do the roll-forward only if it's a real copy. */
11968 			if (foreground) {
11969 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11970 					cgp->cg_cs.cs_ndir++;
11971 				cgp->cg_cs.cs_nifree--;
11972 				setbit(inosused, ino);
11973 				chgs = 1;
11974 			}
11975 			jaddref->ja_state &= ~UNDONE;
11976 			jaddref->ja_state |= ATTACHED;
11977 			free_jaddref(jaddref);
11978 		}
11979 	}
11980 	/*
11981 	 * Restore any block allocations which are pending journal writes.
11982 	 */
11983 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11984 		cgp = (struct cg *)bp->b_data;
11985 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11986 		blksfree = cg_blksfree(cgp);
11987 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11988 		    jntmp) {
11989 			if ((jnewblk->jn_state & UNDONE) == 0)
11990 				continue;
11991 			/* Do the roll-forward only if it's a real copy. */
11992 			if (foreground &&
11993 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11994 				chgs = 1;
11995 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11996 			jnewblk->jn_state |= ATTACHED;
11997 			free_jnewblk(jnewblk);
11998 		}
11999 	}
12000 	/*
12001 	 * If the write did not succeed, we have done all the roll-forward
12002 	 * operations, but we cannot take the actions that will allow its
12003 	 * dependencies to be processed.
12004 	 */
12005 	if ((flags & WRITESUCCEEDED) == 0) {
12006 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12007 		    newblk, nb_deps);
12008 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12009 		    worklist, wk_list);
12010 		if (foreground)
12011 			bdirty(bp);
12012 		return (1);
12013 	}
12014 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12015 		newblk->nb_state |= DEPCOMPLETE;
12016 		newblk->nb_state &= ~ONDEPLIST;
12017 		newblk->nb_bmsafemap = NULL;
12018 		LIST_REMOVE(newblk, nb_deps);
12019 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12020 			handle_allocdirect_partdone(
12021 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12022 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12023 			handle_allocindir_partdone(
12024 			    WK_ALLOCINDIR(&newblk->nb_list));
12025 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12026 			panic("handle_written_bmsafemap: Unexpected type: %s",
12027 			    TYPENAME(newblk->nb_list.wk_type));
12028 	}
12029 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12030 		inodedep->id_state |= DEPCOMPLETE;
12031 		inodedep->id_state &= ~ONDEPLIST;
12032 		LIST_REMOVE(inodedep, id_deps);
12033 		inodedep->id_bmsafemap = NULL;
12034 	}
12035 	LIST_REMOVE(bmsafemap, sm_next);
12036 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12037 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12038 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12039 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12040 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12041 		LIST_REMOVE(bmsafemap, sm_hash);
12042 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12043 		return (0);
12044 	}
12045 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12046 	if (foreground)
12047 		bdirty(bp);
12048 	return (1);
12049 }
12050 
12051 /*
12052  * Try to free a mkdir dependency.
12053  */
12054 static void
12055 complete_mkdir(mkdir)
12056 	struct mkdir *mkdir;
12057 {
12058 	struct diradd *dap;
12059 
12060 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12061 		return;
12062 	LIST_REMOVE(mkdir, md_mkdirs);
12063 	dap = mkdir->md_diradd;
12064 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12065 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12066 		dap->da_state |= DEPCOMPLETE;
12067 		complete_diradd(dap);
12068 	}
12069 	WORKITEM_FREE(mkdir, D_MKDIR);
12070 }
12071 
12072 /*
12073  * Handle the completion of a mkdir dependency.
12074  */
12075 static void
12076 handle_written_mkdir(mkdir, type)
12077 	struct mkdir *mkdir;
12078 	int type;
12079 {
12080 
12081 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12082 		panic("handle_written_mkdir: bad type");
12083 	mkdir->md_state |= COMPLETE;
12084 	complete_mkdir(mkdir);
12085 }
12086 
12087 static int
12088 free_pagedep(pagedep)
12089 	struct pagedep *pagedep;
12090 {
12091 	int i;
12092 
12093 	if (pagedep->pd_state & NEWBLOCK)
12094 		return (0);
12095 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12096 		return (0);
12097 	for (i = 0; i < DAHASHSZ; i++)
12098 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12099 			return (0);
12100 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12101 		return (0);
12102 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12103 		return (0);
12104 	if (pagedep->pd_state & ONWORKLIST)
12105 		WORKLIST_REMOVE(&pagedep->pd_list);
12106 	LIST_REMOVE(pagedep, pd_hash);
12107 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12108 
12109 	return (1);
12110 }
12111 
12112 /*
12113  * Called from within softdep_disk_write_complete above.
12114  * A write operation was just completed. Removed inodes can
12115  * now be freed and associated block pointers may be committed.
12116  * Note that this routine is always called from interrupt level
12117  * with further interrupts from this device blocked.
12118  *
12119  * If the write did not succeed, we will do all the roll-forward
12120  * operations, but we will not take the actions that will allow its
12121  * dependencies to be processed.
12122  */
12123 static int
12124 handle_written_filepage(pagedep, bp, flags)
12125 	struct pagedep *pagedep;
12126 	struct buf *bp;		/* buffer containing the written page */
12127 	int flags;
12128 {
12129 	struct dirrem *dirrem;
12130 	struct diradd *dap, *nextdap;
12131 	struct direct *ep;
12132 	int i, chgs;
12133 
12134 	if ((pagedep->pd_state & IOSTARTED) == 0)
12135 		panic("handle_written_filepage: not started");
12136 	pagedep->pd_state &= ~IOSTARTED;
12137 	if ((flags & WRITESUCCEEDED) == 0)
12138 		goto rollforward;
12139 	/*
12140 	 * Process any directory removals that have been committed.
12141 	 */
12142 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12143 		LIST_REMOVE(dirrem, dm_next);
12144 		dirrem->dm_state |= COMPLETE;
12145 		dirrem->dm_dirinum = pagedep->pd_ino;
12146 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12147 		    ("handle_written_filepage: Journal entries not written."));
12148 		add_to_worklist(&dirrem->dm_list, 0);
12149 	}
12150 	/*
12151 	 * Free any directory additions that have been committed.
12152 	 * If it is a newly allocated block, we have to wait until
12153 	 * the on-disk directory inode claims the new block.
12154 	 */
12155 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12156 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12157 			free_diradd(dap, NULL);
12158 rollforward:
12159 	/*
12160 	 * Uncommitted directory entries must be restored.
12161 	 */
12162 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12163 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12164 		     dap = nextdap) {
12165 			nextdap = LIST_NEXT(dap, da_pdlist);
12166 			if (dap->da_state & ATTACHED)
12167 				panic("handle_written_filepage: attached");
12168 			ep = (struct direct *)
12169 			    ((char *)bp->b_data + dap->da_offset);
12170 			ep->d_ino = dap->da_newinum;
12171 			dap->da_state &= ~UNDONE;
12172 			dap->da_state |= ATTACHED;
12173 			chgs = 1;
12174 			/*
12175 			 * If the inode referenced by the directory has
12176 			 * been written out, then the dependency can be
12177 			 * moved to the pending list.
12178 			 */
12179 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12180 				LIST_REMOVE(dap, da_pdlist);
12181 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12182 				    da_pdlist);
12183 			}
12184 		}
12185 	}
12186 	/*
12187 	 * If there were any rollbacks in the directory, then it must be
12188 	 * marked dirty so that its will eventually get written back in
12189 	 * its correct form.
12190 	 */
12191 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12192 		if ((bp->b_flags & B_DELWRI) == 0)
12193 			stat_dir_entry++;
12194 		bdirty(bp);
12195 		return (1);
12196 	}
12197 	/*
12198 	 * If we are not waiting for a new directory block to be
12199 	 * claimed by its inode, then the pagedep will be freed.
12200 	 * Otherwise it will remain to track any new entries on
12201 	 * the page in case they are fsync'ed.
12202 	 */
12203 	free_pagedep(pagedep);
12204 	return (0);
12205 }
12206 
12207 /*
12208  * Writing back in-core inode structures.
12209  *
12210  * The filesystem only accesses an inode's contents when it occupies an
12211  * "in-core" inode structure.  These "in-core" structures are separate from
12212  * the page frames used to cache inode blocks.  Only the latter are
12213  * transferred to/from the disk.  So, when the updated contents of the
12214  * "in-core" inode structure are copied to the corresponding in-memory inode
12215  * block, the dependencies are also transferred.  The following procedure is
12216  * called when copying a dirty "in-core" inode to a cached inode block.
12217  */
12218 
12219 /*
12220  * Called when an inode is loaded from disk. If the effective link count
12221  * differed from the actual link count when it was last flushed, then we
12222  * need to ensure that the correct effective link count is put back.
12223  */
12224 void
12225 softdep_load_inodeblock(ip)
12226 	struct inode *ip;	/* the "in_core" copy of the inode */
12227 {
12228 	struct inodedep *inodedep;
12229 	struct ufsmount *ump;
12230 
12231 	ump = ITOUMP(ip);
12232 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12233 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12234 	/*
12235 	 * Check for alternate nlink count.
12236 	 */
12237 	ip->i_effnlink = ip->i_nlink;
12238 	ACQUIRE_LOCK(ump);
12239 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12240 		FREE_LOCK(ump);
12241 		return;
12242 	}
12243 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12244 	FREE_LOCK(ump);
12245 }
12246 
12247 /*
12248  * This routine is called just before the "in-core" inode
12249  * information is to be copied to the in-memory inode block.
12250  * Recall that an inode block contains several inodes. If
12251  * the force flag is set, then the dependencies will be
12252  * cleared so that the update can always be made. Note that
12253  * the buffer is locked when this routine is called, so we
12254  * will never be in the middle of writing the inode block
12255  * to disk.
12256  */
12257 void
12258 softdep_update_inodeblock(ip, bp, waitfor)
12259 	struct inode *ip;	/* the "in_core" copy of the inode */
12260 	struct buf *bp;		/* the buffer containing the inode block */
12261 	int waitfor;		/* nonzero => update must be allowed */
12262 {
12263 	struct inodedep *inodedep;
12264 	struct inoref *inoref;
12265 	struct ufsmount *ump;
12266 	struct worklist *wk;
12267 	struct mount *mp;
12268 	struct buf *ibp;
12269 	struct fs *fs;
12270 	int error;
12271 
12272 	ump = ITOUMP(ip);
12273 	mp = UFSTOVFS(ump);
12274 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12275 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12276 	fs = ump->um_fs;
12277 	/*
12278 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12279 	 * does not have access to the in-core ip so must write directly into
12280 	 * the inode block buffer when setting freelink.
12281 	 */
12282 	if (fs->fs_magic == FS_UFS1_MAGIC)
12283 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12284 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12285 	else
12286 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12287 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12288 	/*
12289 	 * If the effective link count is not equal to the actual link
12290 	 * count, then we must track the difference in an inodedep while
12291 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12292 	 * if there is no existing inodedep, then there are no dependencies
12293 	 * to track.
12294 	 */
12295 	ACQUIRE_LOCK(ump);
12296 again:
12297 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12298 		FREE_LOCK(ump);
12299 		if (ip->i_effnlink != ip->i_nlink)
12300 			panic("softdep_update_inodeblock: bad link count");
12301 		return;
12302 	}
12303 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12304 		panic("softdep_update_inodeblock: bad delta");
12305 	/*
12306 	 * If we're flushing all dependencies we must also move any waiting
12307 	 * for journal writes onto the bufwait list prior to I/O.
12308 	 */
12309 	if (waitfor) {
12310 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12311 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12312 			    == DEPCOMPLETE) {
12313 				jwait(&inoref->if_list, MNT_WAIT);
12314 				goto again;
12315 			}
12316 		}
12317 	}
12318 	/*
12319 	 * Changes have been initiated. Anything depending on these
12320 	 * changes cannot occur until this inode has been written.
12321 	 */
12322 	inodedep->id_state &= ~COMPLETE;
12323 	if ((inodedep->id_state & ONWORKLIST) == 0)
12324 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12325 	/*
12326 	 * Any new dependencies associated with the incore inode must
12327 	 * now be moved to the list associated with the buffer holding
12328 	 * the in-memory copy of the inode. Once merged process any
12329 	 * allocdirects that are completed by the merger.
12330 	 */
12331 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12332 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12333 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12334 		    NULL);
12335 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12336 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12337 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12338 		    NULL);
12339 	/*
12340 	 * Now that the inode has been pushed into the buffer, the
12341 	 * operations dependent on the inode being written to disk
12342 	 * can be moved to the id_bufwait so that they will be
12343 	 * processed when the buffer I/O completes.
12344 	 */
12345 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12346 		WORKLIST_REMOVE(wk);
12347 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12348 	}
12349 	/*
12350 	 * Newly allocated inodes cannot be written until the bitmap
12351 	 * that allocates them have been written (indicated by
12352 	 * DEPCOMPLETE being set in id_state). If we are doing a
12353 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12354 	 * to be written so that the update can be done.
12355 	 */
12356 	if (waitfor == 0) {
12357 		FREE_LOCK(ump);
12358 		return;
12359 	}
12360 retry:
12361 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12362 		FREE_LOCK(ump);
12363 		return;
12364 	}
12365 	ibp = inodedep->id_bmsafemap->sm_buf;
12366 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12367 	if (ibp == NULL) {
12368 		/*
12369 		 * If ibp came back as NULL, the dependency could have been
12370 		 * freed while we slept.  Look it up again, and check to see
12371 		 * that it has completed.
12372 		 */
12373 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12374 			goto retry;
12375 		FREE_LOCK(ump);
12376 		return;
12377 	}
12378 	FREE_LOCK(ump);
12379 	if ((error = bwrite(ibp)) != 0)
12380 		softdep_error("softdep_update_inodeblock: bwrite", error);
12381 }
12382 
12383 /*
12384  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12385  * old inode dependency list (such as id_inoupdt).
12386  */
12387 static void
12388 merge_inode_lists(newlisthead, oldlisthead)
12389 	struct allocdirectlst *newlisthead;
12390 	struct allocdirectlst *oldlisthead;
12391 {
12392 	struct allocdirect *listadp, *newadp;
12393 
12394 	newadp = TAILQ_FIRST(newlisthead);
12395 	if (newadp != NULL)
12396 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12397 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12398 		if (listadp->ad_offset < newadp->ad_offset) {
12399 			listadp = TAILQ_NEXT(listadp, ad_next);
12400 			continue;
12401 		}
12402 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12403 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12404 		if (listadp->ad_offset == newadp->ad_offset) {
12405 			allocdirect_merge(oldlisthead, newadp,
12406 			    listadp);
12407 			listadp = newadp;
12408 		}
12409 		newadp = TAILQ_FIRST(newlisthead);
12410 	}
12411 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12412 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12413 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12414 	}
12415 }
12416 
12417 /*
12418  * If we are doing an fsync, then we must ensure that any directory
12419  * entries for the inode have been written after the inode gets to disk.
12420  */
12421 int
12422 softdep_fsync(vp)
12423 	struct vnode *vp;	/* the "in_core" copy of the inode */
12424 {
12425 	struct inodedep *inodedep;
12426 	struct pagedep *pagedep;
12427 	struct inoref *inoref;
12428 	struct ufsmount *ump;
12429 	struct worklist *wk;
12430 	struct diradd *dap;
12431 	struct mount *mp;
12432 	struct vnode *pvp;
12433 	struct inode *ip;
12434 	struct buf *bp;
12435 	struct fs *fs;
12436 	struct thread *td = curthread;
12437 	int error, flushparent, pagedep_new_block;
12438 	ino_t parentino;
12439 	ufs_lbn_t lbn;
12440 
12441 	ip = VTOI(vp);
12442 	mp = vp->v_mount;
12443 	ump = VFSTOUFS(mp);
12444 	fs = ump->um_fs;
12445 	if (MOUNTEDSOFTDEP(mp) == 0)
12446 		return (0);
12447 	ACQUIRE_LOCK(ump);
12448 restart:
12449 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12450 		FREE_LOCK(ump);
12451 		return (0);
12452 	}
12453 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12454 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12455 		    == DEPCOMPLETE) {
12456 			jwait(&inoref->if_list, MNT_WAIT);
12457 			goto restart;
12458 		}
12459 	}
12460 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12461 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12462 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12463 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12464 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12465 		panic("softdep_fsync: pending ops %p", inodedep);
12466 	for (error = 0, flushparent = 0; ; ) {
12467 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12468 			break;
12469 		if (wk->wk_type != D_DIRADD)
12470 			panic("softdep_fsync: Unexpected type %s",
12471 			    TYPENAME(wk->wk_type));
12472 		dap = WK_DIRADD(wk);
12473 		/*
12474 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12475 		 * dependency or is contained in a newly allocated block.
12476 		 */
12477 		if (dap->da_state & DIRCHG)
12478 			pagedep = dap->da_previous->dm_pagedep;
12479 		else
12480 			pagedep = dap->da_pagedep;
12481 		parentino = pagedep->pd_ino;
12482 		lbn = pagedep->pd_lbn;
12483 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12484 			panic("softdep_fsync: dirty");
12485 		if ((dap->da_state & MKDIR_PARENT) ||
12486 		    (pagedep->pd_state & NEWBLOCK))
12487 			flushparent = 1;
12488 		else
12489 			flushparent = 0;
12490 		/*
12491 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12492 		 * then we will not be able to release and recover the
12493 		 * vnode below, so we just have to give up on writing its
12494 		 * directory entry out. It will eventually be written, just
12495 		 * not now, but then the user was not asking to have it
12496 		 * written, so we are not breaking any promises.
12497 		 */
12498 		if (vp->v_iflag & VI_DOOMED)
12499 			break;
12500 		/*
12501 		 * We prevent deadlock by always fetching inodes from the
12502 		 * root, moving down the directory tree. Thus, when fetching
12503 		 * our parent directory, we first try to get the lock. If
12504 		 * that fails, we must unlock ourselves before requesting
12505 		 * the lock on our parent. See the comment in ufs_lookup
12506 		 * for details on possible races.
12507 		 */
12508 		FREE_LOCK(ump);
12509 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12510 		    FFSV_FORCEINSMQ)) {
12511 			error = vfs_busy(mp, MBF_NOWAIT);
12512 			if (error != 0) {
12513 				vfs_ref(mp);
12514 				VOP_UNLOCK(vp, 0);
12515 				error = vfs_busy(mp, 0);
12516 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12517 				vfs_rel(mp);
12518 				if (error != 0)
12519 					return (ENOENT);
12520 				if (vp->v_iflag & VI_DOOMED) {
12521 					vfs_unbusy(mp);
12522 					return (ENOENT);
12523 				}
12524 			}
12525 			VOP_UNLOCK(vp, 0);
12526 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12527 			    &pvp, FFSV_FORCEINSMQ);
12528 			vfs_unbusy(mp);
12529 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12530 			if (vp->v_iflag & VI_DOOMED) {
12531 				if (error == 0)
12532 					vput(pvp);
12533 				error = ENOENT;
12534 			}
12535 			if (error != 0)
12536 				return (error);
12537 		}
12538 		/*
12539 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12540 		 * that are contained in direct blocks will be resolved by
12541 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12542 		 * may require a complete sync'ing of the directory. So, we
12543 		 * try the cheap and fast ffs_update first, and if that fails,
12544 		 * then we do the slower ffs_syncvnode of the directory.
12545 		 */
12546 		if (flushparent) {
12547 			int locked;
12548 
12549 			if ((error = ffs_update(pvp, 1)) != 0) {
12550 				vput(pvp);
12551 				return (error);
12552 			}
12553 			ACQUIRE_LOCK(ump);
12554 			locked = 1;
12555 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12556 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12557 					if (wk->wk_type != D_DIRADD)
12558 						panic("softdep_fsync: Unexpected type %s",
12559 						      TYPENAME(wk->wk_type));
12560 					dap = WK_DIRADD(wk);
12561 					if (dap->da_state & DIRCHG)
12562 						pagedep = dap->da_previous->dm_pagedep;
12563 					else
12564 						pagedep = dap->da_pagedep;
12565 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12566 					FREE_LOCK(ump);
12567 					locked = 0;
12568 					if (pagedep_new_block && (error =
12569 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12570 						vput(pvp);
12571 						return (error);
12572 					}
12573 				}
12574 			}
12575 			if (locked)
12576 				FREE_LOCK(ump);
12577 		}
12578 		/*
12579 		 * Flush directory page containing the inode's name.
12580 		 */
12581 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12582 		    &bp);
12583 		if (error == 0)
12584 			error = bwrite(bp);
12585 		else
12586 			brelse(bp);
12587 		vput(pvp);
12588 		if (error != 0)
12589 			return (error);
12590 		ACQUIRE_LOCK(ump);
12591 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12592 			break;
12593 	}
12594 	FREE_LOCK(ump);
12595 	return (0);
12596 }
12597 
12598 /*
12599  * Flush all the dirty bitmaps associated with the block device
12600  * before flushing the rest of the dirty blocks so as to reduce
12601  * the number of dependencies that will have to be rolled back.
12602  *
12603  * XXX Unused?
12604  */
12605 void
12606 softdep_fsync_mountdev(vp)
12607 	struct vnode *vp;
12608 {
12609 	struct buf *bp, *nbp;
12610 	struct worklist *wk;
12611 	struct bufobj *bo;
12612 
12613 	if (!vn_isdisk(vp, NULL))
12614 		panic("softdep_fsync_mountdev: vnode not a disk");
12615 	bo = &vp->v_bufobj;
12616 restart:
12617 	BO_LOCK(bo);
12618 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12619 		/*
12620 		 * If it is already scheduled, skip to the next buffer.
12621 		 */
12622 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12623 			continue;
12624 
12625 		if ((bp->b_flags & B_DELWRI) == 0)
12626 			panic("softdep_fsync_mountdev: not dirty");
12627 		/*
12628 		 * We are only interested in bitmaps with outstanding
12629 		 * dependencies.
12630 		 */
12631 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12632 		    wk->wk_type != D_BMSAFEMAP ||
12633 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12634 			BUF_UNLOCK(bp);
12635 			continue;
12636 		}
12637 		BO_UNLOCK(bo);
12638 		bremfree(bp);
12639 		(void) bawrite(bp);
12640 		goto restart;
12641 	}
12642 	drain_output(vp);
12643 	BO_UNLOCK(bo);
12644 }
12645 
12646 /*
12647  * Sync all cylinder groups that were dirty at the time this function is
12648  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12649  * is used to flush freedep activity that may be holding up writes to a
12650  * indirect block.
12651  */
12652 static int
12653 sync_cgs(mp, waitfor)
12654 	struct mount *mp;
12655 	int waitfor;
12656 {
12657 	struct bmsafemap *bmsafemap;
12658 	struct bmsafemap *sentinel;
12659 	struct ufsmount *ump;
12660 	struct buf *bp;
12661 	int error;
12662 
12663 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12664 	sentinel->sm_cg = -1;
12665 	ump = VFSTOUFS(mp);
12666 	error = 0;
12667 	ACQUIRE_LOCK(ump);
12668 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12669 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12670 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12671 		/* Skip sentinels and cgs with no work to release. */
12672 		if (bmsafemap->sm_cg == -1 ||
12673 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12674 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12675 			LIST_REMOVE(sentinel, sm_next);
12676 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12677 			continue;
12678 		}
12679 		/*
12680 		 * If we don't get the lock and we're waiting try again, if
12681 		 * not move on to the next buf and try to sync it.
12682 		 */
12683 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12684 		if (bp == NULL && waitfor == MNT_WAIT)
12685 			continue;
12686 		LIST_REMOVE(sentinel, sm_next);
12687 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12688 		if (bp == NULL)
12689 			continue;
12690 		FREE_LOCK(ump);
12691 		if (waitfor == MNT_NOWAIT)
12692 			bawrite(bp);
12693 		else
12694 			error = bwrite(bp);
12695 		ACQUIRE_LOCK(ump);
12696 		if (error)
12697 			break;
12698 	}
12699 	LIST_REMOVE(sentinel, sm_next);
12700 	FREE_LOCK(ump);
12701 	free(sentinel, M_BMSAFEMAP);
12702 	return (error);
12703 }
12704 
12705 /*
12706  * This routine is called when we are trying to synchronously flush a
12707  * file. This routine must eliminate any filesystem metadata dependencies
12708  * so that the syncing routine can succeed.
12709  */
12710 int
12711 softdep_sync_metadata(struct vnode *vp)
12712 {
12713 	struct inode *ip;
12714 	int error;
12715 
12716 	ip = VTOI(vp);
12717 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12718 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12719 	/*
12720 	 * Ensure that any direct block dependencies have been cleared,
12721 	 * truncations are started, and inode references are journaled.
12722 	 */
12723 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12724 	/*
12725 	 * Write all journal records to prevent rollbacks on devvp.
12726 	 */
12727 	if (vp->v_type == VCHR)
12728 		softdep_flushjournal(vp->v_mount);
12729 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12730 	/*
12731 	 * Ensure that all truncates are written so we won't find deps on
12732 	 * indirect blocks.
12733 	 */
12734 	process_truncates(vp);
12735 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12736 
12737 	return (error);
12738 }
12739 
12740 /*
12741  * This routine is called when we are attempting to sync a buf with
12742  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12743  * other IO it can but returns EBUSY if the buffer is not yet able to
12744  * be written.  Dependencies which will not cause rollbacks will always
12745  * return 0.
12746  */
12747 int
12748 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12749 {
12750 	struct indirdep *indirdep;
12751 	struct pagedep *pagedep;
12752 	struct allocindir *aip;
12753 	struct newblk *newblk;
12754 	struct ufsmount *ump;
12755 	struct buf *nbp;
12756 	struct worklist *wk;
12757 	int i, error;
12758 
12759 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12760 	    ("softdep_sync_buf called on non-softdep filesystem"));
12761 	/*
12762 	 * For VCHR we just don't want to force flush any dependencies that
12763 	 * will cause rollbacks.
12764 	 */
12765 	if (vp->v_type == VCHR) {
12766 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12767 			return (EBUSY);
12768 		return (0);
12769 	}
12770 	ump = VFSTOUFS(vp->v_mount);
12771 	ACQUIRE_LOCK(ump);
12772 	/*
12773 	 * As we hold the buffer locked, none of its dependencies
12774 	 * will disappear.
12775 	 */
12776 	error = 0;
12777 top:
12778 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12779 		switch (wk->wk_type) {
12780 
12781 		case D_ALLOCDIRECT:
12782 		case D_ALLOCINDIR:
12783 			newblk = WK_NEWBLK(wk);
12784 			if (newblk->nb_jnewblk != NULL) {
12785 				if (waitfor == MNT_NOWAIT) {
12786 					error = EBUSY;
12787 					goto out_unlock;
12788 				}
12789 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12790 				goto top;
12791 			}
12792 			if (newblk->nb_state & DEPCOMPLETE ||
12793 			    waitfor == MNT_NOWAIT)
12794 				continue;
12795 			nbp = newblk->nb_bmsafemap->sm_buf;
12796 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12797 			if (nbp == NULL)
12798 				goto top;
12799 			FREE_LOCK(ump);
12800 			if ((error = bwrite(nbp)) != 0)
12801 				goto out;
12802 			ACQUIRE_LOCK(ump);
12803 			continue;
12804 
12805 		case D_INDIRDEP:
12806 			indirdep = WK_INDIRDEP(wk);
12807 			if (waitfor == MNT_NOWAIT) {
12808 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12809 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12810 					error = EBUSY;
12811 					goto out_unlock;
12812 				}
12813 			}
12814 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12815 				panic("softdep_sync_buf: truncation pending.");
12816 		restart:
12817 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12818 				newblk = (struct newblk *)aip;
12819 				if (newblk->nb_jnewblk != NULL) {
12820 					jwait(&newblk->nb_jnewblk->jn_list,
12821 					    waitfor);
12822 					goto restart;
12823 				}
12824 				if (newblk->nb_state & DEPCOMPLETE)
12825 					continue;
12826 				nbp = newblk->nb_bmsafemap->sm_buf;
12827 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12828 				if (nbp == NULL)
12829 					goto restart;
12830 				FREE_LOCK(ump);
12831 				if ((error = bwrite(nbp)) != 0)
12832 					goto out;
12833 				ACQUIRE_LOCK(ump);
12834 				goto restart;
12835 			}
12836 			continue;
12837 
12838 		case D_PAGEDEP:
12839 			/*
12840 			 * Only flush directory entries in synchronous passes.
12841 			 */
12842 			if (waitfor != MNT_WAIT) {
12843 				error = EBUSY;
12844 				goto out_unlock;
12845 			}
12846 			/*
12847 			 * While syncing snapshots, we must allow recursive
12848 			 * lookups.
12849 			 */
12850 			BUF_AREC(bp);
12851 			/*
12852 			 * We are trying to sync a directory that may
12853 			 * have dependencies on both its own metadata
12854 			 * and/or dependencies on the inodes of any
12855 			 * recently allocated files. We walk its diradd
12856 			 * lists pushing out the associated inode.
12857 			 */
12858 			pagedep = WK_PAGEDEP(wk);
12859 			for (i = 0; i < DAHASHSZ; i++) {
12860 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12861 					continue;
12862 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12863 				    &pagedep->pd_diraddhd[i]))) {
12864 					BUF_NOREC(bp);
12865 					goto out_unlock;
12866 				}
12867 			}
12868 			BUF_NOREC(bp);
12869 			continue;
12870 
12871 		case D_FREEWORK:
12872 		case D_FREEDEP:
12873 		case D_JSEGDEP:
12874 		case D_JNEWBLK:
12875 			continue;
12876 
12877 		default:
12878 			panic("softdep_sync_buf: Unknown type %s",
12879 			    TYPENAME(wk->wk_type));
12880 			/* NOTREACHED */
12881 		}
12882 	}
12883 out_unlock:
12884 	FREE_LOCK(ump);
12885 out:
12886 	return (error);
12887 }
12888 
12889 /*
12890  * Flush the dependencies associated with an inodedep.
12891  */
12892 static int
12893 flush_inodedep_deps(vp, mp, ino)
12894 	struct vnode *vp;
12895 	struct mount *mp;
12896 	ino_t ino;
12897 {
12898 	struct inodedep *inodedep;
12899 	struct inoref *inoref;
12900 	struct ufsmount *ump;
12901 	int error, waitfor;
12902 
12903 	/*
12904 	 * This work is done in two passes. The first pass grabs most
12905 	 * of the buffers and begins asynchronously writing them. The
12906 	 * only way to wait for these asynchronous writes is to sleep
12907 	 * on the filesystem vnode which may stay busy for a long time
12908 	 * if the filesystem is active. So, instead, we make a second
12909 	 * pass over the dependencies blocking on each write. In the
12910 	 * usual case we will be blocking against a write that we
12911 	 * initiated, so when it is done the dependency will have been
12912 	 * resolved. Thus the second pass is expected to end quickly.
12913 	 * We give a brief window at the top of the loop to allow
12914 	 * any pending I/O to complete.
12915 	 */
12916 	ump = VFSTOUFS(mp);
12917 	LOCK_OWNED(ump);
12918 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12919 		if (error)
12920 			return (error);
12921 		FREE_LOCK(ump);
12922 		ACQUIRE_LOCK(ump);
12923 restart:
12924 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12925 			return (0);
12926 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12927 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12928 			    == DEPCOMPLETE) {
12929 				jwait(&inoref->if_list, MNT_WAIT);
12930 				goto restart;
12931 			}
12932 		}
12933 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12934 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12935 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12936 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12937 			continue;
12938 		/*
12939 		 * If pass2, we are done, otherwise do pass 2.
12940 		 */
12941 		if (waitfor == MNT_WAIT)
12942 			break;
12943 		waitfor = MNT_WAIT;
12944 	}
12945 	/*
12946 	 * Try freeing inodedep in case all dependencies have been removed.
12947 	 */
12948 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12949 		(void) free_inodedep(inodedep);
12950 	return (0);
12951 }
12952 
12953 /*
12954  * Flush an inode dependency list.
12955  */
12956 static int
12957 flush_deplist(listhead, waitfor, errorp)
12958 	struct allocdirectlst *listhead;
12959 	int waitfor;
12960 	int *errorp;
12961 {
12962 	struct allocdirect *adp;
12963 	struct newblk *newblk;
12964 	struct ufsmount *ump;
12965 	struct buf *bp;
12966 
12967 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
12968 		return (0);
12969 	ump = VFSTOUFS(adp->ad_list.wk_mp);
12970 	LOCK_OWNED(ump);
12971 	TAILQ_FOREACH(adp, listhead, ad_next) {
12972 		newblk = (struct newblk *)adp;
12973 		if (newblk->nb_jnewblk != NULL) {
12974 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12975 			return (1);
12976 		}
12977 		if (newblk->nb_state & DEPCOMPLETE)
12978 			continue;
12979 		bp = newblk->nb_bmsafemap->sm_buf;
12980 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12981 		if (bp == NULL) {
12982 			if (waitfor == MNT_NOWAIT)
12983 				continue;
12984 			return (1);
12985 		}
12986 		FREE_LOCK(ump);
12987 		if (waitfor == MNT_NOWAIT)
12988 			bawrite(bp);
12989 		else
12990 			*errorp = bwrite(bp);
12991 		ACQUIRE_LOCK(ump);
12992 		return (1);
12993 	}
12994 	return (0);
12995 }
12996 
12997 /*
12998  * Flush dependencies associated with an allocdirect block.
12999  */
13000 static int
13001 flush_newblk_dep(vp, mp, lbn)
13002 	struct vnode *vp;
13003 	struct mount *mp;
13004 	ufs_lbn_t lbn;
13005 {
13006 	struct newblk *newblk;
13007 	struct ufsmount *ump;
13008 	struct bufobj *bo;
13009 	struct inode *ip;
13010 	struct buf *bp;
13011 	ufs2_daddr_t blkno;
13012 	int error;
13013 
13014 	error = 0;
13015 	bo = &vp->v_bufobj;
13016 	ip = VTOI(vp);
13017 	blkno = DIP(ip, i_db[lbn]);
13018 	if (blkno == 0)
13019 		panic("flush_newblk_dep: Missing block");
13020 	ump = VFSTOUFS(mp);
13021 	ACQUIRE_LOCK(ump);
13022 	/*
13023 	 * Loop until all dependencies related to this block are satisfied.
13024 	 * We must be careful to restart after each sleep in case a write
13025 	 * completes some part of this process for us.
13026 	 */
13027 	for (;;) {
13028 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13029 			FREE_LOCK(ump);
13030 			break;
13031 		}
13032 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13033 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13034 		/*
13035 		 * Flush the journal.
13036 		 */
13037 		if (newblk->nb_jnewblk != NULL) {
13038 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13039 			continue;
13040 		}
13041 		/*
13042 		 * Write the bitmap dependency.
13043 		 */
13044 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13045 			bp = newblk->nb_bmsafemap->sm_buf;
13046 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13047 			if (bp == NULL)
13048 				continue;
13049 			FREE_LOCK(ump);
13050 			error = bwrite(bp);
13051 			if (error)
13052 				break;
13053 			ACQUIRE_LOCK(ump);
13054 			continue;
13055 		}
13056 		/*
13057 		 * Write the buffer.
13058 		 */
13059 		FREE_LOCK(ump);
13060 		BO_LOCK(bo);
13061 		bp = gbincore(bo, lbn);
13062 		if (bp != NULL) {
13063 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13064 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13065 			if (error == ENOLCK) {
13066 				ACQUIRE_LOCK(ump);
13067 				error = 0;
13068 				continue; /* Slept, retry */
13069 			}
13070 			if (error != 0)
13071 				break;	/* Failed */
13072 			if (bp->b_flags & B_DELWRI) {
13073 				bremfree(bp);
13074 				error = bwrite(bp);
13075 				if (error)
13076 					break;
13077 			} else
13078 				BUF_UNLOCK(bp);
13079 		} else
13080 			BO_UNLOCK(bo);
13081 		/*
13082 		 * We have to wait for the direct pointers to
13083 		 * point at the newdirblk before the dependency
13084 		 * will go away.
13085 		 */
13086 		error = ffs_update(vp, 1);
13087 		if (error)
13088 			break;
13089 		ACQUIRE_LOCK(ump);
13090 	}
13091 	return (error);
13092 }
13093 
13094 /*
13095  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13096  */
13097 static int
13098 flush_pagedep_deps(pvp, mp, diraddhdp)
13099 	struct vnode *pvp;
13100 	struct mount *mp;
13101 	struct diraddhd *diraddhdp;
13102 {
13103 	struct inodedep *inodedep;
13104 	struct inoref *inoref;
13105 	struct ufsmount *ump;
13106 	struct diradd *dap;
13107 	struct vnode *vp;
13108 	int error = 0;
13109 	struct buf *bp;
13110 	ino_t inum;
13111 	struct diraddhd unfinished;
13112 
13113 	LIST_INIT(&unfinished);
13114 	ump = VFSTOUFS(mp);
13115 	LOCK_OWNED(ump);
13116 restart:
13117 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13118 		/*
13119 		 * Flush ourselves if this directory entry
13120 		 * has a MKDIR_PARENT dependency.
13121 		 */
13122 		if (dap->da_state & MKDIR_PARENT) {
13123 			FREE_LOCK(ump);
13124 			if ((error = ffs_update(pvp, 1)) != 0)
13125 				break;
13126 			ACQUIRE_LOCK(ump);
13127 			/*
13128 			 * If that cleared dependencies, go on to next.
13129 			 */
13130 			if (dap != LIST_FIRST(diraddhdp))
13131 				continue;
13132 			/*
13133 			 * All MKDIR_PARENT dependencies and all the
13134 			 * NEWBLOCK pagedeps that are contained in direct
13135 			 * blocks were resolved by doing above ffs_update.
13136 			 * Pagedeps contained in indirect blocks may
13137 			 * require a complete sync'ing of the directory.
13138 			 * We are in the midst of doing a complete sync,
13139 			 * so if they are not resolved in this pass we
13140 			 * defer them for now as they will be sync'ed by
13141 			 * our caller shortly.
13142 			 */
13143 			LIST_REMOVE(dap, da_pdlist);
13144 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13145 			continue;
13146 		}
13147 		/*
13148 		 * A newly allocated directory must have its "." and
13149 		 * ".." entries written out before its name can be
13150 		 * committed in its parent.
13151 		 */
13152 		inum = dap->da_newinum;
13153 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13154 			panic("flush_pagedep_deps: lost inode1");
13155 		/*
13156 		 * Wait for any pending journal adds to complete so we don't
13157 		 * cause rollbacks while syncing.
13158 		 */
13159 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13160 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13161 			    == DEPCOMPLETE) {
13162 				jwait(&inoref->if_list, MNT_WAIT);
13163 				goto restart;
13164 			}
13165 		}
13166 		if (dap->da_state & MKDIR_BODY) {
13167 			FREE_LOCK(ump);
13168 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13169 			    FFSV_FORCEINSMQ)))
13170 				break;
13171 			error = flush_newblk_dep(vp, mp, 0);
13172 			/*
13173 			 * If we still have the dependency we might need to
13174 			 * update the vnode to sync the new link count to
13175 			 * disk.
13176 			 */
13177 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13178 				error = ffs_update(vp, 1);
13179 			vput(vp);
13180 			if (error != 0)
13181 				break;
13182 			ACQUIRE_LOCK(ump);
13183 			/*
13184 			 * If that cleared dependencies, go on to next.
13185 			 */
13186 			if (dap != LIST_FIRST(diraddhdp))
13187 				continue;
13188 			if (dap->da_state & MKDIR_BODY) {
13189 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13190 				    &inodedep);
13191 				panic("flush_pagedep_deps: MKDIR_BODY "
13192 				    "inodedep %p dap %p vp %p",
13193 				    inodedep, dap, vp);
13194 			}
13195 		}
13196 		/*
13197 		 * Flush the inode on which the directory entry depends.
13198 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13199 		 * the only remaining dependency is that the updated inode
13200 		 * count must get pushed to disk. The inode has already
13201 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13202 		 * the time of the reference count change. So we need only
13203 		 * locate that buffer, ensure that there will be no rollback
13204 		 * caused by a bitmap dependency, then write the inode buffer.
13205 		 */
13206 retry:
13207 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13208 			panic("flush_pagedep_deps: lost inode");
13209 		/*
13210 		 * If the inode still has bitmap dependencies,
13211 		 * push them to disk.
13212 		 */
13213 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13214 			bp = inodedep->id_bmsafemap->sm_buf;
13215 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13216 			if (bp == NULL)
13217 				goto retry;
13218 			FREE_LOCK(ump);
13219 			if ((error = bwrite(bp)) != 0)
13220 				break;
13221 			ACQUIRE_LOCK(ump);
13222 			if (dap != LIST_FIRST(diraddhdp))
13223 				continue;
13224 		}
13225 		/*
13226 		 * If the inode is still sitting in a buffer waiting
13227 		 * to be written or waiting for the link count to be
13228 		 * adjusted update it here to flush it to disk.
13229 		 */
13230 		if (dap == LIST_FIRST(diraddhdp)) {
13231 			FREE_LOCK(ump);
13232 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13233 			    FFSV_FORCEINSMQ)))
13234 				break;
13235 			error = ffs_update(vp, 1);
13236 			vput(vp);
13237 			if (error)
13238 				break;
13239 			ACQUIRE_LOCK(ump);
13240 		}
13241 		/*
13242 		 * If we have failed to get rid of all the dependencies
13243 		 * then something is seriously wrong.
13244 		 */
13245 		if (dap == LIST_FIRST(diraddhdp)) {
13246 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13247 			panic("flush_pagedep_deps: failed to flush "
13248 			    "inodedep %p ino %ju dap %p",
13249 			    inodedep, (uintmax_t)inum, dap);
13250 		}
13251 	}
13252 	if (error)
13253 		ACQUIRE_LOCK(ump);
13254 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13255 		LIST_REMOVE(dap, da_pdlist);
13256 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13257 	}
13258 	return (error);
13259 }
13260 
13261 /*
13262  * A large burst of file addition or deletion activity can drive the
13263  * memory load excessively high. First attempt to slow things down
13264  * using the techniques below. If that fails, this routine requests
13265  * the offending operations to fall back to running synchronously
13266  * until the memory load returns to a reasonable level.
13267  */
13268 int
13269 softdep_slowdown(vp)
13270 	struct vnode *vp;
13271 {
13272 	struct ufsmount *ump;
13273 	int jlow;
13274 	int max_softdeps_hard;
13275 
13276 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13277 	    ("softdep_slowdown called on non-softdep filesystem"));
13278 	ump = VFSTOUFS(vp->v_mount);
13279 	ACQUIRE_LOCK(ump);
13280 	jlow = 0;
13281 	/*
13282 	 * Check for journal space if needed.
13283 	 */
13284 	if (DOINGSUJ(vp)) {
13285 		if (journal_space(ump, 0) == 0)
13286 			jlow = 1;
13287 	}
13288 	/*
13289 	 * If the system is under its limits and our filesystem is
13290 	 * not responsible for more than our share of the usage and
13291 	 * we are not low on journal space, then no need to slow down.
13292 	 */
13293 	max_softdeps_hard = max_softdeps * 11 / 10;
13294 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13295 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13296 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13297 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13298 	    ump->softdep_curdeps[D_DIRREM] <
13299 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13300 	    ump->softdep_curdeps[D_INODEDEP] <
13301 	    max_softdeps_hard / stat_flush_threads &&
13302 	    ump->softdep_curdeps[D_INDIRDEP] <
13303 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13304 	    ump->softdep_curdeps[D_FREEBLKS] <
13305 	    max_softdeps_hard / stat_flush_threads) {
13306 		FREE_LOCK(ump);
13307   		return (0);
13308 	}
13309 	/*
13310 	 * If the journal is low or our filesystem is over its limit
13311 	 * then speedup the cleanup.
13312 	 */
13313 	if (ump->softdep_curdeps[D_INDIRDEP] <
13314 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13315 		softdep_speedup(ump);
13316 	stat_sync_limit_hit += 1;
13317 	FREE_LOCK(ump);
13318 	/*
13319 	 * We only slow down the rate at which new dependencies are
13320 	 * generated if we are not using journaling. With journaling,
13321 	 * the cleanup should always be sufficient to keep things
13322 	 * under control.
13323 	 */
13324 	if (DOINGSUJ(vp))
13325 		return (0);
13326 	return (1);
13327 }
13328 
13329 /*
13330  * Called by the allocation routines when they are about to fail
13331  * in the hope that we can free up the requested resource (inodes
13332  * or disk space).
13333  *
13334  * First check to see if the work list has anything on it. If it has,
13335  * clean up entries until we successfully free the requested resource.
13336  * Because this process holds inodes locked, we cannot handle any remove
13337  * requests that might block on a locked inode as that could lead to
13338  * deadlock. If the worklist yields none of the requested resource,
13339  * start syncing out vnodes to free up the needed space.
13340  */
13341 int
13342 softdep_request_cleanup(fs, vp, cred, resource)
13343 	struct fs *fs;
13344 	struct vnode *vp;
13345 	struct ucred *cred;
13346 	int resource;
13347 {
13348 	struct ufsmount *ump;
13349 	struct mount *mp;
13350 	long starttime;
13351 	ufs2_daddr_t needed;
13352 	int error, failed_vnode;
13353 
13354 	/*
13355 	 * If we are being called because of a process doing a
13356 	 * copy-on-write, then it is not safe to process any
13357 	 * worklist items as we will recurse into the copyonwrite
13358 	 * routine.  This will result in an incoherent snapshot.
13359 	 * If the vnode that we hold is a snapshot, we must avoid
13360 	 * handling other resources that could cause deadlock.
13361 	 */
13362 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13363 		return (0);
13364 
13365 	if (resource == FLUSH_BLOCKS_WAIT)
13366 		stat_cleanup_blkrequests += 1;
13367 	else
13368 		stat_cleanup_inorequests += 1;
13369 
13370 	mp = vp->v_mount;
13371 	ump = VFSTOUFS(mp);
13372 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13373 	UFS_UNLOCK(ump);
13374 	error = ffs_update(vp, 1);
13375 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13376 		UFS_LOCK(ump);
13377 		return (0);
13378 	}
13379 	/*
13380 	 * If we are in need of resources, start by cleaning up
13381 	 * any block removals associated with our inode.
13382 	 */
13383 	ACQUIRE_LOCK(ump);
13384 	process_removes(vp);
13385 	process_truncates(vp);
13386 	FREE_LOCK(ump);
13387 	/*
13388 	 * Now clean up at least as many resources as we will need.
13389 	 *
13390 	 * When requested to clean up inodes, the number that are needed
13391 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13392 	 * plus a bit of slop (2) in case some more writers show up while
13393 	 * we are cleaning.
13394 	 *
13395 	 * When requested to free up space, the amount of space that
13396 	 * we need is enough blocks to allocate a full-sized segment
13397 	 * (fs_contigsumsize). The number of such segments that will
13398 	 * be needed is set by the number of simultaneous writers
13399 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13400 	 * writers show up while we are cleaning.
13401 	 *
13402 	 * Additionally, if we are unpriviledged and allocating space,
13403 	 * we need to ensure that we clean up enough blocks to get the
13404 	 * needed number of blocks over the threshold of the minimum
13405 	 * number of blocks required to be kept free by the filesystem
13406 	 * (fs_minfree).
13407 	 */
13408 	if (resource == FLUSH_INODES_WAIT) {
13409 		needed = vp->v_mount->mnt_writeopcount + 2;
13410 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13411 		needed = (vp->v_mount->mnt_writeopcount + 2) *
13412 		    fs->fs_contigsumsize;
13413 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13414 			needed += fragstoblks(fs,
13415 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13416 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13417 	} else {
13418 		UFS_LOCK(ump);
13419 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13420 		    resource);
13421 		return (0);
13422 	}
13423 	starttime = time_second;
13424 retry:
13425 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13426 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13427 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13428 	    fs->fs_cstotal.cs_nifree <= needed)) {
13429 		ACQUIRE_LOCK(ump);
13430 		if (ump->softdep_on_worklist > 0 &&
13431 		    process_worklist_item(UFSTOVFS(ump),
13432 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13433 			stat_worklist_push += 1;
13434 		FREE_LOCK(ump);
13435 	}
13436 	/*
13437 	 * If we still need resources and there are no more worklist
13438 	 * entries to process to obtain them, we have to start flushing
13439 	 * the dirty vnodes to force the release of additional requests
13440 	 * to the worklist that we can then process to reap addition
13441 	 * resources. We walk the vnodes associated with the mount point
13442 	 * until we get the needed worklist requests that we can reap.
13443 	 *
13444 	 * If there are several threads all needing to clean the same
13445 	 * mount point, only one is allowed to walk the mount list.
13446 	 * When several threads all try to walk the same mount list,
13447 	 * they end up competing with each other and often end up in
13448 	 * livelock. This approach ensures that forward progress is
13449 	 * made at the cost of occational ENOSPC errors being returned
13450 	 * that might otherwise have been avoided.
13451 	 */
13452 	error = 1;
13453 	if ((resource == FLUSH_BLOCKS_WAIT &&
13454 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13455 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13456 	     fs->fs_cstotal.cs_nifree <= needed)) {
13457 		ACQUIRE_LOCK(ump);
13458 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13459 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13460 			FREE_LOCK(ump);
13461 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13462 			ACQUIRE_LOCK(ump);
13463 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13464 			FREE_LOCK(ump);
13465 			if (ump->softdep_on_worklist > 0) {
13466 				stat_cleanup_retries += 1;
13467 				if (!failed_vnode)
13468 					goto retry;
13469 			}
13470 		} else {
13471 			FREE_LOCK(ump);
13472 			error = 0;
13473 		}
13474 		stat_cleanup_failures += 1;
13475 	}
13476 	if (time_second - starttime > stat_cleanup_high_delay)
13477 		stat_cleanup_high_delay = time_second - starttime;
13478 	UFS_LOCK(ump);
13479 	return (error);
13480 }
13481 
13482 /*
13483  * Scan the vnodes for the specified mount point flushing out any
13484  * vnodes that can be locked without waiting. Finally, try to flush
13485  * the device associated with the mount point if it can be locked
13486  * without waiting.
13487  *
13488  * We return 0 if we were able to lock every vnode in our scan.
13489  * If we had to skip one or more vnodes, we return 1.
13490  */
13491 static int
13492 softdep_request_cleanup_flush(mp, ump)
13493 	struct mount *mp;
13494 	struct ufsmount *ump;
13495 {
13496 	struct thread *td;
13497 	struct vnode *lvp, *mvp;
13498 	int failed_vnode;
13499 
13500 	failed_vnode = 0;
13501 	td = curthread;
13502 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13503 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13504 			VI_UNLOCK(lvp);
13505 			continue;
13506 		}
13507 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13508 		    td) != 0) {
13509 			failed_vnode = 1;
13510 			continue;
13511 		}
13512 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13513 			vput(lvp);
13514 			continue;
13515 		}
13516 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13517 		vput(lvp);
13518 	}
13519 	lvp = ump->um_devvp;
13520 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13521 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13522 		VOP_UNLOCK(lvp, 0);
13523 	}
13524 	return (failed_vnode);
13525 }
13526 
13527 static bool
13528 softdep_excess_items(struct ufsmount *ump, int item)
13529 {
13530 
13531 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13532 	return (dep_current[item] > max_softdeps &&
13533 	    ump->softdep_curdeps[item] > max_softdeps /
13534 	    stat_flush_threads);
13535 }
13536 
13537 static void
13538 schedule_cleanup(struct mount *mp)
13539 {
13540 	struct ufsmount *ump;
13541 	struct thread *td;
13542 
13543 	ump = VFSTOUFS(mp);
13544 	LOCK_OWNED(ump);
13545 	FREE_LOCK(ump);
13546 	td = curthread;
13547 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13548 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13549 		/*
13550 		 * No ast is delivered to kernel threads, so nobody
13551 		 * would deref the mp.  Some kernel threads
13552 		 * explicitely check for AST, e.g. NFS daemon does
13553 		 * this in the serving loop.
13554 		 */
13555 		return;
13556 	}
13557 	if (td->td_su != NULL)
13558 		vfs_rel(td->td_su);
13559 	vfs_ref(mp);
13560 	td->td_su = mp;
13561 	thread_lock(td);
13562 	td->td_flags |= TDF_ASTPENDING;
13563 	thread_unlock(td);
13564 }
13565 
13566 static void
13567 softdep_ast_cleanup_proc(struct thread *td)
13568 {
13569 	struct mount *mp;
13570 	struct ufsmount *ump;
13571 	int error;
13572 	bool req;
13573 
13574 	while ((mp = td->td_su) != NULL) {
13575 		td->td_su = NULL;
13576 		error = vfs_busy(mp, MBF_NOWAIT);
13577 		vfs_rel(mp);
13578 		if (error != 0)
13579 			return;
13580 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13581 			ump = VFSTOUFS(mp);
13582 			for (;;) {
13583 				req = false;
13584 				ACQUIRE_LOCK(ump);
13585 				if (softdep_excess_items(ump, D_INODEDEP)) {
13586 					req = true;
13587 					request_cleanup(mp, FLUSH_INODES);
13588 				}
13589 				if (softdep_excess_items(ump, D_DIRREM)) {
13590 					req = true;
13591 					request_cleanup(mp, FLUSH_BLOCKS);
13592 				}
13593 				FREE_LOCK(ump);
13594 				if (softdep_excess_items(ump, D_NEWBLK) ||
13595 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13596 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13597 					error = vn_start_write(NULL, &mp,
13598 					    V_WAIT);
13599 					if (error == 0) {
13600 						req = true;
13601 						VFS_SYNC(mp, MNT_WAIT);
13602 						vn_finished_write(mp);
13603 					}
13604 				}
13605 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13606 					break;
13607 			}
13608 		}
13609 		vfs_unbusy(mp);
13610 	}
13611 	if ((mp = td->td_su) != NULL) {
13612 		td->td_su = NULL;
13613 		vfs_rel(mp);
13614 	}
13615 }
13616 
13617 /*
13618  * If memory utilization has gotten too high, deliberately slow things
13619  * down and speed up the I/O processing.
13620  */
13621 static int
13622 request_cleanup(mp, resource)
13623 	struct mount *mp;
13624 	int resource;
13625 {
13626 	struct thread *td = curthread;
13627 	struct ufsmount *ump;
13628 
13629 	ump = VFSTOUFS(mp);
13630 	LOCK_OWNED(ump);
13631 	/*
13632 	 * We never hold up the filesystem syncer or buf daemon.
13633 	 */
13634 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13635 		return (0);
13636 	/*
13637 	 * First check to see if the work list has gotten backlogged.
13638 	 * If it has, co-opt this process to help clean up two entries.
13639 	 * Because this process may hold inodes locked, we cannot
13640 	 * handle any remove requests that might block on a locked
13641 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13642 	 * to avoid recursively processing the worklist.
13643 	 */
13644 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13645 		td->td_pflags |= TDP_SOFTDEP;
13646 		process_worklist_item(mp, 2, LK_NOWAIT);
13647 		td->td_pflags &= ~TDP_SOFTDEP;
13648 		stat_worklist_push += 2;
13649 		return(1);
13650 	}
13651 	/*
13652 	 * Next, we attempt to speed up the syncer process. If that
13653 	 * is successful, then we allow the process to continue.
13654 	 */
13655 	if (softdep_speedup(ump) &&
13656 	    resource != FLUSH_BLOCKS_WAIT &&
13657 	    resource != FLUSH_INODES_WAIT)
13658 		return(0);
13659 	/*
13660 	 * If we are resource constrained on inode dependencies, try
13661 	 * flushing some dirty inodes. Otherwise, we are constrained
13662 	 * by file deletions, so try accelerating flushes of directories
13663 	 * with removal dependencies. We would like to do the cleanup
13664 	 * here, but we probably hold an inode locked at this point and
13665 	 * that might deadlock against one that we try to clean. So,
13666 	 * the best that we can do is request the syncer daemon to do
13667 	 * the cleanup for us.
13668 	 */
13669 	switch (resource) {
13670 
13671 	case FLUSH_INODES:
13672 	case FLUSH_INODES_WAIT:
13673 		ACQUIRE_GBLLOCK(&lk);
13674 		stat_ino_limit_push += 1;
13675 		req_clear_inodedeps += 1;
13676 		FREE_GBLLOCK(&lk);
13677 		stat_countp = &stat_ino_limit_hit;
13678 		break;
13679 
13680 	case FLUSH_BLOCKS:
13681 	case FLUSH_BLOCKS_WAIT:
13682 		ACQUIRE_GBLLOCK(&lk);
13683 		stat_blk_limit_push += 1;
13684 		req_clear_remove += 1;
13685 		FREE_GBLLOCK(&lk);
13686 		stat_countp = &stat_blk_limit_hit;
13687 		break;
13688 
13689 	default:
13690 		panic("request_cleanup: unknown type");
13691 	}
13692 	/*
13693 	 * Hopefully the syncer daemon will catch up and awaken us.
13694 	 * We wait at most tickdelay before proceeding in any case.
13695 	 */
13696 	ACQUIRE_GBLLOCK(&lk);
13697 	FREE_LOCK(ump);
13698 	proc_waiting += 1;
13699 	if (callout_pending(&softdep_callout) == FALSE)
13700 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13701 		    pause_timer, 0);
13702 
13703 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13704 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13705 	proc_waiting -= 1;
13706 	FREE_GBLLOCK(&lk);
13707 	ACQUIRE_LOCK(ump);
13708 	return (1);
13709 }
13710 
13711 /*
13712  * Awaken processes pausing in request_cleanup and clear proc_waiting
13713  * to indicate that there is no longer a timer running. Pause_timer
13714  * will be called with the global softdep mutex (&lk) locked.
13715  */
13716 static void
13717 pause_timer(arg)
13718 	void *arg;
13719 {
13720 
13721 	GBLLOCK_OWNED(&lk);
13722 	/*
13723 	 * The callout_ API has acquired mtx and will hold it around this
13724 	 * function call.
13725 	 */
13726 	*stat_countp += proc_waiting;
13727 	wakeup(&proc_waiting);
13728 }
13729 
13730 /*
13731  * If requested, try removing inode or removal dependencies.
13732  */
13733 static void
13734 check_clear_deps(mp)
13735 	struct mount *mp;
13736 {
13737 
13738 	/*
13739 	 * If we are suspended, it may be because of our using
13740 	 * too many inodedeps, so help clear them out.
13741 	 */
13742 	if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13743 		clear_inodedeps(mp);
13744 	/*
13745 	 * General requests for cleanup of backed up dependencies
13746 	 */
13747 	ACQUIRE_GBLLOCK(&lk);
13748 	if (req_clear_inodedeps) {
13749 		req_clear_inodedeps -= 1;
13750 		FREE_GBLLOCK(&lk);
13751 		clear_inodedeps(mp);
13752 		ACQUIRE_GBLLOCK(&lk);
13753 		wakeup(&proc_waiting);
13754 	}
13755 	if (req_clear_remove) {
13756 		req_clear_remove -= 1;
13757 		FREE_GBLLOCK(&lk);
13758 		clear_remove(mp);
13759 		ACQUIRE_GBLLOCK(&lk);
13760 		wakeup(&proc_waiting);
13761 	}
13762 	FREE_GBLLOCK(&lk);
13763 }
13764 
13765 /*
13766  * Flush out a directory with at least one removal dependency in an effort to
13767  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13768  */
13769 static void
13770 clear_remove(mp)
13771 	struct mount *mp;
13772 {
13773 	struct pagedep_hashhead *pagedephd;
13774 	struct pagedep *pagedep;
13775 	struct ufsmount *ump;
13776 	struct vnode *vp;
13777 	struct bufobj *bo;
13778 	int error, cnt;
13779 	ino_t ino;
13780 
13781 	ump = VFSTOUFS(mp);
13782 	LOCK_OWNED(ump);
13783 
13784 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13785 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13786 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13787 			ump->pagedep_nextclean = 0;
13788 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13789 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13790 				continue;
13791 			ino = pagedep->pd_ino;
13792 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13793 				continue;
13794 			FREE_LOCK(ump);
13795 
13796 			/*
13797 			 * Let unmount clear deps
13798 			 */
13799 			error = vfs_busy(mp, MBF_NOWAIT);
13800 			if (error != 0)
13801 				goto finish_write;
13802 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13803 			     FFSV_FORCEINSMQ);
13804 			vfs_unbusy(mp);
13805 			if (error != 0) {
13806 				softdep_error("clear_remove: vget", error);
13807 				goto finish_write;
13808 			}
13809 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13810 				softdep_error("clear_remove: fsync", error);
13811 			bo = &vp->v_bufobj;
13812 			BO_LOCK(bo);
13813 			drain_output(vp);
13814 			BO_UNLOCK(bo);
13815 			vput(vp);
13816 		finish_write:
13817 			vn_finished_write(mp);
13818 			ACQUIRE_LOCK(ump);
13819 			return;
13820 		}
13821 	}
13822 }
13823 
13824 /*
13825  * Clear out a block of dirty inodes in an effort to reduce
13826  * the number of inodedep dependency structures.
13827  */
13828 static void
13829 clear_inodedeps(mp)
13830 	struct mount *mp;
13831 {
13832 	struct inodedep_hashhead *inodedephd;
13833 	struct inodedep *inodedep;
13834 	struct ufsmount *ump;
13835 	struct vnode *vp;
13836 	struct fs *fs;
13837 	int error, cnt;
13838 	ino_t firstino, lastino, ino;
13839 
13840 	ump = VFSTOUFS(mp);
13841 	fs = ump->um_fs;
13842 	LOCK_OWNED(ump);
13843 	/*
13844 	 * Pick a random inode dependency to be cleared.
13845 	 * We will then gather up all the inodes in its block
13846 	 * that have dependencies and flush them out.
13847 	 */
13848 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13849 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13850 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13851 			ump->inodedep_nextclean = 0;
13852 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13853 			break;
13854 	}
13855 	if (inodedep == NULL)
13856 		return;
13857 	/*
13858 	 * Find the last inode in the block with dependencies.
13859 	 */
13860 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13861 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13862 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13863 			break;
13864 	/*
13865 	 * Asynchronously push all but the last inode with dependencies.
13866 	 * Synchronously push the last inode with dependencies to ensure
13867 	 * that the inode block gets written to free up the inodedeps.
13868 	 */
13869 	for (ino = firstino; ino <= lastino; ino++) {
13870 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13871 			continue;
13872 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13873 			continue;
13874 		FREE_LOCK(ump);
13875 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13876 		if (error != 0) {
13877 			vn_finished_write(mp);
13878 			ACQUIRE_LOCK(ump);
13879 			return;
13880 		}
13881 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13882 		    FFSV_FORCEINSMQ)) != 0) {
13883 			softdep_error("clear_inodedeps: vget", error);
13884 			vfs_unbusy(mp);
13885 			vn_finished_write(mp);
13886 			ACQUIRE_LOCK(ump);
13887 			return;
13888 		}
13889 		vfs_unbusy(mp);
13890 		if (ino == lastino) {
13891 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13892 				softdep_error("clear_inodedeps: fsync1", error);
13893 		} else {
13894 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13895 				softdep_error("clear_inodedeps: fsync2", error);
13896 			BO_LOCK(&vp->v_bufobj);
13897 			drain_output(vp);
13898 			BO_UNLOCK(&vp->v_bufobj);
13899 		}
13900 		vput(vp);
13901 		vn_finished_write(mp);
13902 		ACQUIRE_LOCK(ump);
13903 	}
13904 }
13905 
13906 void
13907 softdep_buf_append(bp, wkhd)
13908 	struct buf *bp;
13909 	struct workhead *wkhd;
13910 {
13911 	struct worklist *wk;
13912 	struct ufsmount *ump;
13913 
13914 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13915 		return;
13916 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13917 	    ("softdep_buf_append called on non-softdep filesystem"));
13918 	ump = VFSTOUFS(wk->wk_mp);
13919 	ACQUIRE_LOCK(ump);
13920 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13921 		WORKLIST_REMOVE(wk);
13922 		WORKLIST_INSERT(&bp->b_dep, wk);
13923 	}
13924 	FREE_LOCK(ump);
13925 
13926 }
13927 
13928 void
13929 softdep_inode_append(ip, cred, wkhd)
13930 	struct inode *ip;
13931 	struct ucred *cred;
13932 	struct workhead *wkhd;
13933 {
13934 	struct buf *bp;
13935 	struct fs *fs;
13936 	struct ufsmount *ump;
13937 	int error;
13938 
13939 	ump = ITOUMP(ip);
13940 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13941 	    ("softdep_inode_append called on non-softdep filesystem"));
13942 	fs = ump->um_fs;
13943 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13944 	    (int)fs->fs_bsize, cred, &bp);
13945 	if (error) {
13946 		bqrelse(bp);
13947 		softdep_freework(wkhd);
13948 		return;
13949 	}
13950 	softdep_buf_append(bp, wkhd);
13951 	bqrelse(bp);
13952 }
13953 
13954 void
13955 softdep_freework(wkhd)
13956 	struct workhead *wkhd;
13957 {
13958 	struct worklist *wk;
13959 	struct ufsmount *ump;
13960 
13961 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13962 		return;
13963 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13964 	    ("softdep_freework called on non-softdep filesystem"));
13965 	ump = VFSTOUFS(wk->wk_mp);
13966 	ACQUIRE_LOCK(ump);
13967 	handle_jwork(wkhd);
13968 	FREE_LOCK(ump);
13969 }
13970 
13971 static struct ufsmount *
13972 softdep_bp_to_mp(bp)
13973 	struct buf *bp;
13974 {
13975 	struct mount *mp;
13976 	struct vnode *vp;
13977 
13978 	if (LIST_EMPTY(&bp->b_dep))
13979 		return (NULL);
13980 	vp = bp->b_vp;
13981 	KASSERT(vp != NULL,
13982 	    ("%s, buffer with dependencies lacks vnode", __func__));
13983 
13984 	/*
13985 	 * The ump mount point is stable after we get a correct
13986 	 * pointer, since bp is locked and this prevents unmount from
13987 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
13988 	 * head wk_mp, because we do not yet own SU ump lock and
13989 	 * workitem might be freed while dereferenced.
13990 	 */
13991 retry:
13992 	switch (vp->v_type) {
13993 	case VCHR:
13994 		VI_LOCK(vp);
13995 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
13996 		VI_UNLOCK(vp);
13997 		if (mp == NULL)
13998 			goto retry;
13999 		break;
14000 	case VREG:
14001 	case VDIR:
14002 	case VLNK:
14003 	case VFIFO:
14004 	case VSOCK:
14005 		mp = vp->v_mount;
14006 		break;
14007 	case VBLK:
14008 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14009 		/* FALLTHROUGH */
14010 	case VNON:
14011 	case VBAD:
14012 	case VMARKER:
14013 		mp = NULL;
14014 		break;
14015 	default:
14016 		vn_printf(vp, "unknown vnode type");
14017 		mp = NULL;
14018 		break;
14019 	}
14020 	return (VFSTOUFS(mp));
14021 }
14022 
14023 /*
14024  * Function to determine if the buffer has outstanding dependencies
14025  * that will cause a roll-back if the buffer is written. If wantcount
14026  * is set, return number of dependencies, otherwise just yes or no.
14027  */
14028 static int
14029 softdep_count_dependencies(bp, wantcount)
14030 	struct buf *bp;
14031 	int wantcount;
14032 {
14033 	struct worklist *wk;
14034 	struct ufsmount *ump;
14035 	struct bmsafemap *bmsafemap;
14036 	struct freework *freework;
14037 	struct inodedep *inodedep;
14038 	struct indirdep *indirdep;
14039 	struct freeblks *freeblks;
14040 	struct allocindir *aip;
14041 	struct pagedep *pagedep;
14042 	struct dirrem *dirrem;
14043 	struct newblk *newblk;
14044 	struct mkdir *mkdir;
14045 	struct diradd *dap;
14046 	int i, retval;
14047 
14048 	ump = softdep_bp_to_mp(bp);
14049 	if (ump == NULL)
14050 		return (0);
14051 	retval = 0;
14052 	ACQUIRE_LOCK(ump);
14053 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14054 		switch (wk->wk_type) {
14055 
14056 		case D_INODEDEP:
14057 			inodedep = WK_INODEDEP(wk);
14058 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14059 				/* bitmap allocation dependency */
14060 				retval += 1;
14061 				if (!wantcount)
14062 					goto out;
14063 			}
14064 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14065 				/* direct block pointer dependency */
14066 				retval += 1;
14067 				if (!wantcount)
14068 					goto out;
14069 			}
14070 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14071 				/* direct block pointer dependency */
14072 				retval += 1;
14073 				if (!wantcount)
14074 					goto out;
14075 			}
14076 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14077 				/* Add reference dependency. */
14078 				retval += 1;
14079 				if (!wantcount)
14080 					goto out;
14081 			}
14082 			continue;
14083 
14084 		case D_INDIRDEP:
14085 			indirdep = WK_INDIRDEP(wk);
14086 
14087 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14088 				/* indirect truncation dependency */
14089 				retval += 1;
14090 				if (!wantcount)
14091 					goto out;
14092 			}
14093 
14094 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14095 				/* indirect block pointer dependency */
14096 				retval += 1;
14097 				if (!wantcount)
14098 					goto out;
14099 			}
14100 			continue;
14101 
14102 		case D_PAGEDEP:
14103 			pagedep = WK_PAGEDEP(wk);
14104 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14105 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14106 					/* Journal remove ref dependency. */
14107 					retval += 1;
14108 					if (!wantcount)
14109 						goto out;
14110 				}
14111 			}
14112 			for (i = 0; i < DAHASHSZ; i++) {
14113 
14114 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14115 					/* directory entry dependency */
14116 					retval += 1;
14117 					if (!wantcount)
14118 						goto out;
14119 				}
14120 			}
14121 			continue;
14122 
14123 		case D_BMSAFEMAP:
14124 			bmsafemap = WK_BMSAFEMAP(wk);
14125 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14126 				/* Add reference dependency. */
14127 				retval += 1;
14128 				if (!wantcount)
14129 					goto out;
14130 			}
14131 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14132 				/* Allocate block dependency. */
14133 				retval += 1;
14134 				if (!wantcount)
14135 					goto out;
14136 			}
14137 			continue;
14138 
14139 		case D_FREEBLKS:
14140 			freeblks = WK_FREEBLKS(wk);
14141 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14142 				/* Freeblk journal dependency. */
14143 				retval += 1;
14144 				if (!wantcount)
14145 					goto out;
14146 			}
14147 			continue;
14148 
14149 		case D_ALLOCDIRECT:
14150 		case D_ALLOCINDIR:
14151 			newblk = WK_NEWBLK(wk);
14152 			if (newblk->nb_jnewblk) {
14153 				/* Journal allocate dependency. */
14154 				retval += 1;
14155 				if (!wantcount)
14156 					goto out;
14157 			}
14158 			continue;
14159 
14160 		case D_MKDIR:
14161 			mkdir = WK_MKDIR(wk);
14162 			if (mkdir->md_jaddref) {
14163 				/* Journal reference dependency. */
14164 				retval += 1;
14165 				if (!wantcount)
14166 					goto out;
14167 			}
14168 			continue;
14169 
14170 		case D_FREEWORK:
14171 		case D_FREEDEP:
14172 		case D_JSEGDEP:
14173 		case D_JSEG:
14174 		case D_SBDEP:
14175 			/* never a dependency on these blocks */
14176 			continue;
14177 
14178 		default:
14179 			panic("softdep_count_dependencies: Unexpected type %s",
14180 			    TYPENAME(wk->wk_type));
14181 			/* NOTREACHED */
14182 		}
14183 	}
14184 out:
14185 	FREE_LOCK(ump);
14186 	return (retval);
14187 }
14188 
14189 /*
14190  * Acquire exclusive access to a buffer.
14191  * Must be called with a locked mtx parameter.
14192  * Return acquired buffer or NULL on failure.
14193  */
14194 static struct buf *
14195 getdirtybuf(bp, lock, waitfor)
14196 	struct buf *bp;
14197 	struct rwlock *lock;
14198 	int waitfor;
14199 {
14200 	int error;
14201 
14202 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14203 		if (waitfor != MNT_WAIT)
14204 			return (NULL);
14205 		error = BUF_LOCK(bp,
14206 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14207 		/*
14208 		 * Even if we successfully acquire bp here, we have dropped
14209 		 * lock, which may violates our guarantee.
14210 		 */
14211 		if (error == 0)
14212 			BUF_UNLOCK(bp);
14213 		else if (error != ENOLCK)
14214 			panic("getdirtybuf: inconsistent lock: %d", error);
14215 		rw_wlock(lock);
14216 		return (NULL);
14217 	}
14218 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14219 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14220 			rw_wunlock(lock);
14221 			BO_LOCK(bp->b_bufobj);
14222 			BUF_UNLOCK(bp);
14223 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14224 				bp->b_vflags |= BV_BKGRDWAIT;
14225 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14226 				       PRIBIO | PDROP, "getbuf", 0);
14227 			} else
14228 				BO_UNLOCK(bp->b_bufobj);
14229 			rw_wlock(lock);
14230 			return (NULL);
14231 		}
14232 		BUF_UNLOCK(bp);
14233 		if (waitfor != MNT_WAIT)
14234 			return (NULL);
14235 #ifdef DEBUG_VFS_LOCKS
14236 		if (bp->b_vp->v_type != VCHR)
14237 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14238 #endif
14239 		bp->b_vflags |= BV_BKGRDWAIT;
14240 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14241 		return (NULL);
14242 	}
14243 	if ((bp->b_flags & B_DELWRI) == 0) {
14244 		BUF_UNLOCK(bp);
14245 		return (NULL);
14246 	}
14247 	bremfree(bp);
14248 	return (bp);
14249 }
14250 
14251 
14252 /*
14253  * Check if it is safe to suspend the file system now.  On entry,
14254  * the vnode interlock for devvp should be held.  Return 0 with
14255  * the mount interlock held if the file system can be suspended now,
14256  * otherwise return EAGAIN with the mount interlock held.
14257  */
14258 int
14259 softdep_check_suspend(struct mount *mp,
14260 		      struct vnode *devvp,
14261 		      int softdep_depcnt,
14262 		      int softdep_accdepcnt,
14263 		      int secondary_writes,
14264 		      int secondary_accwrites)
14265 {
14266 	struct bufobj *bo;
14267 	struct ufsmount *ump;
14268 	struct inodedep *inodedep;
14269 	int error, unlinked;
14270 
14271 	bo = &devvp->v_bufobj;
14272 	ASSERT_BO_WLOCKED(bo);
14273 
14274 	/*
14275 	 * If we are not running with soft updates, then we need only
14276 	 * deal with secondary writes as we try to suspend.
14277 	 */
14278 	if (MOUNTEDSOFTDEP(mp) == 0) {
14279 		MNT_ILOCK(mp);
14280 		while (mp->mnt_secondary_writes != 0) {
14281 			BO_UNLOCK(bo);
14282 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14283 			    (PUSER - 1) | PDROP, "secwr", 0);
14284 			BO_LOCK(bo);
14285 			MNT_ILOCK(mp);
14286 		}
14287 
14288 		/*
14289 		 * Reasons for needing more work before suspend:
14290 		 * - Dirty buffers on devvp.
14291 		 * - Secondary writes occurred after start of vnode sync loop
14292 		 */
14293 		error = 0;
14294 		if (bo->bo_numoutput > 0 ||
14295 		    bo->bo_dirty.bv_cnt > 0 ||
14296 		    secondary_writes != 0 ||
14297 		    mp->mnt_secondary_writes != 0 ||
14298 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14299 			error = EAGAIN;
14300 		BO_UNLOCK(bo);
14301 		return (error);
14302 	}
14303 
14304 	/*
14305 	 * If we are running with soft updates, then we need to coordinate
14306 	 * with them as we try to suspend.
14307 	 */
14308 	ump = VFSTOUFS(mp);
14309 	for (;;) {
14310 		if (!TRY_ACQUIRE_LOCK(ump)) {
14311 			BO_UNLOCK(bo);
14312 			ACQUIRE_LOCK(ump);
14313 			FREE_LOCK(ump);
14314 			BO_LOCK(bo);
14315 			continue;
14316 		}
14317 		MNT_ILOCK(mp);
14318 		if (mp->mnt_secondary_writes != 0) {
14319 			FREE_LOCK(ump);
14320 			BO_UNLOCK(bo);
14321 			msleep(&mp->mnt_secondary_writes,
14322 			       MNT_MTX(mp),
14323 			       (PUSER - 1) | PDROP, "secwr", 0);
14324 			BO_LOCK(bo);
14325 			continue;
14326 		}
14327 		break;
14328 	}
14329 
14330 	unlinked = 0;
14331 	if (MOUNTEDSUJ(mp)) {
14332 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14333 		    inodedep != NULL;
14334 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14335 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14336 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14337 			    UNLINKONLIST) ||
14338 			    !check_inodedep_free(inodedep))
14339 				continue;
14340 			unlinked++;
14341 		}
14342 	}
14343 
14344 	/*
14345 	 * Reasons for needing more work before suspend:
14346 	 * - Dirty buffers on devvp.
14347 	 * - Softdep activity occurred after start of vnode sync loop
14348 	 * - Secondary writes occurred after start of vnode sync loop
14349 	 */
14350 	error = 0;
14351 	if (bo->bo_numoutput > 0 ||
14352 	    bo->bo_dirty.bv_cnt > 0 ||
14353 	    softdep_depcnt != unlinked ||
14354 	    ump->softdep_deps != unlinked ||
14355 	    softdep_accdepcnt != ump->softdep_accdeps ||
14356 	    secondary_writes != 0 ||
14357 	    mp->mnt_secondary_writes != 0 ||
14358 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14359 		error = EAGAIN;
14360 	FREE_LOCK(ump);
14361 	BO_UNLOCK(bo);
14362 	return (error);
14363 }
14364 
14365 
14366 /*
14367  * Get the number of dependency structures for the file system, both
14368  * the current number and the total number allocated.  These will
14369  * later be used to detect that softdep processing has occurred.
14370  */
14371 void
14372 softdep_get_depcounts(struct mount *mp,
14373 		      int *softdep_depsp,
14374 		      int *softdep_accdepsp)
14375 {
14376 	struct ufsmount *ump;
14377 
14378 	if (MOUNTEDSOFTDEP(mp) == 0) {
14379 		*softdep_depsp = 0;
14380 		*softdep_accdepsp = 0;
14381 		return;
14382 	}
14383 	ump = VFSTOUFS(mp);
14384 	ACQUIRE_LOCK(ump);
14385 	*softdep_depsp = ump->softdep_deps;
14386 	*softdep_accdepsp = ump->softdep_accdeps;
14387 	FREE_LOCK(ump);
14388 }
14389 
14390 /*
14391  * Wait for pending output on a vnode to complete.
14392  */
14393 static void
14394 drain_output(vp)
14395 	struct vnode *vp;
14396 {
14397 
14398 	ASSERT_VOP_LOCKED(vp, "drain_output");
14399 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14400 }
14401 
14402 /*
14403  * Called whenever a buffer that is being invalidated or reallocated
14404  * contains dependencies. This should only happen if an I/O error has
14405  * occurred. The routine is called with the buffer locked.
14406  */
14407 static void
14408 softdep_deallocate_dependencies(bp)
14409 	struct buf *bp;
14410 {
14411 
14412 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14413 		panic("softdep_deallocate_dependencies: dangling deps");
14414 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14415 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14416 	else
14417 		printf("softdep_deallocate_dependencies: "
14418 		    "got error %d while accessing filesystem\n", bp->b_error);
14419 	if (bp->b_error != ENXIO)
14420 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14421 }
14422 
14423 /*
14424  * Function to handle asynchronous write errors in the filesystem.
14425  */
14426 static void
14427 softdep_error(func, error)
14428 	char *func;
14429 	int error;
14430 {
14431 
14432 	/* XXX should do something better! */
14433 	printf("%s: got error %d while accessing filesystem\n", func, error);
14434 }
14435 
14436 #ifdef DDB
14437 
14438 /* exported to ffs_vfsops.c */
14439 extern void db_print_ffs(struct ufsmount *ump);
14440 void
14441 db_print_ffs(struct ufsmount *ump)
14442 {
14443 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14444 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14445 	db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14446 	    ump->um_fs, ump->softdep_on_worklist,
14447 	    ump->softdep_deps, ump->softdep_req);
14448 }
14449 
14450 static void
14451 worklist_print(struct worklist *wk, int verbose)
14452 {
14453 
14454 	if (!verbose) {
14455 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14456 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14457 		return;
14458 	}
14459 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14460 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14461 	    LIST_NEXT(wk, wk_list));
14462 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14463 }
14464 
14465 static void
14466 inodedep_print(struct inodedep *inodedep, int verbose)
14467 {
14468 
14469 	worklist_print(&inodedep->id_list, 0);
14470 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14471 	    inodedep->id_fs,
14472 	    (intmax_t)inodedep->id_ino,
14473 	    (intmax_t)fsbtodb(inodedep->id_fs,
14474 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14475 	    (intmax_t)inodedep->id_nlinkdelta,
14476 	    (intmax_t)inodedep->id_savednlink);
14477 
14478 	if (verbose == 0)
14479 		return;
14480 
14481 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14482 	    inodedep->id_bmsafemap,
14483 	    inodedep->id_mkdiradd,
14484 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14485 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14486 	    LIST_FIRST(&inodedep->id_dirremhd),
14487 	    LIST_FIRST(&inodedep->id_pendinghd),
14488 	    LIST_FIRST(&inodedep->id_bufwait));
14489 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14490 	    LIST_FIRST(&inodedep->id_inowait),
14491 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14492 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14493 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14494 	    TAILQ_FIRST(&inodedep->id_extupdt),
14495 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14496 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14497 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14498 	    inodedep->id_savedino1,
14499 	    (intmax_t)inodedep->id_savedsize,
14500 	    (intmax_t)inodedep->id_savedextsize);
14501 }
14502 
14503 static void
14504 newblk_print(struct newblk *nbp)
14505 {
14506 
14507 	worklist_print(&nbp->nb_list, 0);
14508 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14509 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14510 	    &nbp->nb_jnewblk,
14511 	    &nbp->nb_bmsafemap,
14512 	    &nbp->nb_freefrag);
14513 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14514 	    LIST_FIRST(&nbp->nb_indirdeps),
14515 	    LIST_FIRST(&nbp->nb_newdirblk),
14516 	    LIST_FIRST(&nbp->nb_jwork));
14517 }
14518 
14519 static void
14520 allocdirect_print(struct allocdirect *adp)
14521 {
14522 
14523 	newblk_print(&adp->ad_block);
14524 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14525 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14526 	db_printf("    offset %d, inodedep %p\n",
14527 	    adp->ad_offset, adp->ad_inodedep);
14528 }
14529 
14530 static void
14531 allocindir_print(struct allocindir *aip)
14532 {
14533 
14534 	newblk_print(&aip->ai_block);
14535 	db_printf("    oldblkno %jd, lbn %jd\n",
14536 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14537 	db_printf("    offset %d, indirdep %p\n",
14538 	    aip->ai_offset, aip->ai_indirdep);
14539 }
14540 
14541 static void
14542 mkdir_print(struct mkdir *mkdir)
14543 {
14544 
14545 	worklist_print(&mkdir->md_list, 0);
14546 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14547 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14548 }
14549 
14550 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14551 {
14552 
14553 	if (have_addr == 0) {
14554 		db_printf("inodedep address required\n");
14555 		return;
14556 	}
14557 	inodedep_print((struct inodedep*)addr, 1);
14558 }
14559 
14560 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14561 {
14562 	struct inodedep_hashhead *inodedephd;
14563 	struct inodedep *inodedep;
14564 	struct ufsmount *ump;
14565 	int cnt;
14566 
14567 	if (have_addr == 0) {
14568 		db_printf("ufsmount address required\n");
14569 		return;
14570 	}
14571 	ump = (struct ufsmount *)addr;
14572 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14573 		inodedephd = &ump->inodedep_hashtbl[cnt];
14574 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14575 			inodedep_print(inodedep, 0);
14576 		}
14577 	}
14578 }
14579 
14580 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14581 {
14582 
14583 	if (have_addr == 0) {
14584 		db_printf("worklist address required\n");
14585 		return;
14586 	}
14587 	worklist_print((struct worklist *)addr, 1);
14588 }
14589 
14590 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14591 {
14592 	struct worklist *wk;
14593 	struct workhead *wkhd;
14594 
14595 	if (have_addr == 0) {
14596 		db_printf("worklist address required "
14597 		    "(for example value in bp->b_dep)\n");
14598 		return;
14599 	}
14600 	/*
14601 	 * We often do not have the address of the worklist head but
14602 	 * instead a pointer to its first entry (e.g., we have the
14603 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
14604 	 * pointer of bp->b_dep will point at the head of the list, so
14605 	 * we cheat and use that instead. If we are in the middle of
14606 	 * a list we will still get the same result, so nothing
14607 	 * unexpected will result.
14608 	 */
14609 	wk = (struct worklist *)addr;
14610 	if (wk == NULL)
14611 		return;
14612 	wkhd = (struct workhead *)wk->wk_list.le_prev;
14613 	LIST_FOREACH(wk, wkhd, wk_list) {
14614 		switch(wk->wk_type) {
14615 		case D_INODEDEP:
14616 			inodedep_print(WK_INODEDEP(wk), 0);
14617 			continue;
14618 		case D_ALLOCDIRECT:
14619 			allocdirect_print(WK_ALLOCDIRECT(wk));
14620 			continue;
14621 		case D_ALLOCINDIR:
14622 			allocindir_print(WK_ALLOCINDIR(wk));
14623 			continue;
14624 		case D_MKDIR:
14625 			mkdir_print(WK_MKDIR(wk));
14626 			continue;
14627 		default:
14628 			worklist_print(wk, 0);
14629 			continue;
14630 		}
14631 	}
14632 }
14633 
14634 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14635 {
14636 	if (have_addr == 0) {
14637 		db_printf("mkdir address required\n");
14638 		return;
14639 	}
14640 	mkdir_print((struct mkdir *)addr);
14641 }
14642 
14643 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14644 {
14645 	struct mkdirlist *mkdirlisthd;
14646 	struct mkdir *mkdir;
14647 
14648 	if (have_addr == 0) {
14649 		db_printf("mkdir listhead address required\n");
14650 		return;
14651 	}
14652 	mkdirlisthd = (struct mkdirlist *)addr;
14653 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14654 		mkdir_print(mkdir);
14655 		if (mkdir->md_diradd != NULL) {
14656 			db_printf("    ");
14657 			worklist_print(&mkdir->md_diradd->da_list, 0);
14658 		}
14659 		if (mkdir->md_jaddref != NULL) {
14660 			db_printf("    ");
14661 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
14662 		}
14663 	}
14664 }
14665 
14666 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
14667 {
14668 	if (have_addr == 0) {
14669 		db_printf("allocdirect address required\n");
14670 		return;
14671 	}
14672 	allocdirect_print((struct allocdirect *)addr);
14673 }
14674 
14675 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
14676 {
14677 	if (have_addr == 0) {
14678 		db_printf("allocindir address required\n");
14679 		return;
14680 	}
14681 	allocindir_print((struct allocindir *)addr);
14682 }
14683 
14684 #endif /* DDB */
14685 
14686 #endif /* SOFTUPDATES */
14687