xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
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 /*
52  * For now we want the safety net that the DEBUG flag provides.
53  */
54 #ifndef DEBUG
55 #define DEBUG
56 #endif
57 
58 #include <sys/param.h>
59 #include <sys/kernel.h>
60 #include <sys/systm.h>
61 #include <sys/bio.h>
62 #include <sys/buf.h>
63 #include <sys/kdb.h>
64 #include <sys/kthread.h>
65 #include <sys/ktr.h>
66 #include <sys/limits.h>
67 #include <sys/lock.h>
68 #include <sys/malloc.h>
69 #include <sys/mount.h>
70 #include <sys/mutex.h>
71 #include <sys/namei.h>
72 #include <sys/priv.h>
73 #include <sys/proc.h>
74 #include <sys/racct.h>
75 #include <sys/rwlock.h>
76 #include <sys/stat.h>
77 #include <sys/sysctl.h>
78 #include <sys/syslog.h>
79 #include <sys/vnode.h>
80 #include <sys/conf.h>
81 
82 #include <ufs/ufs/dir.h>
83 #include <ufs/ufs/extattr.h>
84 #include <ufs/ufs/quota.h>
85 #include <ufs/ufs/inode.h>
86 #include <ufs/ufs/ufsmount.h>
87 #include <ufs/ffs/fs.h>
88 #include <ufs/ffs/softdep.h>
89 #include <ufs/ffs/ffs_extern.h>
90 #include <ufs/ufs/ufs_extern.h>
91 
92 #include <vm/vm.h>
93 #include <vm/vm_extern.h>
94 #include <vm/vm_object.h>
95 
96 #include <geom/geom.h>
97 
98 #include <ddb/ddb.h>
99 
100 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
101 
102 #ifndef SOFTUPDATES
103 
104 int
105 softdep_flushfiles(oldmnt, flags, td)
106 	struct mount *oldmnt;
107 	int flags;
108 	struct thread *td;
109 {
110 
111 	panic("softdep_flushfiles called");
112 }
113 
114 int
115 softdep_mount(devvp, mp, fs, cred)
116 	struct vnode *devvp;
117 	struct mount *mp;
118 	struct fs *fs;
119 	struct ucred *cred;
120 {
121 
122 	return (0);
123 }
124 
125 void
126 softdep_initialize()
127 {
128 
129 	return;
130 }
131 
132 void
133 softdep_uninitialize()
134 {
135 
136 	return;
137 }
138 
139 void
140 softdep_unmount(mp)
141 	struct mount *mp;
142 {
143 
144 	panic("softdep_unmount called");
145 }
146 
147 void
148 softdep_setup_sbupdate(ump, fs, bp)
149 	struct ufsmount *ump;
150 	struct fs *fs;
151 	struct buf *bp;
152 {
153 
154 	panic("softdep_setup_sbupdate called");
155 }
156 
157 void
158 softdep_setup_inomapdep(bp, ip, newinum, mode)
159 	struct buf *bp;
160 	struct inode *ip;
161 	ino_t newinum;
162 	int mode;
163 {
164 
165 	panic("softdep_setup_inomapdep called");
166 }
167 
168 void
169 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
170 	struct buf *bp;
171 	struct mount *mp;
172 	ufs2_daddr_t newblkno;
173 	int frags;
174 	int oldfrags;
175 {
176 
177 	panic("softdep_setup_blkmapdep called");
178 }
179 
180 void
181 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
182 	struct inode *ip;
183 	ufs_lbn_t lbn;
184 	ufs2_daddr_t newblkno;
185 	ufs2_daddr_t oldblkno;
186 	long newsize;
187 	long oldsize;
188 	struct buf *bp;
189 {
190 
191 	panic("softdep_setup_allocdirect called");
192 }
193 
194 void
195 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
196 	struct inode *ip;
197 	ufs_lbn_t lbn;
198 	ufs2_daddr_t newblkno;
199 	ufs2_daddr_t oldblkno;
200 	long newsize;
201 	long oldsize;
202 	struct buf *bp;
203 {
204 
205 	panic("softdep_setup_allocext called");
206 }
207 
208 void
209 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
210 	struct inode *ip;
211 	ufs_lbn_t lbn;
212 	struct buf *bp;
213 	int ptrno;
214 	ufs2_daddr_t newblkno;
215 	ufs2_daddr_t oldblkno;
216 	struct buf *nbp;
217 {
218 
219 	panic("softdep_setup_allocindir_page called");
220 }
221 
222 void
223 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
224 	struct buf *nbp;
225 	struct inode *ip;
226 	struct buf *bp;
227 	int ptrno;
228 	ufs2_daddr_t newblkno;
229 {
230 
231 	panic("softdep_setup_allocindir_meta called");
232 }
233 
234 void
235 softdep_journal_freeblocks(ip, cred, length, flags)
236 	struct inode *ip;
237 	struct ucred *cred;
238 	off_t length;
239 	int flags;
240 {
241 
242 	panic("softdep_journal_freeblocks called");
243 }
244 
245 void
246 softdep_journal_fsync(ip)
247 	struct inode *ip;
248 {
249 
250 	panic("softdep_journal_fsync called");
251 }
252 
253 void
254 softdep_setup_freeblocks(ip, length, flags)
255 	struct inode *ip;
256 	off_t length;
257 	int flags;
258 {
259 
260 	panic("softdep_setup_freeblocks called");
261 }
262 
263 void
264 softdep_freefile(pvp, ino, mode)
265 		struct vnode *pvp;
266 		ino_t ino;
267 		int mode;
268 {
269 
270 	panic("softdep_freefile called");
271 }
272 
273 int
274 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
275 	struct buf *bp;
276 	struct inode *dp;
277 	off_t diroffset;
278 	ino_t newinum;
279 	struct buf *newdirbp;
280 	int isnewblk;
281 {
282 
283 	panic("softdep_setup_directory_add called");
284 }
285 
286 void
287 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
288 	struct buf *bp;
289 	struct inode *dp;
290 	caddr_t base;
291 	caddr_t oldloc;
292 	caddr_t newloc;
293 	int entrysize;
294 {
295 
296 	panic("softdep_change_directoryentry_offset called");
297 }
298 
299 void
300 softdep_setup_remove(bp, dp, ip, isrmdir)
301 	struct buf *bp;
302 	struct inode *dp;
303 	struct inode *ip;
304 	int isrmdir;
305 {
306 
307 	panic("softdep_setup_remove called");
308 }
309 
310 void
311 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
312 	struct buf *bp;
313 	struct inode *dp;
314 	struct inode *ip;
315 	ino_t newinum;
316 	int isrmdir;
317 {
318 
319 	panic("softdep_setup_directory_change called");
320 }
321 
322 void
323 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
324 	struct mount *mp;
325 	struct buf *bp;
326 	ufs2_daddr_t blkno;
327 	int frags;
328 	struct workhead *wkhd;
329 {
330 
331 	panic("%s called", __FUNCTION__);
332 }
333 
334 void
335 softdep_setup_inofree(mp, bp, ino, wkhd)
336 	struct mount *mp;
337 	struct buf *bp;
338 	ino_t ino;
339 	struct workhead *wkhd;
340 {
341 
342 	panic("%s called", __FUNCTION__);
343 }
344 
345 void
346 softdep_setup_unlink(dp, ip)
347 	struct inode *dp;
348 	struct inode *ip;
349 {
350 
351 	panic("%s called", __FUNCTION__);
352 }
353 
354 void
355 softdep_setup_link(dp, ip)
356 	struct inode *dp;
357 	struct inode *ip;
358 {
359 
360 	panic("%s called", __FUNCTION__);
361 }
362 
363 void
364 softdep_revert_link(dp, ip)
365 	struct inode *dp;
366 	struct inode *ip;
367 {
368 
369 	panic("%s called", __FUNCTION__);
370 }
371 
372 void
373 softdep_setup_rmdir(dp, ip)
374 	struct inode *dp;
375 	struct inode *ip;
376 {
377 
378 	panic("%s called", __FUNCTION__);
379 }
380 
381 void
382 softdep_revert_rmdir(dp, ip)
383 	struct inode *dp;
384 	struct inode *ip;
385 {
386 
387 	panic("%s called", __FUNCTION__);
388 }
389 
390 void
391 softdep_setup_create(dp, ip)
392 	struct inode *dp;
393 	struct inode *ip;
394 {
395 
396 	panic("%s called", __FUNCTION__);
397 }
398 
399 void
400 softdep_revert_create(dp, ip)
401 	struct inode *dp;
402 	struct inode *ip;
403 {
404 
405 	panic("%s called", __FUNCTION__);
406 }
407 
408 void
409 softdep_setup_mkdir(dp, ip)
410 	struct inode *dp;
411 	struct inode *ip;
412 {
413 
414 	panic("%s called", __FUNCTION__);
415 }
416 
417 void
418 softdep_revert_mkdir(dp, ip)
419 	struct inode *dp;
420 	struct inode *ip;
421 {
422 
423 	panic("%s called", __FUNCTION__);
424 }
425 
426 void
427 softdep_setup_dotdot_link(dp, ip)
428 	struct inode *dp;
429 	struct inode *ip;
430 {
431 
432 	panic("%s called", __FUNCTION__);
433 }
434 
435 int
436 softdep_prealloc(vp, waitok)
437 	struct vnode *vp;
438 	int waitok;
439 {
440 
441 	panic("%s called", __FUNCTION__);
442 }
443 
444 int
445 softdep_journal_lookup(mp, vpp)
446 	struct mount *mp;
447 	struct vnode **vpp;
448 {
449 
450 	return (ENOENT);
451 }
452 
453 void
454 softdep_change_linkcnt(ip)
455 	struct inode *ip;
456 {
457 
458 	panic("softdep_change_linkcnt called");
459 }
460 
461 void
462 softdep_load_inodeblock(ip)
463 	struct inode *ip;
464 {
465 
466 	panic("softdep_load_inodeblock called");
467 }
468 
469 void
470 softdep_update_inodeblock(ip, bp, waitfor)
471 	struct inode *ip;
472 	struct buf *bp;
473 	int waitfor;
474 {
475 
476 	panic("softdep_update_inodeblock called");
477 }
478 
479 int
480 softdep_fsync(vp)
481 	struct vnode *vp;	/* the "in_core" copy of the inode */
482 {
483 
484 	return (0);
485 }
486 
487 void
488 softdep_fsync_mountdev(vp)
489 	struct vnode *vp;
490 {
491 
492 	return;
493 }
494 
495 int
496 softdep_flushworklist(oldmnt, countp, td)
497 	struct mount *oldmnt;
498 	int *countp;
499 	struct thread *td;
500 {
501 
502 	*countp = 0;
503 	return (0);
504 }
505 
506 int
507 softdep_sync_metadata(struct vnode *vp)
508 {
509 
510 	panic("softdep_sync_metadata called");
511 }
512 
513 int
514 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
515 {
516 
517 	panic("softdep_sync_buf called");
518 }
519 
520 int
521 softdep_slowdown(vp)
522 	struct vnode *vp;
523 {
524 
525 	panic("softdep_slowdown called");
526 }
527 
528 int
529 softdep_request_cleanup(fs, vp, cred, resource)
530 	struct fs *fs;
531 	struct vnode *vp;
532 	struct ucred *cred;
533 	int resource;
534 {
535 
536 	return (0);
537 }
538 
539 int
540 softdep_check_suspend(struct mount *mp,
541 		      struct vnode *devvp,
542 		      int softdep_depcnt,
543 		      int softdep_accdepcnt,
544 		      int secondary_writes,
545 		      int secondary_accwrites)
546 {
547 	struct bufobj *bo;
548 	int error;
549 
550 	(void) softdep_depcnt,
551 	(void) softdep_accdepcnt;
552 
553 	bo = &devvp->v_bufobj;
554 	ASSERT_BO_WLOCKED(bo);
555 
556 	MNT_ILOCK(mp);
557 	while (mp->mnt_secondary_writes != 0) {
558 		BO_UNLOCK(bo);
559 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
560 		    (PUSER - 1) | PDROP, "secwr", 0);
561 		BO_LOCK(bo);
562 		MNT_ILOCK(mp);
563 	}
564 
565 	/*
566 	 * Reasons for needing more work before suspend:
567 	 * - Dirty buffers on devvp.
568 	 * - Secondary writes occurred after start of vnode sync loop
569 	 */
570 	error = 0;
571 	if (bo->bo_numoutput > 0 ||
572 	    bo->bo_dirty.bv_cnt > 0 ||
573 	    secondary_writes != 0 ||
574 	    mp->mnt_secondary_writes != 0 ||
575 	    secondary_accwrites != mp->mnt_secondary_accwrites)
576 		error = EAGAIN;
577 	BO_UNLOCK(bo);
578 	return (error);
579 }
580 
581 void
582 softdep_get_depcounts(struct mount *mp,
583 		      int *softdepactivep,
584 		      int *softdepactiveaccp)
585 {
586 	(void) mp;
587 	*softdepactivep = 0;
588 	*softdepactiveaccp = 0;
589 }
590 
591 void
592 softdep_buf_append(bp, wkhd)
593 	struct buf *bp;
594 	struct workhead *wkhd;
595 {
596 
597 	panic("softdep_buf_appendwork called");
598 }
599 
600 void
601 softdep_inode_append(ip, cred, wkhd)
602 	struct inode *ip;
603 	struct ucred *cred;
604 	struct workhead *wkhd;
605 {
606 
607 	panic("softdep_inode_appendwork called");
608 }
609 
610 void
611 softdep_freework(wkhd)
612 	struct workhead *wkhd;
613 {
614 
615 	panic("softdep_freework called");
616 }
617 
618 #else
619 
620 FEATURE(softupdates, "FFS soft-updates support");
621 
622 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
623     "soft updates stats");
624 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
625     "total dependencies allocated");
626 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
627     "high use dependencies allocated");
628 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
629     "current dependencies allocated");
630 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
631     "current dependencies written");
632 
633 unsigned long dep_current[D_LAST + 1];
634 unsigned long dep_highuse[D_LAST + 1];
635 unsigned long dep_total[D_LAST + 1];
636 unsigned long dep_write[D_LAST + 1];
637 
638 #define	SOFTDEP_TYPE(type, str, long)					\
639     static MALLOC_DEFINE(M_ ## type, #str, long);			\
640     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
641 	&dep_total[D_ ## type], 0, "");					\
642     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
643 	&dep_current[D_ ## type], 0, "");				\
644     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
645 	&dep_highuse[D_ ## type], 0, "");				\
646     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
647 	&dep_write[D_ ## type], 0, "");
648 
649 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
650 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
651 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
652     "Block or frag allocated from cyl group map");
653 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
654 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
655 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
656 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
657 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
658 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
659 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
660 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
661 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
662 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
663 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
664 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
665 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
666 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
667 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
668 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
669 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
670 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
671 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
672 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
673 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
674 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
675 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
676 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
677 
678 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
679 
680 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
681 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
682 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
683 
684 #define M_SOFTDEP_FLAGS	(M_WAITOK)
685 
686 /*
687  * translate from workitem type to memory type
688  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
689  */
690 static struct malloc_type *memtype[] = {
691 	NULL,
692 	M_PAGEDEP,
693 	M_INODEDEP,
694 	M_BMSAFEMAP,
695 	M_NEWBLK,
696 	M_ALLOCDIRECT,
697 	M_INDIRDEP,
698 	M_ALLOCINDIR,
699 	M_FREEFRAG,
700 	M_FREEBLKS,
701 	M_FREEFILE,
702 	M_DIRADD,
703 	M_MKDIR,
704 	M_DIRREM,
705 	M_NEWDIRBLK,
706 	M_FREEWORK,
707 	M_FREEDEP,
708 	M_JADDREF,
709 	M_JREMREF,
710 	M_JMVREF,
711 	M_JNEWBLK,
712 	M_JFREEBLK,
713 	M_JFREEFRAG,
714 	M_JSEG,
715 	M_JSEGDEP,
716 	M_SBDEP,
717 	M_JTRUNC,
718 	M_JFSYNC,
719 	M_SENTINEL
720 };
721 
722 #define DtoM(type) (memtype[type])
723 
724 /*
725  * Names of malloc types.
726  */
727 #define TYPENAME(type)  \
728 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
729 	memtype[type]->ks_shortdesc : "???")
730 /*
731  * End system adaptation definitions.
732  */
733 
734 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
735 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
736 
737 /*
738  * Internal function prototypes.
739  */
740 static	void check_clear_deps(struct mount *);
741 static	void softdep_error(char *, int);
742 static	int softdep_process_worklist(struct mount *, int);
743 static	int softdep_waitidle(struct mount *, int);
744 static	void drain_output(struct vnode *);
745 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
746 static	int check_inodedep_free(struct inodedep *);
747 static	void clear_remove(struct mount *);
748 static	void clear_inodedeps(struct mount *);
749 static	void unlinked_inodedep(struct mount *, struct inodedep *);
750 static	void clear_unlinked_inodedep(struct inodedep *);
751 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
752 static	int flush_pagedep_deps(struct vnode *, struct mount *,
753 	    struct diraddhd *);
754 static	int free_pagedep(struct pagedep *);
755 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
756 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
757 static	int flush_deplist(struct allocdirectlst *, int, int *);
758 static	int sync_cgs(struct mount *, int);
759 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
760 static	int handle_written_sbdep(struct sbdep *, struct buf *);
761 static	void initiate_write_sbdep(struct sbdep *);
762 static	void diradd_inode_written(struct diradd *, struct inodedep *);
763 static	int handle_written_indirdep(struct indirdep *, struct buf *,
764 	    struct buf**, int);
765 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
766 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
767 	    uint8_t *);
768 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
769 static	void handle_written_jaddref(struct jaddref *);
770 static	void handle_written_jremref(struct jremref *);
771 static	void handle_written_jseg(struct jseg *, struct buf *);
772 static	void handle_written_jnewblk(struct jnewblk *);
773 static	void handle_written_jblkdep(struct jblkdep *);
774 static	void handle_written_jfreefrag(struct jfreefrag *);
775 static	void complete_jseg(struct jseg *);
776 static	void complete_jsegs(struct jseg *);
777 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
778 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
779 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
780 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
781 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
782 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
783 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
784 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
785 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
786 static	inline void inoref_write(struct inoref *, struct jseg *,
787 	    struct jrefrec *);
788 static	void handle_allocdirect_partdone(struct allocdirect *,
789 	    struct workhead *);
790 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
791 	    struct workhead *);
792 static	void indirdep_complete(struct indirdep *);
793 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
794 static	void indirblk_insert(struct freework *);
795 static	void indirblk_remove(struct freework *);
796 static	void handle_allocindir_partdone(struct allocindir *);
797 static	void initiate_write_filepage(struct pagedep *, struct buf *);
798 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
799 static	void handle_written_mkdir(struct mkdir *, int);
800 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
801 	    uint8_t *);
802 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
803 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
804 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
805 static	void handle_workitem_freefile(struct freefile *);
806 static	int handle_workitem_remove(struct dirrem *, int);
807 static	struct dirrem *newdirrem(struct buf *, struct inode *,
808 	    struct inode *, int, struct dirrem **);
809 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
810 	    struct buf *);
811 static	void cancel_indirdep(struct indirdep *, struct buf *,
812 	    struct freeblks *);
813 static	void free_indirdep(struct indirdep *);
814 static	void free_diradd(struct diradd *, struct workhead *);
815 static	void merge_diradd(struct inodedep *, struct diradd *);
816 static	void complete_diradd(struct diradd *);
817 static	struct diradd *diradd_lookup(struct pagedep *, int);
818 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
819 	    struct jremref *);
820 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
821 	    struct jremref *);
822 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
823 	    struct jremref *, struct jremref *);
824 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
825 	    struct jremref *);
826 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
827 	    struct freeblks *, int);
828 static	int setup_trunc_indir(struct freeblks *, struct inode *,
829 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
830 static	void complete_trunc_indir(struct freework *);
831 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
832 	    int);
833 static	void complete_mkdir(struct mkdir *);
834 static	void free_newdirblk(struct newdirblk *);
835 static	void free_jremref(struct jremref *);
836 static	void free_jaddref(struct jaddref *);
837 static	void free_jsegdep(struct jsegdep *);
838 static	void free_jsegs(struct jblocks *);
839 static	void rele_jseg(struct jseg *);
840 static	void free_jseg(struct jseg *, struct jblocks *);
841 static	void free_jnewblk(struct jnewblk *);
842 static	void free_jblkdep(struct jblkdep *);
843 static	void free_jfreefrag(struct jfreefrag *);
844 static	void free_freedep(struct freedep *);
845 static	void journal_jremref(struct dirrem *, struct jremref *,
846 	    struct inodedep *);
847 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
848 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
849 	    struct workhead *);
850 static	void cancel_jfreefrag(struct jfreefrag *);
851 static	inline void setup_freedirect(struct freeblks *, struct inode *,
852 	    int, int);
853 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
854 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
855 	    ufs_lbn_t, int);
856 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
857 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
858 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
859 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
860 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
861 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
862 	    int, int);
863 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
864 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
865 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
866 static	void newblk_freefrag(struct newblk*);
867 static	void free_newblk(struct newblk *);
868 static	void cancel_allocdirect(struct allocdirectlst *,
869 	    struct allocdirect *, struct freeblks *);
870 static	int check_inode_unwritten(struct inodedep *);
871 static	int free_inodedep(struct inodedep *);
872 static	void freework_freeblock(struct freework *, u_long);
873 static	void freework_enqueue(struct freework *);
874 static	int handle_workitem_freeblocks(struct freeblks *, int);
875 static	int handle_complete_freeblocks(struct freeblks *, int);
876 static	void handle_workitem_indirblk(struct freework *);
877 static	void handle_written_freework(struct freework *);
878 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
879 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
880 	    struct workhead *);
881 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
882 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
883 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
884 	    ufs2_daddr_t, ufs_lbn_t);
885 static	void handle_workitem_freefrag(struct freefrag *);
886 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
887 	    ufs_lbn_t, u_long);
888 static	void allocdirect_merge(struct allocdirectlst *,
889 	    struct allocdirect *, struct allocdirect *);
890 static	struct freefrag *allocindir_merge(struct allocindir *,
891 	    struct allocindir *);
892 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
893 	    struct bmsafemap **);
894 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
895 	    int cg, struct bmsafemap *);
896 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
897 	    struct newblk **);
898 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
899 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
900 	    struct inodedep **);
901 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
902 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
903 	    int, struct pagedep **);
904 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
905 	    struct pagedep **);
906 static	void pause_timer(void *);
907 static	int request_cleanup(struct mount *, int);
908 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
909 static	void schedule_cleanup(struct mount *);
910 static void softdep_ast_cleanup_proc(struct thread *);
911 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
912 static	int process_worklist_item(struct mount *, int, int);
913 static	void process_removes(struct vnode *);
914 static	void process_truncates(struct vnode *);
915 static	void jwork_move(struct workhead *, struct workhead *);
916 static	void jwork_insert(struct workhead *, struct jsegdep *);
917 static	void add_to_worklist(struct worklist *, int);
918 static	void wake_worklist(struct worklist *);
919 static	void wait_worklist(struct worklist *, char *);
920 static	void remove_from_worklist(struct worklist *);
921 static	void softdep_flush(void *);
922 static	void softdep_flushjournal(struct mount *);
923 static	int softdep_speedup(struct ufsmount *);
924 static	void worklist_speedup(struct mount *);
925 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
926 static	void journal_unmount(struct ufsmount *);
927 static	int journal_space(struct ufsmount *, int);
928 static	void journal_suspend(struct ufsmount *);
929 static	int journal_unsuspend(struct ufsmount *ump);
930 static	void softdep_prelink(struct vnode *, struct vnode *);
931 static	void add_to_journal(struct worklist *);
932 static	void remove_from_journal(struct worklist *);
933 static	bool softdep_excess_items(struct ufsmount *, int);
934 static	void softdep_process_journal(struct mount *, struct worklist *, int);
935 static	struct jremref *newjremref(struct dirrem *, struct inode *,
936 	    struct inode *ip, off_t, nlink_t);
937 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
938 	    uint16_t);
939 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
940 	    uint16_t);
941 static	inline struct jsegdep *inoref_jseg(struct inoref *);
942 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
943 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
944 	    ufs2_daddr_t, int);
945 static	void adjust_newfreework(struct freeblks *, int);
946 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
947 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
948 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
949 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
950 	    ufs2_daddr_t, long, ufs_lbn_t);
951 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
952 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
953 static	int jwait(struct worklist *, int);
954 static	struct inodedep *inodedep_lookup_ip(struct inode *);
955 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
956 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
957 static	void handle_jwork(struct workhead *);
958 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
959 	    struct mkdir **);
960 static	struct jblocks *jblocks_create(void);
961 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
962 static	void jblocks_free(struct jblocks *, struct mount *, int);
963 static	void jblocks_destroy(struct jblocks *);
964 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
965 
966 /*
967  * Exported softdep operations.
968  */
969 static	void softdep_disk_io_initiation(struct buf *);
970 static	void softdep_disk_write_complete(struct buf *);
971 static	void softdep_deallocate_dependencies(struct buf *);
972 static	int softdep_count_dependencies(struct buf *bp, int);
973 
974 /*
975  * Global lock over all of soft updates.
976  */
977 static struct mtx lk;
978 MTX_SYSINIT(softdep_lock, &lk, "Global Softdep Lock", MTX_DEF);
979 
980 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
981 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
982 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
983 
984 /*
985  * Per-filesystem soft-updates locking.
986  */
987 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
988 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
989 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
990 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
991 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
992 				    RA_WLOCKED)
993 
994 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
995 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
996 
997 /*
998  * Worklist queue management.
999  * These routines require that the lock be held.
1000  */
1001 #ifndef /* NOT */ DEBUG
1002 #define WORKLIST_INSERT(head, item) do {	\
1003 	(item)->wk_state |= ONWORKLIST;		\
1004 	LIST_INSERT_HEAD(head, item, wk_list);	\
1005 } while (0)
1006 #define WORKLIST_REMOVE(item) do {		\
1007 	(item)->wk_state &= ~ONWORKLIST;	\
1008 	LIST_REMOVE(item, wk_list);		\
1009 } while (0)
1010 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1011 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1012 
1013 #else /* DEBUG */
1014 static	void worklist_insert(struct workhead *, struct worklist *, int);
1015 static	void worklist_remove(struct worklist *, int);
1016 
1017 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1018 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1019 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1020 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1021 
1022 static void
1023 worklist_insert(head, item, locked)
1024 	struct workhead *head;
1025 	struct worklist *item;
1026 	int locked;
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 		    item, TYPENAME(item->wk_type), item->wk_state);
1034 	item->wk_state |= ONWORKLIST;
1035 	LIST_INSERT_HEAD(head, item, wk_list);
1036 }
1037 
1038 static void
1039 worklist_remove(item, locked)
1040 	struct worklist *item;
1041 	int locked;
1042 {
1043 
1044 	if (locked)
1045 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1046 	if ((item->wk_state & ONWORKLIST) == 0)
1047 		panic("worklist_remove: %p %s(0x%X) not on list",
1048 		    item, TYPENAME(item->wk_type), item->wk_state);
1049 	item->wk_state &= ~ONWORKLIST;
1050 	LIST_REMOVE(item, wk_list);
1051 }
1052 #endif /* DEBUG */
1053 
1054 /*
1055  * Merge two jsegdeps keeping only the oldest one as newer references
1056  * can't be discarded until after older references.
1057  */
1058 static inline struct jsegdep *
1059 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1060 {
1061 	struct jsegdep *swp;
1062 
1063 	if (two == NULL)
1064 		return (one);
1065 
1066 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1067 		swp = one;
1068 		one = two;
1069 		two = swp;
1070 	}
1071 	WORKLIST_REMOVE(&two->jd_list);
1072 	free_jsegdep(two);
1073 
1074 	return (one);
1075 }
1076 
1077 /*
1078  * If two freedeps are compatible free one to reduce list size.
1079  */
1080 static inline struct freedep *
1081 freedep_merge(struct freedep *one, struct freedep *two)
1082 {
1083 	if (two == NULL)
1084 		return (one);
1085 
1086 	if (one->fd_freework == two->fd_freework) {
1087 		WORKLIST_REMOVE(&two->fd_list);
1088 		free_freedep(two);
1089 	}
1090 	return (one);
1091 }
1092 
1093 /*
1094  * Move journal work from one list to another.  Duplicate freedeps and
1095  * jsegdeps are coalesced to keep the lists as small as possible.
1096  */
1097 static void
1098 jwork_move(dst, src)
1099 	struct workhead *dst;
1100 	struct workhead *src;
1101 {
1102 	struct freedep *freedep;
1103 	struct jsegdep *jsegdep;
1104 	struct worklist *wkn;
1105 	struct worklist *wk;
1106 
1107 	KASSERT(dst != src,
1108 	    ("jwork_move: dst == src"));
1109 	freedep = NULL;
1110 	jsegdep = NULL;
1111 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1112 		if (wk->wk_type == D_JSEGDEP)
1113 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1114 		else if (wk->wk_type == D_FREEDEP)
1115 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1116 	}
1117 
1118 	while ((wk = LIST_FIRST(src)) != NULL) {
1119 		WORKLIST_REMOVE(wk);
1120 		WORKLIST_INSERT(dst, wk);
1121 		if (wk->wk_type == D_JSEGDEP) {
1122 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1123 			continue;
1124 		}
1125 		if (wk->wk_type == D_FREEDEP)
1126 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1127 	}
1128 }
1129 
1130 static void
1131 jwork_insert(dst, jsegdep)
1132 	struct workhead *dst;
1133 	struct jsegdep *jsegdep;
1134 {
1135 	struct jsegdep *jsegdepn;
1136 	struct worklist *wk;
1137 
1138 	LIST_FOREACH(wk, dst, wk_list)
1139 		if (wk->wk_type == D_JSEGDEP)
1140 			break;
1141 	if (wk == NULL) {
1142 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1143 		return;
1144 	}
1145 	jsegdepn = WK_JSEGDEP(wk);
1146 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1147 		WORKLIST_REMOVE(wk);
1148 		free_jsegdep(jsegdepn);
1149 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1150 	} else
1151 		free_jsegdep(jsegdep);
1152 }
1153 
1154 /*
1155  * Routines for tracking and managing workitems.
1156  */
1157 static	void workitem_free(struct worklist *, int);
1158 static	void workitem_alloc(struct worklist *, int, struct mount *);
1159 static	void workitem_reassign(struct worklist *, int);
1160 
1161 #define	WORKITEM_FREE(item, type) \
1162 	workitem_free((struct worklist *)(item), (type))
1163 #define	WORKITEM_REASSIGN(item, type) \
1164 	workitem_reassign((struct worklist *)(item), (type))
1165 
1166 static void
1167 workitem_free(item, type)
1168 	struct worklist *item;
1169 	int type;
1170 {
1171 	struct ufsmount *ump;
1172 
1173 #ifdef DEBUG
1174 	if (item->wk_state & ONWORKLIST)
1175 		panic("workitem_free: %s(0x%X) still on list",
1176 		    TYPENAME(item->wk_type), item->wk_state);
1177 	if (item->wk_type != type && type != D_NEWBLK)
1178 		panic("workitem_free: type mismatch %s != %s",
1179 		    TYPENAME(item->wk_type), TYPENAME(type));
1180 #endif
1181 	if (item->wk_state & IOWAITING)
1182 		wakeup(item);
1183 	ump = VFSTOUFS(item->wk_mp);
1184 	LOCK_OWNED(ump);
1185 	KASSERT(ump->softdep_deps > 0,
1186 	    ("workitem_free: %s: softdep_deps going negative",
1187 	    ump->um_fs->fs_fsmnt));
1188 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1189 		wakeup(&ump->softdep_deps);
1190 	KASSERT(dep_current[item->wk_type] > 0,
1191 	    ("workitem_free: %s: dep_current[%s] going negative",
1192 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1193 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1194 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1195 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1196 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1197 	ump->softdep_curdeps[item->wk_type] -= 1;
1198 	free(item, DtoM(type));
1199 }
1200 
1201 static void
1202 workitem_alloc(item, type, mp)
1203 	struct worklist *item;
1204 	int type;
1205 	struct mount *mp;
1206 {
1207 	struct ufsmount *ump;
1208 
1209 	item->wk_type = type;
1210 	item->wk_mp = mp;
1211 	item->wk_state = 0;
1212 
1213 	ump = VFSTOUFS(mp);
1214 	ACQUIRE_GBLLOCK(&lk);
1215 	dep_current[type]++;
1216 	if (dep_current[type] > dep_highuse[type])
1217 		dep_highuse[type] = dep_current[type];
1218 	dep_total[type]++;
1219 	FREE_GBLLOCK(&lk);
1220 	ACQUIRE_LOCK(ump);
1221 	ump->softdep_curdeps[type] += 1;
1222 	ump->softdep_deps++;
1223 	ump->softdep_accdeps++;
1224 	FREE_LOCK(ump);
1225 }
1226 
1227 static void
1228 workitem_reassign(item, newtype)
1229 	struct worklist *item;
1230 	int newtype;
1231 {
1232 	struct ufsmount *ump;
1233 
1234 	ump = VFSTOUFS(item->wk_mp);
1235 	LOCK_OWNED(ump);
1236 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1237 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1238 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1239 	ump->softdep_curdeps[item->wk_type] -= 1;
1240 	ump->softdep_curdeps[newtype] += 1;
1241 	KASSERT(dep_current[item->wk_type] > 0,
1242 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1243 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1244 	ACQUIRE_GBLLOCK(&lk);
1245 	dep_current[newtype]++;
1246 	dep_current[item->wk_type]--;
1247 	if (dep_current[newtype] > dep_highuse[newtype])
1248 		dep_highuse[newtype] = dep_current[newtype];
1249 	dep_total[newtype]++;
1250 	FREE_GBLLOCK(&lk);
1251 	item->wk_type = newtype;
1252 }
1253 
1254 /*
1255  * Workitem queue management
1256  */
1257 static int max_softdeps;	/* maximum number of structs before slowdown */
1258 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1259 static int proc_waiting;	/* tracks whether we have a timeout posted */
1260 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1261 static struct callout softdep_callout;
1262 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1263 static int req_clear_remove;	/* syncer process flush some freeblks */
1264 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1265 
1266 /*
1267  * runtime statistics
1268  */
1269 static int stat_flush_threads;	/* number of softdep flushing threads */
1270 static int stat_worklist_push;	/* number of worklist cleanups */
1271 static int stat_blk_limit_push;	/* number of times block limit neared */
1272 static int stat_ino_limit_push;	/* number of times inode limit neared */
1273 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1274 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1275 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1276 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1277 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1278 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1279 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1280 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1281 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1282 static int stat_journal_min;	/* Times hit journal min threshold */
1283 static int stat_journal_low;	/* Times hit journal low threshold */
1284 static int stat_journal_wait;	/* Times blocked in jwait(). */
1285 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1286 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1287 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1288 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1289 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1290 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1291 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1292 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1293 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1294 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1295 
1296 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1297     &max_softdeps, 0, "");
1298 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1299     &tickdelay, 0, "");
1300 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1301     &stat_flush_threads, 0, "");
1302 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1303     &stat_worklist_push, 0,"");
1304 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1305     &stat_blk_limit_push, 0,"");
1306 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1307     &stat_ino_limit_push, 0,"");
1308 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1309     &stat_blk_limit_hit, 0, "");
1310 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1311     &stat_ino_limit_hit, 0, "");
1312 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1313     &stat_sync_limit_hit, 0, "");
1314 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1315     &stat_indir_blk_ptrs, 0, "");
1316 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1317     &stat_inode_bitmap, 0, "");
1318 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1319     &stat_direct_blk_ptrs, 0, "");
1320 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1321     &stat_dir_entry, 0, "");
1322 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1323     &stat_jaddref, 0, "");
1324 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1325     &stat_jnewblk, 0, "");
1326 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1327     &stat_journal_low, 0, "");
1328 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1329     &stat_journal_min, 0, "");
1330 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1331     &stat_journal_wait, 0, "");
1332 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1333     &stat_jwait_filepage, 0, "");
1334 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1335     &stat_jwait_freeblks, 0, "");
1336 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1337     &stat_jwait_inode, 0, "");
1338 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1339     &stat_jwait_newblk, 0, "");
1340 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1341     &stat_cleanup_blkrequests, 0, "");
1342 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1343     &stat_cleanup_inorequests, 0, "");
1344 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1345     &stat_cleanup_high_delay, 0, "");
1346 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1347     &stat_cleanup_retries, 0, "");
1348 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1349     &stat_cleanup_failures, 0, "");
1350 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1351     &softdep_flushcache, 0, "");
1352 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1353     &stat_emptyjblocks, 0, "");
1354 
1355 SYSCTL_DECL(_vfs_ffs);
1356 
1357 /* Whether to recompute the summary at mount time */
1358 static int compute_summary_at_mount = 0;
1359 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1360 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1361 static int print_threads = 0;
1362 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1363     &print_threads, 0, "Notify flusher thread start/stop");
1364 
1365 /* List of all filesystems mounted with soft updates */
1366 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1367 
1368 /*
1369  * This function cleans the worklist for a filesystem.
1370  * Each filesystem running with soft dependencies gets its own
1371  * thread to run in this function. The thread is started up in
1372  * softdep_mount and shutdown in softdep_unmount. They show up
1373  * as part of the kernel "bufdaemon" process whose process
1374  * entry is available in bufdaemonproc.
1375  */
1376 static int searchfailed;
1377 extern struct proc *bufdaemonproc;
1378 static void
1379 softdep_flush(addr)
1380 	void *addr;
1381 {
1382 	struct mount *mp;
1383 	struct thread *td;
1384 	struct ufsmount *ump;
1385 
1386 	td = curthread;
1387 	td->td_pflags |= TDP_NORUNNINGBUF;
1388 	mp = (struct mount *)addr;
1389 	ump = VFSTOUFS(mp);
1390 	atomic_add_int(&stat_flush_threads, 1);
1391 	ACQUIRE_LOCK(ump);
1392 	ump->softdep_flags &= ~FLUSH_STARTING;
1393 	wakeup(&ump->softdep_flushtd);
1394 	FREE_LOCK(ump);
1395 	if (print_threads) {
1396 		if (stat_flush_threads == 1)
1397 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1398 			    bufdaemonproc->p_pid);
1399 		printf("Start thread %s\n", td->td_name);
1400 	}
1401 	for (;;) {
1402 		while (softdep_process_worklist(mp, 0) > 0 ||
1403 		    (MOUNTEDSUJ(mp) &&
1404 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1405 			kthread_suspend_check();
1406 		ACQUIRE_LOCK(ump);
1407 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1408 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1409 			    "sdflush", hz / 2);
1410 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1411 		/*
1412 		 * Check to see if we are done and need to exit.
1413 		 */
1414 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1415 			FREE_LOCK(ump);
1416 			continue;
1417 		}
1418 		ump->softdep_flags &= ~FLUSH_EXIT;
1419 		FREE_LOCK(ump);
1420 		wakeup(&ump->softdep_flags);
1421 		if (print_threads)
1422 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1423 		atomic_subtract_int(&stat_flush_threads, 1);
1424 		kthread_exit();
1425 		panic("kthread_exit failed\n");
1426 	}
1427 }
1428 
1429 static void
1430 worklist_speedup(mp)
1431 	struct mount *mp;
1432 {
1433 	struct ufsmount *ump;
1434 
1435 	ump = VFSTOUFS(mp);
1436 	LOCK_OWNED(ump);
1437 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1438 		ump->softdep_flags |= FLUSH_CLEANUP;
1439 	wakeup(&ump->softdep_flushtd);
1440 }
1441 
1442 static int
1443 softdep_speedup(ump)
1444 	struct ufsmount *ump;
1445 {
1446 	struct ufsmount *altump;
1447 	struct mount_softdeps *sdp;
1448 
1449 	LOCK_OWNED(ump);
1450 	worklist_speedup(ump->um_mountp);
1451 	bd_speedup();
1452 	/*
1453 	 * If we have global shortages, then we need other
1454 	 * filesystems to help with the cleanup. Here we wakeup a
1455 	 * flusher thread for a filesystem that is over its fair
1456 	 * share of resources.
1457 	 */
1458 	if (req_clear_inodedeps || req_clear_remove) {
1459 		ACQUIRE_GBLLOCK(&lk);
1460 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1461 			if ((altump = sdp->sd_ump) == ump)
1462 				continue;
1463 			if (((req_clear_inodedeps &&
1464 			    altump->softdep_curdeps[D_INODEDEP] >
1465 			    max_softdeps / stat_flush_threads) ||
1466 			    (req_clear_remove &&
1467 			    altump->softdep_curdeps[D_DIRREM] >
1468 			    (max_softdeps / 2) / stat_flush_threads)) &&
1469 			    TRY_ACQUIRE_LOCK(altump))
1470 				break;
1471 		}
1472 		if (sdp == NULL) {
1473 			searchfailed++;
1474 			FREE_GBLLOCK(&lk);
1475 		} else {
1476 			/*
1477 			 * Move to the end of the list so we pick a
1478 			 * different one on out next try.
1479 			 */
1480 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1481 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1482 			FREE_GBLLOCK(&lk);
1483 			if ((altump->softdep_flags &
1484 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1485 				altump->softdep_flags |= FLUSH_CLEANUP;
1486 			altump->um_softdep->sd_cleanups++;
1487 			wakeup(&altump->softdep_flushtd);
1488 			FREE_LOCK(altump);
1489 		}
1490 	}
1491 	return (speedup_syncer());
1492 }
1493 
1494 /*
1495  * Add an item to the end of the work queue.
1496  * This routine requires that the lock be held.
1497  * This is the only routine that adds items to the list.
1498  * The following routine is the only one that removes items
1499  * and does so in order from first to last.
1500  */
1501 
1502 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1503 #define	WK_NODELAY	0x0002	/* Process immediately. */
1504 
1505 static void
1506 add_to_worklist(wk, flags)
1507 	struct worklist *wk;
1508 	int flags;
1509 {
1510 	struct ufsmount *ump;
1511 
1512 	ump = VFSTOUFS(wk->wk_mp);
1513 	LOCK_OWNED(ump);
1514 	if (wk->wk_state & ONWORKLIST)
1515 		panic("add_to_worklist: %s(0x%X) already on list",
1516 		    TYPENAME(wk->wk_type), wk->wk_state);
1517 	wk->wk_state |= ONWORKLIST;
1518 	if (ump->softdep_on_worklist == 0) {
1519 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1520 		ump->softdep_worklist_tail = wk;
1521 	} else if (flags & WK_HEAD) {
1522 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1523 	} else {
1524 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1525 		ump->softdep_worklist_tail = wk;
1526 	}
1527 	ump->softdep_on_worklist += 1;
1528 	if (flags & WK_NODELAY)
1529 		worklist_speedup(wk->wk_mp);
1530 }
1531 
1532 /*
1533  * Remove the item to be processed. If we are removing the last
1534  * item on the list, we need to recalculate the tail pointer.
1535  */
1536 static void
1537 remove_from_worklist(wk)
1538 	struct worklist *wk;
1539 {
1540 	struct ufsmount *ump;
1541 
1542 	ump = VFSTOUFS(wk->wk_mp);
1543 	if (ump->softdep_worklist_tail == wk)
1544 		ump->softdep_worklist_tail =
1545 		    (struct worklist *)wk->wk_list.le_prev;
1546 	WORKLIST_REMOVE(wk);
1547 	ump->softdep_on_worklist -= 1;
1548 }
1549 
1550 static void
1551 wake_worklist(wk)
1552 	struct worklist *wk;
1553 {
1554 	if (wk->wk_state & IOWAITING) {
1555 		wk->wk_state &= ~IOWAITING;
1556 		wakeup(wk);
1557 	}
1558 }
1559 
1560 static void
1561 wait_worklist(wk, wmesg)
1562 	struct worklist *wk;
1563 	char *wmesg;
1564 {
1565 	struct ufsmount *ump;
1566 
1567 	ump = VFSTOUFS(wk->wk_mp);
1568 	wk->wk_state |= IOWAITING;
1569 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1570 }
1571 
1572 /*
1573  * Process that runs once per second to handle items in the background queue.
1574  *
1575  * Note that we ensure that everything is done in the order in which they
1576  * appear in the queue. The code below depends on this property to ensure
1577  * that blocks of a file are freed before the inode itself is freed. This
1578  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1579  * until all the old ones have been purged from the dependency lists.
1580  */
1581 static int
1582 softdep_process_worklist(mp, full)
1583 	struct mount *mp;
1584 	int full;
1585 {
1586 	int cnt, matchcnt;
1587 	struct ufsmount *ump;
1588 	long starttime;
1589 
1590 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1591 	if (MOUNTEDSOFTDEP(mp) == 0)
1592 		return (0);
1593 	matchcnt = 0;
1594 	ump = VFSTOUFS(mp);
1595 	ACQUIRE_LOCK(ump);
1596 	starttime = time_second;
1597 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1598 	check_clear_deps(mp);
1599 	while (ump->softdep_on_worklist > 0) {
1600 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1601 			break;
1602 		else
1603 			matchcnt += cnt;
1604 		check_clear_deps(mp);
1605 		/*
1606 		 * We do not generally want to stop for buffer space, but if
1607 		 * we are really being a buffer hog, we will stop and wait.
1608 		 */
1609 		if (should_yield()) {
1610 			FREE_LOCK(ump);
1611 			kern_yield(PRI_USER);
1612 			bwillwrite();
1613 			ACQUIRE_LOCK(ump);
1614 		}
1615 		/*
1616 		 * Never allow processing to run for more than one
1617 		 * second. This gives the syncer thread the opportunity
1618 		 * to pause if appropriate.
1619 		 */
1620 		if (!full && starttime != time_second)
1621 			break;
1622 	}
1623 	if (full == 0)
1624 		journal_unsuspend(ump);
1625 	FREE_LOCK(ump);
1626 	return (matchcnt);
1627 }
1628 
1629 /*
1630  * Process all removes associated with a vnode if we are running out of
1631  * journal space.  Any other process which attempts to flush these will
1632  * be unable as we have the vnodes locked.
1633  */
1634 static void
1635 process_removes(vp)
1636 	struct vnode *vp;
1637 {
1638 	struct inodedep *inodedep;
1639 	struct dirrem *dirrem;
1640 	struct ufsmount *ump;
1641 	struct mount *mp;
1642 	ino_t inum;
1643 
1644 	mp = vp->v_mount;
1645 	ump = VFSTOUFS(mp);
1646 	LOCK_OWNED(ump);
1647 	inum = VTOI(vp)->i_number;
1648 	for (;;) {
1649 top:
1650 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1651 			return;
1652 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1653 			/*
1654 			 * If another thread is trying to lock this vnode
1655 			 * it will fail but we must wait for it to do so
1656 			 * before we can proceed.
1657 			 */
1658 			if (dirrem->dm_state & INPROGRESS) {
1659 				wait_worklist(&dirrem->dm_list, "pwrwait");
1660 				goto top;
1661 			}
1662 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1663 			    (COMPLETE | ONWORKLIST))
1664 				break;
1665 		}
1666 		if (dirrem == NULL)
1667 			return;
1668 		remove_from_worklist(&dirrem->dm_list);
1669 		FREE_LOCK(ump);
1670 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1671 			panic("process_removes: suspended filesystem");
1672 		handle_workitem_remove(dirrem, 0);
1673 		vn_finished_secondary_write(mp);
1674 		ACQUIRE_LOCK(ump);
1675 	}
1676 }
1677 
1678 /*
1679  * Process all truncations associated with a vnode if we are running out
1680  * of journal space.  This is called when the vnode lock is already held
1681  * and no other process can clear the truncation.  This function returns
1682  * a value greater than zero if it did any work.
1683  */
1684 static void
1685 process_truncates(vp)
1686 	struct vnode *vp;
1687 {
1688 	struct inodedep *inodedep;
1689 	struct freeblks *freeblks;
1690 	struct ufsmount *ump;
1691 	struct mount *mp;
1692 	ino_t inum;
1693 	int cgwait;
1694 
1695 	mp = vp->v_mount;
1696 	ump = VFSTOUFS(mp);
1697 	LOCK_OWNED(ump);
1698 	inum = VTOI(vp)->i_number;
1699 	for (;;) {
1700 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1701 			return;
1702 		cgwait = 0;
1703 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1704 			/* Journal entries not yet written.  */
1705 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1706 				jwait(&LIST_FIRST(
1707 				    &freeblks->fb_jblkdephd)->jb_list,
1708 				    MNT_WAIT);
1709 				break;
1710 			}
1711 			/* Another thread is executing this item. */
1712 			if (freeblks->fb_state & INPROGRESS) {
1713 				wait_worklist(&freeblks->fb_list, "ptrwait");
1714 				break;
1715 			}
1716 			/* Freeblks is waiting on a inode write. */
1717 			if ((freeblks->fb_state & COMPLETE) == 0) {
1718 				FREE_LOCK(ump);
1719 				ffs_update(vp, 1);
1720 				ACQUIRE_LOCK(ump);
1721 				break;
1722 			}
1723 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1724 			    (ALLCOMPLETE | ONWORKLIST)) {
1725 				remove_from_worklist(&freeblks->fb_list);
1726 				freeblks->fb_state |= INPROGRESS;
1727 				FREE_LOCK(ump);
1728 				if (vn_start_secondary_write(NULL, &mp,
1729 				    V_NOWAIT))
1730 					panic("process_truncates: "
1731 					    "suspended filesystem");
1732 				handle_workitem_freeblocks(freeblks, 0);
1733 				vn_finished_secondary_write(mp);
1734 				ACQUIRE_LOCK(ump);
1735 				break;
1736 			}
1737 			if (freeblks->fb_cgwait)
1738 				cgwait++;
1739 		}
1740 		if (cgwait) {
1741 			FREE_LOCK(ump);
1742 			sync_cgs(mp, MNT_WAIT);
1743 			ffs_sync_snap(mp, MNT_WAIT);
1744 			ACQUIRE_LOCK(ump);
1745 			continue;
1746 		}
1747 		if (freeblks == NULL)
1748 			break;
1749 	}
1750 	return;
1751 }
1752 
1753 /*
1754  * Process one item on the worklist.
1755  */
1756 static int
1757 process_worklist_item(mp, target, flags)
1758 	struct mount *mp;
1759 	int target;
1760 	int flags;
1761 {
1762 	struct worklist sentinel;
1763 	struct worklist *wk;
1764 	struct ufsmount *ump;
1765 	int matchcnt;
1766 	int error;
1767 
1768 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1769 	/*
1770 	 * If we are being called because of a process doing a
1771 	 * copy-on-write, then it is not safe to write as we may
1772 	 * recurse into the copy-on-write routine.
1773 	 */
1774 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1775 		return (-1);
1776 	PHOLD(curproc);	/* Don't let the stack go away. */
1777 	ump = VFSTOUFS(mp);
1778 	LOCK_OWNED(ump);
1779 	matchcnt = 0;
1780 	sentinel.wk_mp = NULL;
1781 	sentinel.wk_type = D_SENTINEL;
1782 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1783 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1784 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1785 		if (wk->wk_type == D_SENTINEL) {
1786 			LIST_REMOVE(&sentinel, wk_list);
1787 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1788 			continue;
1789 		}
1790 		if (wk->wk_state & INPROGRESS)
1791 			panic("process_worklist_item: %p already in progress.",
1792 			    wk);
1793 		wk->wk_state |= INPROGRESS;
1794 		remove_from_worklist(wk);
1795 		FREE_LOCK(ump);
1796 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1797 			panic("process_worklist_item: suspended filesystem");
1798 		switch (wk->wk_type) {
1799 		case D_DIRREM:
1800 			/* removal of a directory entry */
1801 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1802 			break;
1803 
1804 		case D_FREEBLKS:
1805 			/* releasing blocks and/or fragments from a file */
1806 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1807 			    flags);
1808 			break;
1809 
1810 		case D_FREEFRAG:
1811 			/* releasing a fragment when replaced as a file grows */
1812 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1813 			error = 0;
1814 			break;
1815 
1816 		case D_FREEFILE:
1817 			/* releasing an inode when its link count drops to 0 */
1818 			handle_workitem_freefile(WK_FREEFILE(wk));
1819 			error = 0;
1820 			break;
1821 
1822 		default:
1823 			panic("%s_process_worklist: Unknown type %s",
1824 			    "softdep", TYPENAME(wk->wk_type));
1825 			/* NOTREACHED */
1826 		}
1827 		vn_finished_secondary_write(mp);
1828 		ACQUIRE_LOCK(ump);
1829 		if (error == 0) {
1830 			if (++matchcnt == target)
1831 				break;
1832 			continue;
1833 		}
1834 		/*
1835 		 * We have to retry the worklist item later.  Wake up any
1836 		 * waiters who may be able to complete it immediately and
1837 		 * add the item back to the head so we don't try to execute
1838 		 * it again.
1839 		 */
1840 		wk->wk_state &= ~INPROGRESS;
1841 		wake_worklist(wk);
1842 		add_to_worklist(wk, WK_HEAD);
1843 	}
1844 	/* Sentinal could've become the tail from remove_from_worklist. */
1845 	if (ump->softdep_worklist_tail == &sentinel)
1846 		ump->softdep_worklist_tail =
1847 		    (struct worklist *)sentinel.wk_list.le_prev;
1848 	LIST_REMOVE(&sentinel, wk_list);
1849 	PRELE(curproc);
1850 	return (matchcnt);
1851 }
1852 
1853 /*
1854  * Move dependencies from one buffer to another.
1855  */
1856 int
1857 softdep_move_dependencies(oldbp, newbp)
1858 	struct buf *oldbp;
1859 	struct buf *newbp;
1860 {
1861 	struct worklist *wk, *wktail;
1862 	struct ufsmount *ump;
1863 	int dirty;
1864 
1865 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1866 		return (0);
1867 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1868 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1869 	dirty = 0;
1870 	wktail = NULL;
1871 	ump = VFSTOUFS(wk->wk_mp);
1872 	ACQUIRE_LOCK(ump);
1873 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1874 		LIST_REMOVE(wk, wk_list);
1875 		if (wk->wk_type == D_BMSAFEMAP &&
1876 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1877 			dirty = 1;
1878 		if (wktail == NULL)
1879 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1880 		else
1881 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1882 		wktail = wk;
1883 	}
1884 	FREE_LOCK(ump);
1885 
1886 	return (dirty);
1887 }
1888 
1889 /*
1890  * Purge the work list of all items associated with a particular mount point.
1891  */
1892 int
1893 softdep_flushworklist(oldmnt, countp, td)
1894 	struct mount *oldmnt;
1895 	int *countp;
1896 	struct thread *td;
1897 {
1898 	struct vnode *devvp;
1899 	struct ufsmount *ump;
1900 	int count, error;
1901 
1902 	/*
1903 	 * Alternately flush the block device associated with the mount
1904 	 * point and process any dependencies that the flushing
1905 	 * creates. We continue until no more worklist dependencies
1906 	 * are found.
1907 	 */
1908 	*countp = 0;
1909 	error = 0;
1910 	ump = VFSTOUFS(oldmnt);
1911 	devvp = ump->um_devvp;
1912 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1913 		*countp += count;
1914 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1915 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1916 		VOP_UNLOCK(devvp, 0);
1917 		if (error != 0)
1918 			break;
1919 	}
1920 	return (error);
1921 }
1922 
1923 #define	SU_WAITIDLE_RETRIES	20
1924 static int
1925 softdep_waitidle(struct mount *mp, int flags __unused)
1926 {
1927 	struct ufsmount *ump;
1928 	struct vnode *devvp;
1929 	struct thread *td;
1930 	int error, i;
1931 
1932 	ump = VFSTOUFS(mp);
1933 	devvp = ump->um_devvp;
1934 	td = curthread;
1935 	error = 0;
1936 	ACQUIRE_LOCK(ump);
1937 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1938 		ump->softdep_req = 1;
1939 		KASSERT((flags & FORCECLOSE) == 0 ||
1940 		    ump->softdep_on_worklist == 0,
1941 		    ("softdep_waitidle: work added after flush"));
1942 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1943 		    "softdeps", 10 * hz);
1944 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1945 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1946 		VOP_UNLOCK(devvp, 0);
1947 		ACQUIRE_LOCK(ump);
1948 		if (error != 0)
1949 			break;
1950 	}
1951 	ump->softdep_req = 0;
1952 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1953 		error = EBUSY;
1954 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1955 		    mp);
1956 	}
1957 	FREE_LOCK(ump);
1958 	return (error);
1959 }
1960 
1961 /*
1962  * Flush all vnodes and worklist items associated with a specified mount point.
1963  */
1964 int
1965 softdep_flushfiles(oldmnt, flags, td)
1966 	struct mount *oldmnt;
1967 	int flags;
1968 	struct thread *td;
1969 {
1970 #ifdef QUOTA
1971 	struct ufsmount *ump;
1972 	int i;
1973 #endif
1974 	int error, early, depcount, loopcnt, retry_flush_count, retry;
1975 	int morework;
1976 
1977 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1978 	    ("softdep_flushfiles called on non-softdep filesystem"));
1979 	loopcnt = 10;
1980 	retry_flush_count = 3;
1981 retry_flush:
1982 	error = 0;
1983 
1984 	/*
1985 	 * Alternately flush the vnodes associated with the mount
1986 	 * point and process any dependencies that the flushing
1987 	 * creates. In theory, this loop can happen at most twice,
1988 	 * but we give it a few extra just to be sure.
1989 	 */
1990 	for (; loopcnt > 0; loopcnt--) {
1991 		/*
1992 		 * Do another flush in case any vnodes were brought in
1993 		 * as part of the cleanup operations.
1994 		 */
1995 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
1996 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
1997 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
1998 			break;
1999 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2000 		    depcount == 0)
2001 			break;
2002 	}
2003 	/*
2004 	 * If we are unmounting then it is an error to fail. If we
2005 	 * are simply trying to downgrade to read-only, then filesystem
2006 	 * activity can keep us busy forever, so we just fail with EBUSY.
2007 	 */
2008 	if (loopcnt == 0) {
2009 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2010 			panic("softdep_flushfiles: looping");
2011 		error = EBUSY;
2012 	}
2013 	if (!error)
2014 		error = softdep_waitidle(oldmnt, flags);
2015 	if (!error) {
2016 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2017 			retry = 0;
2018 			MNT_ILOCK(oldmnt);
2019 			KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
2020 			    ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
2021 			morework = oldmnt->mnt_nvnodelistsize > 0;
2022 #ifdef QUOTA
2023 			ump = VFSTOUFS(oldmnt);
2024 			UFS_LOCK(ump);
2025 			for (i = 0; i < MAXQUOTAS; i++) {
2026 				if (ump->um_quotas[i] != NULLVP)
2027 					morework = 1;
2028 			}
2029 			UFS_UNLOCK(ump);
2030 #endif
2031 			if (morework) {
2032 				if (--retry_flush_count > 0) {
2033 					retry = 1;
2034 					loopcnt = 3;
2035 				} else
2036 					error = EBUSY;
2037 			}
2038 			MNT_IUNLOCK(oldmnt);
2039 			if (retry)
2040 				goto retry_flush;
2041 		}
2042 	}
2043 	return (error);
2044 }
2045 
2046 /*
2047  * Structure hashing.
2048  *
2049  * There are four types of structures that can be looked up:
2050  *	1) pagedep structures identified by mount point, inode number,
2051  *	   and logical block.
2052  *	2) inodedep structures identified by mount point and inode number.
2053  *	3) newblk structures identified by mount point and
2054  *	   physical block number.
2055  *	4) bmsafemap structures identified by mount point and
2056  *	   cylinder group number.
2057  *
2058  * The "pagedep" and "inodedep" dependency structures are hashed
2059  * separately from the file blocks and inodes to which they correspond.
2060  * This separation helps when the in-memory copy of an inode or
2061  * file block must be replaced. It also obviates the need to access
2062  * an inode or file page when simply updating (or de-allocating)
2063  * dependency structures. Lookup of newblk structures is needed to
2064  * find newly allocated blocks when trying to associate them with
2065  * their allocdirect or allocindir structure.
2066  *
2067  * The lookup routines optionally create and hash a new instance when
2068  * an existing entry is not found. The bmsafemap lookup routine always
2069  * allocates a new structure if an existing one is not found.
2070  */
2071 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2072 
2073 /*
2074  * Structures and routines associated with pagedep caching.
2075  */
2076 #define	PAGEDEP_HASH(ump, inum, lbn) \
2077 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2078 
2079 static int
2080 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2081 	struct pagedep_hashhead *pagedephd;
2082 	ino_t ino;
2083 	ufs_lbn_t lbn;
2084 	struct pagedep **pagedeppp;
2085 {
2086 	struct pagedep *pagedep;
2087 
2088 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2089 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2090 			*pagedeppp = pagedep;
2091 			return (1);
2092 		}
2093 	}
2094 	*pagedeppp = NULL;
2095 	return (0);
2096 }
2097 /*
2098  * Look up a pagedep. Return 1 if found, 0 otherwise.
2099  * If not found, allocate if DEPALLOC flag is passed.
2100  * Found or allocated entry is returned in pagedeppp.
2101  * This routine must be called with splbio interrupts blocked.
2102  */
2103 static int
2104 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2105 	struct mount *mp;
2106 	struct buf *bp;
2107 	ino_t ino;
2108 	ufs_lbn_t lbn;
2109 	int flags;
2110 	struct pagedep **pagedeppp;
2111 {
2112 	struct pagedep *pagedep;
2113 	struct pagedep_hashhead *pagedephd;
2114 	struct worklist *wk;
2115 	struct ufsmount *ump;
2116 	int ret;
2117 	int i;
2118 
2119 	ump = VFSTOUFS(mp);
2120 	LOCK_OWNED(ump);
2121 	if (bp) {
2122 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2123 			if (wk->wk_type == D_PAGEDEP) {
2124 				*pagedeppp = WK_PAGEDEP(wk);
2125 				return (1);
2126 			}
2127 		}
2128 	}
2129 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2130 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2131 	if (ret) {
2132 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2133 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2134 		return (1);
2135 	}
2136 	if ((flags & DEPALLOC) == 0)
2137 		return (0);
2138 	FREE_LOCK(ump);
2139 	pagedep = malloc(sizeof(struct pagedep),
2140 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2141 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2142 	ACQUIRE_LOCK(ump);
2143 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2144 	if (*pagedeppp) {
2145 		/*
2146 		 * This should never happen since we only create pagedeps
2147 		 * with the vnode lock held.  Could be an assert.
2148 		 */
2149 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2150 		return (ret);
2151 	}
2152 	pagedep->pd_ino = ino;
2153 	pagedep->pd_lbn = lbn;
2154 	LIST_INIT(&pagedep->pd_dirremhd);
2155 	LIST_INIT(&pagedep->pd_pendinghd);
2156 	for (i = 0; i < DAHASHSZ; i++)
2157 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2158 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2159 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2160 	*pagedeppp = pagedep;
2161 	return (0);
2162 }
2163 
2164 /*
2165  * Structures and routines associated with inodedep caching.
2166  */
2167 #define	INODEDEP_HASH(ump, inum) \
2168       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2169 
2170 static int
2171 inodedep_find(inodedephd, inum, inodedeppp)
2172 	struct inodedep_hashhead *inodedephd;
2173 	ino_t inum;
2174 	struct inodedep **inodedeppp;
2175 {
2176 	struct inodedep *inodedep;
2177 
2178 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2179 		if (inum == inodedep->id_ino)
2180 			break;
2181 	if (inodedep) {
2182 		*inodedeppp = inodedep;
2183 		return (1);
2184 	}
2185 	*inodedeppp = NULL;
2186 
2187 	return (0);
2188 }
2189 /*
2190  * Look up an inodedep. Return 1 if found, 0 if not found.
2191  * If not found, allocate if DEPALLOC flag is passed.
2192  * Found or allocated entry is returned in inodedeppp.
2193  * This routine must be called with splbio interrupts blocked.
2194  */
2195 static int
2196 inodedep_lookup(mp, inum, flags, inodedeppp)
2197 	struct mount *mp;
2198 	ino_t inum;
2199 	int flags;
2200 	struct inodedep **inodedeppp;
2201 {
2202 	struct inodedep *inodedep;
2203 	struct inodedep_hashhead *inodedephd;
2204 	struct ufsmount *ump;
2205 	struct fs *fs;
2206 
2207 	ump = VFSTOUFS(mp);
2208 	LOCK_OWNED(ump);
2209 	fs = ump->um_fs;
2210 	inodedephd = INODEDEP_HASH(ump, inum);
2211 
2212 	if (inodedep_find(inodedephd, inum, inodedeppp))
2213 		return (1);
2214 	if ((flags & DEPALLOC) == 0)
2215 		return (0);
2216 	/*
2217 	 * If the system is over its limit and our filesystem is
2218 	 * responsible for more than our share of that usage and
2219 	 * we are not in a rush, request some inodedep cleanup.
2220 	 */
2221 	if (softdep_excess_items(ump, D_INODEDEP))
2222 		schedule_cleanup(mp);
2223 	else
2224 		FREE_LOCK(ump);
2225 	inodedep = malloc(sizeof(struct inodedep),
2226 		M_INODEDEP, M_SOFTDEP_FLAGS);
2227 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2228 	ACQUIRE_LOCK(ump);
2229 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2230 		WORKITEM_FREE(inodedep, D_INODEDEP);
2231 		return (1);
2232 	}
2233 	inodedep->id_fs = fs;
2234 	inodedep->id_ino = inum;
2235 	inodedep->id_state = ALLCOMPLETE;
2236 	inodedep->id_nlinkdelta = 0;
2237 	inodedep->id_savedino1 = NULL;
2238 	inodedep->id_savedsize = -1;
2239 	inodedep->id_savedextsize = -1;
2240 	inodedep->id_savednlink = -1;
2241 	inodedep->id_bmsafemap = NULL;
2242 	inodedep->id_mkdiradd = NULL;
2243 	LIST_INIT(&inodedep->id_dirremhd);
2244 	LIST_INIT(&inodedep->id_pendinghd);
2245 	LIST_INIT(&inodedep->id_inowait);
2246 	LIST_INIT(&inodedep->id_bufwait);
2247 	TAILQ_INIT(&inodedep->id_inoreflst);
2248 	TAILQ_INIT(&inodedep->id_inoupdt);
2249 	TAILQ_INIT(&inodedep->id_newinoupdt);
2250 	TAILQ_INIT(&inodedep->id_extupdt);
2251 	TAILQ_INIT(&inodedep->id_newextupdt);
2252 	TAILQ_INIT(&inodedep->id_freeblklst);
2253 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2254 	*inodedeppp = inodedep;
2255 	return (0);
2256 }
2257 
2258 /*
2259  * Structures and routines associated with newblk caching.
2260  */
2261 #define	NEWBLK_HASH(ump, inum) \
2262 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2263 
2264 static int
2265 newblk_find(newblkhd, newblkno, flags, newblkpp)
2266 	struct newblk_hashhead *newblkhd;
2267 	ufs2_daddr_t newblkno;
2268 	int flags;
2269 	struct newblk **newblkpp;
2270 {
2271 	struct newblk *newblk;
2272 
2273 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2274 		if (newblkno != newblk->nb_newblkno)
2275 			continue;
2276 		/*
2277 		 * If we're creating a new dependency don't match those that
2278 		 * have already been converted to allocdirects.  This is for
2279 		 * a frag extend.
2280 		 */
2281 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2282 			continue;
2283 		break;
2284 	}
2285 	if (newblk) {
2286 		*newblkpp = newblk;
2287 		return (1);
2288 	}
2289 	*newblkpp = NULL;
2290 	return (0);
2291 }
2292 
2293 /*
2294  * Look up a newblk. Return 1 if found, 0 if not found.
2295  * If not found, allocate if DEPALLOC flag is passed.
2296  * Found or allocated entry is returned in newblkpp.
2297  */
2298 static int
2299 newblk_lookup(mp, newblkno, flags, newblkpp)
2300 	struct mount *mp;
2301 	ufs2_daddr_t newblkno;
2302 	int flags;
2303 	struct newblk **newblkpp;
2304 {
2305 	struct newblk *newblk;
2306 	struct newblk_hashhead *newblkhd;
2307 	struct ufsmount *ump;
2308 
2309 	ump = VFSTOUFS(mp);
2310 	LOCK_OWNED(ump);
2311 	newblkhd = NEWBLK_HASH(ump, newblkno);
2312 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2313 		return (1);
2314 	if ((flags & DEPALLOC) == 0)
2315 		return (0);
2316 	if (softdep_excess_items(ump, D_NEWBLK) ||
2317 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2318 	    softdep_excess_items(ump, D_ALLOCINDIR))
2319 		schedule_cleanup(mp);
2320 	else
2321 		FREE_LOCK(ump);
2322 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2323 	    M_SOFTDEP_FLAGS | M_ZERO);
2324 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2325 	ACQUIRE_LOCK(ump);
2326 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2327 		WORKITEM_FREE(newblk, D_NEWBLK);
2328 		return (1);
2329 	}
2330 	newblk->nb_freefrag = NULL;
2331 	LIST_INIT(&newblk->nb_indirdeps);
2332 	LIST_INIT(&newblk->nb_newdirblk);
2333 	LIST_INIT(&newblk->nb_jwork);
2334 	newblk->nb_state = ATTACHED;
2335 	newblk->nb_newblkno = newblkno;
2336 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2337 	*newblkpp = newblk;
2338 	return (0);
2339 }
2340 
2341 /*
2342  * Structures and routines associated with freed indirect block caching.
2343  */
2344 #define	INDIR_HASH(ump, blkno) \
2345 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2346 
2347 /*
2348  * Lookup an indirect block in the indir hash table.  The freework is
2349  * removed and potentially freed.  The caller must do a blocking journal
2350  * write before writing to the blkno.
2351  */
2352 static int
2353 indirblk_lookup(mp, blkno)
2354 	struct mount *mp;
2355 	ufs2_daddr_t blkno;
2356 {
2357 	struct freework *freework;
2358 	struct indir_hashhead *wkhd;
2359 	struct ufsmount *ump;
2360 
2361 	ump = VFSTOUFS(mp);
2362 	wkhd = INDIR_HASH(ump, blkno);
2363 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2364 		if (freework->fw_blkno != blkno)
2365 			continue;
2366 		indirblk_remove(freework);
2367 		return (1);
2368 	}
2369 	return (0);
2370 }
2371 
2372 /*
2373  * Insert an indirect block represented by freework into the indirblk
2374  * hash table so that it may prevent the block from being re-used prior
2375  * to the journal being written.
2376  */
2377 static void
2378 indirblk_insert(freework)
2379 	struct freework *freework;
2380 {
2381 	struct jblocks *jblocks;
2382 	struct jseg *jseg;
2383 	struct ufsmount *ump;
2384 
2385 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2386 	jblocks = ump->softdep_jblocks;
2387 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2388 	if (jseg == NULL)
2389 		return;
2390 
2391 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2392 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2393 	    fw_next);
2394 	freework->fw_state &= ~DEPCOMPLETE;
2395 }
2396 
2397 static void
2398 indirblk_remove(freework)
2399 	struct freework *freework;
2400 {
2401 	struct ufsmount *ump;
2402 
2403 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2404 	LIST_REMOVE(freework, fw_segs);
2405 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2406 	freework->fw_state |= DEPCOMPLETE;
2407 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2408 		WORKITEM_FREE(freework, D_FREEWORK);
2409 }
2410 
2411 /*
2412  * Executed during filesystem system initialization before
2413  * mounting any filesystems.
2414  */
2415 void
2416 softdep_initialize()
2417 {
2418 
2419 	TAILQ_INIT(&softdepmounts);
2420 #ifdef __LP64__
2421 	max_softdeps = desiredvnodes * 4;
2422 #else
2423 	max_softdeps = desiredvnodes * 2;
2424 #endif
2425 
2426 	/* initialise bioops hack */
2427 	bioops.io_start = softdep_disk_io_initiation;
2428 	bioops.io_complete = softdep_disk_write_complete;
2429 	bioops.io_deallocate = softdep_deallocate_dependencies;
2430 	bioops.io_countdeps = softdep_count_dependencies;
2431 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2432 
2433 	/* Initialize the callout with an mtx. */
2434 	callout_init_mtx(&softdep_callout, &lk, 0);
2435 }
2436 
2437 /*
2438  * Executed after all filesystems have been unmounted during
2439  * filesystem module unload.
2440  */
2441 void
2442 softdep_uninitialize()
2443 {
2444 
2445 	/* clear bioops hack */
2446 	bioops.io_start = NULL;
2447 	bioops.io_complete = NULL;
2448 	bioops.io_deallocate = NULL;
2449 	bioops.io_countdeps = NULL;
2450 	softdep_ast_cleanup = NULL;
2451 
2452 	callout_drain(&softdep_callout);
2453 }
2454 
2455 /*
2456  * Called at mount time to notify the dependency code that a
2457  * filesystem wishes to use it.
2458  */
2459 int
2460 softdep_mount(devvp, mp, fs, cred)
2461 	struct vnode *devvp;
2462 	struct mount *mp;
2463 	struct fs *fs;
2464 	struct ucred *cred;
2465 {
2466 	struct csum_total cstotal;
2467 	struct mount_softdeps *sdp;
2468 	struct ufsmount *ump;
2469 	struct cg *cgp;
2470 	struct buf *bp;
2471 	u_int cyl, i;
2472 	int error;
2473 
2474 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2475 	    M_WAITOK | M_ZERO);
2476 	MNT_ILOCK(mp);
2477 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2478 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2479 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2480 			MNTK_SOFTDEP | MNTK_NOASYNC;
2481 	}
2482 	ump = VFSTOUFS(mp);
2483 	ump->um_softdep = sdp;
2484 	MNT_IUNLOCK(mp);
2485 	rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2486 	sdp->sd_ump = ump;
2487 	LIST_INIT(&ump->softdep_workitem_pending);
2488 	LIST_INIT(&ump->softdep_journal_pending);
2489 	TAILQ_INIT(&ump->softdep_unlinked);
2490 	LIST_INIT(&ump->softdep_dirtycg);
2491 	ump->softdep_worklist_tail = NULL;
2492 	ump->softdep_on_worklist = 0;
2493 	ump->softdep_deps = 0;
2494 	LIST_INIT(&ump->softdep_mkdirlisthd);
2495 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2496 	    &ump->pagedep_hash_size);
2497 	ump->pagedep_nextclean = 0;
2498 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2499 	    &ump->inodedep_hash_size);
2500 	ump->inodedep_nextclean = 0;
2501 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2502 	    &ump->newblk_hash_size);
2503 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2504 	    &ump->bmsafemap_hash_size);
2505 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2506 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2507 	    M_FREEWORK, M_WAITOK);
2508 	ump->indir_hash_size = i - 1;
2509 	for (i = 0; i <= ump->indir_hash_size; i++)
2510 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2511 	ACQUIRE_GBLLOCK(&lk);
2512 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2513 	FREE_GBLLOCK(&lk);
2514 	if ((fs->fs_flags & FS_SUJ) &&
2515 	    (error = journal_mount(mp, fs, cred)) != 0) {
2516 		printf("Failed to start journal: %d\n", error);
2517 		softdep_unmount(mp);
2518 		return (error);
2519 	}
2520 	/*
2521 	 * Start our flushing thread in the bufdaemon process.
2522 	 */
2523 	ACQUIRE_LOCK(ump);
2524 	ump->softdep_flags |= FLUSH_STARTING;
2525 	FREE_LOCK(ump);
2526 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2527 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2528 	    mp->mnt_stat.f_mntonname);
2529 	ACQUIRE_LOCK(ump);
2530 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2531 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2532 		    hz / 2);
2533 	}
2534 	FREE_LOCK(ump);
2535 	/*
2536 	 * When doing soft updates, the counters in the
2537 	 * superblock may have gotten out of sync. Recomputation
2538 	 * can take a long time and can be deferred for background
2539 	 * fsck.  However, the old behavior of scanning the cylinder
2540 	 * groups and recalculating them at mount time is available
2541 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2542 	 */
2543 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2544 		return (0);
2545 	bzero(&cstotal, sizeof cstotal);
2546 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2547 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2548 		    fs->fs_cgsize, cred, &bp)) != 0) {
2549 			brelse(bp);
2550 			softdep_unmount(mp);
2551 			return (error);
2552 		}
2553 		cgp = (struct cg *)bp->b_data;
2554 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2555 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2556 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2557 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2558 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2559 		brelse(bp);
2560 	}
2561 #ifdef DEBUG
2562 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2563 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2564 #endif
2565 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2566 	return (0);
2567 }
2568 
2569 void
2570 softdep_unmount(mp)
2571 	struct mount *mp;
2572 {
2573 	struct ufsmount *ump;
2574 #ifdef INVARIANTS
2575 	int i;
2576 #endif
2577 
2578 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2579 	    ("softdep_unmount called on non-softdep filesystem"));
2580 	ump = VFSTOUFS(mp);
2581 	MNT_ILOCK(mp);
2582 	mp->mnt_flag &= ~MNT_SOFTDEP;
2583 	if (MOUNTEDSUJ(mp) == 0) {
2584 		MNT_IUNLOCK(mp);
2585 	} else {
2586 		mp->mnt_flag &= ~MNT_SUJ;
2587 		MNT_IUNLOCK(mp);
2588 		journal_unmount(ump);
2589 	}
2590 	/*
2591 	 * Shut down our flushing thread. Check for NULL is if
2592 	 * softdep_mount errors out before the thread has been created.
2593 	 */
2594 	if (ump->softdep_flushtd != NULL) {
2595 		ACQUIRE_LOCK(ump);
2596 		ump->softdep_flags |= FLUSH_EXIT;
2597 		wakeup(&ump->softdep_flushtd);
2598 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2599 		    "sdwait", 0);
2600 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2601 		    ("Thread shutdown failed"));
2602 	}
2603 	/*
2604 	 * Free up our resources.
2605 	 */
2606 	ACQUIRE_GBLLOCK(&lk);
2607 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2608 	FREE_GBLLOCK(&lk);
2609 	rw_destroy(LOCK_PTR(ump));
2610 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2611 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2612 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2613 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2614 	    ump->bmsafemap_hash_size);
2615 	free(ump->indir_hashtbl, M_FREEWORK);
2616 #ifdef INVARIANTS
2617 	for (i = 0; i <= D_LAST; i++)
2618 		KASSERT(ump->softdep_curdeps[i] == 0,
2619 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2620 		    TYPENAME(i), ump->softdep_curdeps[i]));
2621 #endif
2622 	free(ump->um_softdep, M_MOUNTDATA);
2623 }
2624 
2625 static struct jblocks *
2626 jblocks_create(void)
2627 {
2628 	struct jblocks *jblocks;
2629 
2630 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2631 	TAILQ_INIT(&jblocks->jb_segs);
2632 	jblocks->jb_avail = 10;
2633 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2634 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2635 
2636 	return (jblocks);
2637 }
2638 
2639 static ufs2_daddr_t
2640 jblocks_alloc(jblocks, bytes, actual)
2641 	struct jblocks *jblocks;
2642 	int bytes;
2643 	int *actual;
2644 {
2645 	ufs2_daddr_t daddr;
2646 	struct jextent *jext;
2647 	int freecnt;
2648 	int blocks;
2649 
2650 	blocks = bytes / DEV_BSIZE;
2651 	jext = &jblocks->jb_extent[jblocks->jb_head];
2652 	freecnt = jext->je_blocks - jblocks->jb_off;
2653 	if (freecnt == 0) {
2654 		jblocks->jb_off = 0;
2655 		if (++jblocks->jb_head > jblocks->jb_used)
2656 			jblocks->jb_head = 0;
2657 		jext = &jblocks->jb_extent[jblocks->jb_head];
2658 		freecnt = jext->je_blocks;
2659 	}
2660 	if (freecnt > blocks)
2661 		freecnt = blocks;
2662 	*actual = freecnt * DEV_BSIZE;
2663 	daddr = jext->je_daddr + jblocks->jb_off;
2664 	jblocks->jb_off += freecnt;
2665 	jblocks->jb_free -= freecnt;
2666 
2667 	return (daddr);
2668 }
2669 
2670 static void
2671 jblocks_free(jblocks, mp, bytes)
2672 	struct jblocks *jblocks;
2673 	struct mount *mp;
2674 	int bytes;
2675 {
2676 
2677 	LOCK_OWNED(VFSTOUFS(mp));
2678 	jblocks->jb_free += bytes / DEV_BSIZE;
2679 	if (jblocks->jb_suspended)
2680 		worklist_speedup(mp);
2681 	wakeup(jblocks);
2682 }
2683 
2684 static void
2685 jblocks_destroy(jblocks)
2686 	struct jblocks *jblocks;
2687 {
2688 
2689 	if (jblocks->jb_extent)
2690 		free(jblocks->jb_extent, M_JBLOCKS);
2691 	free(jblocks, M_JBLOCKS);
2692 }
2693 
2694 static void
2695 jblocks_add(jblocks, daddr, blocks)
2696 	struct jblocks *jblocks;
2697 	ufs2_daddr_t daddr;
2698 	int blocks;
2699 {
2700 	struct jextent *jext;
2701 
2702 	jblocks->jb_blocks += blocks;
2703 	jblocks->jb_free += blocks;
2704 	jext = &jblocks->jb_extent[jblocks->jb_used];
2705 	/* Adding the first block. */
2706 	if (jext->je_daddr == 0) {
2707 		jext->je_daddr = daddr;
2708 		jext->je_blocks = blocks;
2709 		return;
2710 	}
2711 	/* Extending the last extent. */
2712 	if (jext->je_daddr + jext->je_blocks == daddr) {
2713 		jext->je_blocks += blocks;
2714 		return;
2715 	}
2716 	/* Adding a new extent. */
2717 	if (++jblocks->jb_used == jblocks->jb_avail) {
2718 		jblocks->jb_avail *= 2;
2719 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2720 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2721 		memcpy(jext, jblocks->jb_extent,
2722 		    sizeof(struct jextent) * jblocks->jb_used);
2723 		free(jblocks->jb_extent, M_JBLOCKS);
2724 		jblocks->jb_extent = jext;
2725 	}
2726 	jext = &jblocks->jb_extent[jblocks->jb_used];
2727 	jext->je_daddr = daddr;
2728 	jext->je_blocks = blocks;
2729 	return;
2730 }
2731 
2732 int
2733 softdep_journal_lookup(mp, vpp)
2734 	struct mount *mp;
2735 	struct vnode **vpp;
2736 {
2737 	struct componentname cnp;
2738 	struct vnode *dvp;
2739 	ino_t sujournal;
2740 	int error;
2741 
2742 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2743 	if (error)
2744 		return (error);
2745 	bzero(&cnp, sizeof(cnp));
2746 	cnp.cn_nameiop = LOOKUP;
2747 	cnp.cn_flags = ISLASTCN;
2748 	cnp.cn_thread = curthread;
2749 	cnp.cn_cred = curthread->td_ucred;
2750 	cnp.cn_pnbuf = SUJ_FILE;
2751 	cnp.cn_nameptr = SUJ_FILE;
2752 	cnp.cn_namelen = strlen(SUJ_FILE);
2753 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2754 	vput(dvp);
2755 	if (error != 0)
2756 		return (error);
2757 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2758 	return (error);
2759 }
2760 
2761 /*
2762  * Open and verify the journal file.
2763  */
2764 static int
2765 journal_mount(mp, fs, cred)
2766 	struct mount *mp;
2767 	struct fs *fs;
2768 	struct ucred *cred;
2769 {
2770 	struct jblocks *jblocks;
2771 	struct ufsmount *ump;
2772 	struct vnode *vp;
2773 	struct inode *ip;
2774 	ufs2_daddr_t blkno;
2775 	int bcount;
2776 	int error;
2777 	int i;
2778 
2779 	ump = VFSTOUFS(mp);
2780 	ump->softdep_journal_tail = NULL;
2781 	ump->softdep_on_journal = 0;
2782 	ump->softdep_accdeps = 0;
2783 	ump->softdep_req = 0;
2784 	ump->softdep_jblocks = NULL;
2785 	error = softdep_journal_lookup(mp, &vp);
2786 	if (error != 0) {
2787 		printf("Failed to find journal.  Use tunefs to create one\n");
2788 		return (error);
2789 	}
2790 	ip = VTOI(vp);
2791 	if (ip->i_size < SUJ_MIN) {
2792 		error = ENOSPC;
2793 		goto out;
2794 	}
2795 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2796 	jblocks = jblocks_create();
2797 	for (i = 0; i < bcount; i++) {
2798 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2799 		if (error)
2800 			break;
2801 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2802 	}
2803 	if (error) {
2804 		jblocks_destroy(jblocks);
2805 		goto out;
2806 	}
2807 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2808 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2809 	ump->softdep_jblocks = jblocks;
2810 out:
2811 	if (error == 0) {
2812 		MNT_ILOCK(mp);
2813 		mp->mnt_flag |= MNT_SUJ;
2814 		mp->mnt_flag &= ~MNT_SOFTDEP;
2815 		MNT_IUNLOCK(mp);
2816 		/*
2817 		 * Only validate the journal contents if the
2818 		 * filesystem is clean, otherwise we write the logs
2819 		 * but they'll never be used.  If the filesystem was
2820 		 * still dirty when we mounted it the journal is
2821 		 * invalid and a new journal can only be valid if it
2822 		 * starts from a clean mount.
2823 		 */
2824 		if (fs->fs_clean) {
2825 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2826 			ip->i_flags |= IN_MODIFIED;
2827 			ffs_update(vp, 1);
2828 		}
2829 	}
2830 	vput(vp);
2831 	return (error);
2832 }
2833 
2834 static void
2835 journal_unmount(ump)
2836 	struct ufsmount *ump;
2837 {
2838 
2839 	if (ump->softdep_jblocks)
2840 		jblocks_destroy(ump->softdep_jblocks);
2841 	ump->softdep_jblocks = NULL;
2842 }
2843 
2844 /*
2845  * Called when a journal record is ready to be written.  Space is allocated
2846  * and the journal entry is created when the journal is flushed to stable
2847  * store.
2848  */
2849 static void
2850 add_to_journal(wk)
2851 	struct worklist *wk;
2852 {
2853 	struct ufsmount *ump;
2854 
2855 	ump = VFSTOUFS(wk->wk_mp);
2856 	LOCK_OWNED(ump);
2857 	if (wk->wk_state & ONWORKLIST)
2858 		panic("add_to_journal: %s(0x%X) already on list",
2859 		    TYPENAME(wk->wk_type), wk->wk_state);
2860 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2861 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2862 		ump->softdep_jblocks->jb_age = ticks;
2863 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2864 	} else
2865 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2866 	ump->softdep_journal_tail = wk;
2867 	ump->softdep_on_journal += 1;
2868 }
2869 
2870 /*
2871  * Remove an arbitrary item for the journal worklist maintain the tail
2872  * pointer.  This happens when a new operation obviates the need to
2873  * journal an old operation.
2874  */
2875 static void
2876 remove_from_journal(wk)
2877 	struct worklist *wk;
2878 {
2879 	struct ufsmount *ump;
2880 
2881 	ump = VFSTOUFS(wk->wk_mp);
2882 	LOCK_OWNED(ump);
2883 #ifdef SUJ_DEBUG
2884 	{
2885 		struct worklist *wkn;
2886 
2887 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2888 			if (wkn == wk)
2889 				break;
2890 		if (wkn == NULL)
2891 			panic("remove_from_journal: %p is not in journal", wk);
2892 	}
2893 #endif
2894 	/*
2895 	 * We emulate a TAILQ to save space in most structures which do not
2896 	 * require TAILQ semantics.  Here we must update the tail position
2897 	 * when removing the tail which is not the final entry. This works
2898 	 * only if the worklist linkage are at the beginning of the structure.
2899 	 */
2900 	if (ump->softdep_journal_tail == wk)
2901 		ump->softdep_journal_tail =
2902 		    (struct worklist *)wk->wk_list.le_prev;
2903 	WORKLIST_REMOVE(wk);
2904 	ump->softdep_on_journal -= 1;
2905 }
2906 
2907 /*
2908  * Check for journal space as well as dependency limits so the prelink
2909  * code can throttle both journaled and non-journaled filesystems.
2910  * Threshold is 0 for low and 1 for min.
2911  */
2912 static int
2913 journal_space(ump, thresh)
2914 	struct ufsmount *ump;
2915 	int thresh;
2916 {
2917 	struct jblocks *jblocks;
2918 	int limit, avail;
2919 
2920 	jblocks = ump->softdep_jblocks;
2921 	if (jblocks == NULL)
2922 		return (1);
2923 	/*
2924 	 * We use a tighter restriction here to prevent request_cleanup()
2925 	 * running in threads from running into locks we currently hold.
2926 	 * We have to be over the limit and our filesystem has to be
2927 	 * responsible for more than our share of that usage.
2928 	 */
2929 	limit = (max_softdeps / 10) * 9;
2930 	if (dep_current[D_INODEDEP] > limit &&
2931 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2932 		return (0);
2933 	if (thresh)
2934 		thresh = jblocks->jb_min;
2935 	else
2936 		thresh = jblocks->jb_low;
2937 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2938 	avail = jblocks->jb_free - avail;
2939 
2940 	return (avail > thresh);
2941 }
2942 
2943 static void
2944 journal_suspend(ump)
2945 	struct ufsmount *ump;
2946 {
2947 	struct jblocks *jblocks;
2948 	struct mount *mp;
2949 
2950 	mp = UFSTOVFS(ump);
2951 	jblocks = ump->softdep_jblocks;
2952 	MNT_ILOCK(mp);
2953 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2954 		stat_journal_min++;
2955 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2956 		mp->mnt_susp_owner = ump->softdep_flushtd;
2957 	}
2958 	jblocks->jb_suspended = 1;
2959 	MNT_IUNLOCK(mp);
2960 }
2961 
2962 static int
2963 journal_unsuspend(struct ufsmount *ump)
2964 {
2965 	struct jblocks *jblocks;
2966 	struct mount *mp;
2967 
2968 	mp = UFSTOVFS(ump);
2969 	jblocks = ump->softdep_jblocks;
2970 
2971 	if (jblocks != NULL && jblocks->jb_suspended &&
2972 	    journal_space(ump, jblocks->jb_min)) {
2973 		jblocks->jb_suspended = 0;
2974 		FREE_LOCK(ump);
2975 		mp->mnt_susp_owner = curthread;
2976 		vfs_write_resume(mp, 0);
2977 		ACQUIRE_LOCK(ump);
2978 		return (1);
2979 	}
2980 	return (0);
2981 }
2982 
2983 /*
2984  * Called before any allocation function to be certain that there is
2985  * sufficient space in the journal prior to creating any new records.
2986  * Since in the case of block allocation we may have multiple locked
2987  * buffers at the time of the actual allocation we can not block
2988  * when the journal records are created.  Doing so would create a deadlock
2989  * if any of these buffers needed to be flushed to reclaim space.  Instead
2990  * we require a sufficiently large amount of available space such that
2991  * each thread in the system could have passed this allocation check and
2992  * still have sufficient free space.  With 20% of a minimum journal size
2993  * of 1MB we have 6553 records available.
2994  */
2995 int
2996 softdep_prealloc(vp, waitok)
2997 	struct vnode *vp;
2998 	int waitok;
2999 {
3000 	struct ufsmount *ump;
3001 
3002 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3003 	    ("softdep_prealloc called on non-softdep filesystem"));
3004 	/*
3005 	 * Nothing to do if we are not running journaled soft updates.
3006 	 * If we currently hold the snapshot lock, we must avoid
3007 	 * handling other resources that could cause deadlock.  Do not
3008 	 * touch quotas vnode since it is typically recursed with
3009 	 * other vnode locks held.
3010 	 */
3011 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3012 	    (vp->v_vflag & VV_SYSTEM) != 0)
3013 		return (0);
3014 	ump = VFSTOUFS(vp->v_mount);
3015 	ACQUIRE_LOCK(ump);
3016 	if (journal_space(ump, 0)) {
3017 		FREE_LOCK(ump);
3018 		return (0);
3019 	}
3020 	stat_journal_low++;
3021 	FREE_LOCK(ump);
3022 	if (waitok == MNT_NOWAIT)
3023 		return (ENOSPC);
3024 	/*
3025 	 * Attempt to sync this vnode once to flush any journal
3026 	 * work attached to it.
3027 	 */
3028 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3029 		ffs_syncvnode(vp, waitok, 0);
3030 	ACQUIRE_LOCK(ump);
3031 	process_removes(vp);
3032 	process_truncates(vp);
3033 	if (journal_space(ump, 0) == 0) {
3034 		softdep_speedup(ump);
3035 		if (journal_space(ump, 1) == 0)
3036 			journal_suspend(ump);
3037 	}
3038 	FREE_LOCK(ump);
3039 
3040 	return (0);
3041 }
3042 
3043 /*
3044  * Before adjusting a link count on a vnode verify that we have sufficient
3045  * journal space.  If not, process operations that depend on the currently
3046  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3047  * and softdep flush threads can not acquire these locks to reclaim space.
3048  */
3049 static void
3050 softdep_prelink(dvp, vp)
3051 	struct vnode *dvp;
3052 	struct vnode *vp;
3053 {
3054 	struct ufsmount *ump;
3055 
3056 	ump = VFSTOUFS(dvp->v_mount);
3057 	LOCK_OWNED(ump);
3058 	/*
3059 	 * Nothing to do if we have sufficient journal space.
3060 	 * If we currently hold the snapshot lock, we must avoid
3061 	 * handling other resources that could cause deadlock.
3062 	 */
3063 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3064 		return;
3065 	stat_journal_low++;
3066 	FREE_LOCK(ump);
3067 	if (vp)
3068 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3069 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3070 	ACQUIRE_LOCK(ump);
3071 	/* Process vp before dvp as it may create .. removes. */
3072 	if (vp) {
3073 		process_removes(vp);
3074 		process_truncates(vp);
3075 	}
3076 	process_removes(dvp);
3077 	process_truncates(dvp);
3078 	softdep_speedup(ump);
3079 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3080 	if (journal_space(ump, 0) == 0) {
3081 		softdep_speedup(ump);
3082 		if (journal_space(ump, 1) == 0)
3083 			journal_suspend(ump);
3084 	}
3085 }
3086 
3087 static void
3088 jseg_write(ump, jseg, data)
3089 	struct ufsmount *ump;
3090 	struct jseg *jseg;
3091 	uint8_t *data;
3092 {
3093 	struct jsegrec *rec;
3094 
3095 	rec = (struct jsegrec *)data;
3096 	rec->jsr_seq = jseg->js_seq;
3097 	rec->jsr_oldest = jseg->js_oldseq;
3098 	rec->jsr_cnt = jseg->js_cnt;
3099 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3100 	rec->jsr_crc = 0;
3101 	rec->jsr_time = ump->um_fs->fs_mtime;
3102 }
3103 
3104 static inline void
3105 inoref_write(inoref, jseg, rec)
3106 	struct inoref *inoref;
3107 	struct jseg *jseg;
3108 	struct jrefrec *rec;
3109 {
3110 
3111 	inoref->if_jsegdep->jd_seg = jseg;
3112 	rec->jr_ino = inoref->if_ino;
3113 	rec->jr_parent = inoref->if_parent;
3114 	rec->jr_nlink = inoref->if_nlink;
3115 	rec->jr_mode = inoref->if_mode;
3116 	rec->jr_diroff = inoref->if_diroff;
3117 }
3118 
3119 static void
3120 jaddref_write(jaddref, jseg, data)
3121 	struct jaddref *jaddref;
3122 	struct jseg *jseg;
3123 	uint8_t *data;
3124 {
3125 	struct jrefrec *rec;
3126 
3127 	rec = (struct jrefrec *)data;
3128 	rec->jr_op = JOP_ADDREF;
3129 	inoref_write(&jaddref->ja_ref, jseg, rec);
3130 }
3131 
3132 static void
3133 jremref_write(jremref, jseg, data)
3134 	struct jremref *jremref;
3135 	struct jseg *jseg;
3136 	uint8_t *data;
3137 {
3138 	struct jrefrec *rec;
3139 
3140 	rec = (struct jrefrec *)data;
3141 	rec->jr_op = JOP_REMREF;
3142 	inoref_write(&jremref->jr_ref, jseg, rec);
3143 }
3144 
3145 static void
3146 jmvref_write(jmvref, jseg, data)
3147 	struct jmvref *jmvref;
3148 	struct jseg *jseg;
3149 	uint8_t *data;
3150 {
3151 	struct jmvrec *rec;
3152 
3153 	rec = (struct jmvrec *)data;
3154 	rec->jm_op = JOP_MVREF;
3155 	rec->jm_ino = jmvref->jm_ino;
3156 	rec->jm_parent = jmvref->jm_parent;
3157 	rec->jm_oldoff = jmvref->jm_oldoff;
3158 	rec->jm_newoff = jmvref->jm_newoff;
3159 }
3160 
3161 static void
3162 jnewblk_write(jnewblk, jseg, data)
3163 	struct jnewblk *jnewblk;
3164 	struct jseg *jseg;
3165 	uint8_t *data;
3166 {
3167 	struct jblkrec *rec;
3168 
3169 	jnewblk->jn_jsegdep->jd_seg = jseg;
3170 	rec = (struct jblkrec *)data;
3171 	rec->jb_op = JOP_NEWBLK;
3172 	rec->jb_ino = jnewblk->jn_ino;
3173 	rec->jb_blkno = jnewblk->jn_blkno;
3174 	rec->jb_lbn = jnewblk->jn_lbn;
3175 	rec->jb_frags = jnewblk->jn_frags;
3176 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3177 }
3178 
3179 static void
3180 jfreeblk_write(jfreeblk, jseg, data)
3181 	struct jfreeblk *jfreeblk;
3182 	struct jseg *jseg;
3183 	uint8_t *data;
3184 {
3185 	struct jblkrec *rec;
3186 
3187 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3188 	rec = (struct jblkrec *)data;
3189 	rec->jb_op = JOP_FREEBLK;
3190 	rec->jb_ino = jfreeblk->jf_ino;
3191 	rec->jb_blkno = jfreeblk->jf_blkno;
3192 	rec->jb_lbn = jfreeblk->jf_lbn;
3193 	rec->jb_frags = jfreeblk->jf_frags;
3194 	rec->jb_oldfrags = 0;
3195 }
3196 
3197 static void
3198 jfreefrag_write(jfreefrag, jseg, data)
3199 	struct jfreefrag *jfreefrag;
3200 	struct jseg *jseg;
3201 	uint8_t *data;
3202 {
3203 	struct jblkrec *rec;
3204 
3205 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3206 	rec = (struct jblkrec *)data;
3207 	rec->jb_op = JOP_FREEBLK;
3208 	rec->jb_ino = jfreefrag->fr_ino;
3209 	rec->jb_blkno = jfreefrag->fr_blkno;
3210 	rec->jb_lbn = jfreefrag->fr_lbn;
3211 	rec->jb_frags = jfreefrag->fr_frags;
3212 	rec->jb_oldfrags = 0;
3213 }
3214 
3215 static void
3216 jtrunc_write(jtrunc, jseg, data)
3217 	struct jtrunc *jtrunc;
3218 	struct jseg *jseg;
3219 	uint8_t *data;
3220 {
3221 	struct jtrncrec *rec;
3222 
3223 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3224 	rec = (struct jtrncrec *)data;
3225 	rec->jt_op = JOP_TRUNC;
3226 	rec->jt_ino = jtrunc->jt_ino;
3227 	rec->jt_size = jtrunc->jt_size;
3228 	rec->jt_extsize = jtrunc->jt_extsize;
3229 }
3230 
3231 static void
3232 jfsync_write(jfsync, jseg, data)
3233 	struct jfsync *jfsync;
3234 	struct jseg *jseg;
3235 	uint8_t *data;
3236 {
3237 	struct jtrncrec *rec;
3238 
3239 	rec = (struct jtrncrec *)data;
3240 	rec->jt_op = JOP_SYNC;
3241 	rec->jt_ino = jfsync->jfs_ino;
3242 	rec->jt_size = jfsync->jfs_size;
3243 	rec->jt_extsize = jfsync->jfs_extsize;
3244 }
3245 
3246 static void
3247 softdep_flushjournal(mp)
3248 	struct mount *mp;
3249 {
3250 	struct jblocks *jblocks;
3251 	struct ufsmount *ump;
3252 
3253 	if (MOUNTEDSUJ(mp) == 0)
3254 		return;
3255 	ump = VFSTOUFS(mp);
3256 	jblocks = ump->softdep_jblocks;
3257 	ACQUIRE_LOCK(ump);
3258 	while (ump->softdep_on_journal) {
3259 		jblocks->jb_needseg = 1;
3260 		softdep_process_journal(mp, NULL, MNT_WAIT);
3261 	}
3262 	FREE_LOCK(ump);
3263 }
3264 
3265 static void softdep_synchronize_completed(struct bio *);
3266 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3267 
3268 static void
3269 softdep_synchronize_completed(bp)
3270         struct bio *bp;
3271 {
3272 	struct jseg *oldest;
3273 	struct jseg *jseg;
3274 	struct ufsmount *ump;
3275 
3276 	/*
3277 	 * caller1 marks the last segment written before we issued the
3278 	 * synchronize cache.
3279 	 */
3280 	jseg = bp->bio_caller1;
3281 	if (jseg == NULL) {
3282 		g_destroy_bio(bp);
3283 		return;
3284 	}
3285 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3286 	ACQUIRE_LOCK(ump);
3287 	oldest = NULL;
3288 	/*
3289 	 * Mark all the journal entries waiting on the synchronize cache
3290 	 * as completed so they may continue on.
3291 	 */
3292 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3293 		jseg->js_state |= COMPLETE;
3294 		oldest = jseg;
3295 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3296 	}
3297 	/*
3298 	 * Restart deferred journal entry processing from the oldest
3299 	 * completed jseg.
3300 	 */
3301 	if (oldest)
3302 		complete_jsegs(oldest);
3303 
3304 	FREE_LOCK(ump);
3305 	g_destroy_bio(bp);
3306 }
3307 
3308 /*
3309  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3310  * barriers.  The journal must be written prior to any blocks that depend
3311  * on it and the journal can not be released until the blocks have be
3312  * written.  This code handles both barriers simultaneously.
3313  */
3314 static void
3315 softdep_synchronize(bp, ump, caller1)
3316 	struct bio *bp;
3317 	struct ufsmount *ump;
3318 	void *caller1;
3319 {
3320 
3321 	bp->bio_cmd = BIO_FLUSH;
3322 	bp->bio_flags |= BIO_ORDERED;
3323 	bp->bio_data = NULL;
3324 	bp->bio_offset = ump->um_cp->provider->mediasize;
3325 	bp->bio_length = 0;
3326 	bp->bio_done = softdep_synchronize_completed;
3327 	bp->bio_caller1 = caller1;
3328 	g_io_request(bp,
3329 	    (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3330 }
3331 
3332 /*
3333  * Flush some journal records to disk.
3334  */
3335 static void
3336 softdep_process_journal(mp, needwk, flags)
3337 	struct mount *mp;
3338 	struct worklist *needwk;
3339 	int flags;
3340 {
3341 	struct jblocks *jblocks;
3342 	struct ufsmount *ump;
3343 	struct worklist *wk;
3344 	struct jseg *jseg;
3345 	struct buf *bp;
3346 	struct bio *bio;
3347 	uint8_t *data;
3348 	struct fs *fs;
3349 	int shouldflush;
3350 	int segwritten;
3351 	int jrecmin;	/* Minimum records per block. */
3352 	int jrecmax;	/* Maximum records per block. */
3353 	int size;
3354 	int cnt;
3355 	int off;
3356 	int devbsize;
3357 
3358 	if (MOUNTEDSUJ(mp) == 0)
3359 		return;
3360 	shouldflush = softdep_flushcache;
3361 	bio = NULL;
3362 	jseg = NULL;
3363 	ump = VFSTOUFS(mp);
3364 	LOCK_OWNED(ump);
3365 	fs = ump->um_fs;
3366 	jblocks = ump->softdep_jblocks;
3367 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3368 	/*
3369 	 * We write anywhere between a disk block and fs block.  The upper
3370 	 * bound is picked to prevent buffer cache fragmentation and limit
3371 	 * processing time per I/O.
3372 	 */
3373 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3374 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3375 	segwritten = 0;
3376 	for (;;) {
3377 		cnt = ump->softdep_on_journal;
3378 		/*
3379 		 * Criteria for writing a segment:
3380 		 * 1) We have a full block.
3381 		 * 2) We're called from jwait() and haven't found the
3382 		 *    journal item yet.
3383 		 * 3) Always write if needseg is set.
3384 		 * 4) If we are called from process_worklist and have
3385 		 *    not yet written anything we write a partial block
3386 		 *    to enforce a 1 second maximum latency on journal
3387 		 *    entries.
3388 		 */
3389 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3390 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3391 			break;
3392 		cnt++;
3393 		/*
3394 		 * Verify some free journal space.  softdep_prealloc() should
3395 		 * guarantee that we don't run out so this is indicative of
3396 		 * a problem with the flow control.  Try to recover
3397 		 * gracefully in any event.
3398 		 */
3399 		while (jblocks->jb_free == 0) {
3400 			if (flags != MNT_WAIT)
3401 				break;
3402 			printf("softdep: Out of journal space!\n");
3403 			softdep_speedup(ump);
3404 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3405 		}
3406 		FREE_LOCK(ump);
3407 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3408 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3409 		LIST_INIT(&jseg->js_entries);
3410 		LIST_INIT(&jseg->js_indirs);
3411 		jseg->js_state = ATTACHED;
3412 		if (shouldflush == 0)
3413 			jseg->js_state |= COMPLETE;
3414 		else if (bio == NULL)
3415 			bio = g_alloc_bio();
3416 		jseg->js_jblocks = jblocks;
3417 		bp = geteblk(fs->fs_bsize, 0);
3418 		ACQUIRE_LOCK(ump);
3419 		/*
3420 		 * If there was a race while we were allocating the block
3421 		 * and jseg the entry we care about was likely written.
3422 		 * We bail out in both the WAIT and NOWAIT case and assume
3423 		 * the caller will loop if the entry it cares about is
3424 		 * not written.
3425 		 */
3426 		cnt = ump->softdep_on_journal;
3427 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3428 			bp->b_flags |= B_INVAL | B_NOCACHE;
3429 			WORKITEM_FREE(jseg, D_JSEG);
3430 			FREE_LOCK(ump);
3431 			brelse(bp);
3432 			ACQUIRE_LOCK(ump);
3433 			break;
3434 		}
3435 		/*
3436 		 * Calculate the disk block size required for the available
3437 		 * records rounded to the min size.
3438 		 */
3439 		if (cnt == 0)
3440 			size = devbsize;
3441 		else if (cnt < jrecmax)
3442 			size = howmany(cnt, jrecmin) * devbsize;
3443 		else
3444 			size = fs->fs_bsize;
3445 		/*
3446 		 * Allocate a disk block for this journal data and account
3447 		 * for truncation of the requested size if enough contiguous
3448 		 * space was not available.
3449 		 */
3450 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3451 		bp->b_lblkno = bp->b_blkno;
3452 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3453 		bp->b_bcount = size;
3454 		bp->b_flags &= ~B_INVAL;
3455 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3456 		/*
3457 		 * Initialize our jseg with cnt records.  Assign the next
3458 		 * sequence number to it and link it in-order.
3459 		 */
3460 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3461 		jseg->js_buf = bp;
3462 		jseg->js_cnt = cnt;
3463 		jseg->js_refs = cnt + 1;	/* Self ref. */
3464 		jseg->js_size = size;
3465 		jseg->js_seq = jblocks->jb_nextseq++;
3466 		if (jblocks->jb_oldestseg == NULL)
3467 			jblocks->jb_oldestseg = jseg;
3468 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3469 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3470 		if (jblocks->jb_writeseg == NULL)
3471 			jblocks->jb_writeseg = jseg;
3472 		/*
3473 		 * Start filling in records from the pending list.
3474 		 */
3475 		data = bp->b_data;
3476 		off = 0;
3477 
3478 		/*
3479 		 * Always put a header on the first block.
3480 		 * XXX As with below, there might not be a chance to get
3481 		 * into the loop.  Ensure that something valid is written.
3482 		 */
3483 		jseg_write(ump, jseg, data);
3484 		off += JREC_SIZE;
3485 		data = bp->b_data + off;
3486 
3487 		/*
3488 		 * XXX Something is wrong here.  There's no work to do,
3489 		 * but we need to perform and I/O and allow it to complete
3490 		 * anyways.
3491 		 */
3492 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3493 			stat_emptyjblocks++;
3494 
3495 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3496 		    != NULL) {
3497 			if (cnt == 0)
3498 				break;
3499 			/* Place a segment header on every device block. */
3500 			if ((off % devbsize) == 0) {
3501 				jseg_write(ump, jseg, data);
3502 				off += JREC_SIZE;
3503 				data = bp->b_data + off;
3504 			}
3505 			if (wk == needwk)
3506 				needwk = NULL;
3507 			remove_from_journal(wk);
3508 			wk->wk_state |= INPROGRESS;
3509 			WORKLIST_INSERT(&jseg->js_entries, wk);
3510 			switch (wk->wk_type) {
3511 			case D_JADDREF:
3512 				jaddref_write(WK_JADDREF(wk), jseg, data);
3513 				break;
3514 			case D_JREMREF:
3515 				jremref_write(WK_JREMREF(wk), jseg, data);
3516 				break;
3517 			case D_JMVREF:
3518 				jmvref_write(WK_JMVREF(wk), jseg, data);
3519 				break;
3520 			case D_JNEWBLK:
3521 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3522 				break;
3523 			case D_JFREEBLK:
3524 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3525 				break;
3526 			case D_JFREEFRAG:
3527 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3528 				break;
3529 			case D_JTRUNC:
3530 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3531 				break;
3532 			case D_JFSYNC:
3533 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3534 				break;
3535 			default:
3536 				panic("process_journal: Unknown type %s",
3537 				    TYPENAME(wk->wk_type));
3538 				/* NOTREACHED */
3539 			}
3540 			off += JREC_SIZE;
3541 			data = bp->b_data + off;
3542 			cnt--;
3543 		}
3544 
3545 		/* Clear any remaining space so we don't leak kernel data */
3546 		if (size > off)
3547 			bzero(data, size - off);
3548 
3549 		/*
3550 		 * Write this one buffer and continue.
3551 		 */
3552 		segwritten = 1;
3553 		jblocks->jb_needseg = 0;
3554 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3555 		FREE_LOCK(ump);
3556 		pbgetvp(ump->um_devvp, bp);
3557 		/*
3558 		 * We only do the blocking wait once we find the journal
3559 		 * entry we're looking for.
3560 		 */
3561 		if (needwk == NULL && flags == MNT_WAIT)
3562 			bwrite(bp);
3563 		else
3564 			bawrite(bp);
3565 		ACQUIRE_LOCK(ump);
3566 	}
3567 	/*
3568 	 * If we wrote a segment issue a synchronize cache so the journal
3569 	 * is reflected on disk before the data is written.  Since reclaiming
3570 	 * journal space also requires writing a journal record this
3571 	 * process also enforces a barrier before reclamation.
3572 	 */
3573 	if (segwritten && shouldflush) {
3574 		softdep_synchronize(bio, ump,
3575 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3576 	} else if (bio)
3577 		g_destroy_bio(bio);
3578 	/*
3579 	 * If we've suspended the filesystem because we ran out of journal
3580 	 * space either try to sync it here to make some progress or
3581 	 * unsuspend it if we already have.
3582 	 */
3583 	if (flags == 0 && jblocks->jb_suspended) {
3584 		if (journal_unsuspend(ump))
3585 			return;
3586 		FREE_LOCK(ump);
3587 		VFS_SYNC(mp, MNT_NOWAIT);
3588 		ffs_sbupdate(ump, MNT_WAIT, 0);
3589 		ACQUIRE_LOCK(ump);
3590 	}
3591 }
3592 
3593 /*
3594  * Complete a jseg, allowing all dependencies awaiting journal writes
3595  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3596  * structures so that the journal segment can be freed to reclaim space.
3597  */
3598 static void
3599 complete_jseg(jseg)
3600 	struct jseg *jseg;
3601 {
3602 	struct worklist *wk;
3603 	struct jmvref *jmvref;
3604 #ifdef INVARIANTS
3605 	int i = 0;
3606 #endif
3607 
3608 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3609 		WORKLIST_REMOVE(wk);
3610 		wk->wk_state &= ~INPROGRESS;
3611 		wk->wk_state |= COMPLETE;
3612 		KASSERT(i++ < jseg->js_cnt,
3613 		    ("handle_written_jseg: overflow %d >= %d",
3614 		    i - 1, jseg->js_cnt));
3615 		switch (wk->wk_type) {
3616 		case D_JADDREF:
3617 			handle_written_jaddref(WK_JADDREF(wk));
3618 			break;
3619 		case D_JREMREF:
3620 			handle_written_jremref(WK_JREMREF(wk));
3621 			break;
3622 		case D_JMVREF:
3623 			rele_jseg(jseg);	/* No jsegdep. */
3624 			jmvref = WK_JMVREF(wk);
3625 			LIST_REMOVE(jmvref, jm_deps);
3626 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3627 				free_pagedep(jmvref->jm_pagedep);
3628 			WORKITEM_FREE(jmvref, D_JMVREF);
3629 			break;
3630 		case D_JNEWBLK:
3631 			handle_written_jnewblk(WK_JNEWBLK(wk));
3632 			break;
3633 		case D_JFREEBLK:
3634 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3635 			break;
3636 		case D_JTRUNC:
3637 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3638 			break;
3639 		case D_JFSYNC:
3640 			rele_jseg(jseg);	/* No jsegdep. */
3641 			WORKITEM_FREE(wk, D_JFSYNC);
3642 			break;
3643 		case D_JFREEFRAG:
3644 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3645 			break;
3646 		default:
3647 			panic("handle_written_jseg: Unknown type %s",
3648 			    TYPENAME(wk->wk_type));
3649 			/* NOTREACHED */
3650 		}
3651 	}
3652 	/* Release the self reference so the structure may be freed. */
3653 	rele_jseg(jseg);
3654 }
3655 
3656 /*
3657  * Determine which jsegs are ready for completion processing.  Waits for
3658  * synchronize cache to complete as well as forcing in-order completion
3659  * of journal entries.
3660  */
3661 static void
3662 complete_jsegs(jseg)
3663 	struct jseg *jseg;
3664 {
3665 	struct jblocks *jblocks;
3666 	struct jseg *jsegn;
3667 
3668 	jblocks = jseg->js_jblocks;
3669 	/*
3670 	 * Don't allow out of order completions.  If this isn't the first
3671 	 * block wait for it to write before we're done.
3672 	 */
3673 	if (jseg != jblocks->jb_writeseg)
3674 		return;
3675 	/* Iterate through available jsegs processing their entries. */
3676 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3677 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3678 		jsegn = TAILQ_NEXT(jseg, js_next);
3679 		complete_jseg(jseg);
3680 		jseg = jsegn;
3681 	}
3682 	jblocks->jb_writeseg = jseg;
3683 	/*
3684 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3685 	 */
3686 	free_jsegs(jblocks);
3687 }
3688 
3689 /*
3690  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3691  * the final completions.
3692  */
3693 static void
3694 handle_written_jseg(jseg, bp)
3695 	struct jseg *jseg;
3696 	struct buf *bp;
3697 {
3698 
3699 	if (jseg->js_refs == 0)
3700 		panic("handle_written_jseg: No self-reference on %p", jseg);
3701 	jseg->js_state |= DEPCOMPLETE;
3702 	/*
3703 	 * We'll never need this buffer again, set flags so it will be
3704 	 * discarded.
3705 	 */
3706 	bp->b_flags |= B_INVAL | B_NOCACHE;
3707 	pbrelvp(bp);
3708 	complete_jsegs(jseg);
3709 }
3710 
3711 static inline struct jsegdep *
3712 inoref_jseg(inoref)
3713 	struct inoref *inoref;
3714 {
3715 	struct jsegdep *jsegdep;
3716 
3717 	jsegdep = inoref->if_jsegdep;
3718 	inoref->if_jsegdep = NULL;
3719 
3720 	return (jsegdep);
3721 }
3722 
3723 /*
3724  * Called once a jremref has made it to stable store.  The jremref is marked
3725  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3726  * for the jremref to complete will be awoken by free_jremref.
3727  */
3728 static void
3729 handle_written_jremref(jremref)
3730 	struct jremref *jremref;
3731 {
3732 	struct inodedep *inodedep;
3733 	struct jsegdep *jsegdep;
3734 	struct dirrem *dirrem;
3735 
3736 	/* Grab the jsegdep. */
3737 	jsegdep = inoref_jseg(&jremref->jr_ref);
3738 	/*
3739 	 * Remove us from the inoref list.
3740 	 */
3741 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3742 	    0, &inodedep) == 0)
3743 		panic("handle_written_jremref: Lost inodedep");
3744 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3745 	/*
3746 	 * Complete the dirrem.
3747 	 */
3748 	dirrem = jremref->jr_dirrem;
3749 	jremref->jr_dirrem = NULL;
3750 	LIST_REMOVE(jremref, jr_deps);
3751 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3752 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3753 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3754 	    (dirrem->dm_state & COMPLETE) != 0)
3755 		add_to_worklist(&dirrem->dm_list, 0);
3756 	free_jremref(jremref);
3757 }
3758 
3759 /*
3760  * Called once a jaddref has made it to stable store.  The dependency is
3761  * marked complete and any dependent structures are added to the inode
3762  * bufwait list to be completed as soon as it is written.  If a bitmap write
3763  * depends on this entry we move the inode into the inodedephd of the
3764  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3765  */
3766 static void
3767 handle_written_jaddref(jaddref)
3768 	struct jaddref *jaddref;
3769 {
3770 	struct jsegdep *jsegdep;
3771 	struct inodedep *inodedep;
3772 	struct diradd *diradd;
3773 	struct mkdir *mkdir;
3774 
3775 	/* Grab the jsegdep. */
3776 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3777 	mkdir = NULL;
3778 	diradd = NULL;
3779 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3780 	    0, &inodedep) == 0)
3781 		panic("handle_written_jaddref: Lost inodedep.");
3782 	if (jaddref->ja_diradd == NULL)
3783 		panic("handle_written_jaddref: No dependency");
3784 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3785 		diradd = jaddref->ja_diradd;
3786 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3787 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3788 		mkdir = jaddref->ja_mkdir;
3789 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3790 	} else if (jaddref->ja_state & MKDIR_BODY)
3791 		mkdir = jaddref->ja_mkdir;
3792 	else
3793 		panic("handle_written_jaddref: Unknown dependency %p",
3794 		    jaddref->ja_diradd);
3795 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3796 	/*
3797 	 * Remove us from the inode list.
3798 	 */
3799 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3800 	/*
3801 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3802 	 */
3803 	if (mkdir) {
3804 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3805 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3806 		    TYPENAME(mkdir->md_list.wk_type)));
3807 		mkdir->md_jaddref = NULL;
3808 		diradd = mkdir->md_diradd;
3809 		mkdir->md_state |= DEPCOMPLETE;
3810 		complete_mkdir(mkdir);
3811 	}
3812 	jwork_insert(&diradd->da_jwork, jsegdep);
3813 	if (jaddref->ja_state & NEWBLOCK) {
3814 		inodedep->id_state |= ONDEPLIST;
3815 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3816 		    inodedep, id_deps);
3817 	}
3818 	free_jaddref(jaddref);
3819 }
3820 
3821 /*
3822  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3823  * is placed in the bmsafemap to await notification of a written bitmap.  If
3824  * the operation was canceled we add the segdep to the appropriate
3825  * dependency to free the journal space once the canceling operation
3826  * completes.
3827  */
3828 static void
3829 handle_written_jnewblk(jnewblk)
3830 	struct jnewblk *jnewblk;
3831 {
3832 	struct bmsafemap *bmsafemap;
3833 	struct freefrag *freefrag;
3834 	struct freework *freework;
3835 	struct jsegdep *jsegdep;
3836 	struct newblk *newblk;
3837 
3838 	/* Grab the jsegdep. */
3839 	jsegdep = jnewblk->jn_jsegdep;
3840 	jnewblk->jn_jsegdep = NULL;
3841 	if (jnewblk->jn_dep == NULL)
3842 		panic("handle_written_jnewblk: No dependency for the segdep.");
3843 	switch (jnewblk->jn_dep->wk_type) {
3844 	case D_NEWBLK:
3845 	case D_ALLOCDIRECT:
3846 	case D_ALLOCINDIR:
3847 		/*
3848 		 * Add the written block to the bmsafemap so it can
3849 		 * be notified when the bitmap is on disk.
3850 		 */
3851 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3852 		newblk->nb_jnewblk = NULL;
3853 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3854 			bmsafemap = newblk->nb_bmsafemap;
3855 			newblk->nb_state |= ONDEPLIST;
3856 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3857 			    nb_deps);
3858 		}
3859 		jwork_insert(&newblk->nb_jwork, jsegdep);
3860 		break;
3861 	case D_FREEFRAG:
3862 		/*
3863 		 * A newblock being removed by a freefrag when replaced by
3864 		 * frag extension.
3865 		 */
3866 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3867 		freefrag->ff_jdep = NULL;
3868 		jwork_insert(&freefrag->ff_jwork, jsegdep);
3869 		break;
3870 	case D_FREEWORK:
3871 		/*
3872 		 * A direct block was removed by truncate.
3873 		 */
3874 		freework = WK_FREEWORK(jnewblk->jn_dep);
3875 		freework->fw_jnewblk = NULL;
3876 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3877 		break;
3878 	default:
3879 		panic("handle_written_jnewblk: Unknown type %d.",
3880 		    jnewblk->jn_dep->wk_type);
3881 	}
3882 	jnewblk->jn_dep = NULL;
3883 	free_jnewblk(jnewblk);
3884 }
3885 
3886 /*
3887  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3888  * an in-flight allocation that has not yet been committed.  Divorce us
3889  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3890  * to the worklist.
3891  */
3892 static void
3893 cancel_jfreefrag(jfreefrag)
3894 	struct jfreefrag *jfreefrag;
3895 {
3896 	struct freefrag *freefrag;
3897 
3898 	if (jfreefrag->fr_jsegdep) {
3899 		free_jsegdep(jfreefrag->fr_jsegdep);
3900 		jfreefrag->fr_jsegdep = NULL;
3901 	}
3902 	freefrag = jfreefrag->fr_freefrag;
3903 	jfreefrag->fr_freefrag = NULL;
3904 	free_jfreefrag(jfreefrag);
3905 	freefrag->ff_state |= DEPCOMPLETE;
3906 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3907 }
3908 
3909 /*
3910  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3911  */
3912 static void
3913 free_jfreefrag(jfreefrag)
3914 	struct jfreefrag *jfreefrag;
3915 {
3916 
3917 	if (jfreefrag->fr_state & INPROGRESS)
3918 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3919 	else if (jfreefrag->fr_state & ONWORKLIST)
3920 		remove_from_journal(&jfreefrag->fr_list);
3921 	if (jfreefrag->fr_freefrag != NULL)
3922 		panic("free_jfreefrag:  Still attached to a freefrag.");
3923 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3924 }
3925 
3926 /*
3927  * Called when the journal write for a jfreefrag completes.  The parent
3928  * freefrag is added to the worklist if this completes its dependencies.
3929  */
3930 static void
3931 handle_written_jfreefrag(jfreefrag)
3932 	struct jfreefrag *jfreefrag;
3933 {
3934 	struct jsegdep *jsegdep;
3935 	struct freefrag *freefrag;
3936 
3937 	/* Grab the jsegdep. */
3938 	jsegdep = jfreefrag->fr_jsegdep;
3939 	jfreefrag->fr_jsegdep = NULL;
3940 	freefrag = jfreefrag->fr_freefrag;
3941 	if (freefrag == NULL)
3942 		panic("handle_written_jfreefrag: No freefrag.");
3943 	freefrag->ff_state |= DEPCOMPLETE;
3944 	freefrag->ff_jdep = NULL;
3945 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3946 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3947 		add_to_worklist(&freefrag->ff_list, 0);
3948 	jfreefrag->fr_freefrag = NULL;
3949 	free_jfreefrag(jfreefrag);
3950 }
3951 
3952 /*
3953  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3954  * is removed from the freeblks list of pending journal writes and the
3955  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3956  * have been reclaimed.
3957  */
3958 static void
3959 handle_written_jblkdep(jblkdep)
3960 	struct jblkdep *jblkdep;
3961 {
3962 	struct freeblks *freeblks;
3963 	struct jsegdep *jsegdep;
3964 
3965 	/* Grab the jsegdep. */
3966 	jsegdep = jblkdep->jb_jsegdep;
3967 	jblkdep->jb_jsegdep = NULL;
3968 	freeblks = jblkdep->jb_freeblks;
3969 	LIST_REMOVE(jblkdep, jb_deps);
3970 	jwork_insert(&freeblks->fb_jwork, jsegdep);
3971 	/*
3972 	 * If the freeblks is all journaled, we can add it to the worklist.
3973 	 */
3974 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3975 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3976 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3977 
3978 	free_jblkdep(jblkdep);
3979 }
3980 
3981 static struct jsegdep *
3982 newjsegdep(struct worklist *wk)
3983 {
3984 	struct jsegdep *jsegdep;
3985 
3986 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3987 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3988 	jsegdep->jd_seg = NULL;
3989 
3990 	return (jsegdep);
3991 }
3992 
3993 static struct jmvref *
3994 newjmvref(dp, ino, oldoff, newoff)
3995 	struct inode *dp;
3996 	ino_t ino;
3997 	off_t oldoff;
3998 	off_t newoff;
3999 {
4000 	struct jmvref *jmvref;
4001 
4002 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4003 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4004 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4005 	jmvref->jm_parent = dp->i_number;
4006 	jmvref->jm_ino = ino;
4007 	jmvref->jm_oldoff = oldoff;
4008 	jmvref->jm_newoff = newoff;
4009 
4010 	return (jmvref);
4011 }
4012 
4013 /*
4014  * Allocate a new jremref that tracks the removal of ip from dp with the
4015  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4016  * DEPCOMPLETE as we have all the information required for the journal write
4017  * and the directory has already been removed from the buffer.  The caller
4018  * is responsible for linking the jremref into the pagedep and adding it
4019  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4020  * a DOTDOT addition so handle_workitem_remove() can properly assign
4021  * the jsegdep when we're done.
4022  */
4023 static struct jremref *
4024 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4025     off_t diroff, nlink_t nlink)
4026 {
4027 	struct jremref *jremref;
4028 
4029 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4030 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4031 	jremref->jr_state = ATTACHED;
4032 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4033 	   nlink, ip->i_mode);
4034 	jremref->jr_dirrem = dirrem;
4035 
4036 	return (jremref);
4037 }
4038 
4039 static inline void
4040 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4041     nlink_t nlink, uint16_t mode)
4042 {
4043 
4044 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4045 	inoref->if_diroff = diroff;
4046 	inoref->if_ino = ino;
4047 	inoref->if_parent = parent;
4048 	inoref->if_nlink = nlink;
4049 	inoref->if_mode = mode;
4050 }
4051 
4052 /*
4053  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4054  * directory offset may not be known until later.  The caller is responsible
4055  * adding the entry to the journal when this information is available.  nlink
4056  * should be the link count prior to the addition and mode is only required
4057  * to have the correct FMT.
4058  */
4059 static struct jaddref *
4060 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4061     uint16_t mode)
4062 {
4063 	struct jaddref *jaddref;
4064 
4065 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4066 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4067 	jaddref->ja_state = ATTACHED;
4068 	jaddref->ja_mkdir = NULL;
4069 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4070 
4071 	return (jaddref);
4072 }
4073 
4074 /*
4075  * Create a new free dependency for a freework.  The caller is responsible
4076  * for adjusting the reference count when it has the lock held.  The freedep
4077  * will track an outstanding bitmap write that will ultimately clear the
4078  * freework to continue.
4079  */
4080 static struct freedep *
4081 newfreedep(struct freework *freework)
4082 {
4083 	struct freedep *freedep;
4084 
4085 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4086 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4087 	freedep->fd_freework = freework;
4088 
4089 	return (freedep);
4090 }
4091 
4092 /*
4093  * Free a freedep structure once the buffer it is linked to is written.  If
4094  * this is the last reference to the freework schedule it for completion.
4095  */
4096 static void
4097 free_freedep(freedep)
4098 	struct freedep *freedep;
4099 {
4100 	struct freework *freework;
4101 
4102 	freework = freedep->fd_freework;
4103 	freework->fw_freeblks->fb_cgwait--;
4104 	if (--freework->fw_ref == 0)
4105 		freework_enqueue(freework);
4106 	WORKITEM_FREE(freedep, D_FREEDEP);
4107 }
4108 
4109 /*
4110  * Allocate a new freework structure that may be a level in an indirect
4111  * when parent is not NULL or a top level block when it is.  The top level
4112  * freework structures are allocated without the per-filesystem lock held
4113  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4114  */
4115 static struct freework *
4116 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4117 	struct ufsmount *ump;
4118 	struct freeblks *freeblks;
4119 	struct freework *parent;
4120 	ufs_lbn_t lbn;
4121 	ufs2_daddr_t nb;
4122 	int frags;
4123 	int off;
4124 	int journal;
4125 {
4126 	struct freework *freework;
4127 
4128 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4129 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4130 	freework->fw_state = ATTACHED;
4131 	freework->fw_jnewblk = NULL;
4132 	freework->fw_freeblks = freeblks;
4133 	freework->fw_parent = parent;
4134 	freework->fw_lbn = lbn;
4135 	freework->fw_blkno = nb;
4136 	freework->fw_frags = frags;
4137 	freework->fw_indir = NULL;
4138 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4139 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4140 	freework->fw_start = freework->fw_off = off;
4141 	if (journal)
4142 		newjfreeblk(freeblks, lbn, nb, frags);
4143 	if (parent == NULL) {
4144 		ACQUIRE_LOCK(ump);
4145 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4146 		freeblks->fb_ref++;
4147 		FREE_LOCK(ump);
4148 	}
4149 
4150 	return (freework);
4151 }
4152 
4153 /*
4154  * Eliminate a jfreeblk for a block that does not need journaling.
4155  */
4156 static void
4157 cancel_jfreeblk(freeblks, blkno)
4158 	struct freeblks *freeblks;
4159 	ufs2_daddr_t blkno;
4160 {
4161 	struct jfreeblk *jfreeblk;
4162 	struct jblkdep *jblkdep;
4163 
4164 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4165 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4166 			continue;
4167 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4168 		if (jfreeblk->jf_blkno == blkno)
4169 			break;
4170 	}
4171 	if (jblkdep == NULL)
4172 		return;
4173 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4174 	free_jsegdep(jblkdep->jb_jsegdep);
4175 	LIST_REMOVE(jblkdep, jb_deps);
4176 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4177 }
4178 
4179 /*
4180  * Allocate a new jfreeblk to journal top level block pointer when truncating
4181  * a file.  The caller must add this to the worklist when the per-filesystem
4182  * lock is held.
4183  */
4184 static struct jfreeblk *
4185 newjfreeblk(freeblks, lbn, blkno, frags)
4186 	struct freeblks *freeblks;
4187 	ufs_lbn_t lbn;
4188 	ufs2_daddr_t blkno;
4189 	int frags;
4190 {
4191 	struct jfreeblk *jfreeblk;
4192 
4193 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4194 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4195 	    freeblks->fb_list.wk_mp);
4196 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4197 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4198 	jfreeblk->jf_ino = freeblks->fb_inum;
4199 	jfreeblk->jf_lbn = lbn;
4200 	jfreeblk->jf_blkno = blkno;
4201 	jfreeblk->jf_frags = frags;
4202 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4203 
4204 	return (jfreeblk);
4205 }
4206 
4207 /*
4208  * The journal is only prepared to handle full-size block numbers, so we
4209  * have to adjust the record to reflect the change to a full-size block.
4210  * For example, suppose we have a block made up of fragments 8-15 and
4211  * want to free its last two fragments. We are given a request that says:
4212  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4213  * where frags are the number of fragments to free and oldfrags are the
4214  * number of fragments to keep. To block align it, we have to change it to
4215  * have a valid full-size blkno, so it becomes:
4216  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4217  */
4218 static void
4219 adjust_newfreework(freeblks, frag_offset)
4220 	struct freeblks *freeblks;
4221 	int frag_offset;
4222 {
4223 	struct jfreeblk *jfreeblk;
4224 
4225 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4226 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4227 	    ("adjust_newfreework: Missing freeblks dependency"));
4228 
4229 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4230 	jfreeblk->jf_blkno -= frag_offset;
4231 	jfreeblk->jf_frags += frag_offset;
4232 }
4233 
4234 /*
4235  * Allocate a new jtrunc to track a partial truncation.
4236  */
4237 static struct jtrunc *
4238 newjtrunc(freeblks, size, extsize)
4239 	struct freeblks *freeblks;
4240 	off_t size;
4241 	int extsize;
4242 {
4243 	struct jtrunc *jtrunc;
4244 
4245 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4246 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4247 	    freeblks->fb_list.wk_mp);
4248 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4249 	jtrunc->jt_dep.jb_freeblks = freeblks;
4250 	jtrunc->jt_ino = freeblks->fb_inum;
4251 	jtrunc->jt_size = size;
4252 	jtrunc->jt_extsize = extsize;
4253 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4254 
4255 	return (jtrunc);
4256 }
4257 
4258 /*
4259  * If we're canceling a new bitmap we have to search for another ref
4260  * to move into the bmsafemap dep.  This might be better expressed
4261  * with another structure.
4262  */
4263 static void
4264 move_newblock_dep(jaddref, inodedep)
4265 	struct jaddref *jaddref;
4266 	struct inodedep *inodedep;
4267 {
4268 	struct inoref *inoref;
4269 	struct jaddref *jaddrefn;
4270 
4271 	jaddrefn = NULL;
4272 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4273 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4274 		if ((jaddref->ja_state & NEWBLOCK) &&
4275 		    inoref->if_list.wk_type == D_JADDREF) {
4276 			jaddrefn = (struct jaddref *)inoref;
4277 			break;
4278 		}
4279 	}
4280 	if (jaddrefn == NULL)
4281 		return;
4282 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4283 	jaddrefn->ja_state |= jaddref->ja_state &
4284 	    (ATTACHED | UNDONE | NEWBLOCK);
4285 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4286 	jaddref->ja_state |= ATTACHED;
4287 	LIST_REMOVE(jaddref, ja_bmdeps);
4288 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4289 	    ja_bmdeps);
4290 }
4291 
4292 /*
4293  * Cancel a jaddref either before it has been written or while it is being
4294  * written.  This happens when a link is removed before the add reaches
4295  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4296  * and inode to prevent the link count or bitmap from reaching the disk
4297  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4298  * required.
4299  *
4300  * Returns 1 if the canceled addref requires journaling of the remove and
4301  * 0 otherwise.
4302  */
4303 static int
4304 cancel_jaddref(jaddref, inodedep, wkhd)
4305 	struct jaddref *jaddref;
4306 	struct inodedep *inodedep;
4307 	struct workhead *wkhd;
4308 {
4309 	struct inoref *inoref;
4310 	struct jsegdep *jsegdep;
4311 	int needsj;
4312 
4313 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4314 	    ("cancel_jaddref: Canceling complete jaddref"));
4315 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4316 		needsj = 1;
4317 	else
4318 		needsj = 0;
4319 	if (inodedep == NULL)
4320 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4321 		    0, &inodedep) == 0)
4322 			panic("cancel_jaddref: Lost inodedep");
4323 	/*
4324 	 * We must adjust the nlink of any reference operation that follows
4325 	 * us so that it is consistent with the in-memory reference.  This
4326 	 * ensures that inode nlink rollbacks always have the correct link.
4327 	 */
4328 	if (needsj == 0) {
4329 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4330 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4331 			if (inoref->if_state & GOINGAWAY)
4332 				break;
4333 			inoref->if_nlink--;
4334 		}
4335 	}
4336 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4337 	if (jaddref->ja_state & NEWBLOCK)
4338 		move_newblock_dep(jaddref, inodedep);
4339 	wake_worklist(&jaddref->ja_list);
4340 	jaddref->ja_mkdir = NULL;
4341 	if (jaddref->ja_state & INPROGRESS) {
4342 		jaddref->ja_state &= ~INPROGRESS;
4343 		WORKLIST_REMOVE(&jaddref->ja_list);
4344 		jwork_insert(wkhd, jsegdep);
4345 	} else {
4346 		free_jsegdep(jsegdep);
4347 		if (jaddref->ja_state & DEPCOMPLETE)
4348 			remove_from_journal(&jaddref->ja_list);
4349 	}
4350 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4351 	/*
4352 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4353 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4354 	 * no longer need this addref attached to the inoreflst and it
4355 	 * will incorrectly adjust nlink if we leave it.
4356 	 */
4357 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4358 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4359 		    if_deps);
4360 		jaddref->ja_state |= COMPLETE;
4361 		free_jaddref(jaddref);
4362 		return (needsj);
4363 	}
4364 	/*
4365 	 * Leave the head of the list for jsegdeps for fast merging.
4366 	 */
4367 	if (LIST_FIRST(wkhd) != NULL) {
4368 		jaddref->ja_state |= ONWORKLIST;
4369 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4370 	} else
4371 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4372 
4373 	return (needsj);
4374 }
4375 
4376 /*
4377  * Attempt to free a jaddref structure when some work completes.  This
4378  * should only succeed once the entry is written and all dependencies have
4379  * been notified.
4380  */
4381 static void
4382 free_jaddref(jaddref)
4383 	struct jaddref *jaddref;
4384 {
4385 
4386 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4387 		return;
4388 	if (jaddref->ja_ref.if_jsegdep)
4389 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4390 		    jaddref, jaddref->ja_state);
4391 	if (jaddref->ja_state & NEWBLOCK)
4392 		LIST_REMOVE(jaddref, ja_bmdeps);
4393 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4394 		panic("free_jaddref: Bad state %p(0x%X)",
4395 		    jaddref, jaddref->ja_state);
4396 	if (jaddref->ja_mkdir != NULL)
4397 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4398 	WORKITEM_FREE(jaddref, D_JADDREF);
4399 }
4400 
4401 /*
4402  * Free a jremref structure once it has been written or discarded.
4403  */
4404 static void
4405 free_jremref(jremref)
4406 	struct jremref *jremref;
4407 {
4408 
4409 	if (jremref->jr_ref.if_jsegdep)
4410 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4411 	if (jremref->jr_state & INPROGRESS)
4412 		panic("free_jremref: IO still pending");
4413 	WORKITEM_FREE(jremref, D_JREMREF);
4414 }
4415 
4416 /*
4417  * Free a jnewblk structure.
4418  */
4419 static void
4420 free_jnewblk(jnewblk)
4421 	struct jnewblk *jnewblk;
4422 {
4423 
4424 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4425 		return;
4426 	LIST_REMOVE(jnewblk, jn_deps);
4427 	if (jnewblk->jn_dep != NULL)
4428 		panic("free_jnewblk: Dependency still attached.");
4429 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4430 }
4431 
4432 /*
4433  * Cancel a jnewblk which has been been made redundant by frag extension.
4434  */
4435 static void
4436 cancel_jnewblk(jnewblk, wkhd)
4437 	struct jnewblk *jnewblk;
4438 	struct workhead *wkhd;
4439 {
4440 	struct jsegdep *jsegdep;
4441 
4442 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4443 	jsegdep = jnewblk->jn_jsegdep;
4444 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4445 		panic("cancel_jnewblk: Invalid state");
4446 	jnewblk->jn_jsegdep  = NULL;
4447 	jnewblk->jn_dep = NULL;
4448 	jnewblk->jn_state |= GOINGAWAY;
4449 	if (jnewblk->jn_state & INPROGRESS) {
4450 		jnewblk->jn_state &= ~INPROGRESS;
4451 		WORKLIST_REMOVE(&jnewblk->jn_list);
4452 		jwork_insert(wkhd, jsegdep);
4453 	} else {
4454 		free_jsegdep(jsegdep);
4455 		remove_from_journal(&jnewblk->jn_list);
4456 	}
4457 	wake_worklist(&jnewblk->jn_list);
4458 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4459 }
4460 
4461 static void
4462 free_jblkdep(jblkdep)
4463 	struct jblkdep *jblkdep;
4464 {
4465 
4466 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4467 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4468 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4469 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4470 	else
4471 		panic("free_jblkdep: Unexpected type %s",
4472 		    TYPENAME(jblkdep->jb_list.wk_type));
4473 }
4474 
4475 /*
4476  * Free a single jseg once it is no longer referenced in memory or on
4477  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4478  * to disappear.
4479  */
4480 static void
4481 free_jseg(jseg, jblocks)
4482 	struct jseg *jseg;
4483 	struct jblocks *jblocks;
4484 {
4485 	struct freework *freework;
4486 
4487 	/*
4488 	 * Free freework structures that were lingering to indicate freed
4489 	 * indirect blocks that forced journal write ordering on reallocate.
4490 	 */
4491 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4492 		indirblk_remove(freework);
4493 	if (jblocks->jb_oldestseg == jseg)
4494 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4495 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4496 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4497 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4498 	    ("free_jseg: Freed jseg has valid entries."));
4499 	WORKITEM_FREE(jseg, D_JSEG);
4500 }
4501 
4502 /*
4503  * Free all jsegs that meet the criteria for being reclaimed and update
4504  * oldestseg.
4505  */
4506 static void
4507 free_jsegs(jblocks)
4508 	struct jblocks *jblocks;
4509 {
4510 	struct jseg *jseg;
4511 
4512 	/*
4513 	 * Free only those jsegs which have none allocated before them to
4514 	 * preserve the journal space ordering.
4515 	 */
4516 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4517 		/*
4518 		 * Only reclaim space when nothing depends on this journal
4519 		 * set and another set has written that it is no longer
4520 		 * valid.
4521 		 */
4522 		if (jseg->js_refs != 0) {
4523 			jblocks->jb_oldestseg = jseg;
4524 			return;
4525 		}
4526 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4527 			break;
4528 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4529 			break;
4530 		/*
4531 		 * We can free jsegs that didn't write entries when
4532 		 * oldestwrseq == js_seq.
4533 		 */
4534 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4535 		    jseg->js_cnt != 0)
4536 			break;
4537 		free_jseg(jseg, jblocks);
4538 	}
4539 	/*
4540 	 * If we exited the loop above we still must discover the
4541 	 * oldest valid segment.
4542 	 */
4543 	if (jseg)
4544 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4545 		     jseg = TAILQ_NEXT(jseg, js_next))
4546 			if (jseg->js_refs != 0)
4547 				break;
4548 	jblocks->jb_oldestseg = jseg;
4549 	/*
4550 	 * The journal has no valid records but some jsegs may still be
4551 	 * waiting on oldestwrseq to advance.  We force a small record
4552 	 * out to permit these lingering records to be reclaimed.
4553 	 */
4554 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4555 		jblocks->jb_needseg = 1;
4556 }
4557 
4558 /*
4559  * Release one reference to a jseg and free it if the count reaches 0.  This
4560  * should eventually reclaim journal space as well.
4561  */
4562 static void
4563 rele_jseg(jseg)
4564 	struct jseg *jseg;
4565 {
4566 
4567 	KASSERT(jseg->js_refs > 0,
4568 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4569 	if (--jseg->js_refs != 0)
4570 		return;
4571 	free_jsegs(jseg->js_jblocks);
4572 }
4573 
4574 /*
4575  * Release a jsegdep and decrement the jseg count.
4576  */
4577 static void
4578 free_jsegdep(jsegdep)
4579 	struct jsegdep *jsegdep;
4580 {
4581 
4582 	if (jsegdep->jd_seg)
4583 		rele_jseg(jsegdep->jd_seg);
4584 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4585 }
4586 
4587 /*
4588  * Wait for a journal item to make it to disk.  Initiate journal processing
4589  * if required.
4590  */
4591 static int
4592 jwait(wk, waitfor)
4593 	struct worklist *wk;
4594 	int waitfor;
4595 {
4596 
4597 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4598 	/*
4599 	 * Blocking journal waits cause slow synchronous behavior.  Record
4600 	 * stats on the frequency of these blocking operations.
4601 	 */
4602 	if (waitfor == MNT_WAIT) {
4603 		stat_journal_wait++;
4604 		switch (wk->wk_type) {
4605 		case D_JREMREF:
4606 		case D_JMVREF:
4607 			stat_jwait_filepage++;
4608 			break;
4609 		case D_JTRUNC:
4610 		case D_JFREEBLK:
4611 			stat_jwait_freeblks++;
4612 			break;
4613 		case D_JNEWBLK:
4614 			stat_jwait_newblk++;
4615 			break;
4616 		case D_JADDREF:
4617 			stat_jwait_inode++;
4618 			break;
4619 		default:
4620 			break;
4621 		}
4622 	}
4623 	/*
4624 	 * If IO has not started we process the journal.  We can't mark the
4625 	 * worklist item as IOWAITING because we drop the lock while
4626 	 * processing the journal and the worklist entry may be freed after
4627 	 * this point.  The caller may call back in and re-issue the request.
4628 	 */
4629 	if ((wk->wk_state & INPROGRESS) == 0) {
4630 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4631 		if (waitfor != MNT_WAIT)
4632 			return (EBUSY);
4633 		return (0);
4634 	}
4635 	if (waitfor != MNT_WAIT)
4636 		return (EBUSY);
4637 	wait_worklist(wk, "jwait");
4638 	return (0);
4639 }
4640 
4641 /*
4642  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4643  * appropriate.  This is a convenience function to reduce duplicate code
4644  * for the setup and revert functions below.
4645  */
4646 static struct inodedep *
4647 inodedep_lookup_ip(ip)
4648 	struct inode *ip;
4649 {
4650 	struct inodedep *inodedep;
4651 
4652 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4653 	    ("inodedep_lookup_ip: bad delta"));
4654 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4655 	    &inodedep);
4656 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4657 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4658 
4659 	return (inodedep);
4660 }
4661 
4662 /*
4663  * Called prior to creating a new inode and linking it to a directory.  The
4664  * jaddref structure must already be allocated by softdep_setup_inomapdep
4665  * and it is discovered here so we can initialize the mode and update
4666  * nlinkdelta.
4667  */
4668 void
4669 softdep_setup_create(dp, ip)
4670 	struct inode *dp;
4671 	struct inode *ip;
4672 {
4673 	struct inodedep *inodedep;
4674 	struct jaddref *jaddref;
4675 	struct vnode *dvp;
4676 
4677 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4678 	    ("softdep_setup_create called on non-softdep filesystem"));
4679 	KASSERT(ip->i_nlink == 1,
4680 	    ("softdep_setup_create: Invalid link count."));
4681 	dvp = ITOV(dp);
4682 	ACQUIRE_LOCK(ITOUMP(dp));
4683 	inodedep = inodedep_lookup_ip(ip);
4684 	if (DOINGSUJ(dvp)) {
4685 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4686 		    inoreflst);
4687 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4688 		    ("softdep_setup_create: No addref structure present."));
4689 	}
4690 	softdep_prelink(dvp, NULL);
4691 	FREE_LOCK(ITOUMP(dp));
4692 }
4693 
4694 /*
4695  * Create a jaddref structure to track the addition of a DOTDOT link when
4696  * we are reparenting an inode as part of a rename.  This jaddref will be
4697  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4698  * non-journaling softdep.
4699  */
4700 void
4701 softdep_setup_dotdot_link(dp, ip)
4702 	struct inode *dp;
4703 	struct inode *ip;
4704 {
4705 	struct inodedep *inodedep;
4706 	struct jaddref *jaddref;
4707 	struct vnode *dvp;
4708 
4709 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4710 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4711 	dvp = ITOV(dp);
4712 	jaddref = NULL;
4713 	/*
4714 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4715 	 * is used as a normal link would be.
4716 	 */
4717 	if (DOINGSUJ(dvp))
4718 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4719 		    dp->i_effnlink - 1, dp->i_mode);
4720 	ACQUIRE_LOCK(ITOUMP(dp));
4721 	inodedep = inodedep_lookup_ip(dp);
4722 	if (jaddref)
4723 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4724 		    if_deps);
4725 	softdep_prelink(dvp, ITOV(ip));
4726 	FREE_LOCK(ITOUMP(dp));
4727 }
4728 
4729 /*
4730  * Create a jaddref structure to track a new link to an inode.  The directory
4731  * offset is not known until softdep_setup_directory_add or
4732  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4733  * softdep.
4734  */
4735 void
4736 softdep_setup_link(dp, ip)
4737 	struct inode *dp;
4738 	struct inode *ip;
4739 {
4740 	struct inodedep *inodedep;
4741 	struct jaddref *jaddref;
4742 	struct vnode *dvp;
4743 
4744 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4745 	    ("softdep_setup_link called on non-softdep filesystem"));
4746 	dvp = ITOV(dp);
4747 	jaddref = NULL;
4748 	if (DOINGSUJ(dvp))
4749 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4750 		    ip->i_mode);
4751 	ACQUIRE_LOCK(ITOUMP(dp));
4752 	inodedep = inodedep_lookup_ip(ip);
4753 	if (jaddref)
4754 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4755 		    if_deps);
4756 	softdep_prelink(dvp, ITOV(ip));
4757 	FREE_LOCK(ITOUMP(dp));
4758 }
4759 
4760 /*
4761  * Called to create the jaddref structures to track . and .. references as
4762  * well as lookup and further initialize the incomplete jaddref created
4763  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4764  * nlinkdelta for non-journaling softdep.
4765  */
4766 void
4767 softdep_setup_mkdir(dp, ip)
4768 	struct inode *dp;
4769 	struct inode *ip;
4770 {
4771 	struct inodedep *inodedep;
4772 	struct jaddref *dotdotaddref;
4773 	struct jaddref *dotaddref;
4774 	struct jaddref *jaddref;
4775 	struct vnode *dvp;
4776 
4777 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4778 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
4779 	dvp = ITOV(dp);
4780 	dotaddref = dotdotaddref = NULL;
4781 	if (DOINGSUJ(dvp)) {
4782 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4783 		    ip->i_mode);
4784 		dotaddref->ja_state |= MKDIR_BODY;
4785 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4786 		    dp->i_effnlink - 1, dp->i_mode);
4787 		dotdotaddref->ja_state |= MKDIR_PARENT;
4788 	}
4789 	ACQUIRE_LOCK(ITOUMP(dp));
4790 	inodedep = inodedep_lookup_ip(ip);
4791 	if (DOINGSUJ(dvp)) {
4792 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4793 		    inoreflst);
4794 		KASSERT(jaddref != NULL,
4795 		    ("softdep_setup_mkdir: No addref structure present."));
4796 		KASSERT(jaddref->ja_parent == dp->i_number,
4797 		    ("softdep_setup_mkdir: bad parent %ju",
4798 		    (uintmax_t)jaddref->ja_parent));
4799 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4800 		    if_deps);
4801 	}
4802 	inodedep = inodedep_lookup_ip(dp);
4803 	if (DOINGSUJ(dvp))
4804 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4805 		    &dotdotaddref->ja_ref, if_deps);
4806 	softdep_prelink(ITOV(dp), NULL);
4807 	FREE_LOCK(ITOUMP(dp));
4808 }
4809 
4810 /*
4811  * Called to track nlinkdelta of the inode and parent directories prior to
4812  * unlinking a directory.
4813  */
4814 void
4815 softdep_setup_rmdir(dp, ip)
4816 	struct inode *dp;
4817 	struct inode *ip;
4818 {
4819 	struct vnode *dvp;
4820 
4821 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4822 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4823 	dvp = ITOV(dp);
4824 	ACQUIRE_LOCK(ITOUMP(dp));
4825 	(void) inodedep_lookup_ip(ip);
4826 	(void) inodedep_lookup_ip(dp);
4827 	softdep_prelink(dvp, ITOV(ip));
4828 	FREE_LOCK(ITOUMP(dp));
4829 }
4830 
4831 /*
4832  * Called to track nlinkdelta of the inode and parent directories prior to
4833  * unlink.
4834  */
4835 void
4836 softdep_setup_unlink(dp, ip)
4837 	struct inode *dp;
4838 	struct inode *ip;
4839 {
4840 	struct vnode *dvp;
4841 
4842 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4843 	    ("softdep_setup_unlink called on non-softdep filesystem"));
4844 	dvp = ITOV(dp);
4845 	ACQUIRE_LOCK(ITOUMP(dp));
4846 	(void) inodedep_lookup_ip(ip);
4847 	(void) inodedep_lookup_ip(dp);
4848 	softdep_prelink(dvp, ITOV(ip));
4849 	FREE_LOCK(ITOUMP(dp));
4850 }
4851 
4852 /*
4853  * Called to release the journal structures created by a failed non-directory
4854  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4855  */
4856 void
4857 softdep_revert_create(dp, ip)
4858 	struct inode *dp;
4859 	struct inode *ip;
4860 {
4861 	struct inodedep *inodedep;
4862 	struct jaddref *jaddref;
4863 	struct vnode *dvp;
4864 
4865 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4866 	    ("softdep_revert_create called on non-softdep filesystem"));
4867 	dvp = ITOV(dp);
4868 	ACQUIRE_LOCK(ITOUMP(dp));
4869 	inodedep = inodedep_lookup_ip(ip);
4870 	if (DOINGSUJ(dvp)) {
4871 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4872 		    inoreflst);
4873 		KASSERT(jaddref->ja_parent == dp->i_number,
4874 		    ("softdep_revert_create: addref parent mismatch"));
4875 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4876 	}
4877 	FREE_LOCK(ITOUMP(dp));
4878 }
4879 
4880 /*
4881  * Called to release the journal structures created by a failed link
4882  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4883  */
4884 void
4885 softdep_revert_link(dp, ip)
4886 	struct inode *dp;
4887 	struct inode *ip;
4888 {
4889 	struct inodedep *inodedep;
4890 	struct jaddref *jaddref;
4891 	struct vnode *dvp;
4892 
4893 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4894 	    ("softdep_revert_link called on non-softdep filesystem"));
4895 	dvp = ITOV(dp);
4896 	ACQUIRE_LOCK(ITOUMP(dp));
4897 	inodedep = inodedep_lookup_ip(ip);
4898 	if (DOINGSUJ(dvp)) {
4899 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4900 		    inoreflst);
4901 		KASSERT(jaddref->ja_parent == dp->i_number,
4902 		    ("softdep_revert_link: addref parent mismatch"));
4903 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4904 	}
4905 	FREE_LOCK(ITOUMP(dp));
4906 }
4907 
4908 /*
4909  * Called to release the journal structures created by a failed mkdir
4910  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4911  */
4912 void
4913 softdep_revert_mkdir(dp, ip)
4914 	struct inode *dp;
4915 	struct inode *ip;
4916 {
4917 	struct inodedep *inodedep;
4918 	struct jaddref *jaddref;
4919 	struct jaddref *dotaddref;
4920 	struct vnode *dvp;
4921 
4922 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4923 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4924 	dvp = ITOV(dp);
4925 
4926 	ACQUIRE_LOCK(ITOUMP(dp));
4927 	inodedep = inodedep_lookup_ip(dp);
4928 	if (DOINGSUJ(dvp)) {
4929 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4930 		    inoreflst);
4931 		KASSERT(jaddref->ja_parent == ip->i_number,
4932 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4933 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4934 	}
4935 	inodedep = inodedep_lookup_ip(ip);
4936 	if (DOINGSUJ(dvp)) {
4937 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4938 		    inoreflst);
4939 		KASSERT(jaddref->ja_parent == dp->i_number,
4940 		    ("softdep_revert_mkdir: addref parent mismatch"));
4941 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4942 		    inoreflst, if_deps);
4943 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4944 		KASSERT(dotaddref->ja_parent == ip->i_number,
4945 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4946 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4947 	}
4948 	FREE_LOCK(ITOUMP(dp));
4949 }
4950 
4951 /*
4952  * Called to correct nlinkdelta after a failed rmdir.
4953  */
4954 void
4955 softdep_revert_rmdir(dp, ip)
4956 	struct inode *dp;
4957 	struct inode *ip;
4958 {
4959 
4960 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4961 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
4962 	ACQUIRE_LOCK(ITOUMP(dp));
4963 	(void) inodedep_lookup_ip(ip);
4964 	(void) inodedep_lookup_ip(dp);
4965 	FREE_LOCK(ITOUMP(dp));
4966 }
4967 
4968 /*
4969  * Protecting the freemaps (or bitmaps).
4970  *
4971  * To eliminate the need to execute fsck before mounting a filesystem
4972  * after a power failure, one must (conservatively) guarantee that the
4973  * on-disk copy of the bitmaps never indicate that a live inode or block is
4974  * free.  So, when a block or inode is allocated, the bitmap should be
4975  * updated (on disk) before any new pointers.  When a block or inode is
4976  * freed, the bitmap should not be updated until all pointers have been
4977  * reset.  The latter dependency is handled by the delayed de-allocation
4978  * approach described below for block and inode de-allocation.  The former
4979  * dependency is handled by calling the following procedure when a block or
4980  * inode is allocated. When an inode is allocated an "inodedep" is created
4981  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4982  * Each "inodedep" is also inserted into the hash indexing structure so
4983  * that any additional link additions can be made dependent on the inode
4984  * allocation.
4985  *
4986  * The ufs filesystem maintains a number of free block counts (e.g., per
4987  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4988  * in addition to the bitmaps.  These counts are used to improve efficiency
4989  * during allocation and therefore must be consistent with the bitmaps.
4990  * There is no convenient way to guarantee post-crash consistency of these
4991  * counts with simple update ordering, for two main reasons: (1) The counts
4992  * and bitmaps for a single cylinder group block are not in the same disk
4993  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4994  * be written and the other not.  (2) Some of the counts are located in the
4995  * superblock rather than the cylinder group block. So, we focus our soft
4996  * updates implementation on protecting the bitmaps. When mounting a
4997  * filesystem, we recompute the auxiliary counts from the bitmaps.
4998  */
4999 
5000 /*
5001  * Called just after updating the cylinder group block to allocate an inode.
5002  */
5003 void
5004 softdep_setup_inomapdep(bp, ip, newinum, mode)
5005 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5006 	struct inode *ip;	/* inode related to allocation */
5007 	ino_t newinum;		/* new inode number being allocated */
5008 	int mode;
5009 {
5010 	struct inodedep *inodedep;
5011 	struct bmsafemap *bmsafemap;
5012 	struct jaddref *jaddref;
5013 	struct mount *mp;
5014 	struct fs *fs;
5015 
5016 	mp = ITOVFS(ip);
5017 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5018 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5019 	fs = VFSTOUFS(mp)->um_fs;
5020 	jaddref = NULL;
5021 
5022 	/*
5023 	 * Allocate the journal reference add structure so that the bitmap
5024 	 * can be dependent on it.
5025 	 */
5026 	if (MOUNTEDSUJ(mp)) {
5027 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5028 		jaddref->ja_state |= NEWBLOCK;
5029 	}
5030 
5031 	/*
5032 	 * Create a dependency for the newly allocated inode.
5033 	 * Panic if it already exists as something is seriously wrong.
5034 	 * Otherwise add it to the dependency list for the buffer holding
5035 	 * the cylinder group map from which it was allocated.
5036 	 *
5037 	 * We have to preallocate a bmsafemap entry in case it is needed
5038 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5039 	 * have to finish initializing it before we can FREE_LOCK().
5040 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5041 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5042 	 * creating the inodedep as it can be freed during the time
5043 	 * that we FREE_LOCK() while allocating the inodedep. We must
5044 	 * call workitem_alloc() before entering the locked section as
5045 	 * it also acquires the lock and we must avoid trying doing so
5046 	 * recursively.
5047 	 */
5048 	bmsafemap = malloc(sizeof(struct bmsafemap),
5049 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5050 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5051 	ACQUIRE_LOCK(ITOUMP(ip));
5052 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5053 		panic("softdep_setup_inomapdep: dependency %p for new"
5054 		    "inode already exists", inodedep);
5055 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5056 	if (jaddref) {
5057 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5058 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5059 		    if_deps);
5060 	} else {
5061 		inodedep->id_state |= ONDEPLIST;
5062 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5063 	}
5064 	inodedep->id_bmsafemap = bmsafemap;
5065 	inodedep->id_state &= ~DEPCOMPLETE;
5066 	FREE_LOCK(ITOUMP(ip));
5067 }
5068 
5069 /*
5070  * Called just after updating the cylinder group block to
5071  * allocate block or fragment.
5072  */
5073 void
5074 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5075 	struct buf *bp;		/* buffer for cylgroup block with block map */
5076 	struct mount *mp;	/* filesystem doing allocation */
5077 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5078 	int frags;		/* Number of fragments. */
5079 	int oldfrags;		/* Previous number of fragments for extend. */
5080 {
5081 	struct newblk *newblk;
5082 	struct bmsafemap *bmsafemap;
5083 	struct jnewblk *jnewblk;
5084 	struct ufsmount *ump;
5085 	struct fs *fs;
5086 
5087 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5088 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5089 	ump = VFSTOUFS(mp);
5090 	fs = ump->um_fs;
5091 	jnewblk = NULL;
5092 	/*
5093 	 * Create a dependency for the newly allocated block.
5094 	 * Add it to the dependency list for the buffer holding
5095 	 * the cylinder group map from which it was allocated.
5096 	 */
5097 	if (MOUNTEDSUJ(mp)) {
5098 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5099 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5100 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5101 		jnewblk->jn_state = ATTACHED;
5102 		jnewblk->jn_blkno = newblkno;
5103 		jnewblk->jn_frags = frags;
5104 		jnewblk->jn_oldfrags = oldfrags;
5105 #ifdef SUJ_DEBUG
5106 		{
5107 			struct cg *cgp;
5108 			uint8_t *blksfree;
5109 			long bno;
5110 			int i;
5111 
5112 			cgp = (struct cg *)bp->b_data;
5113 			blksfree = cg_blksfree(cgp);
5114 			bno = dtogd(fs, jnewblk->jn_blkno);
5115 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5116 			    i++) {
5117 				if (isset(blksfree, bno + i))
5118 					panic("softdep_setup_blkmapdep: "
5119 					    "free fragment %d from %d-%d "
5120 					    "state 0x%X dep %p", i,
5121 					    jnewblk->jn_oldfrags,
5122 					    jnewblk->jn_frags,
5123 					    jnewblk->jn_state,
5124 					    jnewblk->jn_dep);
5125 			}
5126 		}
5127 #endif
5128 	}
5129 
5130 	CTR3(KTR_SUJ,
5131 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5132 	    newblkno, frags, oldfrags);
5133 	ACQUIRE_LOCK(ump);
5134 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5135 		panic("softdep_setup_blkmapdep: found block");
5136 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5137 	    dtog(fs, newblkno), NULL);
5138 	if (jnewblk) {
5139 		jnewblk->jn_dep = (struct worklist *)newblk;
5140 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5141 	} else {
5142 		newblk->nb_state |= ONDEPLIST;
5143 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5144 	}
5145 	newblk->nb_bmsafemap = bmsafemap;
5146 	newblk->nb_jnewblk = jnewblk;
5147 	FREE_LOCK(ump);
5148 }
5149 
5150 #define	BMSAFEMAP_HASH(ump, cg) \
5151       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5152 
5153 static int
5154 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5155 	struct bmsafemap_hashhead *bmsafemaphd;
5156 	int cg;
5157 	struct bmsafemap **bmsafemapp;
5158 {
5159 	struct bmsafemap *bmsafemap;
5160 
5161 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5162 		if (bmsafemap->sm_cg == cg)
5163 			break;
5164 	if (bmsafemap) {
5165 		*bmsafemapp = bmsafemap;
5166 		return (1);
5167 	}
5168 	*bmsafemapp = NULL;
5169 
5170 	return (0);
5171 }
5172 
5173 /*
5174  * Find the bmsafemap associated with a cylinder group buffer.
5175  * If none exists, create one. The buffer must be locked when
5176  * this routine is called and this routine must be called with
5177  * the softdep lock held. To avoid giving up the lock while
5178  * allocating a new bmsafemap, a preallocated bmsafemap may be
5179  * provided. If it is provided but not needed, it is freed.
5180  */
5181 static struct bmsafemap *
5182 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5183 	struct mount *mp;
5184 	struct buf *bp;
5185 	int cg;
5186 	struct bmsafemap *newbmsafemap;
5187 {
5188 	struct bmsafemap_hashhead *bmsafemaphd;
5189 	struct bmsafemap *bmsafemap, *collision;
5190 	struct worklist *wk;
5191 	struct ufsmount *ump;
5192 
5193 	ump = VFSTOUFS(mp);
5194 	LOCK_OWNED(ump);
5195 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5196 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5197 		if (wk->wk_type == D_BMSAFEMAP) {
5198 			if (newbmsafemap)
5199 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5200 			return (WK_BMSAFEMAP(wk));
5201 		}
5202 	}
5203 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5204 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5205 		if (newbmsafemap)
5206 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5207 		return (bmsafemap);
5208 	}
5209 	if (newbmsafemap) {
5210 		bmsafemap = newbmsafemap;
5211 	} else {
5212 		FREE_LOCK(ump);
5213 		bmsafemap = malloc(sizeof(struct bmsafemap),
5214 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5215 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5216 		ACQUIRE_LOCK(ump);
5217 	}
5218 	bmsafemap->sm_buf = bp;
5219 	LIST_INIT(&bmsafemap->sm_inodedephd);
5220 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5221 	LIST_INIT(&bmsafemap->sm_newblkhd);
5222 	LIST_INIT(&bmsafemap->sm_newblkwr);
5223 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5224 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5225 	LIST_INIT(&bmsafemap->sm_freehd);
5226 	LIST_INIT(&bmsafemap->sm_freewr);
5227 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5228 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5229 		return (collision);
5230 	}
5231 	bmsafemap->sm_cg = cg;
5232 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5233 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5234 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5235 	return (bmsafemap);
5236 }
5237 
5238 /*
5239  * Direct block allocation dependencies.
5240  *
5241  * When a new block is allocated, the corresponding disk locations must be
5242  * initialized (with zeros or new data) before the on-disk inode points to
5243  * them.  Also, the freemap from which the block was allocated must be
5244  * updated (on disk) before the inode's pointer. These two dependencies are
5245  * independent of each other and are needed for all file blocks and indirect
5246  * blocks that are pointed to directly by the inode.  Just before the
5247  * "in-core" version of the inode is updated with a newly allocated block
5248  * number, a procedure (below) is called to setup allocation dependency
5249  * structures.  These structures are removed when the corresponding
5250  * dependencies are satisfied or when the block allocation becomes obsolete
5251  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5252  * fragment that gets upgraded).  All of these cases are handled in
5253  * procedures described later.
5254  *
5255  * When a file extension causes a fragment to be upgraded, either to a larger
5256  * fragment or to a full block, the on-disk location may change (if the
5257  * previous fragment could not simply be extended). In this case, the old
5258  * fragment must be de-allocated, but not until after the inode's pointer has
5259  * been updated. In most cases, this is handled by later procedures, which
5260  * will construct a "freefrag" structure to be added to the workitem queue
5261  * when the inode update is complete (or obsolete).  The main exception to
5262  * this is when an allocation occurs while a pending allocation dependency
5263  * (for the same block pointer) remains.  This case is handled in the main
5264  * allocation dependency setup procedure by immediately freeing the
5265  * unreferenced fragments.
5266  */
5267 void
5268 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5269 	struct inode *ip;	/* inode to which block is being added */
5270 	ufs_lbn_t off;		/* block pointer within inode */
5271 	ufs2_daddr_t newblkno;	/* disk block number being added */
5272 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5273 	long newsize;		/* size of new block */
5274 	long oldsize;		/* size of new block */
5275 	struct buf *bp;		/* bp for allocated block */
5276 {
5277 	struct allocdirect *adp, *oldadp;
5278 	struct allocdirectlst *adphead;
5279 	struct freefrag *freefrag;
5280 	struct inodedep *inodedep;
5281 	struct pagedep *pagedep;
5282 	struct jnewblk *jnewblk;
5283 	struct newblk *newblk;
5284 	struct mount *mp;
5285 	ufs_lbn_t lbn;
5286 
5287 	lbn = bp->b_lblkno;
5288 	mp = ITOVFS(ip);
5289 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5290 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5291 	if (oldblkno && oldblkno != newblkno)
5292 		/*
5293 		 * The usual case is that a smaller fragment that
5294 		 * was just allocated has been replaced with a bigger
5295 		 * fragment or a full-size block. If it is marked as
5296 		 * B_DELWRI, the current contents have not been written
5297 		 * to disk. It is possible that the block was written
5298 		 * earlier, but very uncommon. If the block has never
5299 		 * been written, there is no need to send a BIO_DELETE
5300 		 * for it when it is freed. The gain from avoiding the
5301 		 * TRIMs for the common case of unwritten blocks far
5302 		 * exceeds the cost of the write amplification for the
5303 		 * uncommon case of failing to send a TRIM for a block
5304 		 * that had been written.
5305 		 */
5306 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5307 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5308 	else
5309 		freefrag = NULL;
5310 
5311 	CTR6(KTR_SUJ,
5312 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5313 	    "off %jd newsize %ld oldsize %d",
5314 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5315 	ACQUIRE_LOCK(ITOUMP(ip));
5316 	if (off >= UFS_NDADDR) {
5317 		if (lbn > 0)
5318 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5319 			    lbn, off);
5320 		/* allocating an indirect block */
5321 		if (oldblkno != 0)
5322 			panic("softdep_setup_allocdirect: non-zero indir");
5323 	} else {
5324 		if (off != lbn)
5325 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5326 			    lbn, off);
5327 		/*
5328 		 * Allocating a direct block.
5329 		 *
5330 		 * If we are allocating a directory block, then we must
5331 		 * allocate an associated pagedep to track additions and
5332 		 * deletions.
5333 		 */
5334 		if ((ip->i_mode & IFMT) == IFDIR)
5335 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5336 			    &pagedep);
5337 	}
5338 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5339 		panic("softdep_setup_allocdirect: lost block");
5340 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5341 	    ("softdep_setup_allocdirect: newblk already initialized"));
5342 	/*
5343 	 * Convert the newblk to an allocdirect.
5344 	 */
5345 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5346 	adp = (struct allocdirect *)newblk;
5347 	newblk->nb_freefrag = freefrag;
5348 	adp->ad_offset = off;
5349 	adp->ad_oldblkno = oldblkno;
5350 	adp->ad_newsize = newsize;
5351 	adp->ad_oldsize = oldsize;
5352 
5353 	/*
5354 	 * Finish initializing the journal.
5355 	 */
5356 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5357 		jnewblk->jn_ino = ip->i_number;
5358 		jnewblk->jn_lbn = lbn;
5359 		add_to_journal(&jnewblk->jn_list);
5360 	}
5361 	if (freefrag && freefrag->ff_jdep != NULL &&
5362 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5363 		add_to_journal(freefrag->ff_jdep);
5364 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5365 	adp->ad_inodedep = inodedep;
5366 
5367 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5368 	/*
5369 	 * The list of allocdirects must be kept in sorted and ascending
5370 	 * order so that the rollback routines can quickly determine the
5371 	 * first uncommitted block (the size of the file stored on disk
5372 	 * ends at the end of the lowest committed fragment, or if there
5373 	 * are no fragments, at the end of the highest committed block).
5374 	 * Since files generally grow, the typical case is that the new
5375 	 * block is to be added at the end of the list. We speed this
5376 	 * special case by checking against the last allocdirect in the
5377 	 * list before laboriously traversing the list looking for the
5378 	 * insertion point.
5379 	 */
5380 	adphead = &inodedep->id_newinoupdt;
5381 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5382 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5383 		/* insert at end of list */
5384 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5385 		if (oldadp != NULL && oldadp->ad_offset == off)
5386 			allocdirect_merge(adphead, adp, oldadp);
5387 		FREE_LOCK(ITOUMP(ip));
5388 		return;
5389 	}
5390 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5391 		if (oldadp->ad_offset >= off)
5392 			break;
5393 	}
5394 	if (oldadp == NULL)
5395 		panic("softdep_setup_allocdirect: lost entry");
5396 	/* insert in middle of list */
5397 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5398 	if (oldadp->ad_offset == off)
5399 		allocdirect_merge(adphead, adp, oldadp);
5400 
5401 	FREE_LOCK(ITOUMP(ip));
5402 }
5403 
5404 /*
5405  * Merge a newer and older journal record to be stored either in a
5406  * newblock or freefrag.  This handles aggregating journal records for
5407  * fragment allocation into a second record as well as replacing a
5408  * journal free with an aborted journal allocation.  A segment for the
5409  * oldest record will be placed on wkhd if it has been written.  If not
5410  * the segment for the newer record will suffice.
5411  */
5412 static struct worklist *
5413 jnewblk_merge(new, old, wkhd)
5414 	struct worklist *new;
5415 	struct worklist *old;
5416 	struct workhead *wkhd;
5417 {
5418 	struct jnewblk *njnewblk;
5419 	struct jnewblk *jnewblk;
5420 
5421 	/* Handle NULLs to simplify callers. */
5422 	if (new == NULL)
5423 		return (old);
5424 	if (old == NULL)
5425 		return (new);
5426 	/* Replace a jfreefrag with a jnewblk. */
5427 	if (new->wk_type == D_JFREEFRAG) {
5428 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5429 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5430 			    old, new);
5431 		cancel_jfreefrag(WK_JFREEFRAG(new));
5432 		return (old);
5433 	}
5434 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5435 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5436 		    old->wk_type, new->wk_type);
5437 	/*
5438 	 * Handle merging of two jnewblk records that describe
5439 	 * different sets of fragments in the same block.
5440 	 */
5441 	jnewblk = WK_JNEWBLK(old);
5442 	njnewblk = WK_JNEWBLK(new);
5443 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5444 		panic("jnewblk_merge: Merging disparate blocks.");
5445 	/*
5446 	 * The record may be rolled back in the cg.
5447 	 */
5448 	if (jnewblk->jn_state & UNDONE) {
5449 		jnewblk->jn_state &= ~UNDONE;
5450 		njnewblk->jn_state |= UNDONE;
5451 		njnewblk->jn_state &= ~ATTACHED;
5452 	}
5453 	/*
5454 	 * We modify the newer addref and free the older so that if neither
5455 	 * has been written the most up-to-date copy will be on disk.  If
5456 	 * both have been written but rolled back we only temporarily need
5457 	 * one of them to fix the bits when the cg write completes.
5458 	 */
5459 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5460 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5461 	cancel_jnewblk(jnewblk, wkhd);
5462 	WORKLIST_REMOVE(&jnewblk->jn_list);
5463 	free_jnewblk(jnewblk);
5464 	return (new);
5465 }
5466 
5467 /*
5468  * Replace an old allocdirect dependency with a newer one.
5469  * This routine must be called with splbio interrupts blocked.
5470  */
5471 static void
5472 allocdirect_merge(adphead, newadp, oldadp)
5473 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5474 	struct allocdirect *newadp;	/* allocdirect being added */
5475 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5476 {
5477 	struct worklist *wk;
5478 	struct freefrag *freefrag;
5479 
5480 	freefrag = NULL;
5481 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5482 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5483 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5484 	    newadp->ad_offset >= UFS_NDADDR)
5485 		panic("%s %jd != new %jd || old size %ld != new %ld",
5486 		    "allocdirect_merge: old blkno",
5487 		    (intmax_t)newadp->ad_oldblkno,
5488 		    (intmax_t)oldadp->ad_newblkno,
5489 		    newadp->ad_oldsize, oldadp->ad_newsize);
5490 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5491 	newadp->ad_oldsize = oldadp->ad_oldsize;
5492 	/*
5493 	 * If the old dependency had a fragment to free or had never
5494 	 * previously had a block allocated, then the new dependency
5495 	 * can immediately post its freefrag and adopt the old freefrag.
5496 	 * This action is done by swapping the freefrag dependencies.
5497 	 * The new dependency gains the old one's freefrag, and the
5498 	 * old one gets the new one and then immediately puts it on
5499 	 * the worklist when it is freed by free_newblk. It is
5500 	 * not possible to do this swap when the old dependency had a
5501 	 * non-zero size but no previous fragment to free. This condition
5502 	 * arises when the new block is an extension of the old block.
5503 	 * Here, the first part of the fragment allocated to the new
5504 	 * dependency is part of the block currently claimed on disk by
5505 	 * the old dependency, so cannot legitimately be freed until the
5506 	 * conditions for the new dependency are fulfilled.
5507 	 */
5508 	freefrag = newadp->ad_freefrag;
5509 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5510 		newadp->ad_freefrag = oldadp->ad_freefrag;
5511 		oldadp->ad_freefrag = freefrag;
5512 	}
5513 	/*
5514 	 * If we are tracking a new directory-block allocation,
5515 	 * move it from the old allocdirect to the new allocdirect.
5516 	 */
5517 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5518 		WORKLIST_REMOVE(wk);
5519 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5520 			panic("allocdirect_merge: extra newdirblk");
5521 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5522 	}
5523 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5524 	/*
5525 	 * We need to move any journal dependencies over to the freefrag
5526 	 * that releases this block if it exists.  Otherwise we are
5527 	 * extending an existing block and we'll wait until that is
5528 	 * complete to release the journal space and extend the
5529 	 * new journal to cover this old space as well.
5530 	 */
5531 	if (freefrag == NULL) {
5532 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5533 			panic("allocdirect_merge: %jd != %jd",
5534 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5535 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5536 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5537 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5538 		    &newadp->ad_block.nb_jwork);
5539 		oldadp->ad_block.nb_jnewblk = NULL;
5540 		cancel_newblk(&oldadp->ad_block, NULL,
5541 		    &newadp->ad_block.nb_jwork);
5542 	} else {
5543 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5544 		    &freefrag->ff_list, &freefrag->ff_jwork);
5545 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5546 		    &freefrag->ff_jwork);
5547 	}
5548 	free_newblk(&oldadp->ad_block);
5549 }
5550 
5551 /*
5552  * Allocate a jfreefrag structure to journal a single block free.
5553  */
5554 static struct jfreefrag *
5555 newjfreefrag(freefrag, ip, blkno, size, lbn)
5556 	struct freefrag *freefrag;
5557 	struct inode *ip;
5558 	ufs2_daddr_t blkno;
5559 	long size;
5560 	ufs_lbn_t lbn;
5561 {
5562 	struct jfreefrag *jfreefrag;
5563 	struct fs *fs;
5564 
5565 	fs = ITOFS(ip);
5566 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5567 	    M_SOFTDEP_FLAGS);
5568 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5569 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5570 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5571 	jfreefrag->fr_ino = ip->i_number;
5572 	jfreefrag->fr_lbn = lbn;
5573 	jfreefrag->fr_blkno = blkno;
5574 	jfreefrag->fr_frags = numfrags(fs, size);
5575 	jfreefrag->fr_freefrag = freefrag;
5576 
5577 	return (jfreefrag);
5578 }
5579 
5580 /*
5581  * Allocate a new freefrag structure.
5582  */
5583 static struct freefrag *
5584 newfreefrag(ip, blkno, size, lbn, key)
5585 	struct inode *ip;
5586 	ufs2_daddr_t blkno;
5587 	long size;
5588 	ufs_lbn_t lbn;
5589 	u_long key;
5590 {
5591 	struct freefrag *freefrag;
5592 	struct ufsmount *ump;
5593 	struct fs *fs;
5594 
5595 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5596 	    ip->i_number, blkno, size, lbn);
5597 	ump = ITOUMP(ip);
5598 	fs = ump->um_fs;
5599 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5600 		panic("newfreefrag: frag size");
5601 	freefrag = malloc(sizeof(struct freefrag),
5602 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5603 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5604 	freefrag->ff_state = ATTACHED;
5605 	LIST_INIT(&freefrag->ff_jwork);
5606 	freefrag->ff_inum = ip->i_number;
5607 	freefrag->ff_vtype = ITOV(ip)->v_type;
5608 	freefrag->ff_blkno = blkno;
5609 	freefrag->ff_fragsize = size;
5610 	freefrag->ff_key = key;
5611 
5612 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5613 		freefrag->ff_jdep = (struct worklist *)
5614 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5615 	} else {
5616 		freefrag->ff_state |= DEPCOMPLETE;
5617 		freefrag->ff_jdep = NULL;
5618 	}
5619 
5620 	return (freefrag);
5621 }
5622 
5623 /*
5624  * This workitem de-allocates fragments that were replaced during
5625  * file block allocation.
5626  */
5627 static void
5628 handle_workitem_freefrag(freefrag)
5629 	struct freefrag *freefrag;
5630 {
5631 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5632 	struct workhead wkhd;
5633 
5634 	CTR3(KTR_SUJ,
5635 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5636 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5637 	/*
5638 	 * It would be illegal to add new completion items to the
5639 	 * freefrag after it was schedule to be done so it must be
5640 	 * safe to modify the list head here.
5641 	 */
5642 	LIST_INIT(&wkhd);
5643 	ACQUIRE_LOCK(ump);
5644 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5645 	/*
5646 	 * If the journal has not been written we must cancel it here.
5647 	 */
5648 	if (freefrag->ff_jdep) {
5649 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5650 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5651 			    freefrag->ff_jdep->wk_type);
5652 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5653 	}
5654 	FREE_LOCK(ump);
5655 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5656 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5657 	   &wkhd, freefrag->ff_key);
5658 	ACQUIRE_LOCK(ump);
5659 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5660 	FREE_LOCK(ump);
5661 }
5662 
5663 /*
5664  * Set up a dependency structure for an external attributes data block.
5665  * This routine follows much of the structure of softdep_setup_allocdirect.
5666  * See the description of softdep_setup_allocdirect above for details.
5667  */
5668 void
5669 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5670 	struct inode *ip;
5671 	ufs_lbn_t off;
5672 	ufs2_daddr_t newblkno;
5673 	ufs2_daddr_t oldblkno;
5674 	long newsize;
5675 	long oldsize;
5676 	struct buf *bp;
5677 {
5678 	struct allocdirect *adp, *oldadp;
5679 	struct allocdirectlst *adphead;
5680 	struct freefrag *freefrag;
5681 	struct inodedep *inodedep;
5682 	struct jnewblk *jnewblk;
5683 	struct newblk *newblk;
5684 	struct mount *mp;
5685 	struct ufsmount *ump;
5686 	ufs_lbn_t lbn;
5687 
5688 	mp = ITOVFS(ip);
5689 	ump = VFSTOUFS(mp);
5690 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5691 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5692 	KASSERT(off < UFS_NXADDR,
5693 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5694 
5695 	lbn = bp->b_lblkno;
5696 	if (oldblkno && oldblkno != newblkno)
5697 		/*
5698 		 * The usual case is that a smaller fragment that
5699 		 * was just allocated has been replaced with a bigger
5700 		 * fragment or a full-size block. If it is marked as
5701 		 * B_DELWRI, the current contents have not been written
5702 		 * to disk. It is possible that the block was written
5703 		 * earlier, but very uncommon. If the block has never
5704 		 * been written, there is no need to send a BIO_DELETE
5705 		 * for it when it is freed. The gain from avoiding the
5706 		 * TRIMs for the common case of unwritten blocks far
5707 		 * exceeds the cost of the write amplification for the
5708 		 * uncommon case of failing to send a TRIM for a block
5709 		 * that had been written.
5710 		 */
5711 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5712 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5713 	else
5714 		freefrag = NULL;
5715 
5716 	ACQUIRE_LOCK(ump);
5717 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5718 		panic("softdep_setup_allocext: lost block");
5719 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5720 	    ("softdep_setup_allocext: newblk already initialized"));
5721 	/*
5722 	 * Convert the newblk to an allocdirect.
5723 	 */
5724 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5725 	adp = (struct allocdirect *)newblk;
5726 	newblk->nb_freefrag = freefrag;
5727 	adp->ad_offset = off;
5728 	adp->ad_oldblkno = oldblkno;
5729 	adp->ad_newsize = newsize;
5730 	adp->ad_oldsize = oldsize;
5731 	adp->ad_state |=  EXTDATA;
5732 
5733 	/*
5734 	 * Finish initializing the journal.
5735 	 */
5736 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5737 		jnewblk->jn_ino = ip->i_number;
5738 		jnewblk->jn_lbn = lbn;
5739 		add_to_journal(&jnewblk->jn_list);
5740 	}
5741 	if (freefrag && freefrag->ff_jdep != NULL &&
5742 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5743 		add_to_journal(freefrag->ff_jdep);
5744 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5745 	adp->ad_inodedep = inodedep;
5746 
5747 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5748 	/*
5749 	 * The list of allocdirects must be kept in sorted and ascending
5750 	 * order so that the rollback routines can quickly determine the
5751 	 * first uncommitted block (the size of the file stored on disk
5752 	 * ends at the end of the lowest committed fragment, or if there
5753 	 * are no fragments, at the end of the highest committed block).
5754 	 * Since files generally grow, the typical case is that the new
5755 	 * block is to be added at the end of the list. We speed this
5756 	 * special case by checking against the last allocdirect in the
5757 	 * list before laboriously traversing the list looking for the
5758 	 * insertion point.
5759 	 */
5760 	adphead = &inodedep->id_newextupdt;
5761 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5762 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5763 		/* insert at end of list */
5764 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5765 		if (oldadp != NULL && oldadp->ad_offset == off)
5766 			allocdirect_merge(adphead, adp, oldadp);
5767 		FREE_LOCK(ump);
5768 		return;
5769 	}
5770 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5771 		if (oldadp->ad_offset >= off)
5772 			break;
5773 	}
5774 	if (oldadp == NULL)
5775 		panic("softdep_setup_allocext: lost entry");
5776 	/* insert in middle of list */
5777 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5778 	if (oldadp->ad_offset == off)
5779 		allocdirect_merge(adphead, adp, oldadp);
5780 	FREE_LOCK(ump);
5781 }
5782 
5783 /*
5784  * Indirect block allocation dependencies.
5785  *
5786  * The same dependencies that exist for a direct block also exist when
5787  * a new block is allocated and pointed to by an entry in a block of
5788  * indirect pointers. The undo/redo states described above are also
5789  * used here. Because an indirect block contains many pointers that
5790  * may have dependencies, a second copy of the entire in-memory indirect
5791  * block is kept. The buffer cache copy is always completely up-to-date.
5792  * The second copy, which is used only as a source for disk writes,
5793  * contains only the safe pointers (i.e., those that have no remaining
5794  * update dependencies). The second copy is freed when all pointers
5795  * are safe. The cache is not allowed to replace indirect blocks with
5796  * pending update dependencies. If a buffer containing an indirect
5797  * block with dependencies is written, these routines will mark it
5798  * dirty again. It can only be successfully written once all the
5799  * dependencies are removed. The ffs_fsync routine in conjunction with
5800  * softdep_sync_metadata work together to get all the dependencies
5801  * removed so that a file can be successfully written to disk. Three
5802  * procedures are used when setting up indirect block pointer
5803  * dependencies. The division is necessary because of the organization
5804  * of the "balloc" routine and because of the distinction between file
5805  * pages and file metadata blocks.
5806  */
5807 
5808 /*
5809  * Allocate a new allocindir structure.
5810  */
5811 static struct allocindir *
5812 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5813 	struct inode *ip;	/* inode for file being extended */
5814 	int ptrno;		/* offset of pointer in indirect block */
5815 	ufs2_daddr_t newblkno;	/* disk block number being added */
5816 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5817 	ufs_lbn_t lbn;
5818 {
5819 	struct newblk *newblk;
5820 	struct allocindir *aip;
5821 	struct freefrag *freefrag;
5822 	struct jnewblk *jnewblk;
5823 
5824 	if (oldblkno)
5825 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
5826 		    SINGLETON_KEY);
5827 	else
5828 		freefrag = NULL;
5829 	ACQUIRE_LOCK(ITOUMP(ip));
5830 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5831 		panic("new_allocindir: lost block");
5832 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5833 	    ("newallocindir: newblk already initialized"));
5834 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5835 	newblk->nb_freefrag = freefrag;
5836 	aip = (struct allocindir *)newblk;
5837 	aip->ai_offset = ptrno;
5838 	aip->ai_oldblkno = oldblkno;
5839 	aip->ai_lbn = lbn;
5840 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5841 		jnewblk->jn_ino = ip->i_number;
5842 		jnewblk->jn_lbn = lbn;
5843 		add_to_journal(&jnewblk->jn_list);
5844 	}
5845 	if (freefrag && freefrag->ff_jdep != NULL &&
5846 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5847 		add_to_journal(freefrag->ff_jdep);
5848 	return (aip);
5849 }
5850 
5851 /*
5852  * Called just before setting an indirect block pointer
5853  * to a newly allocated file page.
5854  */
5855 void
5856 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5857 	struct inode *ip;	/* inode for file being extended */
5858 	ufs_lbn_t lbn;		/* allocated block number within file */
5859 	struct buf *bp;		/* buffer with indirect blk referencing page */
5860 	int ptrno;		/* offset of pointer in indirect block */
5861 	ufs2_daddr_t newblkno;	/* disk block number being added */
5862 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5863 	struct buf *nbp;	/* buffer holding allocated page */
5864 {
5865 	struct inodedep *inodedep;
5866 	struct freefrag *freefrag;
5867 	struct allocindir *aip;
5868 	struct pagedep *pagedep;
5869 	struct mount *mp;
5870 	struct ufsmount *ump;
5871 
5872 	mp = ITOVFS(ip);
5873 	ump = VFSTOUFS(mp);
5874 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5875 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5876 	KASSERT(lbn == nbp->b_lblkno,
5877 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5878 	    lbn, bp->b_lblkno));
5879 	CTR4(KTR_SUJ,
5880 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5881 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5882 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5883 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5884 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5885 	/*
5886 	 * If we are allocating a directory page, then we must
5887 	 * allocate an associated pagedep to track additions and
5888 	 * deletions.
5889 	 */
5890 	if ((ip->i_mode & IFMT) == IFDIR)
5891 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5892 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5893 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5894 	FREE_LOCK(ump);
5895 	if (freefrag)
5896 		handle_workitem_freefrag(freefrag);
5897 }
5898 
5899 /*
5900  * Called just before setting an indirect block pointer to a
5901  * newly allocated indirect block.
5902  */
5903 void
5904 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5905 	struct buf *nbp;	/* newly allocated indirect block */
5906 	struct inode *ip;	/* inode for file being extended */
5907 	struct buf *bp;		/* indirect block referencing allocated block */
5908 	int ptrno;		/* offset of pointer in indirect block */
5909 	ufs2_daddr_t newblkno;	/* disk block number being added */
5910 {
5911 	struct inodedep *inodedep;
5912 	struct allocindir *aip;
5913 	struct ufsmount *ump;
5914 	ufs_lbn_t lbn;
5915 
5916 	ump = ITOUMP(ip);
5917 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5918 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5919 	CTR3(KTR_SUJ,
5920 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5921 	    ip->i_number, newblkno, ptrno);
5922 	lbn = nbp->b_lblkno;
5923 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5924 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5925 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5926 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5927 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5928 		panic("softdep_setup_allocindir_meta: Block already existed");
5929 	FREE_LOCK(ump);
5930 }
5931 
5932 static void
5933 indirdep_complete(indirdep)
5934 	struct indirdep *indirdep;
5935 {
5936 	struct allocindir *aip;
5937 
5938 	LIST_REMOVE(indirdep, ir_next);
5939 	indirdep->ir_state |= DEPCOMPLETE;
5940 
5941 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5942 		LIST_REMOVE(aip, ai_next);
5943 		free_newblk(&aip->ai_block);
5944 	}
5945 	/*
5946 	 * If this indirdep is not attached to a buf it was simply waiting
5947 	 * on completion to clear completehd.  free_indirdep() asserts
5948 	 * that nothing is dangling.
5949 	 */
5950 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5951 		free_indirdep(indirdep);
5952 }
5953 
5954 static struct indirdep *
5955 indirdep_lookup(mp, ip, bp)
5956 	struct mount *mp;
5957 	struct inode *ip;
5958 	struct buf *bp;
5959 {
5960 	struct indirdep *indirdep, *newindirdep;
5961 	struct newblk *newblk;
5962 	struct ufsmount *ump;
5963 	struct worklist *wk;
5964 	struct fs *fs;
5965 	ufs2_daddr_t blkno;
5966 
5967 	ump = VFSTOUFS(mp);
5968 	LOCK_OWNED(ump);
5969 	indirdep = NULL;
5970 	newindirdep = NULL;
5971 	fs = ump->um_fs;
5972 	for (;;) {
5973 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5974 			if (wk->wk_type != D_INDIRDEP)
5975 				continue;
5976 			indirdep = WK_INDIRDEP(wk);
5977 			break;
5978 		}
5979 		/* Found on the buffer worklist, no new structure to free. */
5980 		if (indirdep != NULL && newindirdep == NULL)
5981 			return (indirdep);
5982 		if (indirdep != NULL && newindirdep != NULL)
5983 			panic("indirdep_lookup: simultaneous create");
5984 		/* None found on the buffer and a new structure is ready. */
5985 		if (indirdep == NULL && newindirdep != NULL)
5986 			break;
5987 		/* None found and no new structure available. */
5988 		FREE_LOCK(ump);
5989 		newindirdep = malloc(sizeof(struct indirdep),
5990 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
5991 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5992 		newindirdep->ir_state = ATTACHED;
5993 		if (I_IS_UFS1(ip))
5994 			newindirdep->ir_state |= UFS1FMT;
5995 		TAILQ_INIT(&newindirdep->ir_trunc);
5996 		newindirdep->ir_saveddata = NULL;
5997 		LIST_INIT(&newindirdep->ir_deplisthd);
5998 		LIST_INIT(&newindirdep->ir_donehd);
5999 		LIST_INIT(&newindirdep->ir_writehd);
6000 		LIST_INIT(&newindirdep->ir_completehd);
6001 		if (bp->b_blkno == bp->b_lblkno) {
6002 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6003 			    NULL, NULL);
6004 			bp->b_blkno = blkno;
6005 		}
6006 		newindirdep->ir_freeblks = NULL;
6007 		newindirdep->ir_savebp =
6008 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6009 		newindirdep->ir_bp = bp;
6010 		BUF_KERNPROC(newindirdep->ir_savebp);
6011 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6012 		ACQUIRE_LOCK(ump);
6013 	}
6014 	indirdep = newindirdep;
6015 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6016 	/*
6017 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6018 	 * that we don't free dependencies until the pointers are valid.
6019 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6020 	 * than using the hash.
6021 	 */
6022 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6023 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6024 	else
6025 		indirdep->ir_state |= DEPCOMPLETE;
6026 	return (indirdep);
6027 }
6028 
6029 /*
6030  * Called to finish the allocation of the "aip" allocated
6031  * by one of the two routines above.
6032  */
6033 static struct freefrag *
6034 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6035 	struct buf *bp;		/* in-memory copy of the indirect block */
6036 	struct inode *ip;	/* inode for file being extended */
6037 	struct inodedep *inodedep; /* Inodedep for ip */
6038 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6039 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6040 {
6041 	struct fs *fs;
6042 	struct indirdep *indirdep;
6043 	struct allocindir *oldaip;
6044 	struct freefrag *freefrag;
6045 	struct mount *mp;
6046 	struct ufsmount *ump;
6047 
6048 	mp = ITOVFS(ip);
6049 	ump = VFSTOUFS(mp);
6050 	LOCK_OWNED(ump);
6051 	fs = ump->um_fs;
6052 	if (bp->b_lblkno >= 0)
6053 		panic("setup_allocindir_phase2: not indir blk");
6054 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6055 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6056 	indirdep = indirdep_lookup(mp, ip, bp);
6057 	KASSERT(indirdep->ir_savebp != NULL,
6058 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6059 	aip->ai_indirdep = indirdep;
6060 	/*
6061 	 * Check for an unwritten dependency for this indirect offset.  If
6062 	 * there is, merge the old dependency into the new one.  This happens
6063 	 * as a result of reallocblk only.
6064 	 */
6065 	freefrag = NULL;
6066 	if (aip->ai_oldblkno != 0) {
6067 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6068 			if (oldaip->ai_offset == aip->ai_offset) {
6069 				freefrag = allocindir_merge(aip, oldaip);
6070 				goto done;
6071 			}
6072 		}
6073 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6074 			if (oldaip->ai_offset == aip->ai_offset) {
6075 				freefrag = allocindir_merge(aip, oldaip);
6076 				goto done;
6077 			}
6078 		}
6079 	}
6080 done:
6081 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6082 	return (freefrag);
6083 }
6084 
6085 /*
6086  * Merge two allocindirs which refer to the same block.  Move newblock
6087  * dependencies and setup the freefrags appropriately.
6088  */
6089 static struct freefrag *
6090 allocindir_merge(aip, oldaip)
6091 	struct allocindir *aip;
6092 	struct allocindir *oldaip;
6093 {
6094 	struct freefrag *freefrag;
6095 	struct worklist *wk;
6096 
6097 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6098 		panic("allocindir_merge: blkno");
6099 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6100 	freefrag = aip->ai_freefrag;
6101 	aip->ai_freefrag = oldaip->ai_freefrag;
6102 	oldaip->ai_freefrag = NULL;
6103 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6104 	/*
6105 	 * If we are tracking a new directory-block allocation,
6106 	 * move it from the old allocindir to the new allocindir.
6107 	 */
6108 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6109 		WORKLIST_REMOVE(wk);
6110 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6111 			panic("allocindir_merge: extra newdirblk");
6112 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6113 	}
6114 	/*
6115 	 * We can skip journaling for this freefrag and just complete
6116 	 * any pending journal work for the allocindir that is being
6117 	 * removed after the freefrag completes.
6118 	 */
6119 	if (freefrag->ff_jdep)
6120 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6121 	LIST_REMOVE(oldaip, ai_next);
6122 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6123 	    &freefrag->ff_list, &freefrag->ff_jwork);
6124 	free_newblk(&oldaip->ai_block);
6125 
6126 	return (freefrag);
6127 }
6128 
6129 static inline void
6130 setup_freedirect(freeblks, ip, i, needj)
6131 	struct freeblks *freeblks;
6132 	struct inode *ip;
6133 	int i;
6134 	int needj;
6135 {
6136 	struct ufsmount *ump;
6137 	ufs2_daddr_t blkno;
6138 	int frags;
6139 
6140 	blkno = DIP(ip, i_db[i]);
6141 	if (blkno == 0)
6142 		return;
6143 	DIP_SET(ip, i_db[i], 0);
6144 	ump = ITOUMP(ip);
6145 	frags = sblksize(ump->um_fs, ip->i_size, i);
6146 	frags = numfrags(ump->um_fs, frags);
6147 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6148 }
6149 
6150 static inline void
6151 setup_freeext(freeblks, ip, i, needj)
6152 	struct freeblks *freeblks;
6153 	struct inode *ip;
6154 	int i;
6155 	int needj;
6156 {
6157 	struct ufsmount *ump;
6158 	ufs2_daddr_t blkno;
6159 	int frags;
6160 
6161 	blkno = ip->i_din2->di_extb[i];
6162 	if (blkno == 0)
6163 		return;
6164 	ip->i_din2->di_extb[i] = 0;
6165 	ump = ITOUMP(ip);
6166 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6167 	frags = numfrags(ump->um_fs, frags);
6168 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6169 }
6170 
6171 static inline void
6172 setup_freeindir(freeblks, ip, i, lbn, needj)
6173 	struct freeblks *freeblks;
6174 	struct inode *ip;
6175 	int i;
6176 	ufs_lbn_t lbn;
6177 	int needj;
6178 {
6179 	struct ufsmount *ump;
6180 	ufs2_daddr_t blkno;
6181 
6182 	blkno = DIP(ip, i_ib[i]);
6183 	if (blkno == 0)
6184 		return;
6185 	DIP_SET(ip, i_ib[i], 0);
6186 	ump = ITOUMP(ip);
6187 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6188 	    0, needj);
6189 }
6190 
6191 static inline struct freeblks *
6192 newfreeblks(mp, ip)
6193 	struct mount *mp;
6194 	struct inode *ip;
6195 {
6196 	struct freeblks *freeblks;
6197 
6198 	freeblks = malloc(sizeof(struct freeblks),
6199 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6200 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6201 	LIST_INIT(&freeblks->fb_jblkdephd);
6202 	LIST_INIT(&freeblks->fb_jwork);
6203 	freeblks->fb_ref = 0;
6204 	freeblks->fb_cgwait = 0;
6205 	freeblks->fb_state = ATTACHED;
6206 	freeblks->fb_uid = ip->i_uid;
6207 	freeblks->fb_inum = ip->i_number;
6208 	freeblks->fb_vtype = ITOV(ip)->v_type;
6209 	freeblks->fb_modrev = DIP(ip, i_modrev);
6210 	freeblks->fb_devvp = ITODEVVP(ip);
6211 	freeblks->fb_chkcnt = 0;
6212 	freeblks->fb_len = 0;
6213 
6214 	return (freeblks);
6215 }
6216 
6217 static void
6218 trunc_indirdep(indirdep, freeblks, bp, off)
6219 	struct indirdep *indirdep;
6220 	struct freeblks *freeblks;
6221 	struct buf *bp;
6222 	int off;
6223 {
6224 	struct allocindir *aip, *aipn;
6225 
6226 	/*
6227 	 * The first set of allocindirs won't be in savedbp.
6228 	 */
6229 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6230 		if (aip->ai_offset > off)
6231 			cancel_allocindir(aip, bp, freeblks, 1);
6232 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6233 		if (aip->ai_offset > off)
6234 			cancel_allocindir(aip, bp, freeblks, 1);
6235 	/*
6236 	 * These will exist in savedbp.
6237 	 */
6238 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6239 		if (aip->ai_offset > off)
6240 			cancel_allocindir(aip, NULL, freeblks, 0);
6241 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6242 		if (aip->ai_offset > off)
6243 			cancel_allocindir(aip, NULL, freeblks, 0);
6244 }
6245 
6246 /*
6247  * Follow the chain of indirects down to lastlbn creating a freework
6248  * structure for each.  This will be used to start indir_trunc() at
6249  * the right offset and create the journal records for the parrtial
6250  * truncation.  A second step will handle the truncated dependencies.
6251  */
6252 static int
6253 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6254 	struct freeblks *freeblks;
6255 	struct inode *ip;
6256 	ufs_lbn_t lbn;
6257 	ufs_lbn_t lastlbn;
6258 	ufs2_daddr_t blkno;
6259 {
6260 	struct indirdep *indirdep;
6261 	struct indirdep *indirn;
6262 	struct freework *freework;
6263 	struct newblk *newblk;
6264 	struct mount *mp;
6265 	struct ufsmount *ump;
6266 	struct buf *bp;
6267 	uint8_t *start;
6268 	uint8_t *end;
6269 	ufs_lbn_t lbnadd;
6270 	int level;
6271 	int error;
6272 	int off;
6273 
6274 
6275 	freework = NULL;
6276 	if (blkno == 0)
6277 		return (0);
6278 	mp = freeblks->fb_list.wk_mp;
6279 	ump = VFSTOUFS(mp);
6280 	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6281 	if ((bp->b_flags & B_CACHE) == 0) {
6282 		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6283 		bp->b_iocmd = BIO_READ;
6284 		bp->b_flags &= ~B_INVAL;
6285 		bp->b_ioflags &= ~BIO_ERROR;
6286 		vfs_busy_pages(bp, 0);
6287 		bp->b_iooffset = dbtob(bp->b_blkno);
6288 		bstrategy(bp);
6289 #ifdef RACCT
6290 		if (racct_enable) {
6291 			PROC_LOCK(curproc);
6292 			racct_add_buf(curproc, bp, 0);
6293 			PROC_UNLOCK(curproc);
6294 		}
6295 #endif /* RACCT */
6296 		curthread->td_ru.ru_inblock++;
6297 		error = bufwait(bp);
6298 		if (error) {
6299 			brelse(bp);
6300 			return (error);
6301 		}
6302 	}
6303 	level = lbn_level(lbn);
6304 	lbnadd = lbn_offset(ump->um_fs, level);
6305 	/*
6306 	 * Compute the offset of the last block we want to keep.  Store
6307 	 * in the freework the first block we want to completely free.
6308 	 */
6309 	off = (lastlbn - -(lbn + level)) / lbnadd;
6310 	if (off + 1 == NINDIR(ump->um_fs))
6311 		goto nowork;
6312 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6313 	/*
6314 	 * Link the freework into the indirdep.  This will prevent any new
6315 	 * allocations from proceeding until we are finished with the
6316 	 * truncate and the block is written.
6317 	 */
6318 	ACQUIRE_LOCK(ump);
6319 	indirdep = indirdep_lookup(mp, ip, bp);
6320 	if (indirdep->ir_freeblks)
6321 		panic("setup_trunc_indir: indirdep already truncated.");
6322 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6323 	freework->fw_indir = indirdep;
6324 	/*
6325 	 * Cancel any allocindirs that will not make it to disk.
6326 	 * We have to do this for all copies of the indirdep that
6327 	 * live on this newblk.
6328 	 */
6329 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6330 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6331 		    &newblk) == 0)
6332 			panic("setup_trunc_indir: lost block");
6333 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6334 			trunc_indirdep(indirn, freeblks, bp, off);
6335 	} else
6336 		trunc_indirdep(indirdep, freeblks, bp, off);
6337 	FREE_LOCK(ump);
6338 	/*
6339 	 * Creation is protected by the buf lock. The saveddata is only
6340 	 * needed if a full truncation follows a partial truncation but it
6341 	 * is difficult to allocate in that case so we fetch it anyway.
6342 	 */
6343 	if (indirdep->ir_saveddata == NULL)
6344 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6345 		    M_SOFTDEP_FLAGS);
6346 nowork:
6347 	/* Fetch the blkno of the child and the zero start offset. */
6348 	if (I_IS_UFS1(ip)) {
6349 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6350 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6351 	} else {
6352 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6353 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6354 	}
6355 	if (freework) {
6356 		/* Zero the truncated pointers. */
6357 		end = bp->b_data + bp->b_bcount;
6358 		bzero(start, end - start);
6359 		bdwrite(bp);
6360 	} else
6361 		bqrelse(bp);
6362 	if (level == 0)
6363 		return (0);
6364 	lbn++; /* adjust level */
6365 	lbn -= (off * lbnadd);
6366 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6367 }
6368 
6369 /*
6370  * Complete the partial truncation of an indirect block setup by
6371  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6372  * copy and writes them to disk before the freeblks is allowed to complete.
6373  */
6374 static void
6375 complete_trunc_indir(freework)
6376 	struct freework *freework;
6377 {
6378 	struct freework *fwn;
6379 	struct indirdep *indirdep;
6380 	struct ufsmount *ump;
6381 	struct buf *bp;
6382 	uintptr_t start;
6383 	int count;
6384 
6385 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6386 	LOCK_OWNED(ump);
6387 	indirdep = freework->fw_indir;
6388 	for (;;) {
6389 		bp = indirdep->ir_bp;
6390 		/* See if the block was discarded. */
6391 		if (bp == NULL)
6392 			break;
6393 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6394 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6395 			break;
6396 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6397 		    LOCK_PTR(ump)) == 0)
6398 			BUF_UNLOCK(bp);
6399 		ACQUIRE_LOCK(ump);
6400 	}
6401 	freework->fw_state |= DEPCOMPLETE;
6402 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6403 	/*
6404 	 * Zero the pointers in the saved copy.
6405 	 */
6406 	if (indirdep->ir_state & UFS1FMT)
6407 		start = sizeof(ufs1_daddr_t);
6408 	else
6409 		start = sizeof(ufs2_daddr_t);
6410 	start *= freework->fw_start;
6411 	count = indirdep->ir_savebp->b_bcount - start;
6412 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6413 	bzero((char *)start, count);
6414 	/*
6415 	 * We need to start the next truncation in the list if it has not
6416 	 * been started yet.
6417 	 */
6418 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6419 	if (fwn != NULL) {
6420 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6421 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6422 		if ((fwn->fw_state & ONWORKLIST) == 0)
6423 			freework_enqueue(fwn);
6424 	}
6425 	/*
6426 	 * If bp is NULL the block was fully truncated, restore
6427 	 * the saved block list otherwise free it if it is no
6428 	 * longer needed.
6429 	 */
6430 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6431 		if (bp == NULL)
6432 			bcopy(indirdep->ir_saveddata,
6433 			    indirdep->ir_savebp->b_data,
6434 			    indirdep->ir_savebp->b_bcount);
6435 		free(indirdep->ir_saveddata, M_INDIRDEP);
6436 		indirdep->ir_saveddata = NULL;
6437 	}
6438 	/*
6439 	 * When bp is NULL there is a full truncation pending.  We
6440 	 * must wait for this full truncation to be journaled before
6441 	 * we can release this freework because the disk pointers will
6442 	 * never be written as zero.
6443 	 */
6444 	if (bp == NULL)  {
6445 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6446 			handle_written_freework(freework);
6447 		else
6448 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6449 			   &freework->fw_list);
6450 	} else {
6451 		/* Complete when the real copy is written. */
6452 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6453 		BUF_UNLOCK(bp);
6454 	}
6455 }
6456 
6457 /*
6458  * Calculate the number of blocks we are going to release where datablocks
6459  * is the current total and length is the new file size.
6460  */
6461 static ufs2_daddr_t
6462 blkcount(fs, datablocks, length)
6463 	struct fs *fs;
6464 	ufs2_daddr_t datablocks;
6465 	off_t length;
6466 {
6467 	off_t totblks, numblks;
6468 
6469 	totblks = 0;
6470 	numblks = howmany(length, fs->fs_bsize);
6471 	if (numblks <= UFS_NDADDR) {
6472 		totblks = howmany(length, fs->fs_fsize);
6473 		goto out;
6474 	}
6475         totblks = blkstofrags(fs, numblks);
6476 	numblks -= UFS_NDADDR;
6477 	/*
6478 	 * Count all single, then double, then triple indirects required.
6479 	 * Subtracting one indirects worth of blocks for each pass
6480 	 * acknowledges one of each pointed to by the inode.
6481 	 */
6482 	for (;;) {
6483 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6484 		numblks -= NINDIR(fs);
6485 		if (numblks <= 0)
6486 			break;
6487 		numblks = howmany(numblks, NINDIR(fs));
6488 	}
6489 out:
6490 	totblks = fsbtodb(fs, totblks);
6491 	/*
6492 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6493 	 * references.  We will correct it later in handle_complete_freeblks()
6494 	 * when we know the real count.
6495 	 */
6496 	if (totblks > datablocks)
6497 		return (0);
6498 	return (datablocks - totblks);
6499 }
6500 
6501 /*
6502  * Handle freeblocks for journaled softupdate filesystems.
6503  *
6504  * Contrary to normal softupdates, we must preserve the block pointers in
6505  * indirects until their subordinates are free.  This is to avoid journaling
6506  * every block that is freed which may consume more space than the journal
6507  * itself.  The recovery program will see the free block journals at the
6508  * base of the truncated area and traverse them to reclaim space.  The
6509  * pointers in the inode may be cleared immediately after the journal
6510  * records are written because each direct and indirect pointer in the
6511  * inode is recorded in a journal.  This permits full truncation to proceed
6512  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6513  *
6514  * The algorithm is as follows:
6515  * 1) Traverse the in-memory state and create journal entries to release
6516  *    the relevant blocks and full indirect trees.
6517  * 2) Traverse the indirect block chain adding partial truncation freework
6518  *    records to indirects in the path to lastlbn.  The freework will
6519  *    prevent new allocation dependencies from being satisfied in this
6520  *    indirect until the truncation completes.
6521  * 3) Read and lock the inode block, performing an update with the new size
6522  *    and pointers.  This prevents truncated data from becoming valid on
6523  *    disk through step 4.
6524  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6525  *    eliminate journal work for those records that do not require it.
6526  * 5) Schedule the journal records to be written followed by the inode block.
6527  * 6) Allocate any necessary frags for the end of file.
6528  * 7) Zero any partially truncated blocks.
6529  *
6530  * From this truncation proceeds asynchronously using the freework and
6531  * indir_trunc machinery.  The file will not be extended again into a
6532  * partially truncated indirect block until all work is completed but
6533  * the normal dependency mechanism ensures that it is rolled back/forward
6534  * as appropriate.  Further truncation may occur without delay and is
6535  * serialized in indir_trunc().
6536  */
6537 void
6538 softdep_journal_freeblocks(ip, cred, length, flags)
6539 	struct inode *ip;	/* The inode whose length is to be reduced */
6540 	struct ucred *cred;
6541 	off_t length;		/* The new length for the file */
6542 	int flags;		/* IO_EXT and/or IO_NORMAL */
6543 {
6544 	struct freeblks *freeblks, *fbn;
6545 	struct worklist *wk, *wkn;
6546 	struct inodedep *inodedep;
6547 	struct jblkdep *jblkdep;
6548 	struct allocdirect *adp, *adpn;
6549 	struct ufsmount *ump;
6550 	struct fs *fs;
6551 	struct buf *bp;
6552 	struct vnode *vp;
6553 	struct mount *mp;
6554 	ufs2_daddr_t extblocks, datablocks;
6555 	ufs_lbn_t tmpval, lbn, lastlbn;
6556 	int frags, lastoff, iboff, allocblock, needj, error, i;
6557 
6558 	ump = ITOUMP(ip);
6559 	mp = UFSTOVFS(ump);
6560 	fs = ump->um_fs;
6561 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6562 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6563 	vp = ITOV(ip);
6564 	needj = 1;
6565 	iboff = -1;
6566 	allocblock = 0;
6567 	extblocks = 0;
6568 	datablocks = 0;
6569 	frags = 0;
6570 	freeblks = newfreeblks(mp, ip);
6571 	ACQUIRE_LOCK(ump);
6572 	/*
6573 	 * If we're truncating a removed file that will never be written
6574 	 * we don't need to journal the block frees.  The canceled journals
6575 	 * for the allocations will suffice.
6576 	 */
6577 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6578 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6579 	    length == 0)
6580 		needj = 0;
6581 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6582 	    ip->i_number, length, needj);
6583 	FREE_LOCK(ump);
6584 	/*
6585 	 * Calculate the lbn that we are truncating to.  This results in -1
6586 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6587 	 * to keep, not the first lbn we want to truncate.
6588 	 */
6589 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6590 	lastoff = blkoff(fs, length);
6591 	/*
6592 	 * Compute frags we are keeping in lastlbn.  0 means all.
6593 	 */
6594 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6595 		frags = fragroundup(fs, lastoff);
6596 		/* adp offset of last valid allocdirect. */
6597 		iboff = lastlbn;
6598 	} else if (lastlbn > 0)
6599 		iboff = UFS_NDADDR;
6600 	if (fs->fs_magic == FS_UFS2_MAGIC)
6601 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6602 	/*
6603 	 * Handle normal data blocks and indirects.  This section saves
6604 	 * values used after the inode update to complete frag and indirect
6605 	 * truncation.
6606 	 */
6607 	if ((flags & IO_NORMAL) != 0) {
6608 		/*
6609 		 * Handle truncation of whole direct and indirect blocks.
6610 		 */
6611 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6612 			setup_freedirect(freeblks, ip, i, needj);
6613 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6614 		    i < UFS_NIADDR;
6615 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6616 			/* Release a whole indirect tree. */
6617 			if (lbn > lastlbn) {
6618 				setup_freeindir(freeblks, ip, i, -lbn -i,
6619 				    needj);
6620 				continue;
6621 			}
6622 			iboff = i + UFS_NDADDR;
6623 			/*
6624 			 * Traverse partially truncated indirect tree.
6625 			 */
6626 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6627 				setup_trunc_indir(freeblks, ip, -lbn - i,
6628 				    lastlbn, DIP(ip, i_ib[i]));
6629 		}
6630 		/*
6631 		 * Handle partial truncation to a frag boundary.
6632 		 */
6633 		if (frags) {
6634 			ufs2_daddr_t blkno;
6635 			long oldfrags;
6636 
6637 			oldfrags = blksize(fs, ip, lastlbn);
6638 			blkno = DIP(ip, i_db[lastlbn]);
6639 			if (blkno && oldfrags != frags) {
6640 				oldfrags -= frags;
6641 				oldfrags = numfrags(fs, oldfrags);
6642 				blkno += numfrags(fs, frags);
6643 				newfreework(ump, freeblks, NULL, lastlbn,
6644 				    blkno, oldfrags, 0, needj);
6645 				if (needj)
6646 					adjust_newfreework(freeblks,
6647 					    numfrags(fs, frags));
6648 			} else if (blkno == 0)
6649 				allocblock = 1;
6650 		}
6651 		/*
6652 		 * Add a journal record for partial truncate if we are
6653 		 * handling indirect blocks.  Non-indirects need no extra
6654 		 * journaling.
6655 		 */
6656 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6657 			ip->i_flag |= IN_TRUNCATED;
6658 			newjtrunc(freeblks, length, 0);
6659 		}
6660 		ip->i_size = length;
6661 		DIP_SET(ip, i_size, ip->i_size);
6662 		datablocks = DIP(ip, i_blocks) - extblocks;
6663 		if (length != 0)
6664 			datablocks = blkcount(fs, datablocks, length);
6665 		freeblks->fb_len = length;
6666 	}
6667 	if ((flags & IO_EXT) != 0) {
6668 		for (i = 0; i < UFS_NXADDR; i++)
6669 			setup_freeext(freeblks, ip, i, needj);
6670 		ip->i_din2->di_extsize = 0;
6671 		datablocks += extblocks;
6672 	}
6673 #ifdef QUOTA
6674 	/* Reference the quotas in case the block count is wrong in the end. */
6675 	quotaref(vp, freeblks->fb_quota);
6676 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6677 #endif
6678 	freeblks->fb_chkcnt = -datablocks;
6679 	UFS_LOCK(ump);
6680 	fs->fs_pendingblocks += datablocks;
6681 	UFS_UNLOCK(ump);
6682 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6683 	/*
6684 	 * Handle truncation of incomplete alloc direct dependencies.  We
6685 	 * hold the inode block locked to prevent incomplete dependencies
6686 	 * from reaching the disk while we are eliminating those that
6687 	 * have been truncated.  This is a partially inlined ffs_update().
6688 	 */
6689 	ufs_itimes(vp);
6690 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6691 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6692 	    (int)fs->fs_bsize, cred, &bp);
6693 	if (error) {
6694 		brelse(bp);
6695 		softdep_error("softdep_journal_freeblocks", error);
6696 		return;
6697 	}
6698 	if (bp->b_bufsize == fs->fs_bsize)
6699 		bp->b_flags |= B_CLUSTEROK;
6700 	softdep_update_inodeblock(ip, bp, 0);
6701 	if (ump->um_fstype == UFS1) {
6702 		*((struct ufs1_dinode *)bp->b_data +
6703 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6704 	} else {
6705 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6706 		*((struct ufs2_dinode *)bp->b_data +
6707 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6708 	}
6709 	ACQUIRE_LOCK(ump);
6710 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6711 	if ((inodedep->id_state & IOSTARTED) != 0)
6712 		panic("softdep_setup_freeblocks: inode busy");
6713 	/*
6714 	 * Add the freeblks structure to the list of operations that
6715 	 * must await the zero'ed inode being written to disk. If we
6716 	 * still have a bitmap dependency (needj), then the inode
6717 	 * has never been written to disk, so we can process the
6718 	 * freeblks below once we have deleted the dependencies.
6719 	 */
6720 	if (needj)
6721 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6722 	else
6723 		freeblks->fb_state |= COMPLETE;
6724 	if ((flags & IO_NORMAL) != 0) {
6725 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6726 			if (adp->ad_offset > iboff)
6727 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6728 				    freeblks);
6729 			/*
6730 			 * Truncate the allocdirect.  We could eliminate
6731 			 * or modify journal records as well.
6732 			 */
6733 			else if (adp->ad_offset == iboff && frags)
6734 				adp->ad_newsize = frags;
6735 		}
6736 	}
6737 	if ((flags & IO_EXT) != 0)
6738 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6739 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6740 			    freeblks);
6741 	/*
6742 	 * Scan the bufwait list for newblock dependencies that will never
6743 	 * make it to disk.
6744 	 */
6745 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6746 		if (wk->wk_type != D_ALLOCDIRECT)
6747 			continue;
6748 		adp = WK_ALLOCDIRECT(wk);
6749 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6750 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6751 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6752 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6753 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6754 		}
6755 	}
6756 	/*
6757 	 * Add journal work.
6758 	 */
6759 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6760 		add_to_journal(&jblkdep->jb_list);
6761 	FREE_LOCK(ump);
6762 	bdwrite(bp);
6763 	/*
6764 	 * Truncate dependency structures beyond length.
6765 	 */
6766 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6767 	/*
6768 	 * This is only set when we need to allocate a fragment because
6769 	 * none existed at the end of a frag-sized file.  It handles only
6770 	 * allocating a new, zero filled block.
6771 	 */
6772 	if (allocblock) {
6773 		ip->i_size = length - lastoff;
6774 		DIP_SET(ip, i_size, ip->i_size);
6775 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6776 		if (error != 0) {
6777 			softdep_error("softdep_journal_freeblks", error);
6778 			return;
6779 		}
6780 		ip->i_size = length;
6781 		DIP_SET(ip, i_size, length);
6782 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6783 		allocbuf(bp, frags);
6784 		ffs_update(vp, 0);
6785 		bawrite(bp);
6786 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6787 		int size;
6788 
6789 		/*
6790 		 * Zero the end of a truncated frag or block.
6791 		 */
6792 		size = sblksize(fs, length, lastlbn);
6793 		error = bread(vp, lastlbn, size, cred, &bp);
6794 		if (error) {
6795 			softdep_error("softdep_journal_freeblks", error);
6796 			return;
6797 		}
6798 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6799 		bawrite(bp);
6800 
6801 	}
6802 	ACQUIRE_LOCK(ump);
6803 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6804 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6805 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6806 	/*
6807 	 * We zero earlier truncations so they don't erroneously
6808 	 * update i_blocks.
6809 	 */
6810 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6811 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6812 			fbn->fb_len = 0;
6813 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6814 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6815 		freeblks->fb_state |= INPROGRESS;
6816 	else
6817 		freeblks = NULL;
6818 	FREE_LOCK(ump);
6819 	if (freeblks)
6820 		handle_workitem_freeblocks(freeblks, 0);
6821 	trunc_pages(ip, length, extblocks, flags);
6822 
6823 }
6824 
6825 /*
6826  * Flush a JOP_SYNC to the journal.
6827  */
6828 void
6829 softdep_journal_fsync(ip)
6830 	struct inode *ip;
6831 {
6832 	struct jfsync *jfsync;
6833 	struct ufsmount *ump;
6834 
6835 	ump = ITOUMP(ip);
6836 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6837 	    ("softdep_journal_fsync called on non-softdep filesystem"));
6838 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6839 		return;
6840 	ip->i_flag &= ~IN_TRUNCATED;
6841 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6842 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6843 	jfsync->jfs_size = ip->i_size;
6844 	jfsync->jfs_ino = ip->i_number;
6845 	ACQUIRE_LOCK(ump);
6846 	add_to_journal(&jfsync->jfs_list);
6847 	jwait(&jfsync->jfs_list, MNT_WAIT);
6848 	FREE_LOCK(ump);
6849 }
6850 
6851 /*
6852  * Block de-allocation dependencies.
6853  *
6854  * When blocks are de-allocated, the on-disk pointers must be nullified before
6855  * the blocks are made available for use by other files.  (The true
6856  * requirement is that old pointers must be nullified before new on-disk
6857  * pointers are set.  We chose this slightly more stringent requirement to
6858  * reduce complexity.) Our implementation handles this dependency by updating
6859  * the inode (or indirect block) appropriately but delaying the actual block
6860  * de-allocation (i.e., freemap and free space count manipulation) until
6861  * after the updated versions reach stable storage.  After the disk is
6862  * updated, the blocks can be safely de-allocated whenever it is convenient.
6863  * This implementation handles only the common case of reducing a file's
6864  * length to zero. Other cases are handled by the conventional synchronous
6865  * write approach.
6866  *
6867  * The ffs implementation with which we worked double-checks
6868  * the state of the block pointers and file size as it reduces
6869  * a file's length.  Some of this code is replicated here in our
6870  * soft updates implementation.  The freeblks->fb_chkcnt field is
6871  * used to transfer a part of this information to the procedure
6872  * that eventually de-allocates the blocks.
6873  *
6874  * This routine should be called from the routine that shortens
6875  * a file's length, before the inode's size or block pointers
6876  * are modified. It will save the block pointer information for
6877  * later release and zero the inode so that the calling routine
6878  * can release it.
6879  */
6880 void
6881 softdep_setup_freeblocks(ip, length, flags)
6882 	struct inode *ip;	/* The inode whose length is to be reduced */
6883 	off_t length;		/* The new length for the file */
6884 	int flags;		/* IO_EXT and/or IO_NORMAL */
6885 {
6886 	struct ufs1_dinode *dp1;
6887 	struct ufs2_dinode *dp2;
6888 	struct freeblks *freeblks;
6889 	struct inodedep *inodedep;
6890 	struct allocdirect *adp;
6891 	struct ufsmount *ump;
6892 	struct buf *bp;
6893 	struct fs *fs;
6894 	ufs2_daddr_t extblocks, datablocks;
6895 	struct mount *mp;
6896 	int i, delay, error;
6897 	ufs_lbn_t tmpval;
6898 	ufs_lbn_t lbn;
6899 
6900 	ump = ITOUMP(ip);
6901 	mp = UFSTOVFS(ump);
6902 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6903 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6904 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6905 	    ip->i_number, length);
6906 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6907 	fs = ump->um_fs;
6908 	if ((error = bread(ump->um_devvp,
6909 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6910 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6911 		brelse(bp);
6912 		softdep_error("softdep_setup_freeblocks", error);
6913 		return;
6914 	}
6915 	freeblks = newfreeblks(mp, ip);
6916 	extblocks = 0;
6917 	datablocks = 0;
6918 	if (fs->fs_magic == FS_UFS2_MAGIC)
6919 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6920 	if ((flags & IO_NORMAL) != 0) {
6921 		for (i = 0; i < UFS_NDADDR; i++)
6922 			setup_freedirect(freeblks, ip, i, 0);
6923 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6924 		    i < UFS_NIADDR;
6925 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6926 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6927 		ip->i_size = 0;
6928 		DIP_SET(ip, i_size, 0);
6929 		datablocks = DIP(ip, i_blocks) - extblocks;
6930 	}
6931 	if ((flags & IO_EXT) != 0) {
6932 		for (i = 0; i < UFS_NXADDR; i++)
6933 			setup_freeext(freeblks, ip, i, 0);
6934 		ip->i_din2->di_extsize = 0;
6935 		datablocks += extblocks;
6936 	}
6937 #ifdef QUOTA
6938 	/* Reference the quotas in case the block count is wrong in the end. */
6939 	quotaref(ITOV(ip), freeblks->fb_quota);
6940 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6941 #endif
6942 	freeblks->fb_chkcnt = -datablocks;
6943 	UFS_LOCK(ump);
6944 	fs->fs_pendingblocks += datablocks;
6945 	UFS_UNLOCK(ump);
6946 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6947 	/*
6948 	 * Push the zero'ed inode to its disk buffer so that we are free
6949 	 * to delete its dependencies below. Once the dependencies are gone
6950 	 * the buffer can be safely released.
6951 	 */
6952 	if (ump->um_fstype == UFS1) {
6953 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6954 		    ino_to_fsbo(fs, ip->i_number));
6955 		ip->i_din1->di_freelink = dp1->di_freelink;
6956 		*dp1 = *ip->i_din1;
6957 	} else {
6958 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6959 		    ino_to_fsbo(fs, ip->i_number));
6960 		ip->i_din2->di_freelink = dp2->di_freelink;
6961 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6962 		*dp2 = *ip->i_din2;
6963 	}
6964 	/*
6965 	 * Find and eliminate any inode dependencies.
6966 	 */
6967 	ACQUIRE_LOCK(ump);
6968 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6969 	if ((inodedep->id_state & IOSTARTED) != 0)
6970 		panic("softdep_setup_freeblocks: inode busy");
6971 	/*
6972 	 * Add the freeblks structure to the list of operations that
6973 	 * must await the zero'ed inode being written to disk. If we
6974 	 * still have a bitmap dependency (delay == 0), then the inode
6975 	 * has never been written to disk, so we can process the
6976 	 * freeblks below once we have deleted the dependencies.
6977 	 */
6978 	delay = (inodedep->id_state & DEPCOMPLETE);
6979 	if (delay)
6980 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6981 	else
6982 		freeblks->fb_state |= COMPLETE;
6983 	/*
6984 	 * Because the file length has been truncated to zero, any
6985 	 * pending block allocation dependency structures associated
6986 	 * with this inode are obsolete and can simply be de-allocated.
6987 	 * We must first merge the two dependency lists to get rid of
6988 	 * any duplicate freefrag structures, then purge the merged list.
6989 	 * If we still have a bitmap dependency, then the inode has never
6990 	 * been written to disk, so we can free any fragments without delay.
6991 	 */
6992 	if (flags & IO_NORMAL) {
6993 		merge_inode_lists(&inodedep->id_newinoupdt,
6994 		    &inodedep->id_inoupdt);
6995 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
6996 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
6997 			    freeblks);
6998 	}
6999 	if (flags & IO_EXT) {
7000 		merge_inode_lists(&inodedep->id_newextupdt,
7001 		    &inodedep->id_extupdt);
7002 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7003 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7004 			    freeblks);
7005 	}
7006 	FREE_LOCK(ump);
7007 	bdwrite(bp);
7008 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7009 	ACQUIRE_LOCK(ump);
7010 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7011 		(void) free_inodedep(inodedep);
7012 	freeblks->fb_state |= DEPCOMPLETE;
7013 	/*
7014 	 * If the inode with zeroed block pointers is now on disk
7015 	 * we can start freeing blocks.
7016 	 */
7017 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7018 		freeblks->fb_state |= INPROGRESS;
7019 	else
7020 		freeblks = NULL;
7021 	FREE_LOCK(ump);
7022 	if (freeblks)
7023 		handle_workitem_freeblocks(freeblks, 0);
7024 	trunc_pages(ip, length, extblocks, flags);
7025 }
7026 
7027 /*
7028  * Eliminate pages from the page cache that back parts of this inode and
7029  * adjust the vnode pager's idea of our size.  This prevents stale data
7030  * from hanging around in the page cache.
7031  */
7032 static void
7033 trunc_pages(ip, length, extblocks, flags)
7034 	struct inode *ip;
7035 	off_t length;
7036 	ufs2_daddr_t extblocks;
7037 	int flags;
7038 {
7039 	struct vnode *vp;
7040 	struct fs *fs;
7041 	ufs_lbn_t lbn;
7042 	off_t end, extend;
7043 
7044 	vp = ITOV(ip);
7045 	fs = ITOFS(ip);
7046 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7047 	if ((flags & IO_EXT) != 0)
7048 		vn_pages_remove(vp, extend, 0);
7049 	if ((flags & IO_NORMAL) == 0)
7050 		return;
7051 	BO_LOCK(&vp->v_bufobj);
7052 	drain_output(vp);
7053 	BO_UNLOCK(&vp->v_bufobj);
7054 	/*
7055 	 * The vnode pager eliminates file pages we eliminate indirects
7056 	 * below.
7057 	 */
7058 	vnode_pager_setsize(vp, length);
7059 	/*
7060 	 * Calculate the end based on the last indirect we want to keep.  If
7061 	 * the block extends into indirects we can just use the negative of
7062 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7063 	 * be careful not to remove those, if they exist.  double and triple
7064 	 * indirect lbns do not overlap with others so it is not important
7065 	 * to verify how many levels are required.
7066 	 */
7067 	lbn = lblkno(fs, length);
7068 	if (lbn >= UFS_NDADDR) {
7069 		/* Calculate the virtual lbn of the triple indirect. */
7070 		lbn = -lbn - (UFS_NIADDR - 1);
7071 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7072 	} else
7073 		end = extend;
7074 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7075 }
7076 
7077 /*
7078  * See if the buf bp is in the range eliminated by truncation.
7079  */
7080 static int
7081 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7082 	struct buf *bp;
7083 	int *blkoffp;
7084 	ufs_lbn_t lastlbn;
7085 	int lastoff;
7086 	int flags;
7087 {
7088 	ufs_lbn_t lbn;
7089 
7090 	*blkoffp = 0;
7091 	/* Only match ext/normal blocks as appropriate. */
7092 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7093 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7094 		return (0);
7095 	/* ALTDATA is always a full truncation. */
7096 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7097 		return (1);
7098 	/* -1 is full truncation. */
7099 	if (lastlbn == -1)
7100 		return (1);
7101 	/*
7102 	 * If this is a partial truncate we only want those
7103 	 * blocks and indirect blocks that cover the range
7104 	 * we're after.
7105 	 */
7106 	lbn = bp->b_lblkno;
7107 	if (lbn < 0)
7108 		lbn = -(lbn + lbn_level(lbn));
7109 	if (lbn < lastlbn)
7110 		return (0);
7111 	/* Here we only truncate lblkno if it's partial. */
7112 	if (lbn == lastlbn) {
7113 		if (lastoff == 0)
7114 			return (0);
7115 		*blkoffp = lastoff;
7116 	}
7117 	return (1);
7118 }
7119 
7120 /*
7121  * Eliminate any dependencies that exist in memory beyond lblkno:off
7122  */
7123 static void
7124 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7125 	struct inode *ip;
7126 	struct freeblks *freeblks;
7127 	ufs_lbn_t lastlbn;
7128 	int lastoff;
7129 	int flags;
7130 {
7131 	struct bufobj *bo;
7132 	struct vnode *vp;
7133 	struct buf *bp;
7134 	int blkoff;
7135 
7136 	/*
7137 	 * We must wait for any I/O in progress to finish so that
7138 	 * all potential buffers on the dirty list will be visible.
7139 	 * Once they are all there, walk the list and get rid of
7140 	 * any dependencies.
7141 	 */
7142 	vp = ITOV(ip);
7143 	bo = &vp->v_bufobj;
7144 	BO_LOCK(bo);
7145 	drain_output(vp);
7146 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7147 		bp->b_vflags &= ~BV_SCANNED;
7148 restart:
7149 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7150 		if (bp->b_vflags & BV_SCANNED)
7151 			continue;
7152 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7153 			bp->b_vflags |= BV_SCANNED;
7154 			continue;
7155 		}
7156 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7157 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7158 			goto restart;
7159 		BO_UNLOCK(bo);
7160 		if (deallocate_dependencies(bp, freeblks, blkoff))
7161 			bqrelse(bp);
7162 		else
7163 			brelse(bp);
7164 		BO_LOCK(bo);
7165 		goto restart;
7166 	}
7167 	/*
7168 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7169 	 */
7170 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7171 		bp->b_vflags &= ~BV_SCANNED;
7172 cleanrestart:
7173 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7174 		if (bp->b_vflags & BV_SCANNED)
7175 			continue;
7176 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7177 			bp->b_vflags |= BV_SCANNED;
7178 			continue;
7179 		}
7180 		if (BUF_LOCK(bp,
7181 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7182 		    BO_LOCKPTR(bo)) == ENOLCK) {
7183 			BO_LOCK(bo);
7184 			goto cleanrestart;
7185 		}
7186 		bp->b_vflags |= BV_SCANNED;
7187 		bremfree(bp);
7188 		if (blkoff != 0) {
7189 			allocbuf(bp, blkoff);
7190 			bqrelse(bp);
7191 		} else {
7192 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7193 			brelse(bp);
7194 		}
7195 		BO_LOCK(bo);
7196 		goto cleanrestart;
7197 	}
7198 	drain_output(vp);
7199 	BO_UNLOCK(bo);
7200 }
7201 
7202 static int
7203 cancel_pagedep(pagedep, freeblks, blkoff)
7204 	struct pagedep *pagedep;
7205 	struct freeblks *freeblks;
7206 	int blkoff;
7207 {
7208 	struct jremref *jremref;
7209 	struct jmvref *jmvref;
7210 	struct dirrem *dirrem, *tmp;
7211 	int i;
7212 
7213 	/*
7214 	 * Copy any directory remove dependencies to the list
7215 	 * to be processed after the freeblks proceeds.  If
7216 	 * directory entry never made it to disk they
7217 	 * can be dumped directly onto the work list.
7218 	 */
7219 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7220 		/* Skip this directory removal if it is intended to remain. */
7221 		if (dirrem->dm_offset < blkoff)
7222 			continue;
7223 		/*
7224 		 * If there are any dirrems we wait for the journal write
7225 		 * to complete and then restart the buf scan as the lock
7226 		 * has been dropped.
7227 		 */
7228 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7229 			jwait(&jremref->jr_list, MNT_WAIT);
7230 			return (ERESTART);
7231 		}
7232 		LIST_REMOVE(dirrem, dm_next);
7233 		dirrem->dm_dirinum = pagedep->pd_ino;
7234 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7235 	}
7236 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7237 		jwait(&jmvref->jm_list, MNT_WAIT);
7238 		return (ERESTART);
7239 	}
7240 	/*
7241 	 * When we're partially truncating a pagedep we just want to flush
7242 	 * journal entries and return.  There can not be any adds in the
7243 	 * truncated portion of the directory and newblk must remain if
7244 	 * part of the block remains.
7245 	 */
7246 	if (blkoff != 0) {
7247 		struct diradd *dap;
7248 
7249 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7250 			if (dap->da_offset > blkoff)
7251 				panic("cancel_pagedep: diradd %p off %d > %d",
7252 				    dap, dap->da_offset, blkoff);
7253 		for (i = 0; i < DAHASHSZ; i++)
7254 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7255 				if (dap->da_offset > blkoff)
7256 					panic("cancel_pagedep: diradd %p off %d > %d",
7257 					    dap, dap->da_offset, blkoff);
7258 		return (0);
7259 	}
7260 	/*
7261 	 * There should be no directory add dependencies present
7262 	 * as the directory could not be truncated until all
7263 	 * children were removed.
7264 	 */
7265 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7266 	    ("deallocate_dependencies: pendinghd != NULL"));
7267 	for (i = 0; i < DAHASHSZ; i++)
7268 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7269 		    ("deallocate_dependencies: diraddhd != NULL"));
7270 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7271 		free_newdirblk(pagedep->pd_newdirblk);
7272 	if (free_pagedep(pagedep) == 0)
7273 		panic("Failed to free pagedep %p", pagedep);
7274 	return (0);
7275 }
7276 
7277 /*
7278  * Reclaim any dependency structures from a buffer that is about to
7279  * be reallocated to a new vnode. The buffer must be locked, thus,
7280  * no I/O completion operations can occur while we are manipulating
7281  * its associated dependencies. The mutex is held so that other I/O's
7282  * associated with related dependencies do not occur.
7283  */
7284 static int
7285 deallocate_dependencies(bp, freeblks, off)
7286 	struct buf *bp;
7287 	struct freeblks *freeblks;
7288 	int off;
7289 {
7290 	struct indirdep *indirdep;
7291 	struct pagedep *pagedep;
7292 	struct worklist *wk, *wkn;
7293 	struct ufsmount *ump;
7294 
7295 	ump = softdep_bp_to_mp(bp);
7296 	if (ump == NULL)
7297 		goto done;
7298 	ACQUIRE_LOCK(ump);
7299 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7300 		switch (wk->wk_type) {
7301 		case D_INDIRDEP:
7302 			indirdep = WK_INDIRDEP(wk);
7303 			if (bp->b_lblkno >= 0 ||
7304 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7305 				panic("deallocate_dependencies: not indir");
7306 			cancel_indirdep(indirdep, bp, freeblks);
7307 			continue;
7308 
7309 		case D_PAGEDEP:
7310 			pagedep = WK_PAGEDEP(wk);
7311 			if (cancel_pagedep(pagedep, freeblks, off)) {
7312 				FREE_LOCK(ump);
7313 				return (ERESTART);
7314 			}
7315 			continue;
7316 
7317 		case D_ALLOCINDIR:
7318 			/*
7319 			 * Simply remove the allocindir, we'll find it via
7320 			 * the indirdep where we can clear pointers if
7321 			 * needed.
7322 			 */
7323 			WORKLIST_REMOVE(wk);
7324 			continue;
7325 
7326 		case D_FREEWORK:
7327 			/*
7328 			 * A truncation is waiting for the zero'd pointers
7329 			 * to be written.  It can be freed when the freeblks
7330 			 * is journaled.
7331 			 */
7332 			WORKLIST_REMOVE(wk);
7333 			wk->wk_state |= ONDEPLIST;
7334 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7335 			break;
7336 
7337 		case D_ALLOCDIRECT:
7338 			if (off != 0)
7339 				continue;
7340 			/* FALLTHROUGH */
7341 		default:
7342 			panic("deallocate_dependencies: Unexpected type %s",
7343 			    TYPENAME(wk->wk_type));
7344 			/* NOTREACHED */
7345 		}
7346 	}
7347 	FREE_LOCK(ump);
7348 done:
7349 	/*
7350 	 * Don't throw away this buf, we were partially truncating and
7351 	 * some deps may always remain.
7352 	 */
7353 	if (off) {
7354 		allocbuf(bp, off);
7355 		bp->b_vflags |= BV_SCANNED;
7356 		return (EBUSY);
7357 	}
7358 	bp->b_flags |= B_INVAL | B_NOCACHE;
7359 
7360 	return (0);
7361 }
7362 
7363 /*
7364  * An allocdirect is being canceled due to a truncate.  We must make sure
7365  * the journal entry is released in concert with the blkfree that releases
7366  * the storage.  Completed journal entries must not be released until the
7367  * space is no longer pointed to by the inode or in the bitmap.
7368  */
7369 static void
7370 cancel_allocdirect(adphead, adp, freeblks)
7371 	struct allocdirectlst *adphead;
7372 	struct allocdirect *adp;
7373 	struct freeblks *freeblks;
7374 {
7375 	struct freework *freework;
7376 	struct newblk *newblk;
7377 	struct worklist *wk;
7378 
7379 	TAILQ_REMOVE(adphead, adp, ad_next);
7380 	newblk = (struct newblk *)adp;
7381 	freework = NULL;
7382 	/*
7383 	 * Find the correct freework structure.
7384 	 */
7385 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7386 		if (wk->wk_type != D_FREEWORK)
7387 			continue;
7388 		freework = WK_FREEWORK(wk);
7389 		if (freework->fw_blkno == newblk->nb_newblkno)
7390 			break;
7391 	}
7392 	if (freework == NULL)
7393 		panic("cancel_allocdirect: Freework not found");
7394 	/*
7395 	 * If a newblk exists at all we still have the journal entry that
7396 	 * initiated the allocation so we do not need to journal the free.
7397 	 */
7398 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7399 	/*
7400 	 * If the journal hasn't been written the jnewblk must be passed
7401 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7402 	 * this by linking the journal dependency into the freework to be
7403 	 * freed when freework_freeblock() is called.  If the journal has
7404 	 * been written we can simply reclaim the journal space when the
7405 	 * freeblks work is complete.
7406 	 */
7407 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7408 	    &freeblks->fb_jwork);
7409 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7410 }
7411 
7412 
7413 /*
7414  * Cancel a new block allocation.  May be an indirect or direct block.  We
7415  * remove it from various lists and return any journal record that needs to
7416  * be resolved by the caller.
7417  *
7418  * A special consideration is made for indirects which were never pointed
7419  * at on disk and will never be found once this block is released.
7420  */
7421 static struct jnewblk *
7422 cancel_newblk(newblk, wk, wkhd)
7423 	struct newblk *newblk;
7424 	struct worklist *wk;
7425 	struct workhead *wkhd;
7426 {
7427 	struct jnewblk *jnewblk;
7428 
7429 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7430 
7431 	newblk->nb_state |= GOINGAWAY;
7432 	/*
7433 	 * Previously we traversed the completedhd on each indirdep
7434 	 * attached to this newblk to cancel them and gather journal
7435 	 * work.  Since we need only the oldest journal segment and
7436 	 * the lowest point on the tree will always have the oldest
7437 	 * journal segment we are free to release the segments
7438 	 * of any subordinates and may leave the indirdep list to
7439 	 * indirdep_complete() when this newblk is freed.
7440 	 */
7441 	if (newblk->nb_state & ONDEPLIST) {
7442 		newblk->nb_state &= ~ONDEPLIST;
7443 		LIST_REMOVE(newblk, nb_deps);
7444 	}
7445 	if (newblk->nb_state & ONWORKLIST)
7446 		WORKLIST_REMOVE(&newblk->nb_list);
7447 	/*
7448 	 * If the journal entry hasn't been written we save a pointer to
7449 	 * the dependency that frees it until it is written or the
7450 	 * superseding operation completes.
7451 	 */
7452 	jnewblk = newblk->nb_jnewblk;
7453 	if (jnewblk != NULL && wk != NULL) {
7454 		newblk->nb_jnewblk = NULL;
7455 		jnewblk->jn_dep = wk;
7456 	}
7457 	if (!LIST_EMPTY(&newblk->nb_jwork))
7458 		jwork_move(wkhd, &newblk->nb_jwork);
7459 	/*
7460 	 * When truncating we must free the newdirblk early to remove
7461 	 * the pagedep from the hash before returning.
7462 	 */
7463 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7464 		free_newdirblk(WK_NEWDIRBLK(wk));
7465 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7466 		panic("cancel_newblk: extra newdirblk");
7467 
7468 	return (jnewblk);
7469 }
7470 
7471 /*
7472  * Schedule the freefrag associated with a newblk to be released once
7473  * the pointers are written and the previous block is no longer needed.
7474  */
7475 static void
7476 newblk_freefrag(newblk)
7477 	struct newblk *newblk;
7478 {
7479 	struct freefrag *freefrag;
7480 
7481 	if (newblk->nb_freefrag == NULL)
7482 		return;
7483 	freefrag = newblk->nb_freefrag;
7484 	newblk->nb_freefrag = NULL;
7485 	freefrag->ff_state |= COMPLETE;
7486 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7487 		add_to_worklist(&freefrag->ff_list, 0);
7488 }
7489 
7490 /*
7491  * Free a newblk. Generate a new freefrag work request if appropriate.
7492  * This must be called after the inode pointer and any direct block pointers
7493  * are valid or fully removed via truncate or frag extension.
7494  */
7495 static void
7496 free_newblk(newblk)
7497 	struct newblk *newblk;
7498 {
7499 	struct indirdep *indirdep;
7500 	struct worklist *wk;
7501 
7502 	KASSERT(newblk->nb_jnewblk == NULL,
7503 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7504 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7505 	    ("free_newblk: unclaimed newblk"));
7506 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7507 	newblk_freefrag(newblk);
7508 	if (newblk->nb_state & ONDEPLIST)
7509 		LIST_REMOVE(newblk, nb_deps);
7510 	if (newblk->nb_state & ONWORKLIST)
7511 		WORKLIST_REMOVE(&newblk->nb_list);
7512 	LIST_REMOVE(newblk, nb_hash);
7513 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7514 		free_newdirblk(WK_NEWDIRBLK(wk));
7515 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7516 		panic("free_newblk: extra newdirblk");
7517 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7518 		indirdep_complete(indirdep);
7519 	handle_jwork(&newblk->nb_jwork);
7520 	WORKITEM_FREE(newblk, D_NEWBLK);
7521 }
7522 
7523 /*
7524  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7525  * This routine must be called with splbio interrupts blocked.
7526  */
7527 static void
7528 free_newdirblk(newdirblk)
7529 	struct newdirblk *newdirblk;
7530 {
7531 	struct pagedep *pagedep;
7532 	struct diradd *dap;
7533 	struct worklist *wk;
7534 
7535 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7536 	WORKLIST_REMOVE(&newdirblk->db_list);
7537 	/*
7538 	 * If the pagedep is still linked onto the directory buffer
7539 	 * dependency chain, then some of the entries on the
7540 	 * pd_pendinghd list may not be committed to disk yet. In
7541 	 * this case, we will simply clear the NEWBLOCK flag and
7542 	 * let the pd_pendinghd list be processed when the pagedep
7543 	 * is next written. If the pagedep is no longer on the buffer
7544 	 * dependency chain, then all the entries on the pd_pending
7545 	 * list are committed to disk and we can free them here.
7546 	 */
7547 	pagedep = newdirblk->db_pagedep;
7548 	pagedep->pd_state &= ~NEWBLOCK;
7549 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7550 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7551 			free_diradd(dap, NULL);
7552 		/*
7553 		 * If no dependencies remain, the pagedep will be freed.
7554 		 */
7555 		free_pagedep(pagedep);
7556 	}
7557 	/* Should only ever be one item in the list. */
7558 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7559 		WORKLIST_REMOVE(wk);
7560 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7561 	}
7562 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7563 }
7564 
7565 /*
7566  * Prepare an inode to be freed. The actual free operation is not
7567  * done until the zero'ed inode has been written to disk.
7568  */
7569 void
7570 softdep_freefile(pvp, ino, mode)
7571 	struct vnode *pvp;
7572 	ino_t ino;
7573 	int mode;
7574 {
7575 	struct inode *ip = VTOI(pvp);
7576 	struct inodedep *inodedep;
7577 	struct freefile *freefile;
7578 	struct freeblks *freeblks;
7579 	struct ufsmount *ump;
7580 
7581 	ump = ITOUMP(ip);
7582 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7583 	    ("softdep_freefile called on non-softdep filesystem"));
7584 	/*
7585 	 * This sets up the inode de-allocation dependency.
7586 	 */
7587 	freefile = malloc(sizeof(struct freefile),
7588 		M_FREEFILE, M_SOFTDEP_FLAGS);
7589 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7590 	freefile->fx_mode = mode;
7591 	freefile->fx_oldinum = ino;
7592 	freefile->fx_devvp = ump->um_devvp;
7593 	LIST_INIT(&freefile->fx_jwork);
7594 	UFS_LOCK(ump);
7595 	ump->um_fs->fs_pendinginodes += 1;
7596 	UFS_UNLOCK(ump);
7597 
7598 	/*
7599 	 * If the inodedep does not exist, then the zero'ed inode has
7600 	 * been written to disk. If the allocated inode has never been
7601 	 * written to disk, then the on-disk inode is zero'ed. In either
7602 	 * case we can free the file immediately.  If the journal was
7603 	 * canceled before being written the inode will never make it to
7604 	 * disk and we must send the canceled journal entrys to
7605 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7606 	 * Any blocks waiting on the inode to write can be safely freed
7607 	 * here as it will never been written.
7608 	 */
7609 	ACQUIRE_LOCK(ump);
7610 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7611 	if (inodedep) {
7612 		/*
7613 		 * Clear out freeblks that no longer need to reference
7614 		 * this inode.
7615 		 */
7616 		while ((freeblks =
7617 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7618 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7619 			    fb_next);
7620 			freeblks->fb_state &= ~ONDEPLIST;
7621 		}
7622 		/*
7623 		 * Remove this inode from the unlinked list.
7624 		 */
7625 		if (inodedep->id_state & UNLINKED) {
7626 			/*
7627 			 * Save the journal work to be freed with the bitmap
7628 			 * before we clear UNLINKED.  Otherwise it can be lost
7629 			 * if the inode block is written.
7630 			 */
7631 			handle_bufwait(inodedep, &freefile->fx_jwork);
7632 			clear_unlinked_inodedep(inodedep);
7633 			/*
7634 			 * Re-acquire inodedep as we've dropped the
7635 			 * per-filesystem lock in clear_unlinked_inodedep().
7636 			 */
7637 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7638 		}
7639 	}
7640 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7641 		FREE_LOCK(ump);
7642 		handle_workitem_freefile(freefile);
7643 		return;
7644 	}
7645 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7646 		inodedep->id_state |= GOINGAWAY;
7647 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7648 	FREE_LOCK(ump);
7649 	if (ip->i_number == ino)
7650 		ip->i_flag |= IN_MODIFIED;
7651 }
7652 
7653 /*
7654  * Check to see if an inode has never been written to disk. If
7655  * so free the inodedep and return success, otherwise return failure.
7656  * This routine must be called with splbio interrupts blocked.
7657  *
7658  * If we still have a bitmap dependency, then the inode has never
7659  * been written to disk. Drop the dependency as it is no longer
7660  * necessary since the inode is being deallocated. We set the
7661  * ALLCOMPLETE flags since the bitmap now properly shows that the
7662  * inode is not allocated. Even if the inode is actively being
7663  * written, it has been rolled back to its zero'ed state, so we
7664  * are ensured that a zero inode is what is on the disk. For short
7665  * lived files, this change will usually result in removing all the
7666  * dependencies from the inode so that it can be freed immediately.
7667  */
7668 static int
7669 check_inode_unwritten(inodedep)
7670 	struct inodedep *inodedep;
7671 {
7672 
7673 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7674 
7675 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7676 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7677 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7678 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7679 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7680 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7681 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7682 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7683 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7684 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7685 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7686 	    inodedep->id_mkdiradd != NULL ||
7687 	    inodedep->id_nlinkdelta != 0)
7688 		return (0);
7689 	/*
7690 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7691 	 * trying to allocate memory without holding "Softdep Lock".
7692 	 */
7693 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7694 	    inodedep->id_savedino1 == NULL)
7695 		return (0);
7696 
7697 	if (inodedep->id_state & ONDEPLIST)
7698 		LIST_REMOVE(inodedep, id_deps);
7699 	inodedep->id_state &= ~ONDEPLIST;
7700 	inodedep->id_state |= ALLCOMPLETE;
7701 	inodedep->id_bmsafemap = NULL;
7702 	if (inodedep->id_state & ONWORKLIST)
7703 		WORKLIST_REMOVE(&inodedep->id_list);
7704 	if (inodedep->id_savedino1 != NULL) {
7705 		free(inodedep->id_savedino1, M_SAVEDINO);
7706 		inodedep->id_savedino1 = NULL;
7707 	}
7708 	if (free_inodedep(inodedep) == 0)
7709 		panic("check_inode_unwritten: busy inode");
7710 	return (1);
7711 }
7712 
7713 static int
7714 check_inodedep_free(inodedep)
7715 	struct inodedep *inodedep;
7716 {
7717 
7718 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7719 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7720 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7721 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7722 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7723 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7724 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7725 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7726 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7727 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7728 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7729 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7730 	    inodedep->id_mkdiradd != NULL ||
7731 	    inodedep->id_nlinkdelta != 0 ||
7732 	    inodedep->id_savedino1 != NULL)
7733 		return (0);
7734 	return (1);
7735 }
7736 
7737 /*
7738  * Try to free an inodedep structure. Return 1 if it could be freed.
7739  */
7740 static int
7741 free_inodedep(inodedep)
7742 	struct inodedep *inodedep;
7743 {
7744 
7745 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7746 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7747 	    !check_inodedep_free(inodedep))
7748 		return (0);
7749 	if (inodedep->id_state & ONDEPLIST)
7750 		LIST_REMOVE(inodedep, id_deps);
7751 	LIST_REMOVE(inodedep, id_hash);
7752 	WORKITEM_FREE(inodedep, D_INODEDEP);
7753 	return (1);
7754 }
7755 
7756 /*
7757  * Free the block referenced by a freework structure.  The parent freeblks
7758  * structure is released and completed when the final cg bitmap reaches
7759  * the disk.  This routine may be freeing a jnewblk which never made it to
7760  * disk in which case we do not have to wait as the operation is undone
7761  * in memory immediately.
7762  */
7763 static void
7764 freework_freeblock(freework, key)
7765 	struct freework *freework;
7766 	u_long key;
7767 {
7768 	struct freeblks *freeblks;
7769 	struct jnewblk *jnewblk;
7770 	struct ufsmount *ump;
7771 	struct workhead wkhd;
7772 	struct fs *fs;
7773 	int bsize;
7774 	int needj;
7775 
7776 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7777 	LOCK_OWNED(ump);
7778 	/*
7779 	 * Handle partial truncate separately.
7780 	 */
7781 	if (freework->fw_indir) {
7782 		complete_trunc_indir(freework);
7783 		return;
7784 	}
7785 	freeblks = freework->fw_freeblks;
7786 	fs = ump->um_fs;
7787 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7788 	bsize = lfragtosize(fs, freework->fw_frags);
7789 	LIST_INIT(&wkhd);
7790 	/*
7791 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7792 	 * on the indirblk hashtable and prevents premature freeing.
7793 	 */
7794 	freework->fw_state |= DEPCOMPLETE;
7795 	/*
7796 	 * SUJ needs to wait for the segment referencing freed indirect
7797 	 * blocks to expire so that we know the checker will not confuse
7798 	 * a re-allocated indirect block with its old contents.
7799 	 */
7800 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7801 		indirblk_insert(freework);
7802 	/*
7803 	 * If we are canceling an existing jnewblk pass it to the free
7804 	 * routine, otherwise pass the freeblk which will ultimately
7805 	 * release the freeblks.  If we're not journaling, we can just
7806 	 * free the freeblks immediately.
7807 	 */
7808 	jnewblk = freework->fw_jnewblk;
7809 	if (jnewblk != NULL) {
7810 		cancel_jnewblk(jnewblk, &wkhd);
7811 		needj = 0;
7812 	} else if (needj) {
7813 		freework->fw_state |= DELAYEDFREE;
7814 		freeblks->fb_cgwait++;
7815 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7816 	}
7817 	FREE_LOCK(ump);
7818 	freeblks_free(ump, freeblks, btodb(bsize));
7819 	CTR4(KTR_SUJ,
7820 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
7821 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7822 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7823 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
7824 	ACQUIRE_LOCK(ump);
7825 	/*
7826 	 * The jnewblk will be discarded and the bits in the map never
7827 	 * made it to disk.  We can immediately free the freeblk.
7828 	 */
7829 	if (needj == 0)
7830 		handle_written_freework(freework);
7831 }
7832 
7833 /*
7834  * We enqueue freework items that need processing back on the freeblks and
7835  * add the freeblks to the worklist.  This makes it easier to find all work
7836  * required to flush a truncation in process_truncates().
7837  */
7838 static void
7839 freework_enqueue(freework)
7840 	struct freework *freework;
7841 {
7842 	struct freeblks *freeblks;
7843 
7844 	freeblks = freework->fw_freeblks;
7845 	if ((freework->fw_state & INPROGRESS) == 0)
7846 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7847 	if ((freeblks->fb_state &
7848 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7849 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7850 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7851 }
7852 
7853 /*
7854  * Start, continue, or finish the process of freeing an indirect block tree.
7855  * The free operation may be paused at any point with fw_off containing the
7856  * offset to restart from.  This enables us to implement some flow control
7857  * for large truncates which may fan out and generate a huge number of
7858  * dependencies.
7859  */
7860 static void
7861 handle_workitem_indirblk(freework)
7862 	struct freework *freework;
7863 {
7864 	struct freeblks *freeblks;
7865 	struct ufsmount *ump;
7866 	struct fs *fs;
7867 
7868 	freeblks = freework->fw_freeblks;
7869 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7870 	fs = ump->um_fs;
7871 	if (freework->fw_state & DEPCOMPLETE) {
7872 		handle_written_freework(freework);
7873 		return;
7874 	}
7875 	if (freework->fw_off == NINDIR(fs)) {
7876 		freework_freeblock(freework, SINGLETON_KEY);
7877 		return;
7878 	}
7879 	freework->fw_state |= INPROGRESS;
7880 	FREE_LOCK(ump);
7881 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7882 	    freework->fw_lbn);
7883 	ACQUIRE_LOCK(ump);
7884 }
7885 
7886 /*
7887  * Called when a freework structure attached to a cg buf is written.  The
7888  * ref on either the parent or the freeblks structure is released and
7889  * the freeblks is added back to the worklist if there is more work to do.
7890  */
7891 static void
7892 handle_written_freework(freework)
7893 	struct freework *freework;
7894 {
7895 	struct freeblks *freeblks;
7896 	struct freework *parent;
7897 
7898 	freeblks = freework->fw_freeblks;
7899 	parent = freework->fw_parent;
7900 	if (freework->fw_state & DELAYEDFREE)
7901 		freeblks->fb_cgwait--;
7902 	freework->fw_state |= COMPLETE;
7903 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7904 		WORKITEM_FREE(freework, D_FREEWORK);
7905 	if (parent) {
7906 		if (--parent->fw_ref == 0)
7907 			freework_enqueue(parent);
7908 		return;
7909 	}
7910 	if (--freeblks->fb_ref != 0)
7911 		return;
7912 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7913 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7914 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7915 }
7916 
7917 /*
7918  * This workitem routine performs the block de-allocation.
7919  * The workitem is added to the pending list after the updated
7920  * inode block has been written to disk.  As mentioned above,
7921  * checks regarding the number of blocks de-allocated (compared
7922  * to the number of blocks allocated for the file) are also
7923  * performed in this function.
7924  */
7925 static int
7926 handle_workitem_freeblocks(freeblks, flags)
7927 	struct freeblks *freeblks;
7928 	int flags;
7929 {
7930 	struct freework *freework;
7931 	struct newblk *newblk;
7932 	struct allocindir *aip;
7933 	struct ufsmount *ump;
7934 	struct worklist *wk;
7935 	u_long key;
7936 
7937 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7938 	    ("handle_workitem_freeblocks: Journal entries not written."));
7939 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7940 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
7941 	ACQUIRE_LOCK(ump);
7942 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7943 		WORKLIST_REMOVE(wk);
7944 		switch (wk->wk_type) {
7945 		case D_DIRREM:
7946 			wk->wk_state |= COMPLETE;
7947 			add_to_worklist(wk, 0);
7948 			continue;
7949 
7950 		case D_ALLOCDIRECT:
7951 			free_newblk(WK_NEWBLK(wk));
7952 			continue;
7953 
7954 		case D_ALLOCINDIR:
7955 			aip = WK_ALLOCINDIR(wk);
7956 			freework = NULL;
7957 			if (aip->ai_state & DELAYEDFREE) {
7958 				FREE_LOCK(ump);
7959 				freework = newfreework(ump, freeblks, NULL,
7960 				    aip->ai_lbn, aip->ai_newblkno,
7961 				    ump->um_fs->fs_frag, 0, 0);
7962 				ACQUIRE_LOCK(ump);
7963 			}
7964 			newblk = WK_NEWBLK(wk);
7965 			if (newblk->nb_jnewblk) {
7966 				freework->fw_jnewblk = newblk->nb_jnewblk;
7967 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7968 				newblk->nb_jnewblk = NULL;
7969 			}
7970 			free_newblk(newblk);
7971 			continue;
7972 
7973 		case D_FREEWORK:
7974 			freework = WK_FREEWORK(wk);
7975 			if (freework->fw_lbn <= -UFS_NDADDR)
7976 				handle_workitem_indirblk(freework);
7977 			else
7978 				freework_freeblock(freework, key);
7979 			continue;
7980 		default:
7981 			panic("handle_workitem_freeblocks: Unknown type %s",
7982 			    TYPENAME(wk->wk_type));
7983 		}
7984 	}
7985 	if (freeblks->fb_ref != 0) {
7986 		freeblks->fb_state &= ~INPROGRESS;
7987 		wake_worklist(&freeblks->fb_list);
7988 		freeblks = NULL;
7989 	}
7990 	FREE_LOCK(ump);
7991 	ffs_blkrelease_finish(ump, key);
7992 	if (freeblks)
7993 		return handle_complete_freeblocks(freeblks, flags);
7994 	return (0);
7995 }
7996 
7997 /*
7998  * Handle completion of block free via truncate.  This allows fs_pending
7999  * to track the actual free block count more closely than if we only updated
8000  * it at the end.  We must be careful to handle cases where the block count
8001  * on free was incorrect.
8002  */
8003 static void
8004 freeblks_free(ump, freeblks, blocks)
8005 	struct ufsmount *ump;
8006 	struct freeblks *freeblks;
8007 	int blocks;
8008 {
8009 	struct fs *fs;
8010 	ufs2_daddr_t remain;
8011 
8012 	UFS_LOCK(ump);
8013 	remain = -freeblks->fb_chkcnt;
8014 	freeblks->fb_chkcnt += blocks;
8015 	if (remain > 0) {
8016 		if (remain < blocks)
8017 			blocks = remain;
8018 		fs = ump->um_fs;
8019 		fs->fs_pendingblocks -= blocks;
8020 	}
8021 	UFS_UNLOCK(ump);
8022 }
8023 
8024 /*
8025  * Once all of the freework workitems are complete we can retire the
8026  * freeblocks dependency and any journal work awaiting completion.  This
8027  * can not be called until all other dependencies are stable on disk.
8028  */
8029 static int
8030 handle_complete_freeblocks(freeblks, flags)
8031 	struct freeblks *freeblks;
8032 	int flags;
8033 {
8034 	struct inodedep *inodedep;
8035 	struct inode *ip;
8036 	struct vnode *vp;
8037 	struct fs *fs;
8038 	struct ufsmount *ump;
8039 	ufs2_daddr_t spare;
8040 
8041 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8042 	fs = ump->um_fs;
8043 	flags = LK_EXCLUSIVE | flags;
8044 	spare = freeblks->fb_chkcnt;
8045 
8046 	/*
8047 	 * If we did not release the expected number of blocks we may have
8048 	 * to adjust the inode block count here.  Only do so if it wasn't
8049 	 * a truncation to zero and the modrev still matches.
8050 	 */
8051 	if (spare && freeblks->fb_len != 0) {
8052 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8053 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8054 			return (EBUSY);
8055 		ip = VTOI(vp);
8056 		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8057 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8058 			ip->i_flag |= IN_CHANGE;
8059 			/*
8060 			 * We must wait so this happens before the
8061 			 * journal is reclaimed.
8062 			 */
8063 			ffs_update(vp, 1);
8064 		}
8065 		vput(vp);
8066 	}
8067 	if (spare < 0) {
8068 		UFS_LOCK(ump);
8069 		fs->fs_pendingblocks += spare;
8070 		UFS_UNLOCK(ump);
8071 	}
8072 #ifdef QUOTA
8073 	/* Handle spare. */
8074 	if (spare)
8075 		quotaadj(freeblks->fb_quota, ump, -spare);
8076 	quotarele(freeblks->fb_quota);
8077 #endif
8078 	ACQUIRE_LOCK(ump);
8079 	if (freeblks->fb_state & ONDEPLIST) {
8080 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8081 		    0, &inodedep);
8082 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8083 		freeblks->fb_state &= ~ONDEPLIST;
8084 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8085 			free_inodedep(inodedep);
8086 	}
8087 	/*
8088 	 * All of the freeblock deps must be complete prior to this call
8089 	 * so it's now safe to complete earlier outstanding journal entries.
8090 	 */
8091 	handle_jwork(&freeblks->fb_jwork);
8092 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8093 	FREE_LOCK(ump);
8094 	return (0);
8095 }
8096 
8097 /*
8098  * Release blocks associated with the freeblks and stored in the indirect
8099  * block dbn. If level is greater than SINGLE, the block is an indirect block
8100  * and recursive calls to indirtrunc must be used to cleanse other indirect
8101  * blocks.
8102  *
8103  * This handles partial and complete truncation of blocks.  Partial is noted
8104  * with goingaway == 0.  In this case the freework is completed after the
8105  * zero'd indirects are written to disk.  For full truncation the freework
8106  * is completed after the block is freed.
8107  */
8108 static void
8109 indir_trunc(freework, dbn, lbn)
8110 	struct freework *freework;
8111 	ufs2_daddr_t dbn;
8112 	ufs_lbn_t lbn;
8113 {
8114 	struct freework *nfreework;
8115 	struct workhead wkhd;
8116 	struct freeblks *freeblks;
8117 	struct buf *bp;
8118 	struct fs *fs;
8119 	struct indirdep *indirdep;
8120 	struct ufsmount *ump;
8121 	ufs1_daddr_t *bap1;
8122 	ufs2_daddr_t nb, nnb, *bap2;
8123 	ufs_lbn_t lbnadd, nlbn;
8124 	u_long key;
8125 	int nblocks, ufs1fmt, freedblocks;
8126 	int goingaway, freedeps, needj, level, cnt, i;
8127 
8128 	freeblks = freework->fw_freeblks;
8129 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8130 	fs = ump->um_fs;
8131 	/*
8132 	 * Get buffer of block pointers to be freed.  There are three cases:
8133 	 *
8134 	 * 1) Partial truncate caches the indirdep pointer in the freework
8135 	 *    which provides us a back copy to the save bp which holds the
8136 	 *    pointers we want to clear.  When this completes the zero
8137 	 *    pointers are written to the real copy.
8138 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8139 	 *    eliminated the real copy and placed the indirdep on the saved
8140 	 *    copy.  The indirdep and buf are discarded when this completes.
8141 	 * 3) The indirect was not in memory, we read a copy off of the disk
8142 	 *    using the devvp and drop and invalidate the buffer when we're
8143 	 *    done.
8144 	 */
8145 	goingaway = 1;
8146 	indirdep = NULL;
8147 	if (freework->fw_indir != NULL) {
8148 		goingaway = 0;
8149 		indirdep = freework->fw_indir;
8150 		bp = indirdep->ir_savebp;
8151 		if (bp == NULL || bp->b_blkno != dbn)
8152 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8153 			    bp, (intmax_t)dbn);
8154 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8155 		/*
8156 		 * The lock prevents the buf dep list from changing and
8157 	 	 * indirects on devvp should only ever have one dependency.
8158 		 */
8159 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8160 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8161 			panic("indir_trunc: Bad indirdep %p from buf %p",
8162 			    indirdep, bp);
8163 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8164 	    NOCRED, &bp) != 0) {
8165 		brelse(bp);
8166 		return;
8167 	}
8168 	ACQUIRE_LOCK(ump);
8169 	/* Protects against a race with complete_trunc_indir(). */
8170 	freework->fw_state &= ~INPROGRESS;
8171 	/*
8172 	 * If we have an indirdep we need to enforce the truncation order
8173 	 * and discard it when it is complete.
8174 	 */
8175 	if (indirdep) {
8176 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8177 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8178 			/*
8179 			 * Add the complete truncate to the list on the
8180 			 * indirdep to enforce in-order processing.
8181 			 */
8182 			if (freework->fw_indir == NULL)
8183 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8184 				    freework, fw_next);
8185 			FREE_LOCK(ump);
8186 			return;
8187 		}
8188 		/*
8189 		 * If we're goingaway, free the indirdep.  Otherwise it will
8190 		 * linger until the write completes.
8191 		 */
8192 		if (goingaway)
8193 			free_indirdep(indirdep);
8194 	}
8195 	FREE_LOCK(ump);
8196 	/* Initialize pointers depending on block size. */
8197 	if (ump->um_fstype == UFS1) {
8198 		bap1 = (ufs1_daddr_t *)bp->b_data;
8199 		nb = bap1[freework->fw_off];
8200 		ufs1fmt = 1;
8201 		bap2 = NULL;
8202 	} else {
8203 		bap2 = (ufs2_daddr_t *)bp->b_data;
8204 		nb = bap2[freework->fw_off];
8205 		ufs1fmt = 0;
8206 		bap1 = NULL;
8207 	}
8208 	level = lbn_level(lbn);
8209 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8210 	lbnadd = lbn_offset(fs, level);
8211 	nblocks = btodb(fs->fs_bsize);
8212 	nfreework = freework;
8213 	freedeps = 0;
8214 	cnt = 0;
8215 	/*
8216 	 * Reclaim blocks.  Traverses into nested indirect levels and
8217 	 * arranges for the current level to be freed when subordinates
8218 	 * are free when journaling.
8219 	 */
8220 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8221 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8222 		if (i != NINDIR(fs) - 1) {
8223 			if (ufs1fmt)
8224 				nnb = bap1[i+1];
8225 			else
8226 				nnb = bap2[i+1];
8227 		} else
8228 			nnb = 0;
8229 		if (nb == 0)
8230 			continue;
8231 		cnt++;
8232 		if (level != 0) {
8233 			nlbn = (lbn + 1) - (i * lbnadd);
8234 			if (needj != 0) {
8235 				nfreework = newfreework(ump, freeblks, freework,
8236 				    nlbn, nb, fs->fs_frag, 0, 0);
8237 				freedeps++;
8238 			}
8239 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8240 		} else {
8241 			struct freedep *freedep;
8242 
8243 			/*
8244 			 * Attempt to aggregate freedep dependencies for
8245 			 * all blocks being released to the same CG.
8246 			 */
8247 			LIST_INIT(&wkhd);
8248 			if (needj != 0 &&
8249 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8250 				freedep = newfreedep(freework);
8251 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8252 				    &freedep->fd_list);
8253 				freedeps++;
8254 			}
8255 			CTR3(KTR_SUJ,
8256 			    "indir_trunc: ino %jd blkno %jd size %d",
8257 			    freeblks->fb_inum, nb, fs->fs_bsize);
8258 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8259 			    fs->fs_bsize, freeblks->fb_inum,
8260 			    freeblks->fb_vtype, &wkhd, key);
8261 		}
8262 	}
8263 	ffs_blkrelease_finish(ump, key);
8264 	if (goingaway) {
8265 		bp->b_flags |= B_INVAL | B_NOCACHE;
8266 		brelse(bp);
8267 	}
8268 	freedblocks = 0;
8269 	if (level == 0)
8270 		freedblocks = (nblocks * cnt);
8271 	if (needj == 0)
8272 		freedblocks += nblocks;
8273 	freeblks_free(ump, freeblks, freedblocks);
8274 	/*
8275 	 * If we are journaling set up the ref counts and offset so this
8276 	 * indirect can be completed when its children are free.
8277 	 */
8278 	if (needj) {
8279 		ACQUIRE_LOCK(ump);
8280 		freework->fw_off = i;
8281 		freework->fw_ref += freedeps;
8282 		freework->fw_ref -= NINDIR(fs) + 1;
8283 		if (level == 0)
8284 			freeblks->fb_cgwait += freedeps;
8285 		if (freework->fw_ref == 0)
8286 			freework_freeblock(freework, SINGLETON_KEY);
8287 		FREE_LOCK(ump);
8288 		return;
8289 	}
8290 	/*
8291 	 * If we're not journaling we can free the indirect now.
8292 	 */
8293 	dbn = dbtofsb(fs, dbn);
8294 	CTR3(KTR_SUJ,
8295 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8296 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8297 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8298 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8299 	/* Non SUJ softdep does single-threaded truncations. */
8300 	if (freework->fw_blkno == dbn) {
8301 		freework->fw_state |= ALLCOMPLETE;
8302 		ACQUIRE_LOCK(ump);
8303 		handle_written_freework(freework);
8304 		FREE_LOCK(ump);
8305 	}
8306 	return;
8307 }
8308 
8309 /*
8310  * Cancel an allocindir when it is removed via truncation.  When bp is not
8311  * NULL the indirect never appeared on disk and is scheduled to be freed
8312  * independently of the indir so we can more easily track journal work.
8313  */
8314 static void
8315 cancel_allocindir(aip, bp, freeblks, trunc)
8316 	struct allocindir *aip;
8317 	struct buf *bp;
8318 	struct freeblks *freeblks;
8319 	int trunc;
8320 {
8321 	struct indirdep *indirdep;
8322 	struct freefrag *freefrag;
8323 	struct newblk *newblk;
8324 
8325 	newblk = (struct newblk *)aip;
8326 	LIST_REMOVE(aip, ai_next);
8327 	/*
8328 	 * We must eliminate the pointer in bp if it must be freed on its
8329 	 * own due to partial truncate or pending journal work.
8330 	 */
8331 	if (bp && (trunc || newblk->nb_jnewblk)) {
8332 		/*
8333 		 * Clear the pointer and mark the aip to be freed
8334 		 * directly if it never existed on disk.
8335 		 */
8336 		aip->ai_state |= DELAYEDFREE;
8337 		indirdep = aip->ai_indirdep;
8338 		if (indirdep->ir_state & UFS1FMT)
8339 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8340 		else
8341 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8342 	}
8343 	/*
8344 	 * When truncating the previous pointer will be freed via
8345 	 * savedbp.  Eliminate the freefrag which would dup free.
8346 	 */
8347 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8348 		newblk->nb_freefrag = NULL;
8349 		if (freefrag->ff_jdep)
8350 			cancel_jfreefrag(
8351 			    WK_JFREEFRAG(freefrag->ff_jdep));
8352 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8353 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8354 	}
8355 	/*
8356 	 * If the journal hasn't been written the jnewblk must be passed
8357 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8358 	 * this by leaving the journal dependency on the newblk to be freed
8359 	 * when a freework is created in handle_workitem_freeblocks().
8360 	 */
8361 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8362 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8363 }
8364 
8365 /*
8366  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8367  * in to a newdirblk so any subsequent additions are tracked properly.  The
8368  * caller is responsible for adding the mkdir1 dependency to the journal
8369  * and updating id_mkdiradd.  This function returns with the per-filesystem
8370  * lock held.
8371  */
8372 static struct mkdir *
8373 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8374 	struct diradd *dap;
8375 	ino_t newinum;
8376 	ino_t dinum;
8377 	struct buf *newdirbp;
8378 	struct mkdir **mkdirp;
8379 {
8380 	struct newblk *newblk;
8381 	struct pagedep *pagedep;
8382 	struct inodedep *inodedep;
8383 	struct newdirblk *newdirblk;
8384 	struct mkdir *mkdir1, *mkdir2;
8385 	struct worklist *wk;
8386 	struct jaddref *jaddref;
8387 	struct ufsmount *ump;
8388 	struct mount *mp;
8389 
8390 	mp = dap->da_list.wk_mp;
8391 	ump = VFSTOUFS(mp);
8392 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8393 	    M_SOFTDEP_FLAGS);
8394 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8395 	LIST_INIT(&newdirblk->db_mkdir);
8396 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8397 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8398 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8399 	mkdir1->md_diradd = dap;
8400 	mkdir1->md_jaddref = NULL;
8401 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8402 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8403 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8404 	mkdir2->md_diradd = dap;
8405 	mkdir2->md_jaddref = NULL;
8406 	if (MOUNTEDSUJ(mp) == 0) {
8407 		mkdir1->md_state |= DEPCOMPLETE;
8408 		mkdir2->md_state |= DEPCOMPLETE;
8409 	}
8410 	/*
8411 	 * Dependency on "." and ".." being written to disk.
8412 	 */
8413 	mkdir1->md_buf = newdirbp;
8414 	ACQUIRE_LOCK(VFSTOUFS(mp));
8415 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8416 	/*
8417 	 * We must link the pagedep, allocdirect, and newdirblk for
8418 	 * the initial file page so the pointer to the new directory
8419 	 * is not written until the directory contents are live and
8420 	 * any subsequent additions are not marked live until the
8421 	 * block is reachable via the inode.
8422 	 */
8423 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8424 		panic("setup_newdir: lost pagedep");
8425 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8426 		if (wk->wk_type == D_ALLOCDIRECT)
8427 			break;
8428 	if (wk == NULL)
8429 		panic("setup_newdir: lost allocdirect");
8430 	if (pagedep->pd_state & NEWBLOCK)
8431 		panic("setup_newdir: NEWBLOCK already set");
8432 	newblk = WK_NEWBLK(wk);
8433 	pagedep->pd_state |= NEWBLOCK;
8434 	pagedep->pd_newdirblk = newdirblk;
8435 	newdirblk->db_pagedep = pagedep;
8436 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8437 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8438 	/*
8439 	 * Look up the inodedep for the parent directory so that we
8440 	 * can link mkdir2 into the pending dotdot jaddref or
8441 	 * the inode write if there is none.  If the inode is
8442 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8443 	 * been satisfied and mkdir2 can be freed.
8444 	 */
8445 	inodedep_lookup(mp, dinum, 0, &inodedep);
8446 	if (MOUNTEDSUJ(mp)) {
8447 		if (inodedep == NULL)
8448 			panic("setup_newdir: Lost parent.");
8449 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8450 		    inoreflst);
8451 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8452 		    (jaddref->ja_state & MKDIR_PARENT),
8453 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8454 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8455 		mkdir2->md_jaddref = jaddref;
8456 		jaddref->ja_mkdir = mkdir2;
8457 	} else if (inodedep == NULL ||
8458 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8459 		dap->da_state &= ~MKDIR_PARENT;
8460 		WORKITEM_FREE(mkdir2, D_MKDIR);
8461 		mkdir2 = NULL;
8462 	} else {
8463 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8464 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8465 	}
8466 	*mkdirp = mkdir2;
8467 
8468 	return (mkdir1);
8469 }
8470 
8471 /*
8472  * Directory entry addition dependencies.
8473  *
8474  * When adding a new directory entry, the inode (with its incremented link
8475  * count) must be written to disk before the directory entry's pointer to it.
8476  * Also, if the inode is newly allocated, the corresponding freemap must be
8477  * updated (on disk) before the directory entry's pointer. These requirements
8478  * are met via undo/redo on the directory entry's pointer, which consists
8479  * simply of the inode number.
8480  *
8481  * As directory entries are added and deleted, the free space within a
8482  * directory block can become fragmented.  The ufs filesystem will compact
8483  * a fragmented directory block to make space for a new entry. When this
8484  * occurs, the offsets of previously added entries change. Any "diradd"
8485  * dependency structures corresponding to these entries must be updated with
8486  * the new offsets.
8487  */
8488 
8489 /*
8490  * This routine is called after the in-memory inode's link
8491  * count has been incremented, but before the directory entry's
8492  * pointer to the inode has been set.
8493  */
8494 int
8495 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8496 	struct buf *bp;		/* buffer containing directory block */
8497 	struct inode *dp;	/* inode for directory */
8498 	off_t diroffset;	/* offset of new entry in directory */
8499 	ino_t newinum;		/* inode referenced by new directory entry */
8500 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8501 	int isnewblk;		/* entry is in a newly allocated block */
8502 {
8503 	int offset;		/* offset of new entry within directory block */
8504 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8505 	struct fs *fs;
8506 	struct diradd *dap;
8507 	struct newblk *newblk;
8508 	struct pagedep *pagedep;
8509 	struct inodedep *inodedep;
8510 	struct newdirblk *newdirblk;
8511 	struct mkdir *mkdir1, *mkdir2;
8512 	struct jaddref *jaddref;
8513 	struct ufsmount *ump;
8514 	struct mount *mp;
8515 	int isindir;
8516 
8517 	mp = ITOVFS(dp);
8518 	ump = VFSTOUFS(mp);
8519 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8520 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8521 	/*
8522 	 * Whiteouts have no dependencies.
8523 	 */
8524 	if (newinum == UFS_WINO) {
8525 		if (newdirbp != NULL)
8526 			bdwrite(newdirbp);
8527 		return (0);
8528 	}
8529 	jaddref = NULL;
8530 	mkdir1 = mkdir2 = NULL;
8531 	fs = ump->um_fs;
8532 	lbn = lblkno(fs, diroffset);
8533 	offset = blkoff(fs, diroffset);
8534 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8535 		M_SOFTDEP_FLAGS|M_ZERO);
8536 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8537 	dap->da_offset = offset;
8538 	dap->da_newinum = newinum;
8539 	dap->da_state = ATTACHED;
8540 	LIST_INIT(&dap->da_jwork);
8541 	isindir = bp->b_lblkno >= UFS_NDADDR;
8542 	newdirblk = NULL;
8543 	if (isnewblk &&
8544 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8545 		newdirblk = malloc(sizeof(struct newdirblk),
8546 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8547 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8548 		LIST_INIT(&newdirblk->db_mkdir);
8549 	}
8550 	/*
8551 	 * If we're creating a new directory setup the dependencies and set
8552 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8553 	 * we can move on.
8554 	 */
8555 	if (newdirbp == NULL) {
8556 		dap->da_state |= DEPCOMPLETE;
8557 		ACQUIRE_LOCK(ump);
8558 	} else {
8559 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8560 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8561 		    &mkdir2);
8562 	}
8563 	/*
8564 	 * Link into parent directory pagedep to await its being written.
8565 	 */
8566 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8567 #ifdef DEBUG
8568 	if (diradd_lookup(pagedep, offset) != NULL)
8569 		panic("softdep_setup_directory_add: %p already at off %d\n",
8570 		    diradd_lookup(pagedep, offset), offset);
8571 #endif
8572 	dap->da_pagedep = pagedep;
8573 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8574 	    da_pdlist);
8575 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8576 	/*
8577 	 * If we're journaling, link the diradd into the jaddref so it
8578 	 * may be completed after the journal entry is written.  Otherwise,
8579 	 * link the diradd into its inodedep.  If the inode is not yet
8580 	 * written place it on the bufwait list, otherwise do the post-inode
8581 	 * write processing to put it on the id_pendinghd list.
8582 	 */
8583 	if (MOUNTEDSUJ(mp)) {
8584 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8585 		    inoreflst);
8586 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8587 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8588 		jaddref->ja_diroff = diroffset;
8589 		jaddref->ja_diradd = dap;
8590 		add_to_journal(&jaddref->ja_list);
8591 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8592 		diradd_inode_written(dap, inodedep);
8593 	else
8594 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8595 	/*
8596 	 * Add the journal entries for . and .. links now that the primary
8597 	 * link is written.
8598 	 */
8599 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8600 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8601 		    inoreflst, if_deps);
8602 		KASSERT(jaddref != NULL &&
8603 		    jaddref->ja_ino == jaddref->ja_parent &&
8604 		    (jaddref->ja_state & MKDIR_BODY),
8605 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8606 		    jaddref));
8607 		mkdir1->md_jaddref = jaddref;
8608 		jaddref->ja_mkdir = mkdir1;
8609 		/*
8610 		 * It is important that the dotdot journal entry
8611 		 * is added prior to the dot entry since dot writes
8612 		 * both the dot and dotdot links.  These both must
8613 		 * be added after the primary link for the journal
8614 		 * to remain consistent.
8615 		 */
8616 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8617 		add_to_journal(&jaddref->ja_list);
8618 	}
8619 	/*
8620 	 * If we are adding a new directory remember this diradd so that if
8621 	 * we rename it we can keep the dot and dotdot dependencies.  If
8622 	 * we are adding a new name for an inode that has a mkdiradd we
8623 	 * must be in rename and we have to move the dot and dotdot
8624 	 * dependencies to this new name.  The old name is being orphaned
8625 	 * soon.
8626 	 */
8627 	if (mkdir1 != NULL) {
8628 		if (inodedep->id_mkdiradd != NULL)
8629 			panic("softdep_setup_directory_add: Existing mkdir");
8630 		inodedep->id_mkdiradd = dap;
8631 	} else if (inodedep->id_mkdiradd)
8632 		merge_diradd(inodedep, dap);
8633 	if (newdirblk != NULL) {
8634 		/*
8635 		 * There is nothing to do if we are already tracking
8636 		 * this block.
8637 		 */
8638 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8639 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8640 			FREE_LOCK(ump);
8641 			return (0);
8642 		}
8643 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8644 		    == 0)
8645 			panic("softdep_setup_directory_add: lost entry");
8646 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8647 		pagedep->pd_state |= NEWBLOCK;
8648 		pagedep->pd_newdirblk = newdirblk;
8649 		newdirblk->db_pagedep = pagedep;
8650 		FREE_LOCK(ump);
8651 		/*
8652 		 * If we extended into an indirect signal direnter to sync.
8653 		 */
8654 		if (isindir)
8655 			return (1);
8656 		return (0);
8657 	}
8658 	FREE_LOCK(ump);
8659 	return (0);
8660 }
8661 
8662 /*
8663  * This procedure is called to change the offset of a directory
8664  * entry when compacting a directory block which must be owned
8665  * exclusively by the caller. Note that the actual entry movement
8666  * must be done in this procedure to ensure that no I/O completions
8667  * occur while the move is in progress.
8668  */
8669 void
8670 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8671 	struct buf *bp;		/* Buffer holding directory block. */
8672 	struct inode *dp;	/* inode for directory */
8673 	caddr_t base;		/* address of dp->i_offset */
8674 	caddr_t oldloc;		/* address of old directory location */
8675 	caddr_t newloc;		/* address of new directory location */
8676 	int entrysize;		/* size of directory entry */
8677 {
8678 	int offset, oldoffset, newoffset;
8679 	struct pagedep *pagedep;
8680 	struct jmvref *jmvref;
8681 	struct diradd *dap;
8682 	struct direct *de;
8683 	struct mount *mp;
8684 	struct ufsmount *ump;
8685 	ufs_lbn_t lbn;
8686 	int flags;
8687 
8688 	mp = ITOVFS(dp);
8689 	ump = VFSTOUFS(mp);
8690 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8691 	    ("softdep_change_directoryentry_offset called on "
8692 	     "non-softdep filesystem"));
8693 	de = (struct direct *)oldloc;
8694 	jmvref = NULL;
8695 	flags = 0;
8696 	/*
8697 	 * Moves are always journaled as it would be too complex to
8698 	 * determine if any affected adds or removes are present in the
8699 	 * journal.
8700 	 */
8701 	if (MOUNTEDSUJ(mp)) {
8702 		flags = DEPALLOC;
8703 		jmvref = newjmvref(dp, de->d_ino,
8704 		    dp->i_offset + (oldloc - base),
8705 		    dp->i_offset + (newloc - base));
8706 	}
8707 	lbn = lblkno(ump->um_fs, dp->i_offset);
8708 	offset = blkoff(ump->um_fs, dp->i_offset);
8709 	oldoffset = offset + (oldloc - base);
8710 	newoffset = offset + (newloc - base);
8711 	ACQUIRE_LOCK(ump);
8712 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8713 		goto done;
8714 	dap = diradd_lookup(pagedep, oldoffset);
8715 	if (dap) {
8716 		dap->da_offset = newoffset;
8717 		newoffset = DIRADDHASH(newoffset);
8718 		oldoffset = DIRADDHASH(oldoffset);
8719 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8720 		    newoffset != oldoffset) {
8721 			LIST_REMOVE(dap, da_pdlist);
8722 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8723 			    dap, da_pdlist);
8724 		}
8725 	}
8726 done:
8727 	if (jmvref) {
8728 		jmvref->jm_pagedep = pagedep;
8729 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8730 		add_to_journal(&jmvref->jm_list);
8731 	}
8732 	bcopy(oldloc, newloc, entrysize);
8733 	FREE_LOCK(ump);
8734 }
8735 
8736 /*
8737  * Move the mkdir dependencies and journal work from one diradd to another
8738  * when renaming a directory.  The new name must depend on the mkdir deps
8739  * completing as the old name did.  Directories can only have one valid link
8740  * at a time so one must be canonical.
8741  */
8742 static void
8743 merge_diradd(inodedep, newdap)
8744 	struct inodedep *inodedep;
8745 	struct diradd *newdap;
8746 {
8747 	struct diradd *olddap;
8748 	struct mkdir *mkdir, *nextmd;
8749 	struct ufsmount *ump;
8750 	short state;
8751 
8752 	olddap = inodedep->id_mkdiradd;
8753 	inodedep->id_mkdiradd = newdap;
8754 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8755 		newdap->da_state &= ~DEPCOMPLETE;
8756 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8757 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8758 		     mkdir = nextmd) {
8759 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8760 			if (mkdir->md_diradd != olddap)
8761 				continue;
8762 			mkdir->md_diradd = newdap;
8763 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8764 			newdap->da_state |= state;
8765 			olddap->da_state &= ~state;
8766 			if ((olddap->da_state &
8767 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8768 				break;
8769 		}
8770 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8771 			panic("merge_diradd: unfound ref");
8772 	}
8773 	/*
8774 	 * Any mkdir related journal items are not safe to be freed until
8775 	 * the new name is stable.
8776 	 */
8777 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8778 	olddap->da_state |= DEPCOMPLETE;
8779 	complete_diradd(olddap);
8780 }
8781 
8782 /*
8783  * Move the diradd to the pending list when all diradd dependencies are
8784  * complete.
8785  */
8786 static void
8787 complete_diradd(dap)
8788 	struct diradd *dap;
8789 {
8790 	struct pagedep *pagedep;
8791 
8792 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8793 		if (dap->da_state & DIRCHG)
8794 			pagedep = dap->da_previous->dm_pagedep;
8795 		else
8796 			pagedep = dap->da_pagedep;
8797 		LIST_REMOVE(dap, da_pdlist);
8798 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8799 	}
8800 }
8801 
8802 /*
8803  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8804  * add entries and conditonally journal the remove.
8805  */
8806 static void
8807 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8808 	struct diradd *dap;
8809 	struct dirrem *dirrem;
8810 	struct jremref *jremref;
8811 	struct jremref *dotremref;
8812 	struct jremref *dotdotremref;
8813 {
8814 	struct inodedep *inodedep;
8815 	struct jaddref *jaddref;
8816 	struct inoref *inoref;
8817 	struct ufsmount *ump;
8818 	struct mkdir *mkdir;
8819 
8820 	/*
8821 	 * If no remove references were allocated we're on a non-journaled
8822 	 * filesystem and can skip the cancel step.
8823 	 */
8824 	if (jremref == NULL) {
8825 		free_diradd(dap, NULL);
8826 		return;
8827 	}
8828 	/*
8829 	 * Cancel the primary name an free it if it does not require
8830 	 * journaling.
8831 	 */
8832 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8833 	    0, &inodedep) != 0) {
8834 		/* Abort the addref that reference this diradd.  */
8835 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8836 			if (inoref->if_list.wk_type != D_JADDREF)
8837 				continue;
8838 			jaddref = (struct jaddref *)inoref;
8839 			if (jaddref->ja_diradd != dap)
8840 				continue;
8841 			if (cancel_jaddref(jaddref, inodedep,
8842 			    &dirrem->dm_jwork) == 0) {
8843 				free_jremref(jremref);
8844 				jremref = NULL;
8845 			}
8846 			break;
8847 		}
8848 	}
8849 	/*
8850 	 * Cancel subordinate names and free them if they do not require
8851 	 * journaling.
8852 	 */
8853 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8854 		ump = VFSTOUFS(dap->da_list.wk_mp);
8855 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8856 			if (mkdir->md_diradd != dap)
8857 				continue;
8858 			if ((jaddref = mkdir->md_jaddref) == NULL)
8859 				continue;
8860 			mkdir->md_jaddref = NULL;
8861 			if (mkdir->md_state & MKDIR_PARENT) {
8862 				if (cancel_jaddref(jaddref, NULL,
8863 				    &dirrem->dm_jwork) == 0) {
8864 					free_jremref(dotdotremref);
8865 					dotdotremref = NULL;
8866 				}
8867 			} else {
8868 				if (cancel_jaddref(jaddref, inodedep,
8869 				    &dirrem->dm_jwork) == 0) {
8870 					free_jremref(dotremref);
8871 					dotremref = NULL;
8872 				}
8873 			}
8874 		}
8875 	}
8876 
8877 	if (jremref)
8878 		journal_jremref(dirrem, jremref, inodedep);
8879 	if (dotremref)
8880 		journal_jremref(dirrem, dotremref, inodedep);
8881 	if (dotdotremref)
8882 		journal_jremref(dirrem, dotdotremref, NULL);
8883 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8884 	free_diradd(dap, &dirrem->dm_jwork);
8885 }
8886 
8887 /*
8888  * Free a diradd dependency structure. This routine must be called
8889  * with splbio interrupts blocked.
8890  */
8891 static void
8892 free_diradd(dap, wkhd)
8893 	struct diradd *dap;
8894 	struct workhead *wkhd;
8895 {
8896 	struct dirrem *dirrem;
8897 	struct pagedep *pagedep;
8898 	struct inodedep *inodedep;
8899 	struct mkdir *mkdir, *nextmd;
8900 	struct ufsmount *ump;
8901 
8902 	ump = VFSTOUFS(dap->da_list.wk_mp);
8903 	LOCK_OWNED(ump);
8904 	LIST_REMOVE(dap, da_pdlist);
8905 	if (dap->da_state & ONWORKLIST)
8906 		WORKLIST_REMOVE(&dap->da_list);
8907 	if ((dap->da_state & DIRCHG) == 0) {
8908 		pagedep = dap->da_pagedep;
8909 	} else {
8910 		dirrem = dap->da_previous;
8911 		pagedep = dirrem->dm_pagedep;
8912 		dirrem->dm_dirinum = pagedep->pd_ino;
8913 		dirrem->dm_state |= COMPLETE;
8914 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8915 			add_to_worklist(&dirrem->dm_list, 0);
8916 	}
8917 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8918 	    0, &inodedep) != 0)
8919 		if (inodedep->id_mkdiradd == dap)
8920 			inodedep->id_mkdiradd = NULL;
8921 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8922 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8923 		     mkdir = nextmd) {
8924 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8925 			if (mkdir->md_diradd != dap)
8926 				continue;
8927 			dap->da_state &=
8928 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8929 			LIST_REMOVE(mkdir, md_mkdirs);
8930 			if (mkdir->md_state & ONWORKLIST)
8931 				WORKLIST_REMOVE(&mkdir->md_list);
8932 			if (mkdir->md_jaddref != NULL)
8933 				panic("free_diradd: Unexpected jaddref");
8934 			WORKITEM_FREE(mkdir, D_MKDIR);
8935 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8936 				break;
8937 		}
8938 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8939 			panic("free_diradd: unfound ref");
8940 	}
8941 	if (inodedep)
8942 		free_inodedep(inodedep);
8943 	/*
8944 	 * Free any journal segments waiting for the directory write.
8945 	 */
8946 	handle_jwork(&dap->da_jwork);
8947 	WORKITEM_FREE(dap, D_DIRADD);
8948 }
8949 
8950 /*
8951  * Directory entry removal dependencies.
8952  *
8953  * When removing a directory entry, the entry's inode pointer must be
8954  * zero'ed on disk before the corresponding inode's link count is decremented
8955  * (possibly freeing the inode for re-use). This dependency is handled by
8956  * updating the directory entry but delaying the inode count reduction until
8957  * after the directory block has been written to disk. After this point, the
8958  * inode count can be decremented whenever it is convenient.
8959  */
8960 
8961 /*
8962  * This routine should be called immediately after removing
8963  * a directory entry.  The inode's link count should not be
8964  * decremented by the calling procedure -- the soft updates
8965  * code will do this task when it is safe.
8966  */
8967 void
8968 softdep_setup_remove(bp, dp, ip, isrmdir)
8969 	struct buf *bp;		/* buffer containing directory block */
8970 	struct inode *dp;	/* inode for the directory being modified */
8971 	struct inode *ip;	/* inode for directory entry being removed */
8972 	int isrmdir;		/* indicates if doing RMDIR */
8973 {
8974 	struct dirrem *dirrem, *prevdirrem;
8975 	struct inodedep *inodedep;
8976 	struct ufsmount *ump;
8977 	int direct;
8978 
8979 	ump = ITOUMP(ip);
8980 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8981 	    ("softdep_setup_remove called on non-softdep filesystem"));
8982 	/*
8983 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8984 	 * newdirrem() to setup the full directory remove which requires
8985 	 * isrmdir > 1.
8986 	 */
8987 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8988 	/*
8989 	 * Add the dirrem to the inodedep's pending remove list for quick
8990 	 * discovery later.
8991 	 */
8992 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
8993 		panic("softdep_setup_remove: Lost inodedep.");
8994 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8995 	dirrem->dm_state |= ONDEPLIST;
8996 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8997 
8998 	/*
8999 	 * If the COMPLETE flag is clear, then there were no active
9000 	 * entries and we want to roll back to a zeroed entry until
9001 	 * the new inode is committed to disk. If the COMPLETE flag is
9002 	 * set then we have deleted an entry that never made it to
9003 	 * disk. If the entry we deleted resulted from a name change,
9004 	 * then the old name still resides on disk. We cannot delete
9005 	 * its inode (returned to us in prevdirrem) until the zeroed
9006 	 * directory entry gets to disk. The new inode has never been
9007 	 * referenced on the disk, so can be deleted immediately.
9008 	 */
9009 	if ((dirrem->dm_state & COMPLETE) == 0) {
9010 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9011 		    dm_next);
9012 		FREE_LOCK(ump);
9013 	} else {
9014 		if (prevdirrem != NULL)
9015 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9016 			    prevdirrem, dm_next);
9017 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9018 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9019 		FREE_LOCK(ump);
9020 		if (direct)
9021 			handle_workitem_remove(dirrem, 0);
9022 	}
9023 }
9024 
9025 /*
9026  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9027  * pd_pendinghd list of a pagedep.
9028  */
9029 static struct diradd *
9030 diradd_lookup(pagedep, offset)
9031 	struct pagedep *pagedep;
9032 	int offset;
9033 {
9034 	struct diradd *dap;
9035 
9036 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9037 		if (dap->da_offset == offset)
9038 			return (dap);
9039 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9040 		if (dap->da_offset == offset)
9041 			return (dap);
9042 	return (NULL);
9043 }
9044 
9045 /*
9046  * Search for a .. diradd dependency in a directory that is being removed.
9047  * If the directory was renamed to a new parent we have a diradd rather
9048  * than a mkdir for the .. entry.  We need to cancel it now before
9049  * it is found in truncate().
9050  */
9051 static struct jremref *
9052 cancel_diradd_dotdot(ip, dirrem, jremref)
9053 	struct inode *ip;
9054 	struct dirrem *dirrem;
9055 	struct jremref *jremref;
9056 {
9057 	struct pagedep *pagedep;
9058 	struct diradd *dap;
9059 	struct worklist *wk;
9060 
9061 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9062 		return (jremref);
9063 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9064 	if (dap == NULL)
9065 		return (jremref);
9066 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9067 	/*
9068 	 * Mark any journal work as belonging to the parent so it is freed
9069 	 * with the .. reference.
9070 	 */
9071 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9072 		wk->wk_state |= MKDIR_PARENT;
9073 	return (NULL);
9074 }
9075 
9076 /*
9077  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9078  * replace it with a dirrem/diradd pair as a result of re-parenting a
9079  * directory.  This ensures that we don't simultaneously have a mkdir and
9080  * a diradd for the same .. entry.
9081  */
9082 static struct jremref *
9083 cancel_mkdir_dotdot(ip, dirrem, jremref)
9084 	struct inode *ip;
9085 	struct dirrem *dirrem;
9086 	struct jremref *jremref;
9087 {
9088 	struct inodedep *inodedep;
9089 	struct jaddref *jaddref;
9090 	struct ufsmount *ump;
9091 	struct mkdir *mkdir;
9092 	struct diradd *dap;
9093 	struct mount *mp;
9094 
9095 	mp = ITOVFS(ip);
9096 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9097 		return (jremref);
9098 	dap = inodedep->id_mkdiradd;
9099 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9100 		return (jremref);
9101 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9102 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9103 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9104 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9105 			break;
9106 	if (mkdir == NULL)
9107 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9108 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9109 		mkdir->md_jaddref = NULL;
9110 		jaddref->ja_state &= ~MKDIR_PARENT;
9111 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9112 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9113 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9114 			journal_jremref(dirrem, jremref, inodedep);
9115 			jremref = NULL;
9116 		}
9117 	}
9118 	if (mkdir->md_state & ONWORKLIST)
9119 		WORKLIST_REMOVE(&mkdir->md_list);
9120 	mkdir->md_state |= ALLCOMPLETE;
9121 	complete_mkdir(mkdir);
9122 	return (jremref);
9123 }
9124 
9125 static void
9126 journal_jremref(dirrem, jremref, inodedep)
9127 	struct dirrem *dirrem;
9128 	struct jremref *jremref;
9129 	struct inodedep *inodedep;
9130 {
9131 
9132 	if (inodedep == NULL)
9133 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9134 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9135 			panic("journal_jremref: Lost inodedep");
9136 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9137 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9138 	add_to_journal(&jremref->jr_list);
9139 }
9140 
9141 static void
9142 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9143 	struct dirrem *dirrem;
9144 	struct jremref *jremref;
9145 	struct jremref *dotremref;
9146 	struct jremref *dotdotremref;
9147 {
9148 	struct inodedep *inodedep;
9149 
9150 
9151 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9152 	    &inodedep) == 0)
9153 		panic("dirrem_journal: Lost inodedep");
9154 	journal_jremref(dirrem, jremref, inodedep);
9155 	if (dotremref)
9156 		journal_jremref(dirrem, dotremref, inodedep);
9157 	if (dotdotremref)
9158 		journal_jremref(dirrem, dotdotremref, NULL);
9159 }
9160 
9161 /*
9162  * Allocate a new dirrem if appropriate and return it along with
9163  * its associated pagedep. Called without a lock, returns with lock.
9164  */
9165 static struct dirrem *
9166 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9167 	struct buf *bp;		/* buffer containing directory block */
9168 	struct inode *dp;	/* inode for the directory being modified */
9169 	struct inode *ip;	/* inode for directory entry being removed */
9170 	int isrmdir;		/* indicates if doing RMDIR */
9171 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9172 {
9173 	int offset;
9174 	ufs_lbn_t lbn;
9175 	struct diradd *dap;
9176 	struct dirrem *dirrem;
9177 	struct pagedep *pagedep;
9178 	struct jremref *jremref;
9179 	struct jremref *dotremref;
9180 	struct jremref *dotdotremref;
9181 	struct vnode *dvp;
9182 	struct ufsmount *ump;
9183 
9184 	/*
9185 	 * Whiteouts have no deletion dependencies.
9186 	 */
9187 	if (ip == NULL)
9188 		panic("newdirrem: whiteout");
9189 	dvp = ITOV(dp);
9190 	ump = ITOUMP(dp);
9191 
9192 	/*
9193 	 * If the system is over its limit and our filesystem is
9194 	 * responsible for more than our share of that usage and
9195 	 * we are not a snapshot, request some inodedep cleanup.
9196 	 * Limiting the number of dirrem structures will also limit
9197 	 * the number of freefile and freeblks structures.
9198 	 */
9199 	ACQUIRE_LOCK(ump);
9200 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9201 		schedule_cleanup(UFSTOVFS(ump));
9202 	else
9203 		FREE_LOCK(ump);
9204 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9205 	    M_ZERO);
9206 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9207 	LIST_INIT(&dirrem->dm_jremrefhd);
9208 	LIST_INIT(&dirrem->dm_jwork);
9209 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9210 	dirrem->dm_oldinum = ip->i_number;
9211 	*prevdirremp = NULL;
9212 	/*
9213 	 * Allocate remove reference structures to track journal write
9214 	 * dependencies.  We will always have one for the link and
9215 	 * when doing directories we will always have one more for dot.
9216 	 * When renaming a directory we skip the dotdot link change so
9217 	 * this is not needed.
9218 	 */
9219 	jremref = dotremref = dotdotremref = NULL;
9220 	if (DOINGSUJ(dvp)) {
9221 		if (isrmdir) {
9222 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9223 			    ip->i_effnlink + 2);
9224 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9225 			    ip->i_effnlink + 1);
9226 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9227 			    dp->i_effnlink + 1);
9228 			dotdotremref->jr_state |= MKDIR_PARENT;
9229 		} else
9230 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9231 			    ip->i_effnlink + 1);
9232 	}
9233 	ACQUIRE_LOCK(ump);
9234 	lbn = lblkno(ump->um_fs, dp->i_offset);
9235 	offset = blkoff(ump->um_fs, dp->i_offset);
9236 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9237 	    &pagedep);
9238 	dirrem->dm_pagedep = pagedep;
9239 	dirrem->dm_offset = offset;
9240 	/*
9241 	 * If we're renaming a .. link to a new directory, cancel any
9242 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9243 	 * the jremref is preserved for any potential diradd in this
9244 	 * location.  This can not coincide with a rmdir.
9245 	 */
9246 	if (dp->i_offset == DOTDOT_OFFSET) {
9247 		if (isrmdir)
9248 			panic("newdirrem: .. directory change during remove?");
9249 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9250 	}
9251 	/*
9252 	 * If we're removing a directory search for the .. dependency now and
9253 	 * cancel it.  Any pending journal work will be added to the dirrem
9254 	 * to be completed when the workitem remove completes.
9255 	 */
9256 	if (isrmdir)
9257 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9258 	/*
9259 	 * Check for a diradd dependency for the same directory entry.
9260 	 * If present, then both dependencies become obsolete and can
9261 	 * be de-allocated.
9262 	 */
9263 	dap = diradd_lookup(pagedep, offset);
9264 	if (dap == NULL) {
9265 		/*
9266 		 * Link the jremref structures into the dirrem so they are
9267 		 * written prior to the pagedep.
9268 		 */
9269 		if (jremref)
9270 			dirrem_journal(dirrem, jremref, dotremref,
9271 			    dotdotremref);
9272 		return (dirrem);
9273 	}
9274 	/*
9275 	 * Must be ATTACHED at this point.
9276 	 */
9277 	if ((dap->da_state & ATTACHED) == 0)
9278 		panic("newdirrem: not ATTACHED");
9279 	if (dap->da_newinum != ip->i_number)
9280 		panic("newdirrem: inum %ju should be %ju",
9281 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9282 	/*
9283 	 * If we are deleting a changed name that never made it to disk,
9284 	 * then return the dirrem describing the previous inode (which
9285 	 * represents the inode currently referenced from this entry on disk).
9286 	 */
9287 	if ((dap->da_state & DIRCHG) != 0) {
9288 		*prevdirremp = dap->da_previous;
9289 		dap->da_state &= ~DIRCHG;
9290 		dap->da_pagedep = pagedep;
9291 	}
9292 	/*
9293 	 * We are deleting an entry that never made it to disk.
9294 	 * Mark it COMPLETE so we can delete its inode immediately.
9295 	 */
9296 	dirrem->dm_state |= COMPLETE;
9297 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9298 #ifdef SUJ_DEBUG
9299 	if (isrmdir == 0) {
9300 		struct worklist *wk;
9301 
9302 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9303 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9304 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9305 	}
9306 #endif
9307 
9308 	return (dirrem);
9309 }
9310 
9311 /*
9312  * Directory entry change dependencies.
9313  *
9314  * Changing an existing directory entry requires that an add operation
9315  * be completed first followed by a deletion. The semantics for the addition
9316  * are identical to the description of adding a new entry above except
9317  * that the rollback is to the old inode number rather than zero. Once
9318  * the addition dependency is completed, the removal is done as described
9319  * in the removal routine above.
9320  */
9321 
9322 /*
9323  * This routine should be called immediately after changing
9324  * a directory entry.  The inode's link count should not be
9325  * decremented by the calling procedure -- the soft updates
9326  * code will perform this task when it is safe.
9327  */
9328 void
9329 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9330 	struct buf *bp;		/* buffer containing directory block */
9331 	struct inode *dp;	/* inode for the directory being modified */
9332 	struct inode *ip;	/* inode for directory entry being removed */
9333 	ino_t newinum;		/* new inode number for changed entry */
9334 	int isrmdir;		/* indicates if doing RMDIR */
9335 {
9336 	int offset;
9337 	struct diradd *dap = NULL;
9338 	struct dirrem *dirrem, *prevdirrem;
9339 	struct pagedep *pagedep;
9340 	struct inodedep *inodedep;
9341 	struct jaddref *jaddref;
9342 	struct mount *mp;
9343 	struct ufsmount *ump;
9344 
9345 	mp = ITOVFS(dp);
9346 	ump = VFSTOUFS(mp);
9347 	offset = blkoff(ump->um_fs, dp->i_offset);
9348 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9349 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9350 
9351 	/*
9352 	 * Whiteouts do not need diradd dependencies.
9353 	 */
9354 	if (newinum != UFS_WINO) {
9355 		dap = malloc(sizeof(struct diradd),
9356 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9357 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9358 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9359 		dap->da_offset = offset;
9360 		dap->da_newinum = newinum;
9361 		LIST_INIT(&dap->da_jwork);
9362 	}
9363 
9364 	/*
9365 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9366 	 */
9367 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9368 	pagedep = dirrem->dm_pagedep;
9369 	/*
9370 	 * The possible values for isrmdir:
9371 	 *	0 - non-directory file rename
9372 	 *	1 - directory rename within same directory
9373 	 *   inum - directory rename to new directory of given inode number
9374 	 * When renaming to a new directory, we are both deleting and
9375 	 * creating a new directory entry, so the link count on the new
9376 	 * directory should not change. Thus we do not need the followup
9377 	 * dirrem which is usually done in handle_workitem_remove. We set
9378 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9379 	 * followup dirrem.
9380 	 */
9381 	if (isrmdir > 1)
9382 		dirrem->dm_state |= DIRCHG;
9383 
9384 	/*
9385 	 * Whiteouts have no additional dependencies,
9386 	 * so just put the dirrem on the correct list.
9387 	 */
9388 	if (newinum == UFS_WINO) {
9389 		if ((dirrem->dm_state & COMPLETE) == 0) {
9390 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9391 			    dm_next);
9392 		} else {
9393 			dirrem->dm_dirinum = pagedep->pd_ino;
9394 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9395 				add_to_worklist(&dirrem->dm_list, 0);
9396 		}
9397 		FREE_LOCK(ump);
9398 		return;
9399 	}
9400 	/*
9401 	 * Add the dirrem to the inodedep's pending remove list for quick
9402 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9403 	 * will not fail.
9404 	 */
9405 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9406 		panic("softdep_setup_directory_change: Lost inodedep.");
9407 	dirrem->dm_state |= ONDEPLIST;
9408 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9409 
9410 	/*
9411 	 * If the COMPLETE flag is clear, then there were no active
9412 	 * entries and we want to roll back to the previous inode until
9413 	 * the new inode is committed to disk. If the COMPLETE flag is
9414 	 * set, then we have deleted an entry that never made it to disk.
9415 	 * If the entry we deleted resulted from a name change, then the old
9416 	 * inode reference still resides on disk. Any rollback that we do
9417 	 * needs to be to that old inode (returned to us in prevdirrem). If
9418 	 * the entry we deleted resulted from a create, then there is
9419 	 * no entry on the disk, so we want to roll back to zero rather
9420 	 * than the uncommitted inode. In either of the COMPLETE cases we
9421 	 * want to immediately free the unwritten and unreferenced inode.
9422 	 */
9423 	if ((dirrem->dm_state & COMPLETE) == 0) {
9424 		dap->da_previous = dirrem;
9425 	} else {
9426 		if (prevdirrem != NULL) {
9427 			dap->da_previous = prevdirrem;
9428 		} else {
9429 			dap->da_state &= ~DIRCHG;
9430 			dap->da_pagedep = pagedep;
9431 		}
9432 		dirrem->dm_dirinum = pagedep->pd_ino;
9433 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9434 			add_to_worklist(&dirrem->dm_list, 0);
9435 	}
9436 	/*
9437 	 * Lookup the jaddref for this journal entry.  We must finish
9438 	 * initializing it and make the diradd write dependent on it.
9439 	 * If we're not journaling, put it on the id_bufwait list if the
9440 	 * inode is not yet written. If it is written, do the post-inode
9441 	 * write processing to put it on the id_pendinghd list.
9442 	 */
9443 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9444 	if (MOUNTEDSUJ(mp)) {
9445 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9446 		    inoreflst);
9447 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9448 		    ("softdep_setup_directory_change: bad jaddref %p",
9449 		    jaddref));
9450 		jaddref->ja_diroff = dp->i_offset;
9451 		jaddref->ja_diradd = dap;
9452 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9453 		    dap, da_pdlist);
9454 		add_to_journal(&jaddref->ja_list);
9455 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9456 		dap->da_state |= COMPLETE;
9457 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9458 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9459 	} else {
9460 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9461 		    dap, da_pdlist);
9462 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9463 	}
9464 	/*
9465 	 * If we're making a new name for a directory that has not been
9466 	 * committed when need to move the dot and dotdot references to
9467 	 * this new name.
9468 	 */
9469 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9470 		merge_diradd(inodedep, dap);
9471 	FREE_LOCK(ump);
9472 }
9473 
9474 /*
9475  * Called whenever the link count on an inode is changed.
9476  * It creates an inode dependency so that the new reference(s)
9477  * to the inode cannot be committed to disk until the updated
9478  * inode has been written.
9479  */
9480 void
9481 softdep_change_linkcnt(ip)
9482 	struct inode *ip;	/* the inode with the increased link count */
9483 {
9484 	struct inodedep *inodedep;
9485 	struct ufsmount *ump;
9486 
9487 	ump = ITOUMP(ip);
9488 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9489 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9490 	ACQUIRE_LOCK(ump);
9491 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9492 	if (ip->i_nlink < ip->i_effnlink)
9493 		panic("softdep_change_linkcnt: bad delta");
9494 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9495 	FREE_LOCK(ump);
9496 }
9497 
9498 /*
9499  * Attach a sbdep dependency to the superblock buf so that we can keep
9500  * track of the head of the linked list of referenced but unlinked inodes.
9501  */
9502 void
9503 softdep_setup_sbupdate(ump, fs, bp)
9504 	struct ufsmount *ump;
9505 	struct fs *fs;
9506 	struct buf *bp;
9507 {
9508 	struct sbdep *sbdep;
9509 	struct worklist *wk;
9510 
9511 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9512 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9513 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9514 		if (wk->wk_type == D_SBDEP)
9515 			break;
9516 	if (wk != NULL)
9517 		return;
9518 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9519 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9520 	sbdep->sb_fs = fs;
9521 	sbdep->sb_ump = ump;
9522 	ACQUIRE_LOCK(ump);
9523 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9524 	FREE_LOCK(ump);
9525 }
9526 
9527 /*
9528  * Return the first unlinked inodedep which is ready to be the head of the
9529  * list.  The inodedep and all those after it must have valid next pointers.
9530  */
9531 static struct inodedep *
9532 first_unlinked_inodedep(ump)
9533 	struct ufsmount *ump;
9534 {
9535 	struct inodedep *inodedep;
9536 	struct inodedep *idp;
9537 
9538 	LOCK_OWNED(ump);
9539 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9540 	    inodedep; inodedep = idp) {
9541 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9542 			return (NULL);
9543 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9544 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9545 			break;
9546 		if ((inodedep->id_state & UNLINKPREV) == 0)
9547 			break;
9548 	}
9549 	return (inodedep);
9550 }
9551 
9552 /*
9553  * Set the sujfree unlinked head pointer prior to writing a superblock.
9554  */
9555 static void
9556 initiate_write_sbdep(sbdep)
9557 	struct sbdep *sbdep;
9558 {
9559 	struct inodedep *inodedep;
9560 	struct fs *bpfs;
9561 	struct fs *fs;
9562 
9563 	bpfs = sbdep->sb_fs;
9564 	fs = sbdep->sb_ump->um_fs;
9565 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9566 	if (inodedep) {
9567 		fs->fs_sujfree = inodedep->id_ino;
9568 		inodedep->id_state |= UNLINKPREV;
9569 	} else
9570 		fs->fs_sujfree = 0;
9571 	bpfs->fs_sujfree = fs->fs_sujfree;
9572 }
9573 
9574 /*
9575  * After a superblock is written determine whether it must be written again
9576  * due to a changing unlinked list head.
9577  */
9578 static int
9579 handle_written_sbdep(sbdep, bp)
9580 	struct sbdep *sbdep;
9581 	struct buf *bp;
9582 {
9583 	struct inodedep *inodedep;
9584 	struct fs *fs;
9585 
9586 	LOCK_OWNED(sbdep->sb_ump);
9587 	fs = sbdep->sb_fs;
9588 	/*
9589 	 * If the superblock doesn't match the in-memory list start over.
9590 	 */
9591 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9592 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9593 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9594 		bdirty(bp);
9595 		return (1);
9596 	}
9597 	WORKITEM_FREE(sbdep, D_SBDEP);
9598 	if (fs->fs_sujfree == 0)
9599 		return (0);
9600 	/*
9601 	 * Now that we have a record of this inode in stable store allow it
9602 	 * to be written to free up pending work.  Inodes may see a lot of
9603 	 * write activity after they are unlinked which we must not hold up.
9604 	 */
9605 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9606 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9607 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9608 			    inodedep, inodedep->id_state);
9609 		if (inodedep->id_state & UNLINKONLIST)
9610 			break;
9611 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9612 	}
9613 
9614 	return (0);
9615 }
9616 
9617 /*
9618  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9619  */
9620 static void
9621 unlinked_inodedep(mp, inodedep)
9622 	struct mount *mp;
9623 	struct inodedep *inodedep;
9624 {
9625 	struct ufsmount *ump;
9626 
9627 	ump = VFSTOUFS(mp);
9628 	LOCK_OWNED(ump);
9629 	if (MOUNTEDSUJ(mp) == 0)
9630 		return;
9631 	ump->um_fs->fs_fmod = 1;
9632 	if (inodedep->id_state & UNLINKED)
9633 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9634 	inodedep->id_state |= UNLINKED;
9635 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9636 }
9637 
9638 /*
9639  * Remove an inodedep from the unlinked inodedep list.  This may require
9640  * disk writes if the inode has made it that far.
9641  */
9642 static void
9643 clear_unlinked_inodedep(inodedep)
9644 	struct inodedep *inodedep;
9645 {
9646 	struct ufs2_dinode *dip;
9647 	struct ufsmount *ump;
9648 	struct inodedep *idp;
9649 	struct inodedep *idn;
9650 	struct fs *fs;
9651 	struct buf *bp;
9652 	ino_t ino;
9653 	ino_t nino;
9654 	ino_t pino;
9655 	int error;
9656 
9657 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9658 	fs = ump->um_fs;
9659 	ino = inodedep->id_ino;
9660 	error = 0;
9661 	for (;;) {
9662 		LOCK_OWNED(ump);
9663 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9664 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9665 		    inodedep));
9666 		/*
9667 		 * If nothing has yet been written simply remove us from
9668 		 * the in memory list and return.  This is the most common
9669 		 * case where handle_workitem_remove() loses the final
9670 		 * reference.
9671 		 */
9672 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9673 			break;
9674 		/*
9675 		 * If we have a NEXT pointer and no PREV pointer we can simply
9676 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9677 		 * careful not to clear PREV if the superblock points at
9678 		 * next as well.
9679 		 */
9680 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9681 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9682 			if (idn && fs->fs_sujfree != idn->id_ino)
9683 				idn->id_state &= ~UNLINKPREV;
9684 			break;
9685 		}
9686 		/*
9687 		 * Here we have an inodedep which is actually linked into
9688 		 * the list.  We must remove it by forcing a write to the
9689 		 * link before us, whether it be the superblock or an inode.
9690 		 * Unfortunately the list may change while we're waiting
9691 		 * on the buf lock for either resource so we must loop until
9692 		 * we lock the right one.  If both the superblock and an
9693 		 * inode point to this inode we must clear the inode first
9694 		 * followed by the superblock.
9695 		 */
9696 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9697 		pino = 0;
9698 		if (idp && (idp->id_state & UNLINKNEXT))
9699 			pino = idp->id_ino;
9700 		FREE_LOCK(ump);
9701 		if (pino == 0) {
9702 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9703 			    (int)fs->fs_sbsize, 0, 0, 0);
9704 		} else {
9705 			error = bread(ump->um_devvp,
9706 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9707 			    (int)fs->fs_bsize, NOCRED, &bp);
9708 			if (error)
9709 				brelse(bp);
9710 		}
9711 		ACQUIRE_LOCK(ump);
9712 		if (error)
9713 			break;
9714 		/* If the list has changed restart the loop. */
9715 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9716 		nino = 0;
9717 		if (idp && (idp->id_state & UNLINKNEXT))
9718 			nino = idp->id_ino;
9719 		if (nino != pino ||
9720 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9721 			FREE_LOCK(ump);
9722 			brelse(bp);
9723 			ACQUIRE_LOCK(ump);
9724 			continue;
9725 		}
9726 		nino = 0;
9727 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9728 		if (idn)
9729 			nino = idn->id_ino;
9730 		/*
9731 		 * Remove us from the in memory list.  After this we cannot
9732 		 * access the inodedep.
9733 		 */
9734 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9735 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9736 		    inodedep));
9737 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9738 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9739 		FREE_LOCK(ump);
9740 		/*
9741 		 * The predecessor's next pointer is manually updated here
9742 		 * so that the NEXT flag is never cleared for an element
9743 		 * that is in the list.
9744 		 */
9745 		if (pino == 0) {
9746 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9747 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9748 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9749 			    bp);
9750 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
9751 			((struct ufs1_dinode *)bp->b_data +
9752 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9753 		} else {
9754 			dip = (struct ufs2_dinode *)bp->b_data +
9755 			    ino_to_fsbo(fs, pino);
9756 			dip->di_freelink = nino;
9757 			ffs_update_dinode_ckhash(fs, dip);
9758 		}
9759 		/*
9760 		 * If the bwrite fails we have no recourse to recover.  The
9761 		 * filesystem is corrupted already.
9762 		 */
9763 		bwrite(bp);
9764 		ACQUIRE_LOCK(ump);
9765 		/*
9766 		 * If the superblock pointer still needs to be cleared force
9767 		 * a write here.
9768 		 */
9769 		if (fs->fs_sujfree == ino) {
9770 			FREE_LOCK(ump);
9771 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9772 			    (int)fs->fs_sbsize, 0, 0, 0);
9773 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9774 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9775 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9776 			    bp);
9777 			bwrite(bp);
9778 			ACQUIRE_LOCK(ump);
9779 		}
9780 
9781 		if (fs->fs_sujfree != ino)
9782 			return;
9783 		panic("clear_unlinked_inodedep: Failed to clear free head");
9784 	}
9785 	if (inodedep->id_ino == fs->fs_sujfree)
9786 		panic("clear_unlinked_inodedep: Freeing head of free list");
9787 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9788 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9789 	return;
9790 }
9791 
9792 /*
9793  * This workitem decrements the inode's link count.
9794  * If the link count reaches zero, the file is removed.
9795  */
9796 static int
9797 handle_workitem_remove(dirrem, flags)
9798 	struct dirrem *dirrem;
9799 	int flags;
9800 {
9801 	struct inodedep *inodedep;
9802 	struct workhead dotdotwk;
9803 	struct worklist *wk;
9804 	struct ufsmount *ump;
9805 	struct mount *mp;
9806 	struct vnode *vp;
9807 	struct inode *ip;
9808 	ino_t oldinum;
9809 
9810 	if (dirrem->dm_state & ONWORKLIST)
9811 		panic("handle_workitem_remove: dirrem %p still on worklist",
9812 		    dirrem);
9813 	oldinum = dirrem->dm_oldinum;
9814 	mp = dirrem->dm_list.wk_mp;
9815 	ump = VFSTOUFS(mp);
9816 	flags |= LK_EXCLUSIVE;
9817 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9818 		return (EBUSY);
9819 	ip = VTOI(vp);
9820 	ACQUIRE_LOCK(ump);
9821 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9822 		panic("handle_workitem_remove: lost inodedep");
9823 	if (dirrem->dm_state & ONDEPLIST)
9824 		LIST_REMOVE(dirrem, dm_inonext);
9825 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9826 	    ("handle_workitem_remove:  Journal entries not written."));
9827 
9828 	/*
9829 	 * Move all dependencies waiting on the remove to complete
9830 	 * from the dirrem to the inode inowait list to be completed
9831 	 * after the inode has been updated and written to disk.  Any
9832 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9833 	 * is removed.
9834 	 */
9835 	LIST_INIT(&dotdotwk);
9836 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9837 		WORKLIST_REMOVE(wk);
9838 		if (wk->wk_state & MKDIR_PARENT) {
9839 			wk->wk_state &= ~MKDIR_PARENT;
9840 			WORKLIST_INSERT(&dotdotwk, wk);
9841 			continue;
9842 		}
9843 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9844 	}
9845 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9846 	/*
9847 	 * Normal file deletion.
9848 	 */
9849 	if ((dirrem->dm_state & RMDIR) == 0) {
9850 		ip->i_nlink--;
9851 		DIP_SET(ip, i_nlink, ip->i_nlink);
9852 		ip->i_flag |= IN_CHANGE;
9853 		if (ip->i_nlink < ip->i_effnlink)
9854 			panic("handle_workitem_remove: bad file delta");
9855 		if (ip->i_nlink == 0)
9856 			unlinked_inodedep(mp, inodedep);
9857 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9858 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9859 		    ("handle_workitem_remove: worklist not empty. %s",
9860 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9861 		WORKITEM_FREE(dirrem, D_DIRREM);
9862 		FREE_LOCK(ump);
9863 		goto out;
9864 	}
9865 	/*
9866 	 * Directory deletion. Decrement reference count for both the
9867 	 * just deleted parent directory entry and the reference for ".".
9868 	 * Arrange to have the reference count on the parent decremented
9869 	 * to account for the loss of "..".
9870 	 */
9871 	ip->i_nlink -= 2;
9872 	DIP_SET(ip, i_nlink, ip->i_nlink);
9873 	ip->i_flag |= IN_CHANGE;
9874 	if (ip->i_nlink < ip->i_effnlink)
9875 		panic("handle_workitem_remove: bad dir delta");
9876 	if (ip->i_nlink == 0)
9877 		unlinked_inodedep(mp, inodedep);
9878 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9879 	/*
9880 	 * Rename a directory to a new parent. Since, we are both deleting
9881 	 * and creating a new directory entry, the link count on the new
9882 	 * directory should not change. Thus we skip the followup dirrem.
9883 	 */
9884 	if (dirrem->dm_state & DIRCHG) {
9885 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9886 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9887 		WORKITEM_FREE(dirrem, D_DIRREM);
9888 		FREE_LOCK(ump);
9889 		goto out;
9890 	}
9891 	dirrem->dm_state = ONDEPLIST;
9892 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9893 	/*
9894 	 * Place the dirrem on the parent's diremhd list.
9895 	 */
9896 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9897 		panic("handle_workitem_remove: lost dir inodedep");
9898 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9899 	/*
9900 	 * If the allocated inode has never been written to disk, then
9901 	 * the on-disk inode is zero'ed and we can remove the file
9902 	 * immediately.  When journaling if the inode has been marked
9903 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9904 	 */
9905 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9906 	if (inodedep == NULL ||
9907 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9908 	    check_inode_unwritten(inodedep)) {
9909 		FREE_LOCK(ump);
9910 		vput(vp);
9911 		return handle_workitem_remove(dirrem, flags);
9912 	}
9913 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9914 	FREE_LOCK(ump);
9915 	ip->i_flag |= IN_CHANGE;
9916 out:
9917 	ffs_update(vp, 0);
9918 	vput(vp);
9919 	return (0);
9920 }
9921 
9922 /*
9923  * Inode de-allocation dependencies.
9924  *
9925  * When an inode's link count is reduced to zero, it can be de-allocated. We
9926  * found it convenient to postpone de-allocation until after the inode is
9927  * written to disk with its new link count (zero).  At this point, all of the
9928  * on-disk inode's block pointers are nullified and, with careful dependency
9929  * list ordering, all dependencies related to the inode will be satisfied and
9930  * the corresponding dependency structures de-allocated.  So, if/when the
9931  * inode is reused, there will be no mixing of old dependencies with new
9932  * ones.  This artificial dependency is set up by the block de-allocation
9933  * procedure above (softdep_setup_freeblocks) and completed by the
9934  * following procedure.
9935  */
9936 static void
9937 handle_workitem_freefile(freefile)
9938 	struct freefile *freefile;
9939 {
9940 	struct workhead wkhd;
9941 	struct fs *fs;
9942 	struct inodedep *idp;
9943 	struct ufsmount *ump;
9944 	int error;
9945 
9946 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9947 	fs = ump->um_fs;
9948 #ifdef DEBUG
9949 	ACQUIRE_LOCK(ump);
9950 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9951 	FREE_LOCK(ump);
9952 	if (error)
9953 		panic("handle_workitem_freefile: inodedep %p survived", idp);
9954 #endif
9955 	UFS_LOCK(ump);
9956 	fs->fs_pendinginodes -= 1;
9957 	UFS_UNLOCK(ump);
9958 	LIST_INIT(&wkhd);
9959 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9960 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9961 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9962 		softdep_error("handle_workitem_freefile", error);
9963 	ACQUIRE_LOCK(ump);
9964 	WORKITEM_FREE(freefile, D_FREEFILE);
9965 	FREE_LOCK(ump);
9966 }
9967 
9968 
9969 /*
9970  * Helper function which unlinks marker element from work list and returns
9971  * the next element on the list.
9972  */
9973 static __inline struct worklist *
9974 markernext(struct worklist *marker)
9975 {
9976 	struct worklist *next;
9977 
9978 	next = LIST_NEXT(marker, wk_list);
9979 	LIST_REMOVE(marker, wk_list);
9980 	return next;
9981 }
9982 
9983 /*
9984  * Disk writes.
9985  *
9986  * The dependency structures constructed above are most actively used when file
9987  * system blocks are written to disk.  No constraints are placed on when a
9988  * block can be written, but unsatisfied update dependencies are made safe by
9989  * modifying (or replacing) the source memory for the duration of the disk
9990  * write.  When the disk write completes, the memory block is again brought
9991  * up-to-date.
9992  *
9993  * In-core inode structure reclamation.
9994  *
9995  * Because there are a finite number of "in-core" inode structures, they are
9996  * reused regularly.  By transferring all inode-related dependencies to the
9997  * in-memory inode block and indexing them separately (via "inodedep"s), we
9998  * can allow "in-core" inode structures to be reused at any time and avoid
9999  * any increase in contention.
10000  *
10001  * Called just before entering the device driver to initiate a new disk I/O.
10002  * The buffer must be locked, thus, no I/O completion operations can occur
10003  * while we are manipulating its associated dependencies.
10004  */
10005 static void
10006 softdep_disk_io_initiation(bp)
10007 	struct buf *bp;		/* structure describing disk write to occur */
10008 {
10009 	struct worklist *wk;
10010 	struct worklist marker;
10011 	struct inodedep *inodedep;
10012 	struct freeblks *freeblks;
10013 	struct jblkdep *jblkdep;
10014 	struct newblk *newblk;
10015 	struct ufsmount *ump;
10016 
10017 	/*
10018 	 * We only care about write operations. There should never
10019 	 * be dependencies for reads.
10020 	 */
10021 	if (bp->b_iocmd != BIO_WRITE)
10022 		panic("softdep_disk_io_initiation: not write");
10023 
10024 	if (bp->b_vflags & BV_BKGRDINPROG)
10025 		panic("softdep_disk_io_initiation: Writing buffer with "
10026 		    "background write in progress: %p", bp);
10027 
10028 	ump = softdep_bp_to_mp(bp);
10029 	if (ump == NULL)
10030 		return;
10031 
10032 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10033 	PHOLD(curproc);			/* Don't swap out kernel stack */
10034 	ACQUIRE_LOCK(ump);
10035 	/*
10036 	 * Do any necessary pre-I/O processing.
10037 	 */
10038 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10039 	     wk = markernext(&marker)) {
10040 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10041 		switch (wk->wk_type) {
10042 
10043 		case D_PAGEDEP:
10044 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10045 			continue;
10046 
10047 		case D_INODEDEP:
10048 			inodedep = WK_INODEDEP(wk);
10049 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10050 				initiate_write_inodeblock_ufs1(inodedep, bp);
10051 			else
10052 				initiate_write_inodeblock_ufs2(inodedep, bp);
10053 			continue;
10054 
10055 		case D_INDIRDEP:
10056 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10057 			continue;
10058 
10059 		case D_BMSAFEMAP:
10060 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10061 			continue;
10062 
10063 		case D_JSEG:
10064 			WK_JSEG(wk)->js_buf = NULL;
10065 			continue;
10066 
10067 		case D_FREEBLKS:
10068 			freeblks = WK_FREEBLKS(wk);
10069 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10070 			/*
10071 			 * We have to wait for the freeblks to be journaled
10072 			 * before we can write an inodeblock with updated
10073 			 * pointers.  Be careful to arrange the marker so
10074 			 * we revisit the freeblks if it's not removed by
10075 			 * the first jwait().
10076 			 */
10077 			if (jblkdep != NULL) {
10078 				LIST_REMOVE(&marker, wk_list);
10079 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10080 				jwait(&jblkdep->jb_list, MNT_WAIT);
10081 			}
10082 			continue;
10083 		case D_ALLOCDIRECT:
10084 		case D_ALLOCINDIR:
10085 			/*
10086 			 * We have to wait for the jnewblk to be journaled
10087 			 * before we can write to a block if the contents
10088 			 * may be confused with an earlier file's indirect
10089 			 * at recovery time.  Handle the marker as described
10090 			 * above.
10091 			 */
10092 			newblk = WK_NEWBLK(wk);
10093 			if (newblk->nb_jnewblk != NULL &&
10094 			    indirblk_lookup(newblk->nb_list.wk_mp,
10095 			    newblk->nb_newblkno)) {
10096 				LIST_REMOVE(&marker, wk_list);
10097 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10098 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10099 			}
10100 			continue;
10101 
10102 		case D_SBDEP:
10103 			initiate_write_sbdep(WK_SBDEP(wk));
10104 			continue;
10105 
10106 		case D_MKDIR:
10107 		case D_FREEWORK:
10108 		case D_FREEDEP:
10109 		case D_JSEGDEP:
10110 			continue;
10111 
10112 		default:
10113 			panic("handle_disk_io_initiation: Unexpected type %s",
10114 			    TYPENAME(wk->wk_type));
10115 			/* NOTREACHED */
10116 		}
10117 	}
10118 	FREE_LOCK(ump);
10119 	PRELE(curproc);			/* Allow swapout of kernel stack */
10120 }
10121 
10122 /*
10123  * Called from within the procedure above to deal with unsatisfied
10124  * allocation dependencies in a directory. The buffer must be locked,
10125  * thus, no I/O completion operations can occur while we are
10126  * manipulating its associated dependencies.
10127  */
10128 static void
10129 initiate_write_filepage(pagedep, bp)
10130 	struct pagedep *pagedep;
10131 	struct buf *bp;
10132 {
10133 	struct jremref *jremref;
10134 	struct jmvref *jmvref;
10135 	struct dirrem *dirrem;
10136 	struct diradd *dap;
10137 	struct direct *ep;
10138 	int i;
10139 
10140 	if (pagedep->pd_state & IOSTARTED) {
10141 		/*
10142 		 * This can only happen if there is a driver that does not
10143 		 * understand chaining. Here biodone will reissue the call
10144 		 * to strategy for the incomplete buffers.
10145 		 */
10146 		printf("initiate_write_filepage: already started\n");
10147 		return;
10148 	}
10149 	pagedep->pd_state |= IOSTARTED;
10150 	/*
10151 	 * Wait for all journal remove dependencies to hit the disk.
10152 	 * We can not allow any potentially conflicting directory adds
10153 	 * to be visible before removes and rollback is too difficult.
10154 	 * The per-filesystem lock may be dropped and re-acquired, however
10155 	 * we hold the buf locked so the dependency can not go away.
10156 	 */
10157 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10158 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10159 			jwait(&jremref->jr_list, MNT_WAIT);
10160 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10161 		jwait(&jmvref->jm_list, MNT_WAIT);
10162 	for (i = 0; i < DAHASHSZ; i++) {
10163 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10164 			ep = (struct direct *)
10165 			    ((char *)bp->b_data + dap->da_offset);
10166 			if (ep->d_ino != dap->da_newinum)
10167 				panic("%s: dir inum %ju != new %ju",
10168 				    "initiate_write_filepage",
10169 				    (uintmax_t)ep->d_ino,
10170 				    (uintmax_t)dap->da_newinum);
10171 			if (dap->da_state & DIRCHG)
10172 				ep->d_ino = dap->da_previous->dm_oldinum;
10173 			else
10174 				ep->d_ino = 0;
10175 			dap->da_state &= ~ATTACHED;
10176 			dap->da_state |= UNDONE;
10177 		}
10178 	}
10179 }
10180 
10181 /*
10182  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10183  * Note that any bug fixes made to this routine must be done in the
10184  * version found below.
10185  *
10186  * Called from within the procedure above to deal with unsatisfied
10187  * allocation dependencies in an inodeblock. The buffer must be
10188  * locked, thus, no I/O completion operations can occur while we
10189  * are manipulating its associated dependencies.
10190  */
10191 static void
10192 initiate_write_inodeblock_ufs1(inodedep, bp)
10193 	struct inodedep *inodedep;
10194 	struct buf *bp;			/* The inode block */
10195 {
10196 	struct allocdirect *adp, *lastadp;
10197 	struct ufs1_dinode *dp;
10198 	struct ufs1_dinode *sip;
10199 	struct inoref *inoref;
10200 	struct ufsmount *ump;
10201 	struct fs *fs;
10202 	ufs_lbn_t i;
10203 #ifdef INVARIANTS
10204 	ufs_lbn_t prevlbn = 0;
10205 #endif
10206 	int deplist;
10207 
10208 	if (inodedep->id_state & IOSTARTED)
10209 		panic("initiate_write_inodeblock_ufs1: already started");
10210 	inodedep->id_state |= IOSTARTED;
10211 	fs = inodedep->id_fs;
10212 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10213 	LOCK_OWNED(ump);
10214 	dp = (struct ufs1_dinode *)bp->b_data +
10215 	    ino_to_fsbo(fs, inodedep->id_ino);
10216 
10217 	/*
10218 	 * If we're on the unlinked list but have not yet written our
10219 	 * next pointer initialize it here.
10220 	 */
10221 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10222 		struct inodedep *inon;
10223 
10224 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10225 		dp->di_freelink = inon ? inon->id_ino : 0;
10226 	}
10227 	/*
10228 	 * If the bitmap is not yet written, then the allocated
10229 	 * inode cannot be written to disk.
10230 	 */
10231 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10232 		if (inodedep->id_savedino1 != NULL)
10233 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10234 		FREE_LOCK(ump);
10235 		sip = malloc(sizeof(struct ufs1_dinode),
10236 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10237 		ACQUIRE_LOCK(ump);
10238 		inodedep->id_savedino1 = sip;
10239 		*inodedep->id_savedino1 = *dp;
10240 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10241 		dp->di_gen = inodedep->id_savedino1->di_gen;
10242 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10243 		return;
10244 	}
10245 	/*
10246 	 * If no dependencies, then there is nothing to roll back.
10247 	 */
10248 	inodedep->id_savedsize = dp->di_size;
10249 	inodedep->id_savedextsize = 0;
10250 	inodedep->id_savednlink = dp->di_nlink;
10251 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10252 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10253 		return;
10254 	/*
10255 	 * Revert the link count to that of the first unwritten journal entry.
10256 	 */
10257 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10258 	if (inoref)
10259 		dp->di_nlink = inoref->if_nlink;
10260 	/*
10261 	 * Set the dependencies to busy.
10262 	 */
10263 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10264 	     adp = TAILQ_NEXT(adp, ad_next)) {
10265 #ifdef INVARIANTS
10266 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10267 			panic("softdep_write_inodeblock: lbn order");
10268 		prevlbn = adp->ad_offset;
10269 		if (adp->ad_offset < UFS_NDADDR &&
10270 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10271 			panic("initiate_write_inodeblock_ufs1: "
10272 			    "direct pointer #%jd mismatch %d != %jd",
10273 			    (intmax_t)adp->ad_offset,
10274 			    dp->di_db[adp->ad_offset],
10275 			    (intmax_t)adp->ad_newblkno);
10276 		if (adp->ad_offset >= UFS_NDADDR &&
10277 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10278 			panic("initiate_write_inodeblock_ufs1: "
10279 			    "indirect pointer #%jd mismatch %d != %jd",
10280 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10281 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10282 			    (intmax_t)adp->ad_newblkno);
10283 		deplist |= 1 << adp->ad_offset;
10284 		if ((adp->ad_state & ATTACHED) == 0)
10285 			panic("initiate_write_inodeblock_ufs1: "
10286 			    "Unknown state 0x%x", adp->ad_state);
10287 #endif /* INVARIANTS */
10288 		adp->ad_state &= ~ATTACHED;
10289 		adp->ad_state |= UNDONE;
10290 	}
10291 	/*
10292 	 * The on-disk inode cannot claim to be any larger than the last
10293 	 * fragment that has been written. Otherwise, the on-disk inode
10294 	 * might have fragments that were not the last block in the file
10295 	 * which would corrupt the filesystem.
10296 	 */
10297 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10298 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10299 		if (adp->ad_offset >= UFS_NDADDR)
10300 			break;
10301 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10302 		/* keep going until hitting a rollback to a frag */
10303 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10304 			continue;
10305 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10306 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10307 #ifdef INVARIANTS
10308 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10309 				panic("initiate_write_inodeblock_ufs1: "
10310 				    "lost dep1");
10311 #endif /* INVARIANTS */
10312 			dp->di_db[i] = 0;
10313 		}
10314 		for (i = 0; i < UFS_NIADDR; i++) {
10315 #ifdef INVARIANTS
10316 			if (dp->di_ib[i] != 0 &&
10317 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10318 				panic("initiate_write_inodeblock_ufs1: "
10319 				    "lost dep2");
10320 #endif /* INVARIANTS */
10321 			dp->di_ib[i] = 0;
10322 		}
10323 		return;
10324 	}
10325 	/*
10326 	 * If we have zero'ed out the last allocated block of the file,
10327 	 * roll back the size to the last currently allocated block.
10328 	 * We know that this last allocated block is a full-sized as
10329 	 * we already checked for fragments in the loop above.
10330 	 */
10331 	if (lastadp != NULL &&
10332 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10333 		for (i = lastadp->ad_offset; i >= 0; i--)
10334 			if (dp->di_db[i] != 0)
10335 				break;
10336 		dp->di_size = (i + 1) * fs->fs_bsize;
10337 	}
10338 	/*
10339 	 * The only dependencies are for indirect blocks.
10340 	 *
10341 	 * The file size for indirect block additions is not guaranteed.
10342 	 * Such a guarantee would be non-trivial to achieve. The conventional
10343 	 * synchronous write implementation also does not make this guarantee.
10344 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10345 	 * can be over-estimated without destroying integrity when the file
10346 	 * moves into the indirect blocks (i.e., is large). If we want to
10347 	 * postpone fsck, we are stuck with this argument.
10348 	 */
10349 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10350 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10351 }
10352 
10353 /*
10354  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10355  * Note that any bug fixes made to this routine must be done in the
10356  * version found above.
10357  *
10358  * Called from within the procedure above to deal with unsatisfied
10359  * allocation dependencies in an inodeblock. The buffer must be
10360  * locked, thus, no I/O completion operations can occur while we
10361  * are manipulating its associated dependencies.
10362  */
10363 static void
10364 initiate_write_inodeblock_ufs2(inodedep, bp)
10365 	struct inodedep *inodedep;
10366 	struct buf *bp;			/* The inode block */
10367 {
10368 	struct allocdirect *adp, *lastadp;
10369 	struct ufs2_dinode *dp;
10370 	struct ufs2_dinode *sip;
10371 	struct inoref *inoref;
10372 	struct ufsmount *ump;
10373 	struct fs *fs;
10374 	ufs_lbn_t i;
10375 #ifdef INVARIANTS
10376 	ufs_lbn_t prevlbn = 0;
10377 #endif
10378 	int deplist;
10379 
10380 	if (inodedep->id_state & IOSTARTED)
10381 		panic("initiate_write_inodeblock_ufs2: already started");
10382 	inodedep->id_state |= IOSTARTED;
10383 	fs = inodedep->id_fs;
10384 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10385 	LOCK_OWNED(ump);
10386 	dp = (struct ufs2_dinode *)bp->b_data +
10387 	    ino_to_fsbo(fs, inodedep->id_ino);
10388 
10389 	/*
10390 	 * If we're on the unlinked list but have not yet written our
10391 	 * next pointer initialize it here.
10392 	 */
10393 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10394 		struct inodedep *inon;
10395 
10396 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10397 		dp->di_freelink = inon ? inon->id_ino : 0;
10398 		ffs_update_dinode_ckhash(fs, dp);
10399 	}
10400 	/*
10401 	 * If the bitmap is not yet written, then the allocated
10402 	 * inode cannot be written to disk.
10403 	 */
10404 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10405 		if (inodedep->id_savedino2 != NULL)
10406 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10407 		FREE_LOCK(ump);
10408 		sip = malloc(sizeof(struct ufs2_dinode),
10409 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10410 		ACQUIRE_LOCK(ump);
10411 		inodedep->id_savedino2 = sip;
10412 		*inodedep->id_savedino2 = *dp;
10413 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10414 		dp->di_gen = inodedep->id_savedino2->di_gen;
10415 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10416 		return;
10417 	}
10418 	/*
10419 	 * If no dependencies, then there is nothing to roll back.
10420 	 */
10421 	inodedep->id_savedsize = dp->di_size;
10422 	inodedep->id_savedextsize = dp->di_extsize;
10423 	inodedep->id_savednlink = dp->di_nlink;
10424 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10425 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10426 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10427 		return;
10428 	/*
10429 	 * Revert the link count to that of the first unwritten journal entry.
10430 	 */
10431 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10432 	if (inoref)
10433 		dp->di_nlink = inoref->if_nlink;
10434 
10435 	/*
10436 	 * Set the ext data dependencies to busy.
10437 	 */
10438 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10439 	     adp = TAILQ_NEXT(adp, ad_next)) {
10440 #ifdef INVARIANTS
10441 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10442 			panic("initiate_write_inodeblock_ufs2: lbn order");
10443 		prevlbn = adp->ad_offset;
10444 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10445 			panic("initiate_write_inodeblock_ufs2: "
10446 			    "ext pointer #%jd mismatch %jd != %jd",
10447 			    (intmax_t)adp->ad_offset,
10448 			    (intmax_t)dp->di_extb[adp->ad_offset],
10449 			    (intmax_t)adp->ad_newblkno);
10450 		deplist |= 1 << adp->ad_offset;
10451 		if ((adp->ad_state & ATTACHED) == 0)
10452 			panic("initiate_write_inodeblock_ufs2: Unknown "
10453 			    "state 0x%x", adp->ad_state);
10454 #endif /* INVARIANTS */
10455 		adp->ad_state &= ~ATTACHED;
10456 		adp->ad_state |= UNDONE;
10457 	}
10458 	/*
10459 	 * The on-disk inode cannot claim to be any larger than the last
10460 	 * fragment that has been written. Otherwise, the on-disk inode
10461 	 * might have fragments that were not the last block in the ext
10462 	 * data which would corrupt the filesystem.
10463 	 */
10464 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10465 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10466 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10467 		/* keep going until hitting a rollback to a frag */
10468 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10469 			continue;
10470 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10471 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10472 #ifdef INVARIANTS
10473 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10474 				panic("initiate_write_inodeblock_ufs2: "
10475 				    "lost dep1");
10476 #endif /* INVARIANTS */
10477 			dp->di_extb[i] = 0;
10478 		}
10479 		lastadp = NULL;
10480 		break;
10481 	}
10482 	/*
10483 	 * If we have zero'ed out the last allocated block of the ext
10484 	 * data, roll back the size to the last currently allocated block.
10485 	 * We know that this last allocated block is a full-sized as
10486 	 * we already checked for fragments in the loop above.
10487 	 */
10488 	if (lastadp != NULL &&
10489 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10490 		for (i = lastadp->ad_offset; i >= 0; i--)
10491 			if (dp->di_extb[i] != 0)
10492 				break;
10493 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10494 	}
10495 	/*
10496 	 * Set the file data dependencies to busy.
10497 	 */
10498 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10499 	     adp = TAILQ_NEXT(adp, ad_next)) {
10500 #ifdef INVARIANTS
10501 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10502 			panic("softdep_write_inodeblock: lbn order");
10503 		if ((adp->ad_state & ATTACHED) == 0)
10504 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10505 		prevlbn = adp->ad_offset;
10506 		if (adp->ad_offset < UFS_NDADDR &&
10507 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10508 			panic("initiate_write_inodeblock_ufs2: "
10509 			    "direct pointer #%jd mismatch %jd != %jd",
10510 			    (intmax_t)adp->ad_offset,
10511 			    (intmax_t)dp->di_db[adp->ad_offset],
10512 			    (intmax_t)adp->ad_newblkno);
10513 		if (adp->ad_offset >= UFS_NDADDR &&
10514 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10515 			panic("initiate_write_inodeblock_ufs2: "
10516 			    "indirect pointer #%jd mismatch %jd != %jd",
10517 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10518 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10519 			    (intmax_t)adp->ad_newblkno);
10520 		deplist |= 1 << adp->ad_offset;
10521 		if ((adp->ad_state & ATTACHED) == 0)
10522 			panic("initiate_write_inodeblock_ufs2: Unknown "
10523 			     "state 0x%x", adp->ad_state);
10524 #endif /* INVARIANTS */
10525 		adp->ad_state &= ~ATTACHED;
10526 		adp->ad_state |= UNDONE;
10527 	}
10528 	/*
10529 	 * The on-disk inode cannot claim to be any larger than the last
10530 	 * fragment that has been written. Otherwise, the on-disk inode
10531 	 * might have fragments that were not the last block in the file
10532 	 * which would corrupt the filesystem.
10533 	 */
10534 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10535 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10536 		if (adp->ad_offset >= UFS_NDADDR)
10537 			break;
10538 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10539 		/* keep going until hitting a rollback to a frag */
10540 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10541 			continue;
10542 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10543 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10544 #ifdef INVARIANTS
10545 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10546 				panic("initiate_write_inodeblock_ufs2: "
10547 				    "lost dep2");
10548 #endif /* INVARIANTS */
10549 			dp->di_db[i] = 0;
10550 		}
10551 		for (i = 0; i < UFS_NIADDR; i++) {
10552 #ifdef INVARIANTS
10553 			if (dp->di_ib[i] != 0 &&
10554 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10555 				panic("initiate_write_inodeblock_ufs2: "
10556 				    "lost dep3");
10557 #endif /* INVARIANTS */
10558 			dp->di_ib[i] = 0;
10559 		}
10560 		ffs_update_dinode_ckhash(fs, dp);
10561 		return;
10562 	}
10563 	/*
10564 	 * If we have zero'ed out the last allocated block of the file,
10565 	 * roll back the size to the last currently allocated block.
10566 	 * We know that this last allocated block is a full-sized as
10567 	 * we already checked for fragments in the loop above.
10568 	 */
10569 	if (lastadp != NULL &&
10570 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10571 		for (i = lastadp->ad_offset; i >= 0; i--)
10572 			if (dp->di_db[i] != 0)
10573 				break;
10574 		dp->di_size = (i + 1) * fs->fs_bsize;
10575 	}
10576 	/*
10577 	 * The only dependencies are for indirect blocks.
10578 	 *
10579 	 * The file size for indirect block additions is not guaranteed.
10580 	 * Such a guarantee would be non-trivial to achieve. The conventional
10581 	 * synchronous write implementation also does not make this guarantee.
10582 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10583 	 * can be over-estimated without destroying integrity when the file
10584 	 * moves into the indirect blocks (i.e., is large). If we want to
10585 	 * postpone fsck, we are stuck with this argument.
10586 	 */
10587 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10588 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10589 	ffs_update_dinode_ckhash(fs, dp);
10590 }
10591 
10592 /*
10593  * Cancel an indirdep as a result of truncation.  Release all of the
10594  * children allocindirs and place their journal work on the appropriate
10595  * list.
10596  */
10597 static void
10598 cancel_indirdep(indirdep, bp, freeblks)
10599 	struct indirdep *indirdep;
10600 	struct buf *bp;
10601 	struct freeblks *freeblks;
10602 {
10603 	struct allocindir *aip;
10604 
10605 	/*
10606 	 * None of the indirect pointers will ever be visible,
10607 	 * so they can simply be tossed. GOINGAWAY ensures
10608 	 * that allocated pointers will be saved in the buffer
10609 	 * cache until they are freed. Note that they will
10610 	 * only be able to be found by their physical address
10611 	 * since the inode mapping the logical address will
10612 	 * be gone. The save buffer used for the safe copy
10613 	 * was allocated in setup_allocindir_phase2 using
10614 	 * the physical address so it could be used for this
10615 	 * purpose. Hence we swap the safe copy with the real
10616 	 * copy, allowing the safe copy to be freed and holding
10617 	 * on to the real copy for later use in indir_trunc.
10618 	 */
10619 	if (indirdep->ir_state & GOINGAWAY)
10620 		panic("cancel_indirdep: already gone");
10621 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10622 		indirdep->ir_state |= DEPCOMPLETE;
10623 		LIST_REMOVE(indirdep, ir_next);
10624 	}
10625 	indirdep->ir_state |= GOINGAWAY;
10626 	/*
10627 	 * Pass in bp for blocks still have journal writes
10628 	 * pending so we can cancel them on their own.
10629 	 */
10630 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10631 		cancel_allocindir(aip, bp, freeblks, 0);
10632 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10633 		cancel_allocindir(aip, NULL, freeblks, 0);
10634 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10635 		cancel_allocindir(aip, NULL, freeblks, 0);
10636 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10637 		cancel_allocindir(aip, NULL, freeblks, 0);
10638 	/*
10639 	 * If there are pending partial truncations we need to keep the
10640 	 * old block copy around until they complete.  This is because
10641 	 * the current b_data is not a perfect superset of the available
10642 	 * blocks.
10643 	 */
10644 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10645 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10646 	else
10647 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10648 	WORKLIST_REMOVE(&indirdep->ir_list);
10649 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10650 	indirdep->ir_bp = NULL;
10651 	indirdep->ir_freeblks = freeblks;
10652 }
10653 
10654 /*
10655  * Free an indirdep once it no longer has new pointers to track.
10656  */
10657 static void
10658 free_indirdep(indirdep)
10659 	struct indirdep *indirdep;
10660 {
10661 
10662 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10663 	    ("free_indirdep: Indir trunc list not empty."));
10664 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10665 	    ("free_indirdep: Complete head not empty."));
10666 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10667 	    ("free_indirdep: write head not empty."));
10668 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10669 	    ("free_indirdep: done head not empty."));
10670 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10671 	    ("free_indirdep: deplist head not empty."));
10672 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10673 	    ("free_indirdep: %p still on newblk list.", indirdep));
10674 	KASSERT(indirdep->ir_saveddata == NULL,
10675 	    ("free_indirdep: %p still has saved data.", indirdep));
10676 	if (indirdep->ir_state & ONWORKLIST)
10677 		WORKLIST_REMOVE(&indirdep->ir_list);
10678 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10679 }
10680 
10681 /*
10682  * Called before a write to an indirdep.  This routine is responsible for
10683  * rolling back pointers to a safe state which includes only those
10684  * allocindirs which have been completed.
10685  */
10686 static void
10687 initiate_write_indirdep(indirdep, bp)
10688 	struct indirdep *indirdep;
10689 	struct buf *bp;
10690 {
10691 	struct ufsmount *ump;
10692 
10693 	indirdep->ir_state |= IOSTARTED;
10694 	if (indirdep->ir_state & GOINGAWAY)
10695 		panic("disk_io_initiation: indirdep gone");
10696 	/*
10697 	 * If there are no remaining dependencies, this will be writing
10698 	 * the real pointers.
10699 	 */
10700 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10701 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10702 		return;
10703 	/*
10704 	 * Replace up-to-date version with safe version.
10705 	 */
10706 	if (indirdep->ir_saveddata == NULL) {
10707 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10708 		LOCK_OWNED(ump);
10709 		FREE_LOCK(ump);
10710 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10711 		    M_SOFTDEP_FLAGS);
10712 		ACQUIRE_LOCK(ump);
10713 	}
10714 	indirdep->ir_state &= ~ATTACHED;
10715 	indirdep->ir_state |= UNDONE;
10716 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10717 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10718 	    bp->b_bcount);
10719 }
10720 
10721 /*
10722  * Called when an inode has been cleared in a cg bitmap.  This finally
10723  * eliminates any canceled jaddrefs
10724  */
10725 void
10726 softdep_setup_inofree(mp, bp, ino, wkhd)
10727 	struct mount *mp;
10728 	struct buf *bp;
10729 	ino_t ino;
10730 	struct workhead *wkhd;
10731 {
10732 	struct worklist *wk, *wkn;
10733 	struct inodedep *inodedep;
10734 	struct ufsmount *ump;
10735 	uint8_t *inosused;
10736 	struct cg *cgp;
10737 	struct fs *fs;
10738 
10739 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10740 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10741 	ump = VFSTOUFS(mp);
10742 	ACQUIRE_LOCK(ump);
10743 	fs = ump->um_fs;
10744 	cgp = (struct cg *)bp->b_data;
10745 	inosused = cg_inosused(cgp);
10746 	if (isset(inosused, ino % fs->fs_ipg))
10747 		panic("softdep_setup_inofree: inode %ju not freed.",
10748 		    (uintmax_t)ino);
10749 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10750 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10751 		    (uintmax_t)ino, inodedep);
10752 	if (wkhd) {
10753 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10754 			if (wk->wk_type != D_JADDREF)
10755 				continue;
10756 			WORKLIST_REMOVE(wk);
10757 			/*
10758 			 * We can free immediately even if the jaddref
10759 			 * isn't attached in a background write as now
10760 			 * the bitmaps are reconciled.
10761 			 */
10762 			wk->wk_state |= COMPLETE | ATTACHED;
10763 			free_jaddref(WK_JADDREF(wk));
10764 		}
10765 		jwork_move(&bp->b_dep, wkhd);
10766 	}
10767 	FREE_LOCK(ump);
10768 }
10769 
10770 
10771 /*
10772  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10773  * map.  Any dependencies waiting for the write to clear are added to the
10774  * buf's list and any jnewblks that are being canceled are discarded
10775  * immediately.
10776  */
10777 void
10778 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10779 	struct mount *mp;
10780 	struct buf *bp;
10781 	ufs2_daddr_t blkno;
10782 	int frags;
10783 	struct workhead *wkhd;
10784 {
10785 	struct bmsafemap *bmsafemap;
10786 	struct jnewblk *jnewblk;
10787 	struct ufsmount *ump;
10788 	struct worklist *wk;
10789 	struct fs *fs;
10790 #ifdef SUJ_DEBUG
10791 	uint8_t *blksfree;
10792 	struct cg *cgp;
10793 	ufs2_daddr_t jstart;
10794 	ufs2_daddr_t jend;
10795 	ufs2_daddr_t end;
10796 	long bno;
10797 	int i;
10798 #endif
10799 
10800 	CTR3(KTR_SUJ,
10801 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10802 	    blkno, frags, wkhd);
10803 
10804 	ump = VFSTOUFS(mp);
10805 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10806 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10807 	ACQUIRE_LOCK(ump);
10808 	/* Lookup the bmsafemap so we track when it is dirty. */
10809 	fs = ump->um_fs;
10810 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10811 	/*
10812 	 * Detach any jnewblks which have been canceled.  They must linger
10813 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10814 	 * an unjournaled allocation from hitting the disk.
10815 	 */
10816 	if (wkhd) {
10817 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10818 			CTR2(KTR_SUJ,
10819 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10820 			    blkno, wk->wk_type);
10821 			WORKLIST_REMOVE(wk);
10822 			if (wk->wk_type != D_JNEWBLK) {
10823 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10824 				continue;
10825 			}
10826 			jnewblk = WK_JNEWBLK(wk);
10827 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10828 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10829 #ifdef SUJ_DEBUG
10830 			/*
10831 			 * Assert that this block is free in the bitmap
10832 			 * before we discard the jnewblk.
10833 			 */
10834 			cgp = (struct cg *)bp->b_data;
10835 			blksfree = cg_blksfree(cgp);
10836 			bno = dtogd(fs, jnewblk->jn_blkno);
10837 			for (i = jnewblk->jn_oldfrags;
10838 			    i < jnewblk->jn_frags; i++) {
10839 				if (isset(blksfree, bno + i))
10840 					continue;
10841 				panic("softdep_setup_blkfree: not free");
10842 			}
10843 #endif
10844 			/*
10845 			 * Even if it's not attached we can free immediately
10846 			 * as the new bitmap is correct.
10847 			 */
10848 			wk->wk_state |= COMPLETE | ATTACHED;
10849 			free_jnewblk(jnewblk);
10850 		}
10851 	}
10852 
10853 #ifdef SUJ_DEBUG
10854 	/*
10855 	 * Assert that we are not freeing a block which has an outstanding
10856 	 * allocation dependency.
10857 	 */
10858 	fs = VFSTOUFS(mp)->um_fs;
10859 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10860 	end = blkno + frags;
10861 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10862 		/*
10863 		 * Don't match against blocks that will be freed when the
10864 		 * background write is done.
10865 		 */
10866 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10867 		    (COMPLETE | DEPCOMPLETE))
10868 			continue;
10869 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10870 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10871 		if ((blkno >= jstart && blkno < jend) ||
10872 		    (end > jstart && end <= jend)) {
10873 			printf("state 0x%X %jd - %d %d dep %p\n",
10874 			    jnewblk->jn_state, jnewblk->jn_blkno,
10875 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10876 			    jnewblk->jn_dep);
10877 			panic("softdep_setup_blkfree: "
10878 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10879 			    blkno, end, frags, jstart, jend);
10880 		}
10881 	}
10882 #endif
10883 	FREE_LOCK(ump);
10884 }
10885 
10886 /*
10887  * Revert a block allocation when the journal record that describes it
10888  * is not yet written.
10889  */
10890 static int
10891 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10892 	struct jnewblk *jnewblk;
10893 	struct fs *fs;
10894 	struct cg *cgp;
10895 	uint8_t *blksfree;
10896 {
10897 	ufs1_daddr_t fragno;
10898 	long cgbno, bbase;
10899 	int frags, blk;
10900 	int i;
10901 
10902 	frags = 0;
10903 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10904 	/*
10905 	 * We have to test which frags need to be rolled back.  We may
10906 	 * be operating on a stale copy when doing background writes.
10907 	 */
10908 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10909 		if (isclr(blksfree, cgbno + i))
10910 			frags++;
10911 	if (frags == 0)
10912 		return (0);
10913 	/*
10914 	 * This is mostly ffs_blkfree() sans some validation and
10915 	 * superblock updates.
10916 	 */
10917 	if (frags == fs->fs_frag) {
10918 		fragno = fragstoblks(fs, cgbno);
10919 		ffs_setblock(fs, blksfree, fragno);
10920 		ffs_clusteracct(fs, cgp, fragno, 1);
10921 		cgp->cg_cs.cs_nbfree++;
10922 	} else {
10923 		cgbno += jnewblk->jn_oldfrags;
10924 		bbase = cgbno - fragnum(fs, cgbno);
10925 		/* Decrement the old frags.  */
10926 		blk = blkmap(fs, blksfree, bbase);
10927 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10928 		/* Deallocate the fragment */
10929 		for (i = 0; i < frags; i++)
10930 			setbit(blksfree, cgbno + i);
10931 		cgp->cg_cs.cs_nffree += frags;
10932 		/* Add back in counts associated with the new frags */
10933 		blk = blkmap(fs, blksfree, bbase);
10934 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10935 		/* If a complete block has been reassembled, account for it. */
10936 		fragno = fragstoblks(fs, bbase);
10937 		if (ffs_isblock(fs, blksfree, fragno)) {
10938 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10939 			ffs_clusteracct(fs, cgp, fragno, 1);
10940 			cgp->cg_cs.cs_nbfree++;
10941 		}
10942 	}
10943 	stat_jnewblk++;
10944 	jnewblk->jn_state &= ~ATTACHED;
10945 	jnewblk->jn_state |= UNDONE;
10946 
10947 	return (frags);
10948 }
10949 
10950 static void
10951 initiate_write_bmsafemap(bmsafemap, bp)
10952 	struct bmsafemap *bmsafemap;
10953 	struct buf *bp;			/* The cg block. */
10954 {
10955 	struct jaddref *jaddref;
10956 	struct jnewblk *jnewblk;
10957 	uint8_t *inosused;
10958 	uint8_t *blksfree;
10959 	struct cg *cgp;
10960 	struct fs *fs;
10961 	ino_t ino;
10962 
10963 	/*
10964 	 * If this is a background write, we did this at the time that
10965 	 * the copy was made, so do not need to do it again.
10966 	 */
10967 	if (bmsafemap->sm_state & IOSTARTED)
10968 		return;
10969 	bmsafemap->sm_state |= IOSTARTED;
10970 	/*
10971 	 * Clear any inode allocations which are pending journal writes.
10972 	 */
10973 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10974 		cgp = (struct cg *)bp->b_data;
10975 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10976 		inosused = cg_inosused(cgp);
10977 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10978 			ino = jaddref->ja_ino % fs->fs_ipg;
10979 			if (isset(inosused, ino)) {
10980 				if ((jaddref->ja_mode & IFMT) == IFDIR)
10981 					cgp->cg_cs.cs_ndir--;
10982 				cgp->cg_cs.cs_nifree++;
10983 				clrbit(inosused, ino);
10984 				jaddref->ja_state &= ~ATTACHED;
10985 				jaddref->ja_state |= UNDONE;
10986 				stat_jaddref++;
10987 			} else
10988 				panic("initiate_write_bmsafemap: inode %ju "
10989 				    "marked free", (uintmax_t)jaddref->ja_ino);
10990 		}
10991 	}
10992 	/*
10993 	 * Clear any block allocations which are pending journal writes.
10994 	 */
10995 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10996 		cgp = (struct cg *)bp->b_data;
10997 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10998 		blksfree = cg_blksfree(cgp);
10999 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11000 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11001 				continue;
11002 			panic("initiate_write_bmsafemap: block %jd "
11003 			    "marked free", jnewblk->jn_blkno);
11004 		}
11005 	}
11006 	/*
11007 	 * Move allocation lists to the written lists so they can be
11008 	 * cleared once the block write is complete.
11009 	 */
11010 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11011 	    inodedep, id_deps);
11012 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11013 	    newblk, nb_deps);
11014 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11015 	    wk_list);
11016 }
11017 
11018 /*
11019  * This routine is called during the completion interrupt
11020  * service routine for a disk write (from the procedure called
11021  * by the device driver to inform the filesystem caches of
11022  * a request completion).  It should be called early in this
11023  * procedure, before the block is made available to other
11024  * processes or other routines are called.
11025  *
11026  */
11027 static void
11028 softdep_disk_write_complete(bp)
11029 	struct buf *bp;		/* describes the completed disk write */
11030 {
11031 	struct worklist *wk;
11032 	struct worklist *owk;
11033 	struct ufsmount *ump;
11034 	struct workhead reattach;
11035 	struct freeblks *freeblks;
11036 	struct buf *sbp;
11037 
11038 	ump = softdep_bp_to_mp(bp);
11039 	if (ump == NULL)
11040 		return;
11041 
11042 	sbp = NULL;
11043 
11044 	/*
11045 	 * If an error occurred while doing the write, then the data
11046 	 * has not hit the disk and the dependencies cannot be processed.
11047 	 * But we do have to go through and roll forward any dependencies
11048 	 * that were rolled back before the disk write.
11049 	 */
11050 	ACQUIRE_LOCK(ump);
11051 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11052 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11053 			switch (wk->wk_type) {
11054 
11055 			case D_PAGEDEP:
11056 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11057 				continue;
11058 
11059 			case D_INODEDEP:
11060 				handle_written_inodeblock(WK_INODEDEP(wk),
11061 				    bp, 0);
11062 				continue;
11063 
11064 			case D_BMSAFEMAP:
11065 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11066 				    bp, 0);
11067 				continue;
11068 
11069 			case D_INDIRDEP:
11070 				handle_written_indirdep(WK_INDIRDEP(wk),
11071 				    bp, &sbp, 0);
11072 				continue;
11073 			default:
11074 				/* nothing to roll forward */
11075 				continue;
11076 			}
11077 		}
11078 		FREE_LOCK(ump);
11079 		return;
11080 	}
11081 	LIST_INIT(&reattach);
11082 
11083 	/*
11084 	 * Ump SU lock must not be released anywhere in this code segment.
11085 	 */
11086 	owk = NULL;
11087 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11088 		WORKLIST_REMOVE(wk);
11089 		atomic_add_long(&dep_write[wk->wk_type], 1);
11090 		if (wk == owk)
11091 			panic("duplicate worklist: %p\n", wk);
11092 		owk = wk;
11093 		switch (wk->wk_type) {
11094 
11095 		case D_PAGEDEP:
11096 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11097 			    WRITESUCCEEDED))
11098 				WORKLIST_INSERT(&reattach, wk);
11099 			continue;
11100 
11101 		case D_INODEDEP:
11102 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11103 			    WRITESUCCEEDED))
11104 				WORKLIST_INSERT(&reattach, wk);
11105 			continue;
11106 
11107 		case D_BMSAFEMAP:
11108 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11109 			    WRITESUCCEEDED))
11110 				WORKLIST_INSERT(&reattach, wk);
11111 			continue;
11112 
11113 		case D_MKDIR:
11114 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11115 			continue;
11116 
11117 		case D_ALLOCDIRECT:
11118 			wk->wk_state |= COMPLETE;
11119 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11120 			continue;
11121 
11122 		case D_ALLOCINDIR:
11123 			wk->wk_state |= COMPLETE;
11124 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11125 			continue;
11126 
11127 		case D_INDIRDEP:
11128 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11129 			    WRITESUCCEEDED))
11130 				WORKLIST_INSERT(&reattach, wk);
11131 			continue;
11132 
11133 		case D_FREEBLKS:
11134 			wk->wk_state |= COMPLETE;
11135 			freeblks = WK_FREEBLKS(wk);
11136 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11137 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11138 				add_to_worklist(wk, WK_NODELAY);
11139 			continue;
11140 
11141 		case D_FREEWORK:
11142 			handle_written_freework(WK_FREEWORK(wk));
11143 			break;
11144 
11145 		case D_JSEGDEP:
11146 			free_jsegdep(WK_JSEGDEP(wk));
11147 			continue;
11148 
11149 		case D_JSEG:
11150 			handle_written_jseg(WK_JSEG(wk), bp);
11151 			continue;
11152 
11153 		case D_SBDEP:
11154 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11155 				WORKLIST_INSERT(&reattach, wk);
11156 			continue;
11157 
11158 		case D_FREEDEP:
11159 			free_freedep(WK_FREEDEP(wk));
11160 			continue;
11161 
11162 		default:
11163 			panic("handle_disk_write_complete: Unknown type %s",
11164 			    TYPENAME(wk->wk_type));
11165 			/* NOTREACHED */
11166 		}
11167 	}
11168 	/*
11169 	 * Reattach any requests that must be redone.
11170 	 */
11171 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11172 		WORKLIST_REMOVE(wk);
11173 		WORKLIST_INSERT(&bp->b_dep, wk);
11174 	}
11175 	FREE_LOCK(ump);
11176 	if (sbp)
11177 		brelse(sbp);
11178 }
11179 
11180 /*
11181  * Called from within softdep_disk_write_complete above. Note that
11182  * this routine is always called from interrupt level with further
11183  * splbio interrupts blocked.
11184  */
11185 static void
11186 handle_allocdirect_partdone(adp, wkhd)
11187 	struct allocdirect *adp;	/* the completed allocdirect */
11188 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11189 {
11190 	struct allocdirectlst *listhead;
11191 	struct allocdirect *listadp;
11192 	struct inodedep *inodedep;
11193 	long bsize;
11194 
11195 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11196 		return;
11197 	/*
11198 	 * The on-disk inode cannot claim to be any larger than the last
11199 	 * fragment that has been written. Otherwise, the on-disk inode
11200 	 * might have fragments that were not the last block in the file
11201 	 * which would corrupt the filesystem. Thus, we cannot free any
11202 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11203 	 * these blocks must be rolled back to zero before writing the inode.
11204 	 * We check the currently active set of allocdirects in id_inoupdt
11205 	 * or id_extupdt as appropriate.
11206 	 */
11207 	inodedep = adp->ad_inodedep;
11208 	bsize = inodedep->id_fs->fs_bsize;
11209 	if (adp->ad_state & EXTDATA)
11210 		listhead = &inodedep->id_extupdt;
11211 	else
11212 		listhead = &inodedep->id_inoupdt;
11213 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11214 		/* found our block */
11215 		if (listadp == adp)
11216 			break;
11217 		/* continue if ad_oldlbn is not a fragment */
11218 		if (listadp->ad_oldsize == 0 ||
11219 		    listadp->ad_oldsize == bsize)
11220 			continue;
11221 		/* hit a fragment */
11222 		return;
11223 	}
11224 	/*
11225 	 * If we have reached the end of the current list without
11226 	 * finding the just finished dependency, then it must be
11227 	 * on the future dependency list. Future dependencies cannot
11228 	 * be freed until they are moved to the current list.
11229 	 */
11230 	if (listadp == NULL) {
11231 #ifdef DEBUG
11232 		if (adp->ad_state & EXTDATA)
11233 			listhead = &inodedep->id_newextupdt;
11234 		else
11235 			listhead = &inodedep->id_newinoupdt;
11236 		TAILQ_FOREACH(listadp, listhead, ad_next)
11237 			/* found our block */
11238 			if (listadp == adp)
11239 				break;
11240 		if (listadp == NULL)
11241 			panic("handle_allocdirect_partdone: lost dep");
11242 #endif /* DEBUG */
11243 		return;
11244 	}
11245 	/*
11246 	 * If we have found the just finished dependency, then queue
11247 	 * it along with anything that follows it that is complete.
11248 	 * Since the pointer has not yet been written in the inode
11249 	 * as the dependency prevents it, place the allocdirect on the
11250 	 * bufwait list where it will be freed once the pointer is
11251 	 * valid.
11252 	 */
11253 	if (wkhd == NULL)
11254 		wkhd = &inodedep->id_bufwait;
11255 	for (; adp; adp = listadp) {
11256 		listadp = TAILQ_NEXT(adp, ad_next);
11257 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11258 			return;
11259 		TAILQ_REMOVE(listhead, adp, ad_next);
11260 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11261 	}
11262 }
11263 
11264 /*
11265  * Called from within softdep_disk_write_complete above.  This routine
11266  * completes successfully written allocindirs.
11267  */
11268 static void
11269 handle_allocindir_partdone(aip)
11270 	struct allocindir *aip;		/* the completed allocindir */
11271 {
11272 	struct indirdep *indirdep;
11273 
11274 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11275 		return;
11276 	indirdep = aip->ai_indirdep;
11277 	LIST_REMOVE(aip, ai_next);
11278 	/*
11279 	 * Don't set a pointer while the buffer is undergoing IO or while
11280 	 * we have active truncations.
11281 	 */
11282 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11283 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11284 		return;
11285 	}
11286 	if (indirdep->ir_state & UFS1FMT)
11287 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11288 		    aip->ai_newblkno;
11289 	else
11290 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11291 		    aip->ai_newblkno;
11292 	/*
11293 	 * Await the pointer write before freeing the allocindir.
11294 	 */
11295 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11296 }
11297 
11298 /*
11299  * Release segments held on a jwork list.
11300  */
11301 static void
11302 handle_jwork(wkhd)
11303 	struct workhead *wkhd;
11304 {
11305 	struct worklist *wk;
11306 
11307 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11308 		WORKLIST_REMOVE(wk);
11309 		switch (wk->wk_type) {
11310 		case D_JSEGDEP:
11311 			free_jsegdep(WK_JSEGDEP(wk));
11312 			continue;
11313 		case D_FREEDEP:
11314 			free_freedep(WK_FREEDEP(wk));
11315 			continue;
11316 		case D_FREEFRAG:
11317 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11318 			WORKITEM_FREE(wk, D_FREEFRAG);
11319 			continue;
11320 		case D_FREEWORK:
11321 			handle_written_freework(WK_FREEWORK(wk));
11322 			continue;
11323 		default:
11324 			panic("handle_jwork: Unknown type %s\n",
11325 			    TYPENAME(wk->wk_type));
11326 		}
11327 	}
11328 }
11329 
11330 /*
11331  * Handle the bufwait list on an inode when it is safe to release items
11332  * held there.  This normally happens after an inode block is written but
11333  * may be delayed and handled later if there are pending journal items that
11334  * are not yet safe to be released.
11335  */
11336 static struct freefile *
11337 handle_bufwait(inodedep, refhd)
11338 	struct inodedep *inodedep;
11339 	struct workhead *refhd;
11340 {
11341 	struct jaddref *jaddref;
11342 	struct freefile *freefile;
11343 	struct worklist *wk;
11344 
11345 	freefile = NULL;
11346 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11347 		WORKLIST_REMOVE(wk);
11348 		switch (wk->wk_type) {
11349 		case D_FREEFILE:
11350 			/*
11351 			 * We defer adding freefile to the worklist
11352 			 * until all other additions have been made to
11353 			 * ensure that it will be done after all the
11354 			 * old blocks have been freed.
11355 			 */
11356 			if (freefile != NULL)
11357 				panic("handle_bufwait: freefile");
11358 			freefile = WK_FREEFILE(wk);
11359 			continue;
11360 
11361 		case D_MKDIR:
11362 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11363 			continue;
11364 
11365 		case D_DIRADD:
11366 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11367 			continue;
11368 
11369 		case D_FREEFRAG:
11370 			wk->wk_state |= COMPLETE;
11371 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11372 				add_to_worklist(wk, 0);
11373 			continue;
11374 
11375 		case D_DIRREM:
11376 			wk->wk_state |= COMPLETE;
11377 			add_to_worklist(wk, 0);
11378 			continue;
11379 
11380 		case D_ALLOCDIRECT:
11381 		case D_ALLOCINDIR:
11382 			free_newblk(WK_NEWBLK(wk));
11383 			continue;
11384 
11385 		case D_JNEWBLK:
11386 			wk->wk_state |= COMPLETE;
11387 			free_jnewblk(WK_JNEWBLK(wk));
11388 			continue;
11389 
11390 		/*
11391 		 * Save freed journal segments and add references on
11392 		 * the supplied list which will delay their release
11393 		 * until the cg bitmap is cleared on disk.
11394 		 */
11395 		case D_JSEGDEP:
11396 			if (refhd == NULL)
11397 				free_jsegdep(WK_JSEGDEP(wk));
11398 			else
11399 				WORKLIST_INSERT(refhd, wk);
11400 			continue;
11401 
11402 		case D_JADDREF:
11403 			jaddref = WK_JADDREF(wk);
11404 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11405 			    if_deps);
11406 			/*
11407 			 * Transfer any jaddrefs to the list to be freed with
11408 			 * the bitmap if we're handling a removed file.
11409 			 */
11410 			if (refhd == NULL) {
11411 				wk->wk_state |= COMPLETE;
11412 				free_jaddref(jaddref);
11413 			} else
11414 				WORKLIST_INSERT(refhd, wk);
11415 			continue;
11416 
11417 		default:
11418 			panic("handle_bufwait: Unknown type %p(%s)",
11419 			    wk, TYPENAME(wk->wk_type));
11420 			/* NOTREACHED */
11421 		}
11422 	}
11423 	return (freefile);
11424 }
11425 /*
11426  * Called from within softdep_disk_write_complete above to restore
11427  * in-memory inode block contents to their most up-to-date state. Note
11428  * that this routine is always called from interrupt level with further
11429  * interrupts from this device blocked.
11430  *
11431  * If the write did not succeed, we will do all the roll-forward
11432  * operations, but we will not take the actions that will allow its
11433  * dependencies to be processed.
11434  */
11435 static int
11436 handle_written_inodeblock(inodedep, bp, flags)
11437 	struct inodedep *inodedep;
11438 	struct buf *bp;		/* buffer containing the inode block */
11439 	int flags;
11440 {
11441 	struct freefile *freefile;
11442 	struct allocdirect *adp, *nextadp;
11443 	struct ufs1_dinode *dp1 = NULL;
11444 	struct ufs2_dinode *dp2 = NULL;
11445 	struct workhead wkhd;
11446 	int hadchanges, fstype;
11447 	ino_t freelink;
11448 
11449 	LIST_INIT(&wkhd);
11450 	hadchanges = 0;
11451 	freefile = NULL;
11452 	if ((inodedep->id_state & IOSTARTED) == 0)
11453 		panic("handle_written_inodeblock: not started");
11454 	inodedep->id_state &= ~IOSTARTED;
11455 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11456 		fstype = UFS1;
11457 		dp1 = (struct ufs1_dinode *)bp->b_data +
11458 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11459 		freelink = dp1->di_freelink;
11460 	} else {
11461 		fstype = UFS2;
11462 		dp2 = (struct ufs2_dinode *)bp->b_data +
11463 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11464 		freelink = dp2->di_freelink;
11465 	}
11466 	/*
11467 	 * Leave this inodeblock dirty until it's in the list.
11468 	 */
11469 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11470 	    (flags & WRITESUCCEEDED)) {
11471 		struct inodedep *inon;
11472 
11473 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11474 		if ((inon == NULL && freelink == 0) ||
11475 		    (inon && inon->id_ino == freelink)) {
11476 			if (inon)
11477 				inon->id_state |= UNLINKPREV;
11478 			inodedep->id_state |= UNLINKNEXT;
11479 		}
11480 		hadchanges = 1;
11481 	}
11482 	/*
11483 	 * If we had to rollback the inode allocation because of
11484 	 * bitmaps being incomplete, then simply restore it.
11485 	 * Keep the block dirty so that it will not be reclaimed until
11486 	 * all associated dependencies have been cleared and the
11487 	 * corresponding updates written to disk.
11488 	 */
11489 	if (inodedep->id_savedino1 != NULL) {
11490 		hadchanges = 1;
11491 		if (fstype == UFS1)
11492 			*dp1 = *inodedep->id_savedino1;
11493 		else
11494 			*dp2 = *inodedep->id_savedino2;
11495 		free(inodedep->id_savedino1, M_SAVEDINO);
11496 		inodedep->id_savedino1 = NULL;
11497 		if ((bp->b_flags & B_DELWRI) == 0)
11498 			stat_inode_bitmap++;
11499 		bdirty(bp);
11500 		/*
11501 		 * If the inode is clear here and GOINGAWAY it will never
11502 		 * be written.  Process the bufwait and clear any pending
11503 		 * work which may include the freefile.
11504 		 */
11505 		if (inodedep->id_state & GOINGAWAY)
11506 			goto bufwait;
11507 		return (1);
11508 	}
11509 	if (flags & WRITESUCCEEDED)
11510 		inodedep->id_state |= COMPLETE;
11511 	/*
11512 	 * Roll forward anything that had to be rolled back before
11513 	 * the inode could be updated.
11514 	 */
11515 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11516 		nextadp = TAILQ_NEXT(adp, ad_next);
11517 		if (adp->ad_state & ATTACHED)
11518 			panic("handle_written_inodeblock: new entry");
11519 		if (fstype == UFS1) {
11520 			if (adp->ad_offset < UFS_NDADDR) {
11521 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11522 					panic("%s %s #%jd mismatch %d != %jd",
11523 					    "handle_written_inodeblock:",
11524 					    "direct pointer",
11525 					    (intmax_t)adp->ad_offset,
11526 					    dp1->di_db[adp->ad_offset],
11527 					    (intmax_t)adp->ad_oldblkno);
11528 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11529 			} else {
11530 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11531 				    0)
11532 					panic("%s: %s #%jd allocated as %d",
11533 					    "handle_written_inodeblock",
11534 					    "indirect pointer",
11535 					    (intmax_t)adp->ad_offset -
11536 					    UFS_NDADDR,
11537 					    dp1->di_ib[adp->ad_offset -
11538 					    UFS_NDADDR]);
11539 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11540 				    adp->ad_newblkno;
11541 			}
11542 		} else {
11543 			if (adp->ad_offset < UFS_NDADDR) {
11544 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11545 					panic("%s: %s #%jd %s %jd != %jd",
11546 					    "handle_written_inodeblock",
11547 					    "direct pointer",
11548 					    (intmax_t)adp->ad_offset, "mismatch",
11549 					    (intmax_t)dp2->di_db[adp->ad_offset],
11550 					    (intmax_t)adp->ad_oldblkno);
11551 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11552 			} else {
11553 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11554 				    0)
11555 					panic("%s: %s #%jd allocated as %jd",
11556 					    "handle_written_inodeblock",
11557 					    "indirect pointer",
11558 					    (intmax_t)adp->ad_offset -
11559 					    UFS_NDADDR,
11560 					    (intmax_t)
11561 					    dp2->di_ib[adp->ad_offset -
11562 					    UFS_NDADDR]);
11563 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11564 				    adp->ad_newblkno;
11565 			}
11566 		}
11567 		adp->ad_state &= ~UNDONE;
11568 		adp->ad_state |= ATTACHED;
11569 		hadchanges = 1;
11570 	}
11571 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11572 		nextadp = TAILQ_NEXT(adp, ad_next);
11573 		if (adp->ad_state & ATTACHED)
11574 			panic("handle_written_inodeblock: new entry");
11575 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11576 			panic("%s: direct pointers #%jd %s %jd != %jd",
11577 			    "handle_written_inodeblock",
11578 			    (intmax_t)adp->ad_offset, "mismatch",
11579 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11580 			    (intmax_t)adp->ad_oldblkno);
11581 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11582 		adp->ad_state &= ~UNDONE;
11583 		adp->ad_state |= ATTACHED;
11584 		hadchanges = 1;
11585 	}
11586 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11587 		stat_direct_blk_ptrs++;
11588 	/*
11589 	 * Reset the file size to its most up-to-date value.
11590 	 */
11591 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11592 		panic("handle_written_inodeblock: bad size");
11593 	if (inodedep->id_savednlink > UFS_LINK_MAX)
11594 		panic("handle_written_inodeblock: Invalid link count "
11595 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11596 		    inodedep);
11597 	if (fstype == UFS1) {
11598 		if (dp1->di_nlink != inodedep->id_savednlink) {
11599 			dp1->di_nlink = inodedep->id_savednlink;
11600 			hadchanges = 1;
11601 		}
11602 		if (dp1->di_size != inodedep->id_savedsize) {
11603 			dp1->di_size = inodedep->id_savedsize;
11604 			hadchanges = 1;
11605 		}
11606 	} else {
11607 		if (dp2->di_nlink != inodedep->id_savednlink) {
11608 			dp2->di_nlink = inodedep->id_savednlink;
11609 			hadchanges = 1;
11610 		}
11611 		if (dp2->di_size != inodedep->id_savedsize) {
11612 			dp2->di_size = inodedep->id_savedsize;
11613 			hadchanges = 1;
11614 		}
11615 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11616 			dp2->di_extsize = inodedep->id_savedextsize;
11617 			hadchanges = 1;
11618 		}
11619 	}
11620 	inodedep->id_savedsize = -1;
11621 	inodedep->id_savedextsize = -1;
11622 	inodedep->id_savednlink = -1;
11623 	/*
11624 	 * If there were any rollbacks in the inode block, then it must be
11625 	 * marked dirty so that its will eventually get written back in
11626 	 * its correct form.
11627 	 */
11628 	if (hadchanges) {
11629 		if (fstype == UFS2)
11630 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11631 		bdirty(bp);
11632 	}
11633 bufwait:
11634 	/*
11635 	 * If the write did not succeed, we have done all the roll-forward
11636 	 * operations, but we cannot take the actions that will allow its
11637 	 * dependencies to be processed.
11638 	 */
11639 	if ((flags & WRITESUCCEEDED) == 0)
11640 		return (hadchanges);
11641 	/*
11642 	 * Process any allocdirects that completed during the update.
11643 	 */
11644 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11645 		handle_allocdirect_partdone(adp, &wkhd);
11646 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11647 		handle_allocdirect_partdone(adp, &wkhd);
11648 	/*
11649 	 * Process deallocations that were held pending until the
11650 	 * inode had been written to disk. Freeing of the inode
11651 	 * is delayed until after all blocks have been freed to
11652 	 * avoid creation of new <vfsid, inum, lbn> triples
11653 	 * before the old ones have been deleted.  Completely
11654 	 * unlinked inodes are not processed until the unlinked
11655 	 * inode list is written or the last reference is removed.
11656 	 */
11657 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11658 		freefile = handle_bufwait(inodedep, NULL);
11659 		if (freefile && !LIST_EMPTY(&wkhd)) {
11660 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11661 			freefile = NULL;
11662 		}
11663 	}
11664 	/*
11665 	 * Move rolled forward dependency completions to the bufwait list
11666 	 * now that those that were already written have been processed.
11667 	 */
11668 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11669 		panic("handle_written_inodeblock: bufwait but no changes");
11670 	jwork_move(&inodedep->id_bufwait, &wkhd);
11671 
11672 	if (freefile != NULL) {
11673 		/*
11674 		 * If the inode is goingaway it was never written.  Fake up
11675 		 * the state here so free_inodedep() can succeed.
11676 		 */
11677 		if (inodedep->id_state & GOINGAWAY)
11678 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11679 		if (free_inodedep(inodedep) == 0)
11680 			panic("handle_written_inodeblock: live inodedep %p",
11681 			    inodedep);
11682 		add_to_worklist(&freefile->fx_list, 0);
11683 		return (0);
11684 	}
11685 
11686 	/*
11687 	 * If no outstanding dependencies, free it.
11688 	 */
11689 	if (free_inodedep(inodedep) ||
11690 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11691 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11692 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11693 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11694 		return (0);
11695 	return (hadchanges);
11696 }
11697 
11698 /*
11699  * Perform needed roll-forwards and kick off any dependencies that
11700  * can now be processed.
11701  *
11702  * If the write did not succeed, we will do all the roll-forward
11703  * operations, but we will not take the actions that will allow its
11704  * dependencies to be processed.
11705  */
11706 static int
11707 handle_written_indirdep(indirdep, bp, bpp, flags)
11708 	struct indirdep *indirdep;
11709 	struct buf *bp;
11710 	struct buf **bpp;
11711 	int flags;
11712 {
11713 	struct allocindir *aip;
11714 	struct buf *sbp;
11715 	int chgs;
11716 
11717 	if (indirdep->ir_state & GOINGAWAY)
11718 		panic("handle_written_indirdep: indirdep gone");
11719 	if ((indirdep->ir_state & IOSTARTED) == 0)
11720 		panic("handle_written_indirdep: IO not started");
11721 	chgs = 0;
11722 	/*
11723 	 * If there were rollbacks revert them here.
11724 	 */
11725 	if (indirdep->ir_saveddata) {
11726 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11727 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11728 			free(indirdep->ir_saveddata, M_INDIRDEP);
11729 			indirdep->ir_saveddata = NULL;
11730 		}
11731 		chgs = 1;
11732 	}
11733 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11734 	indirdep->ir_state |= ATTACHED;
11735 	/*
11736 	 * If the write did not succeed, we have done all the roll-forward
11737 	 * operations, but we cannot take the actions that will allow its
11738 	 * dependencies to be processed.
11739 	 */
11740 	if ((flags & WRITESUCCEEDED) == 0) {
11741 		stat_indir_blk_ptrs++;
11742 		bdirty(bp);
11743 		return (1);
11744 	}
11745 	/*
11746 	 * Move allocindirs with written pointers to the completehd if
11747 	 * the indirdep's pointer is not yet written.  Otherwise
11748 	 * free them here.
11749 	 */
11750 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11751 		LIST_REMOVE(aip, ai_next);
11752 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11753 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11754 			    ai_next);
11755 			newblk_freefrag(&aip->ai_block);
11756 			continue;
11757 		}
11758 		free_newblk(&aip->ai_block);
11759 	}
11760 	/*
11761 	 * Move allocindirs that have finished dependency processing from
11762 	 * the done list to the write list after updating the pointers.
11763 	 */
11764 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11765 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11766 			handle_allocindir_partdone(aip);
11767 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11768 				panic("disk_write_complete: not gone");
11769 			chgs = 1;
11770 		}
11771 	}
11772 	/*
11773 	 * Preserve the indirdep if there were any changes or if it is not
11774 	 * yet valid on disk.
11775 	 */
11776 	if (chgs) {
11777 		stat_indir_blk_ptrs++;
11778 		bdirty(bp);
11779 		return (1);
11780 	}
11781 	/*
11782 	 * If there were no changes we can discard the savedbp and detach
11783 	 * ourselves from the buf.  We are only carrying completed pointers
11784 	 * in this case.
11785 	 */
11786 	sbp = indirdep->ir_savebp;
11787 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11788 	indirdep->ir_savebp = NULL;
11789 	indirdep->ir_bp = NULL;
11790 	if (*bpp != NULL)
11791 		panic("handle_written_indirdep: bp already exists.");
11792 	*bpp = sbp;
11793 	/*
11794 	 * The indirdep may not be freed until its parent points at it.
11795 	 */
11796 	if (indirdep->ir_state & DEPCOMPLETE)
11797 		free_indirdep(indirdep);
11798 
11799 	return (0);
11800 }
11801 
11802 /*
11803  * Process a diradd entry after its dependent inode has been written.
11804  * This routine must be called with splbio interrupts blocked.
11805  */
11806 static void
11807 diradd_inode_written(dap, inodedep)
11808 	struct diradd *dap;
11809 	struct inodedep *inodedep;
11810 {
11811 
11812 	dap->da_state |= COMPLETE;
11813 	complete_diradd(dap);
11814 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11815 }
11816 
11817 /*
11818  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11819  * be called with the per-filesystem lock and the buf lock on the cg held.
11820  */
11821 static int
11822 bmsafemap_backgroundwrite(bmsafemap, bp)
11823 	struct bmsafemap *bmsafemap;
11824 	struct buf *bp;
11825 {
11826 	int dirty;
11827 
11828 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11829 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11830 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11831 	/*
11832 	 * If we're initiating a background write we need to process the
11833 	 * rollbacks as they exist now, not as they exist when IO starts.
11834 	 * No other consumers will look at the contents of the shadowed
11835 	 * buf so this is safe to do here.
11836 	 */
11837 	if (bp->b_xflags & BX_BKGRDMARKER)
11838 		initiate_write_bmsafemap(bmsafemap, bp);
11839 
11840 	return (dirty);
11841 }
11842 
11843 /*
11844  * Re-apply an allocation when a cg write is complete.
11845  */
11846 static int
11847 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11848 	struct jnewblk *jnewblk;
11849 	struct fs *fs;
11850 	struct cg *cgp;
11851 	uint8_t *blksfree;
11852 {
11853 	ufs1_daddr_t fragno;
11854 	ufs2_daddr_t blkno;
11855 	long cgbno, bbase;
11856 	int frags, blk;
11857 	int i;
11858 
11859 	frags = 0;
11860 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11861 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11862 		if (isclr(blksfree, cgbno + i))
11863 			panic("jnewblk_rollforward: re-allocated fragment");
11864 		frags++;
11865 	}
11866 	if (frags == fs->fs_frag) {
11867 		blkno = fragstoblks(fs, cgbno);
11868 		ffs_clrblock(fs, blksfree, (long)blkno);
11869 		ffs_clusteracct(fs, cgp, blkno, -1);
11870 		cgp->cg_cs.cs_nbfree--;
11871 	} else {
11872 		bbase = cgbno - fragnum(fs, cgbno);
11873 		cgbno += jnewblk->jn_oldfrags;
11874                 /* If a complete block had been reassembled, account for it. */
11875 		fragno = fragstoblks(fs, bbase);
11876 		if (ffs_isblock(fs, blksfree, fragno)) {
11877 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11878 			ffs_clusteracct(fs, cgp, fragno, -1);
11879 			cgp->cg_cs.cs_nbfree--;
11880 		}
11881 		/* Decrement the old frags.  */
11882 		blk = blkmap(fs, blksfree, bbase);
11883 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11884 		/* Allocate the fragment */
11885 		for (i = 0; i < frags; i++)
11886 			clrbit(blksfree, cgbno + i);
11887 		cgp->cg_cs.cs_nffree -= frags;
11888 		/* Add back in counts associated with the new frags */
11889 		blk = blkmap(fs, blksfree, bbase);
11890 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11891 	}
11892 	return (frags);
11893 }
11894 
11895 /*
11896  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11897  * changes if it's not a background write.  Set all written dependencies
11898  * to DEPCOMPLETE and free the structure if possible.
11899  *
11900  * If the write did not succeed, we will do all the roll-forward
11901  * operations, but we will not take the actions that will allow its
11902  * dependencies to be processed.
11903  */
11904 static int
11905 handle_written_bmsafemap(bmsafemap, bp, flags)
11906 	struct bmsafemap *bmsafemap;
11907 	struct buf *bp;
11908 	int flags;
11909 {
11910 	struct newblk *newblk;
11911 	struct inodedep *inodedep;
11912 	struct jaddref *jaddref, *jatmp;
11913 	struct jnewblk *jnewblk, *jntmp;
11914 	struct ufsmount *ump;
11915 	uint8_t *inosused;
11916 	uint8_t *blksfree;
11917 	struct cg *cgp;
11918 	struct fs *fs;
11919 	ino_t ino;
11920 	int foreground;
11921 	int chgs;
11922 
11923 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11924 		panic("handle_written_bmsafemap: Not started\n");
11925 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11926 	chgs = 0;
11927 	bmsafemap->sm_state &= ~IOSTARTED;
11928 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11929 	/*
11930 	 * If write was successful, release journal work that was waiting
11931 	 * on the write. Otherwise move the work back.
11932 	 */
11933 	if (flags & WRITESUCCEEDED)
11934 		handle_jwork(&bmsafemap->sm_freewr);
11935 	else
11936 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11937 		    worklist, wk_list);
11938 
11939 	/*
11940 	 * Restore unwritten inode allocation pending jaddref writes.
11941 	 */
11942 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11943 		cgp = (struct cg *)bp->b_data;
11944 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11945 		inosused = cg_inosused(cgp);
11946 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11947 		    ja_bmdeps, jatmp) {
11948 			if ((jaddref->ja_state & UNDONE) == 0)
11949 				continue;
11950 			ino = jaddref->ja_ino % fs->fs_ipg;
11951 			if (isset(inosused, ino))
11952 				panic("handle_written_bmsafemap: "
11953 				    "re-allocated inode");
11954 			/* Do the roll-forward only if it's a real copy. */
11955 			if (foreground) {
11956 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11957 					cgp->cg_cs.cs_ndir++;
11958 				cgp->cg_cs.cs_nifree--;
11959 				setbit(inosused, ino);
11960 				chgs = 1;
11961 			}
11962 			jaddref->ja_state &= ~UNDONE;
11963 			jaddref->ja_state |= ATTACHED;
11964 			free_jaddref(jaddref);
11965 		}
11966 	}
11967 	/*
11968 	 * Restore any block allocations which are pending journal writes.
11969 	 */
11970 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11971 		cgp = (struct cg *)bp->b_data;
11972 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11973 		blksfree = cg_blksfree(cgp);
11974 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11975 		    jntmp) {
11976 			if ((jnewblk->jn_state & UNDONE) == 0)
11977 				continue;
11978 			/* Do the roll-forward only if it's a real copy. */
11979 			if (foreground &&
11980 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11981 				chgs = 1;
11982 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11983 			jnewblk->jn_state |= ATTACHED;
11984 			free_jnewblk(jnewblk);
11985 		}
11986 	}
11987 	/*
11988 	 * If the write did not succeed, we have done all the roll-forward
11989 	 * operations, but we cannot take the actions that will allow its
11990 	 * dependencies to be processed.
11991 	 */
11992 	if ((flags & WRITESUCCEEDED) == 0) {
11993 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11994 		    newblk, nb_deps);
11995 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11996 		    worklist, wk_list);
11997 		if (foreground)
11998 			bdirty(bp);
11999 		return (1);
12000 	}
12001 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12002 		newblk->nb_state |= DEPCOMPLETE;
12003 		newblk->nb_state &= ~ONDEPLIST;
12004 		newblk->nb_bmsafemap = NULL;
12005 		LIST_REMOVE(newblk, nb_deps);
12006 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12007 			handle_allocdirect_partdone(
12008 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12009 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12010 			handle_allocindir_partdone(
12011 			    WK_ALLOCINDIR(&newblk->nb_list));
12012 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12013 			panic("handle_written_bmsafemap: Unexpected type: %s",
12014 			    TYPENAME(newblk->nb_list.wk_type));
12015 	}
12016 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12017 		inodedep->id_state |= DEPCOMPLETE;
12018 		inodedep->id_state &= ~ONDEPLIST;
12019 		LIST_REMOVE(inodedep, id_deps);
12020 		inodedep->id_bmsafemap = NULL;
12021 	}
12022 	LIST_REMOVE(bmsafemap, sm_next);
12023 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12024 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12025 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12026 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12027 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12028 		LIST_REMOVE(bmsafemap, sm_hash);
12029 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12030 		return (0);
12031 	}
12032 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12033 	if (foreground)
12034 		bdirty(bp);
12035 	return (1);
12036 }
12037 
12038 /*
12039  * Try to free a mkdir dependency.
12040  */
12041 static void
12042 complete_mkdir(mkdir)
12043 	struct mkdir *mkdir;
12044 {
12045 	struct diradd *dap;
12046 
12047 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12048 		return;
12049 	LIST_REMOVE(mkdir, md_mkdirs);
12050 	dap = mkdir->md_diradd;
12051 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12052 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12053 		dap->da_state |= DEPCOMPLETE;
12054 		complete_diradd(dap);
12055 	}
12056 	WORKITEM_FREE(mkdir, D_MKDIR);
12057 }
12058 
12059 /*
12060  * Handle the completion of a mkdir dependency.
12061  */
12062 static void
12063 handle_written_mkdir(mkdir, type)
12064 	struct mkdir *mkdir;
12065 	int type;
12066 {
12067 
12068 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12069 		panic("handle_written_mkdir: bad type");
12070 	mkdir->md_state |= COMPLETE;
12071 	complete_mkdir(mkdir);
12072 }
12073 
12074 static int
12075 free_pagedep(pagedep)
12076 	struct pagedep *pagedep;
12077 {
12078 	int i;
12079 
12080 	if (pagedep->pd_state & NEWBLOCK)
12081 		return (0);
12082 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12083 		return (0);
12084 	for (i = 0; i < DAHASHSZ; i++)
12085 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12086 			return (0);
12087 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12088 		return (0);
12089 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12090 		return (0);
12091 	if (pagedep->pd_state & ONWORKLIST)
12092 		WORKLIST_REMOVE(&pagedep->pd_list);
12093 	LIST_REMOVE(pagedep, pd_hash);
12094 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12095 
12096 	return (1);
12097 }
12098 
12099 /*
12100  * Called from within softdep_disk_write_complete above.
12101  * A write operation was just completed. Removed inodes can
12102  * now be freed and associated block pointers may be committed.
12103  * Note that this routine is always called from interrupt level
12104  * with further interrupts from this device blocked.
12105  *
12106  * If the write did not succeed, we will do all the roll-forward
12107  * operations, but we will not take the actions that will allow its
12108  * dependencies to be processed.
12109  */
12110 static int
12111 handle_written_filepage(pagedep, bp, flags)
12112 	struct pagedep *pagedep;
12113 	struct buf *bp;		/* buffer containing the written page */
12114 	int flags;
12115 {
12116 	struct dirrem *dirrem;
12117 	struct diradd *dap, *nextdap;
12118 	struct direct *ep;
12119 	int i, chgs;
12120 
12121 	if ((pagedep->pd_state & IOSTARTED) == 0)
12122 		panic("handle_written_filepage: not started");
12123 	pagedep->pd_state &= ~IOSTARTED;
12124 	if ((flags & WRITESUCCEEDED) == 0)
12125 		goto rollforward;
12126 	/*
12127 	 * Process any directory removals that have been committed.
12128 	 */
12129 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12130 		LIST_REMOVE(dirrem, dm_next);
12131 		dirrem->dm_state |= COMPLETE;
12132 		dirrem->dm_dirinum = pagedep->pd_ino;
12133 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12134 		    ("handle_written_filepage: Journal entries not written."));
12135 		add_to_worklist(&dirrem->dm_list, 0);
12136 	}
12137 	/*
12138 	 * Free any directory additions that have been committed.
12139 	 * If it is a newly allocated block, we have to wait until
12140 	 * the on-disk directory inode claims the new block.
12141 	 */
12142 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12143 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12144 			free_diradd(dap, NULL);
12145 rollforward:
12146 	/*
12147 	 * Uncommitted directory entries must be restored.
12148 	 */
12149 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12150 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12151 		     dap = nextdap) {
12152 			nextdap = LIST_NEXT(dap, da_pdlist);
12153 			if (dap->da_state & ATTACHED)
12154 				panic("handle_written_filepage: attached");
12155 			ep = (struct direct *)
12156 			    ((char *)bp->b_data + dap->da_offset);
12157 			ep->d_ino = dap->da_newinum;
12158 			dap->da_state &= ~UNDONE;
12159 			dap->da_state |= ATTACHED;
12160 			chgs = 1;
12161 			/*
12162 			 * If the inode referenced by the directory has
12163 			 * been written out, then the dependency can be
12164 			 * moved to the pending list.
12165 			 */
12166 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12167 				LIST_REMOVE(dap, da_pdlist);
12168 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12169 				    da_pdlist);
12170 			}
12171 		}
12172 	}
12173 	/*
12174 	 * If there were any rollbacks in the directory, then it must be
12175 	 * marked dirty so that its will eventually get written back in
12176 	 * its correct form.
12177 	 */
12178 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12179 		if ((bp->b_flags & B_DELWRI) == 0)
12180 			stat_dir_entry++;
12181 		bdirty(bp);
12182 		return (1);
12183 	}
12184 	/*
12185 	 * If we are not waiting for a new directory block to be
12186 	 * claimed by its inode, then the pagedep will be freed.
12187 	 * Otherwise it will remain to track any new entries on
12188 	 * the page in case they are fsync'ed.
12189 	 */
12190 	free_pagedep(pagedep);
12191 	return (0);
12192 }
12193 
12194 /*
12195  * Writing back in-core inode structures.
12196  *
12197  * The filesystem only accesses an inode's contents when it occupies an
12198  * "in-core" inode structure.  These "in-core" structures are separate from
12199  * the page frames used to cache inode blocks.  Only the latter are
12200  * transferred to/from the disk.  So, when the updated contents of the
12201  * "in-core" inode structure are copied to the corresponding in-memory inode
12202  * block, the dependencies are also transferred.  The following procedure is
12203  * called when copying a dirty "in-core" inode to a cached inode block.
12204  */
12205 
12206 /*
12207  * Called when an inode is loaded from disk. If the effective link count
12208  * differed from the actual link count when it was last flushed, then we
12209  * need to ensure that the correct effective link count is put back.
12210  */
12211 void
12212 softdep_load_inodeblock(ip)
12213 	struct inode *ip;	/* the "in_core" copy of the inode */
12214 {
12215 	struct inodedep *inodedep;
12216 	struct ufsmount *ump;
12217 
12218 	ump = ITOUMP(ip);
12219 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12220 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12221 	/*
12222 	 * Check for alternate nlink count.
12223 	 */
12224 	ip->i_effnlink = ip->i_nlink;
12225 	ACQUIRE_LOCK(ump);
12226 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12227 		FREE_LOCK(ump);
12228 		return;
12229 	}
12230 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12231 	FREE_LOCK(ump);
12232 }
12233 
12234 /*
12235  * This routine is called just before the "in-core" inode
12236  * information is to be copied to the in-memory inode block.
12237  * Recall that an inode block contains several inodes. If
12238  * the force flag is set, then the dependencies will be
12239  * cleared so that the update can always be made. Note that
12240  * the buffer is locked when this routine is called, so we
12241  * will never be in the middle of writing the inode block
12242  * to disk.
12243  */
12244 void
12245 softdep_update_inodeblock(ip, bp, waitfor)
12246 	struct inode *ip;	/* the "in_core" copy of the inode */
12247 	struct buf *bp;		/* the buffer containing the inode block */
12248 	int waitfor;		/* nonzero => update must be allowed */
12249 {
12250 	struct inodedep *inodedep;
12251 	struct inoref *inoref;
12252 	struct ufsmount *ump;
12253 	struct worklist *wk;
12254 	struct mount *mp;
12255 	struct buf *ibp;
12256 	struct fs *fs;
12257 	int error;
12258 
12259 	ump = ITOUMP(ip);
12260 	mp = UFSTOVFS(ump);
12261 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12262 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12263 	fs = ump->um_fs;
12264 	/*
12265 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12266 	 * does not have access to the in-core ip so must write directly into
12267 	 * the inode block buffer when setting freelink.
12268 	 */
12269 	if (fs->fs_magic == FS_UFS1_MAGIC)
12270 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12271 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12272 	else
12273 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12274 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12275 	/*
12276 	 * If the effective link count is not equal to the actual link
12277 	 * count, then we must track the difference in an inodedep while
12278 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12279 	 * if there is no existing inodedep, then there are no dependencies
12280 	 * to track.
12281 	 */
12282 	ACQUIRE_LOCK(ump);
12283 again:
12284 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12285 		FREE_LOCK(ump);
12286 		if (ip->i_effnlink != ip->i_nlink)
12287 			panic("softdep_update_inodeblock: bad link count");
12288 		return;
12289 	}
12290 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12291 		panic("softdep_update_inodeblock: bad delta");
12292 	/*
12293 	 * If we're flushing all dependencies we must also move any waiting
12294 	 * for journal writes onto the bufwait list prior to I/O.
12295 	 */
12296 	if (waitfor) {
12297 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12298 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12299 			    == DEPCOMPLETE) {
12300 				jwait(&inoref->if_list, MNT_WAIT);
12301 				goto again;
12302 			}
12303 		}
12304 	}
12305 	/*
12306 	 * Changes have been initiated. Anything depending on these
12307 	 * changes cannot occur until this inode has been written.
12308 	 */
12309 	inodedep->id_state &= ~COMPLETE;
12310 	if ((inodedep->id_state & ONWORKLIST) == 0)
12311 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12312 	/*
12313 	 * Any new dependencies associated with the incore inode must
12314 	 * now be moved to the list associated with the buffer holding
12315 	 * the in-memory copy of the inode. Once merged process any
12316 	 * allocdirects that are completed by the merger.
12317 	 */
12318 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12319 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12320 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12321 		    NULL);
12322 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12323 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12324 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12325 		    NULL);
12326 	/*
12327 	 * Now that the inode has been pushed into the buffer, the
12328 	 * operations dependent on the inode being written to disk
12329 	 * can be moved to the id_bufwait so that they will be
12330 	 * processed when the buffer I/O completes.
12331 	 */
12332 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12333 		WORKLIST_REMOVE(wk);
12334 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12335 	}
12336 	/*
12337 	 * Newly allocated inodes cannot be written until the bitmap
12338 	 * that allocates them have been written (indicated by
12339 	 * DEPCOMPLETE being set in id_state). If we are doing a
12340 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12341 	 * to be written so that the update can be done.
12342 	 */
12343 	if (waitfor == 0) {
12344 		FREE_LOCK(ump);
12345 		return;
12346 	}
12347 retry:
12348 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12349 		FREE_LOCK(ump);
12350 		return;
12351 	}
12352 	ibp = inodedep->id_bmsafemap->sm_buf;
12353 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12354 	if (ibp == NULL) {
12355 		/*
12356 		 * If ibp came back as NULL, the dependency could have been
12357 		 * freed while we slept.  Look it up again, and check to see
12358 		 * that it has completed.
12359 		 */
12360 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12361 			goto retry;
12362 		FREE_LOCK(ump);
12363 		return;
12364 	}
12365 	FREE_LOCK(ump);
12366 	if ((error = bwrite(ibp)) != 0)
12367 		softdep_error("softdep_update_inodeblock: bwrite", error);
12368 }
12369 
12370 /*
12371  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12372  * old inode dependency list (such as id_inoupdt). This routine must be
12373  * called with splbio interrupts blocked.
12374  */
12375 static void
12376 merge_inode_lists(newlisthead, oldlisthead)
12377 	struct allocdirectlst *newlisthead;
12378 	struct allocdirectlst *oldlisthead;
12379 {
12380 	struct allocdirect *listadp, *newadp;
12381 
12382 	newadp = TAILQ_FIRST(newlisthead);
12383 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12384 		if (listadp->ad_offset < newadp->ad_offset) {
12385 			listadp = TAILQ_NEXT(listadp, ad_next);
12386 			continue;
12387 		}
12388 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12389 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12390 		if (listadp->ad_offset == newadp->ad_offset) {
12391 			allocdirect_merge(oldlisthead, newadp,
12392 			    listadp);
12393 			listadp = newadp;
12394 		}
12395 		newadp = TAILQ_FIRST(newlisthead);
12396 	}
12397 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12398 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12399 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12400 	}
12401 }
12402 
12403 /*
12404  * If we are doing an fsync, then we must ensure that any directory
12405  * entries for the inode have been written after the inode gets to disk.
12406  */
12407 int
12408 softdep_fsync(vp)
12409 	struct vnode *vp;	/* the "in_core" copy of the inode */
12410 {
12411 	struct inodedep *inodedep;
12412 	struct pagedep *pagedep;
12413 	struct inoref *inoref;
12414 	struct ufsmount *ump;
12415 	struct worklist *wk;
12416 	struct diradd *dap;
12417 	struct mount *mp;
12418 	struct vnode *pvp;
12419 	struct inode *ip;
12420 	struct buf *bp;
12421 	struct fs *fs;
12422 	struct thread *td = curthread;
12423 	int error, flushparent, pagedep_new_block;
12424 	ino_t parentino;
12425 	ufs_lbn_t lbn;
12426 
12427 	ip = VTOI(vp);
12428 	mp = vp->v_mount;
12429 	ump = VFSTOUFS(mp);
12430 	fs = ump->um_fs;
12431 	if (MOUNTEDSOFTDEP(mp) == 0)
12432 		return (0);
12433 	ACQUIRE_LOCK(ump);
12434 restart:
12435 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12436 		FREE_LOCK(ump);
12437 		return (0);
12438 	}
12439 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12440 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12441 		    == DEPCOMPLETE) {
12442 			jwait(&inoref->if_list, MNT_WAIT);
12443 			goto restart;
12444 		}
12445 	}
12446 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12447 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12448 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12449 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12450 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12451 		panic("softdep_fsync: pending ops %p", inodedep);
12452 	for (error = 0, flushparent = 0; ; ) {
12453 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12454 			break;
12455 		if (wk->wk_type != D_DIRADD)
12456 			panic("softdep_fsync: Unexpected type %s",
12457 			    TYPENAME(wk->wk_type));
12458 		dap = WK_DIRADD(wk);
12459 		/*
12460 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12461 		 * dependency or is contained in a newly allocated block.
12462 		 */
12463 		if (dap->da_state & DIRCHG)
12464 			pagedep = dap->da_previous->dm_pagedep;
12465 		else
12466 			pagedep = dap->da_pagedep;
12467 		parentino = pagedep->pd_ino;
12468 		lbn = pagedep->pd_lbn;
12469 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12470 			panic("softdep_fsync: dirty");
12471 		if ((dap->da_state & MKDIR_PARENT) ||
12472 		    (pagedep->pd_state & NEWBLOCK))
12473 			flushparent = 1;
12474 		else
12475 			flushparent = 0;
12476 		/*
12477 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12478 		 * then we will not be able to release and recover the
12479 		 * vnode below, so we just have to give up on writing its
12480 		 * directory entry out. It will eventually be written, just
12481 		 * not now, but then the user was not asking to have it
12482 		 * written, so we are not breaking any promises.
12483 		 */
12484 		if (vp->v_iflag & VI_DOOMED)
12485 			break;
12486 		/*
12487 		 * We prevent deadlock by always fetching inodes from the
12488 		 * root, moving down the directory tree. Thus, when fetching
12489 		 * our parent directory, we first try to get the lock. If
12490 		 * that fails, we must unlock ourselves before requesting
12491 		 * the lock on our parent. See the comment in ufs_lookup
12492 		 * for details on possible races.
12493 		 */
12494 		FREE_LOCK(ump);
12495 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12496 		    FFSV_FORCEINSMQ)) {
12497 			error = vfs_busy(mp, MBF_NOWAIT);
12498 			if (error != 0) {
12499 				vfs_ref(mp);
12500 				VOP_UNLOCK(vp, 0);
12501 				error = vfs_busy(mp, 0);
12502 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12503 				vfs_rel(mp);
12504 				if (error != 0)
12505 					return (ENOENT);
12506 				if (vp->v_iflag & VI_DOOMED) {
12507 					vfs_unbusy(mp);
12508 					return (ENOENT);
12509 				}
12510 			}
12511 			VOP_UNLOCK(vp, 0);
12512 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12513 			    &pvp, FFSV_FORCEINSMQ);
12514 			vfs_unbusy(mp);
12515 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12516 			if (vp->v_iflag & VI_DOOMED) {
12517 				if (error == 0)
12518 					vput(pvp);
12519 				error = ENOENT;
12520 			}
12521 			if (error != 0)
12522 				return (error);
12523 		}
12524 		/*
12525 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12526 		 * that are contained in direct blocks will be resolved by
12527 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12528 		 * may require a complete sync'ing of the directory. So, we
12529 		 * try the cheap and fast ffs_update first, and if that fails,
12530 		 * then we do the slower ffs_syncvnode of the directory.
12531 		 */
12532 		if (flushparent) {
12533 			int locked;
12534 
12535 			if ((error = ffs_update(pvp, 1)) != 0) {
12536 				vput(pvp);
12537 				return (error);
12538 			}
12539 			ACQUIRE_LOCK(ump);
12540 			locked = 1;
12541 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12542 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12543 					if (wk->wk_type != D_DIRADD)
12544 						panic("softdep_fsync: Unexpected type %s",
12545 						      TYPENAME(wk->wk_type));
12546 					dap = WK_DIRADD(wk);
12547 					if (dap->da_state & DIRCHG)
12548 						pagedep = dap->da_previous->dm_pagedep;
12549 					else
12550 						pagedep = dap->da_pagedep;
12551 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12552 					FREE_LOCK(ump);
12553 					locked = 0;
12554 					if (pagedep_new_block && (error =
12555 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12556 						vput(pvp);
12557 						return (error);
12558 					}
12559 				}
12560 			}
12561 			if (locked)
12562 				FREE_LOCK(ump);
12563 		}
12564 		/*
12565 		 * Flush directory page containing the inode's name.
12566 		 */
12567 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12568 		    &bp);
12569 		if (error == 0)
12570 			error = bwrite(bp);
12571 		else
12572 			brelse(bp);
12573 		vput(pvp);
12574 		if (error != 0)
12575 			return (error);
12576 		ACQUIRE_LOCK(ump);
12577 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12578 			break;
12579 	}
12580 	FREE_LOCK(ump);
12581 	return (0);
12582 }
12583 
12584 /*
12585  * Flush all the dirty bitmaps associated with the block device
12586  * before flushing the rest of the dirty blocks so as to reduce
12587  * the number of dependencies that will have to be rolled back.
12588  *
12589  * XXX Unused?
12590  */
12591 void
12592 softdep_fsync_mountdev(vp)
12593 	struct vnode *vp;
12594 {
12595 	struct buf *bp, *nbp;
12596 	struct worklist *wk;
12597 	struct bufobj *bo;
12598 
12599 	if (!vn_isdisk(vp, NULL))
12600 		panic("softdep_fsync_mountdev: vnode not a disk");
12601 	bo = &vp->v_bufobj;
12602 restart:
12603 	BO_LOCK(bo);
12604 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12605 		/*
12606 		 * If it is already scheduled, skip to the next buffer.
12607 		 */
12608 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12609 			continue;
12610 
12611 		if ((bp->b_flags & B_DELWRI) == 0)
12612 			panic("softdep_fsync_mountdev: not dirty");
12613 		/*
12614 		 * We are only interested in bitmaps with outstanding
12615 		 * dependencies.
12616 		 */
12617 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12618 		    wk->wk_type != D_BMSAFEMAP ||
12619 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12620 			BUF_UNLOCK(bp);
12621 			continue;
12622 		}
12623 		BO_UNLOCK(bo);
12624 		bremfree(bp);
12625 		(void) bawrite(bp);
12626 		goto restart;
12627 	}
12628 	drain_output(vp);
12629 	BO_UNLOCK(bo);
12630 }
12631 
12632 /*
12633  * Sync all cylinder groups that were dirty at the time this function is
12634  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12635  * is used to flush freedep activity that may be holding up writes to a
12636  * indirect block.
12637  */
12638 static int
12639 sync_cgs(mp, waitfor)
12640 	struct mount *mp;
12641 	int waitfor;
12642 {
12643 	struct bmsafemap *bmsafemap;
12644 	struct bmsafemap *sentinel;
12645 	struct ufsmount *ump;
12646 	struct buf *bp;
12647 	int error;
12648 
12649 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12650 	sentinel->sm_cg = -1;
12651 	ump = VFSTOUFS(mp);
12652 	error = 0;
12653 	ACQUIRE_LOCK(ump);
12654 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12655 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12656 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12657 		/* Skip sentinels and cgs with no work to release. */
12658 		if (bmsafemap->sm_cg == -1 ||
12659 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12660 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12661 			LIST_REMOVE(sentinel, sm_next);
12662 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12663 			continue;
12664 		}
12665 		/*
12666 		 * If we don't get the lock and we're waiting try again, if
12667 		 * not move on to the next buf and try to sync it.
12668 		 */
12669 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12670 		if (bp == NULL && waitfor == MNT_WAIT)
12671 			continue;
12672 		LIST_REMOVE(sentinel, sm_next);
12673 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12674 		if (bp == NULL)
12675 			continue;
12676 		FREE_LOCK(ump);
12677 		if (waitfor == MNT_NOWAIT)
12678 			bawrite(bp);
12679 		else
12680 			error = bwrite(bp);
12681 		ACQUIRE_LOCK(ump);
12682 		if (error)
12683 			break;
12684 	}
12685 	LIST_REMOVE(sentinel, sm_next);
12686 	FREE_LOCK(ump);
12687 	free(sentinel, M_BMSAFEMAP);
12688 	return (error);
12689 }
12690 
12691 /*
12692  * This routine is called when we are trying to synchronously flush a
12693  * file. This routine must eliminate any filesystem metadata dependencies
12694  * so that the syncing routine can succeed.
12695  */
12696 int
12697 softdep_sync_metadata(struct vnode *vp)
12698 {
12699 	struct inode *ip;
12700 	int error;
12701 
12702 	ip = VTOI(vp);
12703 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12704 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12705 	/*
12706 	 * Ensure that any direct block dependencies have been cleared,
12707 	 * truncations are started, and inode references are journaled.
12708 	 */
12709 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12710 	/*
12711 	 * Write all journal records to prevent rollbacks on devvp.
12712 	 */
12713 	if (vp->v_type == VCHR)
12714 		softdep_flushjournal(vp->v_mount);
12715 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12716 	/*
12717 	 * Ensure that all truncates are written so we won't find deps on
12718 	 * indirect blocks.
12719 	 */
12720 	process_truncates(vp);
12721 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12722 
12723 	return (error);
12724 }
12725 
12726 /*
12727  * This routine is called when we are attempting to sync a buf with
12728  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12729  * other IO it can but returns EBUSY if the buffer is not yet able to
12730  * be written.  Dependencies which will not cause rollbacks will always
12731  * return 0.
12732  */
12733 int
12734 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12735 {
12736 	struct indirdep *indirdep;
12737 	struct pagedep *pagedep;
12738 	struct allocindir *aip;
12739 	struct newblk *newblk;
12740 	struct ufsmount *ump;
12741 	struct buf *nbp;
12742 	struct worklist *wk;
12743 	int i, error;
12744 
12745 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12746 	    ("softdep_sync_buf called on non-softdep filesystem"));
12747 	/*
12748 	 * For VCHR we just don't want to force flush any dependencies that
12749 	 * will cause rollbacks.
12750 	 */
12751 	if (vp->v_type == VCHR) {
12752 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12753 			return (EBUSY);
12754 		return (0);
12755 	}
12756 	ump = VFSTOUFS(vp->v_mount);
12757 	ACQUIRE_LOCK(ump);
12758 	/*
12759 	 * As we hold the buffer locked, none of its dependencies
12760 	 * will disappear.
12761 	 */
12762 	error = 0;
12763 top:
12764 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12765 		switch (wk->wk_type) {
12766 
12767 		case D_ALLOCDIRECT:
12768 		case D_ALLOCINDIR:
12769 			newblk = WK_NEWBLK(wk);
12770 			if (newblk->nb_jnewblk != NULL) {
12771 				if (waitfor == MNT_NOWAIT) {
12772 					error = EBUSY;
12773 					goto out_unlock;
12774 				}
12775 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12776 				goto top;
12777 			}
12778 			if (newblk->nb_state & DEPCOMPLETE ||
12779 			    waitfor == MNT_NOWAIT)
12780 				continue;
12781 			nbp = newblk->nb_bmsafemap->sm_buf;
12782 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12783 			if (nbp == NULL)
12784 				goto top;
12785 			FREE_LOCK(ump);
12786 			if ((error = bwrite(nbp)) != 0)
12787 				goto out;
12788 			ACQUIRE_LOCK(ump);
12789 			continue;
12790 
12791 		case D_INDIRDEP:
12792 			indirdep = WK_INDIRDEP(wk);
12793 			if (waitfor == MNT_NOWAIT) {
12794 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12795 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12796 					error = EBUSY;
12797 					goto out_unlock;
12798 				}
12799 			}
12800 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12801 				panic("softdep_sync_buf: truncation pending.");
12802 		restart:
12803 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12804 				newblk = (struct newblk *)aip;
12805 				if (newblk->nb_jnewblk != NULL) {
12806 					jwait(&newblk->nb_jnewblk->jn_list,
12807 					    waitfor);
12808 					goto restart;
12809 				}
12810 				if (newblk->nb_state & DEPCOMPLETE)
12811 					continue;
12812 				nbp = newblk->nb_bmsafemap->sm_buf;
12813 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12814 				if (nbp == NULL)
12815 					goto restart;
12816 				FREE_LOCK(ump);
12817 				if ((error = bwrite(nbp)) != 0)
12818 					goto out;
12819 				ACQUIRE_LOCK(ump);
12820 				goto restart;
12821 			}
12822 			continue;
12823 
12824 		case D_PAGEDEP:
12825 			/*
12826 			 * Only flush directory entries in synchronous passes.
12827 			 */
12828 			if (waitfor != MNT_WAIT) {
12829 				error = EBUSY;
12830 				goto out_unlock;
12831 			}
12832 			/*
12833 			 * While syncing snapshots, we must allow recursive
12834 			 * lookups.
12835 			 */
12836 			BUF_AREC(bp);
12837 			/*
12838 			 * We are trying to sync a directory that may
12839 			 * have dependencies on both its own metadata
12840 			 * and/or dependencies on the inodes of any
12841 			 * recently allocated files. We walk its diradd
12842 			 * lists pushing out the associated inode.
12843 			 */
12844 			pagedep = WK_PAGEDEP(wk);
12845 			for (i = 0; i < DAHASHSZ; i++) {
12846 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12847 					continue;
12848 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12849 				    &pagedep->pd_diraddhd[i]))) {
12850 					BUF_NOREC(bp);
12851 					goto out_unlock;
12852 				}
12853 			}
12854 			BUF_NOREC(bp);
12855 			continue;
12856 
12857 		case D_FREEWORK:
12858 		case D_FREEDEP:
12859 		case D_JSEGDEP:
12860 		case D_JNEWBLK:
12861 			continue;
12862 
12863 		default:
12864 			panic("softdep_sync_buf: Unknown type %s",
12865 			    TYPENAME(wk->wk_type));
12866 			/* NOTREACHED */
12867 		}
12868 	}
12869 out_unlock:
12870 	FREE_LOCK(ump);
12871 out:
12872 	return (error);
12873 }
12874 
12875 /*
12876  * Flush the dependencies associated with an inodedep.
12877  * Called with splbio blocked.
12878  */
12879 static int
12880 flush_inodedep_deps(vp, mp, ino)
12881 	struct vnode *vp;
12882 	struct mount *mp;
12883 	ino_t ino;
12884 {
12885 	struct inodedep *inodedep;
12886 	struct inoref *inoref;
12887 	struct ufsmount *ump;
12888 	int error, waitfor;
12889 
12890 	/*
12891 	 * This work is done in two passes. The first pass grabs most
12892 	 * of the buffers and begins asynchronously writing them. The
12893 	 * only way to wait for these asynchronous writes is to sleep
12894 	 * on the filesystem vnode which may stay busy for a long time
12895 	 * if the filesystem is active. So, instead, we make a second
12896 	 * pass over the dependencies blocking on each write. In the
12897 	 * usual case we will be blocking against a write that we
12898 	 * initiated, so when it is done the dependency will have been
12899 	 * resolved. Thus the second pass is expected to end quickly.
12900 	 * We give a brief window at the top of the loop to allow
12901 	 * any pending I/O to complete.
12902 	 */
12903 	ump = VFSTOUFS(mp);
12904 	LOCK_OWNED(ump);
12905 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12906 		if (error)
12907 			return (error);
12908 		FREE_LOCK(ump);
12909 		ACQUIRE_LOCK(ump);
12910 restart:
12911 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12912 			return (0);
12913 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12914 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12915 			    == DEPCOMPLETE) {
12916 				jwait(&inoref->if_list, MNT_WAIT);
12917 				goto restart;
12918 			}
12919 		}
12920 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12921 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12922 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12923 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12924 			continue;
12925 		/*
12926 		 * If pass2, we are done, otherwise do pass 2.
12927 		 */
12928 		if (waitfor == MNT_WAIT)
12929 			break;
12930 		waitfor = MNT_WAIT;
12931 	}
12932 	/*
12933 	 * Try freeing inodedep in case all dependencies have been removed.
12934 	 */
12935 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12936 		(void) free_inodedep(inodedep);
12937 	return (0);
12938 }
12939 
12940 /*
12941  * Flush an inode dependency list.
12942  * Called with splbio blocked.
12943  */
12944 static int
12945 flush_deplist(listhead, waitfor, errorp)
12946 	struct allocdirectlst *listhead;
12947 	int waitfor;
12948 	int *errorp;
12949 {
12950 	struct allocdirect *adp;
12951 	struct newblk *newblk;
12952 	struct ufsmount *ump;
12953 	struct buf *bp;
12954 
12955 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
12956 		return (0);
12957 	ump = VFSTOUFS(adp->ad_list.wk_mp);
12958 	LOCK_OWNED(ump);
12959 	TAILQ_FOREACH(adp, listhead, ad_next) {
12960 		newblk = (struct newblk *)adp;
12961 		if (newblk->nb_jnewblk != NULL) {
12962 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12963 			return (1);
12964 		}
12965 		if (newblk->nb_state & DEPCOMPLETE)
12966 			continue;
12967 		bp = newblk->nb_bmsafemap->sm_buf;
12968 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12969 		if (bp == NULL) {
12970 			if (waitfor == MNT_NOWAIT)
12971 				continue;
12972 			return (1);
12973 		}
12974 		FREE_LOCK(ump);
12975 		if (waitfor == MNT_NOWAIT)
12976 			bawrite(bp);
12977 		else
12978 			*errorp = bwrite(bp);
12979 		ACQUIRE_LOCK(ump);
12980 		return (1);
12981 	}
12982 	return (0);
12983 }
12984 
12985 /*
12986  * Flush dependencies associated with an allocdirect block.
12987  */
12988 static int
12989 flush_newblk_dep(vp, mp, lbn)
12990 	struct vnode *vp;
12991 	struct mount *mp;
12992 	ufs_lbn_t lbn;
12993 {
12994 	struct newblk *newblk;
12995 	struct ufsmount *ump;
12996 	struct bufobj *bo;
12997 	struct inode *ip;
12998 	struct buf *bp;
12999 	ufs2_daddr_t blkno;
13000 	int error;
13001 
13002 	error = 0;
13003 	bo = &vp->v_bufobj;
13004 	ip = VTOI(vp);
13005 	blkno = DIP(ip, i_db[lbn]);
13006 	if (blkno == 0)
13007 		panic("flush_newblk_dep: Missing block");
13008 	ump = VFSTOUFS(mp);
13009 	ACQUIRE_LOCK(ump);
13010 	/*
13011 	 * Loop until all dependencies related to this block are satisfied.
13012 	 * We must be careful to restart after each sleep in case a write
13013 	 * completes some part of this process for us.
13014 	 */
13015 	for (;;) {
13016 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13017 			FREE_LOCK(ump);
13018 			break;
13019 		}
13020 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13021 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13022 		/*
13023 		 * Flush the journal.
13024 		 */
13025 		if (newblk->nb_jnewblk != NULL) {
13026 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13027 			continue;
13028 		}
13029 		/*
13030 		 * Write the bitmap dependency.
13031 		 */
13032 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13033 			bp = newblk->nb_bmsafemap->sm_buf;
13034 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13035 			if (bp == NULL)
13036 				continue;
13037 			FREE_LOCK(ump);
13038 			error = bwrite(bp);
13039 			if (error)
13040 				break;
13041 			ACQUIRE_LOCK(ump);
13042 			continue;
13043 		}
13044 		/*
13045 		 * Write the buffer.
13046 		 */
13047 		FREE_LOCK(ump);
13048 		BO_LOCK(bo);
13049 		bp = gbincore(bo, lbn);
13050 		if (bp != NULL) {
13051 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13052 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13053 			if (error == ENOLCK) {
13054 				ACQUIRE_LOCK(ump);
13055 				error = 0;
13056 				continue; /* Slept, retry */
13057 			}
13058 			if (error != 0)
13059 				break;	/* Failed */
13060 			if (bp->b_flags & B_DELWRI) {
13061 				bremfree(bp);
13062 				error = bwrite(bp);
13063 				if (error)
13064 					break;
13065 			} else
13066 				BUF_UNLOCK(bp);
13067 		} else
13068 			BO_UNLOCK(bo);
13069 		/*
13070 		 * We have to wait for the direct pointers to
13071 		 * point at the newdirblk before the dependency
13072 		 * will go away.
13073 		 */
13074 		error = ffs_update(vp, 1);
13075 		if (error)
13076 			break;
13077 		ACQUIRE_LOCK(ump);
13078 	}
13079 	return (error);
13080 }
13081 
13082 /*
13083  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13084  * Called with splbio blocked.
13085  */
13086 static int
13087 flush_pagedep_deps(pvp, mp, diraddhdp)
13088 	struct vnode *pvp;
13089 	struct mount *mp;
13090 	struct diraddhd *diraddhdp;
13091 {
13092 	struct inodedep *inodedep;
13093 	struct inoref *inoref;
13094 	struct ufsmount *ump;
13095 	struct diradd *dap;
13096 	struct vnode *vp;
13097 	int error = 0;
13098 	struct buf *bp;
13099 	ino_t inum;
13100 	struct diraddhd unfinished;
13101 
13102 	LIST_INIT(&unfinished);
13103 	ump = VFSTOUFS(mp);
13104 	LOCK_OWNED(ump);
13105 restart:
13106 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13107 		/*
13108 		 * Flush ourselves if this directory entry
13109 		 * has a MKDIR_PARENT dependency.
13110 		 */
13111 		if (dap->da_state & MKDIR_PARENT) {
13112 			FREE_LOCK(ump);
13113 			if ((error = ffs_update(pvp, 1)) != 0)
13114 				break;
13115 			ACQUIRE_LOCK(ump);
13116 			/*
13117 			 * If that cleared dependencies, go on to next.
13118 			 */
13119 			if (dap != LIST_FIRST(diraddhdp))
13120 				continue;
13121 			/*
13122 			 * All MKDIR_PARENT dependencies and all the
13123 			 * NEWBLOCK pagedeps that are contained in direct
13124 			 * blocks were resolved by doing above ffs_update.
13125 			 * Pagedeps contained in indirect blocks may
13126 			 * require a complete sync'ing of the directory.
13127 			 * We are in the midst of doing a complete sync,
13128 			 * so if they are not resolved in this pass we
13129 			 * defer them for now as they will be sync'ed by
13130 			 * our caller shortly.
13131 			 */
13132 			LIST_REMOVE(dap, da_pdlist);
13133 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13134 			continue;
13135 		}
13136 		/*
13137 		 * A newly allocated directory must have its "." and
13138 		 * ".." entries written out before its name can be
13139 		 * committed in its parent.
13140 		 */
13141 		inum = dap->da_newinum;
13142 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13143 			panic("flush_pagedep_deps: lost inode1");
13144 		/*
13145 		 * Wait for any pending journal adds to complete so we don't
13146 		 * cause rollbacks while syncing.
13147 		 */
13148 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13149 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13150 			    == DEPCOMPLETE) {
13151 				jwait(&inoref->if_list, MNT_WAIT);
13152 				goto restart;
13153 			}
13154 		}
13155 		if (dap->da_state & MKDIR_BODY) {
13156 			FREE_LOCK(ump);
13157 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13158 			    FFSV_FORCEINSMQ)))
13159 				break;
13160 			error = flush_newblk_dep(vp, mp, 0);
13161 			/*
13162 			 * If we still have the dependency we might need to
13163 			 * update the vnode to sync the new link count to
13164 			 * disk.
13165 			 */
13166 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13167 				error = ffs_update(vp, 1);
13168 			vput(vp);
13169 			if (error != 0)
13170 				break;
13171 			ACQUIRE_LOCK(ump);
13172 			/*
13173 			 * If that cleared dependencies, go on to next.
13174 			 */
13175 			if (dap != LIST_FIRST(diraddhdp))
13176 				continue;
13177 			if (dap->da_state & MKDIR_BODY) {
13178 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13179 				    &inodedep);
13180 				panic("flush_pagedep_deps: MKDIR_BODY "
13181 				    "inodedep %p dap %p vp %p",
13182 				    inodedep, dap, vp);
13183 			}
13184 		}
13185 		/*
13186 		 * Flush the inode on which the directory entry depends.
13187 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13188 		 * the only remaining dependency is that the updated inode
13189 		 * count must get pushed to disk. The inode has already
13190 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13191 		 * the time of the reference count change. So we need only
13192 		 * locate that buffer, ensure that there will be no rollback
13193 		 * caused by a bitmap dependency, then write the inode buffer.
13194 		 */
13195 retry:
13196 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13197 			panic("flush_pagedep_deps: lost inode");
13198 		/*
13199 		 * If the inode still has bitmap dependencies,
13200 		 * push them to disk.
13201 		 */
13202 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13203 			bp = inodedep->id_bmsafemap->sm_buf;
13204 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13205 			if (bp == NULL)
13206 				goto retry;
13207 			FREE_LOCK(ump);
13208 			if ((error = bwrite(bp)) != 0)
13209 				break;
13210 			ACQUIRE_LOCK(ump);
13211 			if (dap != LIST_FIRST(diraddhdp))
13212 				continue;
13213 		}
13214 		/*
13215 		 * If the inode is still sitting in a buffer waiting
13216 		 * to be written or waiting for the link count to be
13217 		 * adjusted update it here to flush it to disk.
13218 		 */
13219 		if (dap == LIST_FIRST(diraddhdp)) {
13220 			FREE_LOCK(ump);
13221 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13222 			    FFSV_FORCEINSMQ)))
13223 				break;
13224 			error = ffs_update(vp, 1);
13225 			vput(vp);
13226 			if (error)
13227 				break;
13228 			ACQUIRE_LOCK(ump);
13229 		}
13230 		/*
13231 		 * If we have failed to get rid of all the dependencies
13232 		 * then something is seriously wrong.
13233 		 */
13234 		if (dap == LIST_FIRST(diraddhdp)) {
13235 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13236 			panic("flush_pagedep_deps: failed to flush "
13237 			    "inodedep %p ino %ju dap %p",
13238 			    inodedep, (uintmax_t)inum, dap);
13239 		}
13240 	}
13241 	if (error)
13242 		ACQUIRE_LOCK(ump);
13243 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13244 		LIST_REMOVE(dap, da_pdlist);
13245 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13246 	}
13247 	return (error);
13248 }
13249 
13250 /*
13251  * A large burst of file addition or deletion activity can drive the
13252  * memory load excessively high. First attempt to slow things down
13253  * using the techniques below. If that fails, this routine requests
13254  * the offending operations to fall back to running synchronously
13255  * until the memory load returns to a reasonable level.
13256  */
13257 int
13258 softdep_slowdown(vp)
13259 	struct vnode *vp;
13260 {
13261 	struct ufsmount *ump;
13262 	int jlow;
13263 	int max_softdeps_hard;
13264 
13265 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13266 	    ("softdep_slowdown called on non-softdep filesystem"));
13267 	ump = VFSTOUFS(vp->v_mount);
13268 	ACQUIRE_LOCK(ump);
13269 	jlow = 0;
13270 	/*
13271 	 * Check for journal space if needed.
13272 	 */
13273 	if (DOINGSUJ(vp)) {
13274 		if (journal_space(ump, 0) == 0)
13275 			jlow = 1;
13276 	}
13277 	/*
13278 	 * If the system is under its limits and our filesystem is
13279 	 * not responsible for more than our share of the usage and
13280 	 * we are not low on journal space, then no need to slow down.
13281 	 */
13282 	max_softdeps_hard = max_softdeps * 11 / 10;
13283 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13284 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13285 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13286 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13287 	    ump->softdep_curdeps[D_DIRREM] <
13288 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13289 	    ump->softdep_curdeps[D_INODEDEP] <
13290 	    max_softdeps_hard / stat_flush_threads &&
13291 	    ump->softdep_curdeps[D_INDIRDEP] <
13292 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13293 	    ump->softdep_curdeps[D_FREEBLKS] <
13294 	    max_softdeps_hard / stat_flush_threads) {
13295 		FREE_LOCK(ump);
13296   		return (0);
13297 	}
13298 	/*
13299 	 * If the journal is low or our filesystem is over its limit
13300 	 * then speedup the cleanup.
13301 	 */
13302 	if (ump->softdep_curdeps[D_INDIRDEP] <
13303 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13304 		softdep_speedup(ump);
13305 	stat_sync_limit_hit += 1;
13306 	FREE_LOCK(ump);
13307 	/*
13308 	 * We only slow down the rate at which new dependencies are
13309 	 * generated if we are not using journaling. With journaling,
13310 	 * the cleanup should always be sufficient to keep things
13311 	 * under control.
13312 	 */
13313 	if (DOINGSUJ(vp))
13314 		return (0);
13315 	return (1);
13316 }
13317 
13318 /*
13319  * Called by the allocation routines when they are about to fail
13320  * in the hope that we can free up the requested resource (inodes
13321  * or disk space).
13322  *
13323  * First check to see if the work list has anything on it. If it has,
13324  * clean up entries until we successfully free the requested resource.
13325  * Because this process holds inodes locked, we cannot handle any remove
13326  * requests that might block on a locked inode as that could lead to
13327  * deadlock. If the worklist yields none of the requested resource,
13328  * start syncing out vnodes to free up the needed space.
13329  */
13330 int
13331 softdep_request_cleanup(fs, vp, cred, resource)
13332 	struct fs *fs;
13333 	struct vnode *vp;
13334 	struct ucred *cred;
13335 	int resource;
13336 {
13337 	struct ufsmount *ump;
13338 	struct mount *mp;
13339 	long starttime;
13340 	ufs2_daddr_t needed;
13341 	int error, failed_vnode;
13342 
13343 	/*
13344 	 * If we are being called because of a process doing a
13345 	 * copy-on-write, then it is not safe to process any
13346 	 * worklist items as we will recurse into the copyonwrite
13347 	 * routine.  This will result in an incoherent snapshot.
13348 	 * If the vnode that we hold is a snapshot, we must avoid
13349 	 * handling other resources that could cause deadlock.
13350 	 */
13351 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13352 		return (0);
13353 
13354 	if (resource == FLUSH_BLOCKS_WAIT)
13355 		stat_cleanup_blkrequests += 1;
13356 	else
13357 		stat_cleanup_inorequests += 1;
13358 
13359 	mp = vp->v_mount;
13360 	ump = VFSTOUFS(mp);
13361 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13362 	UFS_UNLOCK(ump);
13363 	error = ffs_update(vp, 1);
13364 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13365 		UFS_LOCK(ump);
13366 		return (0);
13367 	}
13368 	/*
13369 	 * If we are in need of resources, start by cleaning up
13370 	 * any block removals associated with our inode.
13371 	 */
13372 	ACQUIRE_LOCK(ump);
13373 	process_removes(vp);
13374 	process_truncates(vp);
13375 	FREE_LOCK(ump);
13376 	/*
13377 	 * Now clean up at least as many resources as we will need.
13378 	 *
13379 	 * When requested to clean up inodes, the number that are needed
13380 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13381 	 * plus a bit of slop (2) in case some more writers show up while
13382 	 * we are cleaning.
13383 	 *
13384 	 * When requested to free up space, the amount of space that
13385 	 * we need is enough blocks to allocate a full-sized segment
13386 	 * (fs_contigsumsize). The number of such segments that will
13387 	 * be needed is set by the number of simultaneous writers
13388 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13389 	 * writers show up while we are cleaning.
13390 	 *
13391 	 * Additionally, if we are unpriviledged and allocating space,
13392 	 * we need to ensure that we clean up enough blocks to get the
13393 	 * needed number of blocks over the threshold of the minimum
13394 	 * number of blocks required to be kept free by the filesystem
13395 	 * (fs_minfree).
13396 	 */
13397 	if (resource == FLUSH_INODES_WAIT) {
13398 		needed = vp->v_mount->mnt_writeopcount + 2;
13399 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13400 		needed = (vp->v_mount->mnt_writeopcount + 2) *
13401 		    fs->fs_contigsumsize;
13402 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13403 			needed += fragstoblks(fs,
13404 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13405 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13406 	} else {
13407 		UFS_LOCK(ump);
13408 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13409 		    resource);
13410 		return (0);
13411 	}
13412 	starttime = time_second;
13413 retry:
13414 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13415 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13416 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13417 	    fs->fs_cstotal.cs_nifree <= needed)) {
13418 		ACQUIRE_LOCK(ump);
13419 		if (ump->softdep_on_worklist > 0 &&
13420 		    process_worklist_item(UFSTOVFS(ump),
13421 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13422 			stat_worklist_push += 1;
13423 		FREE_LOCK(ump);
13424 	}
13425 	/*
13426 	 * If we still need resources and there are no more worklist
13427 	 * entries to process to obtain them, we have to start flushing
13428 	 * the dirty vnodes to force the release of additional requests
13429 	 * to the worklist that we can then process to reap addition
13430 	 * resources. We walk the vnodes associated with the mount point
13431 	 * until we get the needed worklist requests that we can reap.
13432 	 *
13433 	 * If there are several threads all needing to clean the same
13434 	 * mount point, only one is allowed to walk the mount list.
13435 	 * When several threads all try to walk the same mount list,
13436 	 * they end up competing with each other and often end up in
13437 	 * livelock. This approach ensures that forward progress is
13438 	 * made at the cost of occational ENOSPC errors being returned
13439 	 * that might otherwise have been avoided.
13440 	 */
13441 	error = 1;
13442 	if ((resource == FLUSH_BLOCKS_WAIT &&
13443 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13444 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13445 	     fs->fs_cstotal.cs_nifree <= needed)) {
13446 		ACQUIRE_LOCK(ump);
13447 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13448 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13449 			FREE_LOCK(ump);
13450 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13451 			ACQUIRE_LOCK(ump);
13452 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13453 			FREE_LOCK(ump);
13454 			if (ump->softdep_on_worklist > 0) {
13455 				stat_cleanup_retries += 1;
13456 				if (!failed_vnode)
13457 					goto retry;
13458 			}
13459 		} else {
13460 			FREE_LOCK(ump);
13461 			error = 0;
13462 		}
13463 		stat_cleanup_failures += 1;
13464 	}
13465 	if (time_second - starttime > stat_cleanup_high_delay)
13466 		stat_cleanup_high_delay = time_second - starttime;
13467 	UFS_LOCK(ump);
13468 	return (error);
13469 }
13470 
13471 /*
13472  * Scan the vnodes for the specified mount point flushing out any
13473  * vnodes that can be locked without waiting. Finally, try to flush
13474  * the device associated with the mount point if it can be locked
13475  * without waiting.
13476  *
13477  * We return 0 if we were able to lock every vnode in our scan.
13478  * If we had to skip one or more vnodes, we return 1.
13479  */
13480 static int
13481 softdep_request_cleanup_flush(mp, ump)
13482 	struct mount *mp;
13483 	struct ufsmount *ump;
13484 {
13485 	struct thread *td;
13486 	struct vnode *lvp, *mvp;
13487 	int failed_vnode;
13488 
13489 	failed_vnode = 0;
13490 	td = curthread;
13491 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13492 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13493 			VI_UNLOCK(lvp);
13494 			continue;
13495 		}
13496 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13497 		    td) != 0) {
13498 			failed_vnode = 1;
13499 			continue;
13500 		}
13501 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13502 			vput(lvp);
13503 			continue;
13504 		}
13505 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13506 		vput(lvp);
13507 	}
13508 	lvp = ump->um_devvp;
13509 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13510 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13511 		VOP_UNLOCK(lvp, 0);
13512 	}
13513 	return (failed_vnode);
13514 }
13515 
13516 static bool
13517 softdep_excess_items(struct ufsmount *ump, int item)
13518 {
13519 
13520 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13521 	return (dep_current[item] > max_softdeps &&
13522 	    ump->softdep_curdeps[item] > max_softdeps /
13523 	    stat_flush_threads);
13524 }
13525 
13526 static void
13527 schedule_cleanup(struct mount *mp)
13528 {
13529 	struct ufsmount *ump;
13530 	struct thread *td;
13531 
13532 	ump = VFSTOUFS(mp);
13533 	LOCK_OWNED(ump);
13534 	FREE_LOCK(ump);
13535 	td = curthread;
13536 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13537 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13538 		/*
13539 		 * No ast is delivered to kernel threads, so nobody
13540 		 * would deref the mp.  Some kernel threads
13541 		 * explicitely check for AST, e.g. NFS daemon does
13542 		 * this in the serving loop.
13543 		 */
13544 		return;
13545 	}
13546 	if (td->td_su != NULL)
13547 		vfs_rel(td->td_su);
13548 	vfs_ref(mp);
13549 	td->td_su = mp;
13550 	thread_lock(td);
13551 	td->td_flags |= TDF_ASTPENDING;
13552 	thread_unlock(td);
13553 }
13554 
13555 static void
13556 softdep_ast_cleanup_proc(struct thread *td)
13557 {
13558 	struct mount *mp;
13559 	struct ufsmount *ump;
13560 	int error;
13561 	bool req;
13562 
13563 	while ((mp = td->td_su) != NULL) {
13564 		td->td_su = NULL;
13565 		error = vfs_busy(mp, MBF_NOWAIT);
13566 		vfs_rel(mp);
13567 		if (error != 0)
13568 			return;
13569 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13570 			ump = VFSTOUFS(mp);
13571 			for (;;) {
13572 				req = false;
13573 				ACQUIRE_LOCK(ump);
13574 				if (softdep_excess_items(ump, D_INODEDEP)) {
13575 					req = true;
13576 					request_cleanup(mp, FLUSH_INODES);
13577 				}
13578 				if (softdep_excess_items(ump, D_DIRREM)) {
13579 					req = true;
13580 					request_cleanup(mp, FLUSH_BLOCKS);
13581 				}
13582 				FREE_LOCK(ump);
13583 				if (softdep_excess_items(ump, D_NEWBLK) ||
13584 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13585 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13586 					error = vn_start_write(NULL, &mp,
13587 					    V_WAIT);
13588 					if (error == 0) {
13589 						req = true;
13590 						VFS_SYNC(mp, MNT_WAIT);
13591 						vn_finished_write(mp);
13592 					}
13593 				}
13594 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13595 					break;
13596 			}
13597 		}
13598 		vfs_unbusy(mp);
13599 	}
13600 	if ((mp = td->td_su) != NULL) {
13601 		td->td_su = NULL;
13602 		vfs_rel(mp);
13603 	}
13604 }
13605 
13606 /*
13607  * If memory utilization has gotten too high, deliberately slow things
13608  * down and speed up the I/O processing.
13609  */
13610 static int
13611 request_cleanup(mp, resource)
13612 	struct mount *mp;
13613 	int resource;
13614 {
13615 	struct thread *td = curthread;
13616 	struct ufsmount *ump;
13617 
13618 	ump = VFSTOUFS(mp);
13619 	LOCK_OWNED(ump);
13620 	/*
13621 	 * We never hold up the filesystem syncer or buf daemon.
13622 	 */
13623 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13624 		return (0);
13625 	/*
13626 	 * First check to see if the work list has gotten backlogged.
13627 	 * If it has, co-opt this process to help clean up two entries.
13628 	 * Because this process may hold inodes locked, we cannot
13629 	 * handle any remove requests that might block on a locked
13630 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13631 	 * to avoid recursively processing the worklist.
13632 	 */
13633 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13634 		td->td_pflags |= TDP_SOFTDEP;
13635 		process_worklist_item(mp, 2, LK_NOWAIT);
13636 		td->td_pflags &= ~TDP_SOFTDEP;
13637 		stat_worklist_push += 2;
13638 		return(1);
13639 	}
13640 	/*
13641 	 * Next, we attempt to speed up the syncer process. If that
13642 	 * is successful, then we allow the process to continue.
13643 	 */
13644 	if (softdep_speedup(ump) &&
13645 	    resource != FLUSH_BLOCKS_WAIT &&
13646 	    resource != FLUSH_INODES_WAIT)
13647 		return(0);
13648 	/*
13649 	 * If we are resource constrained on inode dependencies, try
13650 	 * flushing some dirty inodes. Otherwise, we are constrained
13651 	 * by file deletions, so try accelerating flushes of directories
13652 	 * with removal dependencies. We would like to do the cleanup
13653 	 * here, but we probably hold an inode locked at this point and
13654 	 * that might deadlock against one that we try to clean. So,
13655 	 * the best that we can do is request the syncer daemon to do
13656 	 * the cleanup for us.
13657 	 */
13658 	switch (resource) {
13659 
13660 	case FLUSH_INODES:
13661 	case FLUSH_INODES_WAIT:
13662 		ACQUIRE_GBLLOCK(&lk);
13663 		stat_ino_limit_push += 1;
13664 		req_clear_inodedeps += 1;
13665 		FREE_GBLLOCK(&lk);
13666 		stat_countp = &stat_ino_limit_hit;
13667 		break;
13668 
13669 	case FLUSH_BLOCKS:
13670 	case FLUSH_BLOCKS_WAIT:
13671 		ACQUIRE_GBLLOCK(&lk);
13672 		stat_blk_limit_push += 1;
13673 		req_clear_remove += 1;
13674 		FREE_GBLLOCK(&lk);
13675 		stat_countp = &stat_blk_limit_hit;
13676 		break;
13677 
13678 	default:
13679 		panic("request_cleanup: unknown type");
13680 	}
13681 	/*
13682 	 * Hopefully the syncer daemon will catch up and awaken us.
13683 	 * We wait at most tickdelay before proceeding in any case.
13684 	 */
13685 	ACQUIRE_GBLLOCK(&lk);
13686 	FREE_LOCK(ump);
13687 	proc_waiting += 1;
13688 	if (callout_pending(&softdep_callout) == FALSE)
13689 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13690 		    pause_timer, 0);
13691 
13692 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13693 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13694 	proc_waiting -= 1;
13695 	FREE_GBLLOCK(&lk);
13696 	ACQUIRE_LOCK(ump);
13697 	return (1);
13698 }
13699 
13700 /*
13701  * Awaken processes pausing in request_cleanup and clear proc_waiting
13702  * to indicate that there is no longer a timer running. Pause_timer
13703  * will be called with the global softdep mutex (&lk) locked.
13704  */
13705 static void
13706 pause_timer(arg)
13707 	void *arg;
13708 {
13709 
13710 	GBLLOCK_OWNED(&lk);
13711 	/*
13712 	 * The callout_ API has acquired mtx and will hold it around this
13713 	 * function call.
13714 	 */
13715 	*stat_countp += proc_waiting;
13716 	wakeup(&proc_waiting);
13717 }
13718 
13719 /*
13720  * If requested, try removing inode or removal dependencies.
13721  */
13722 static void
13723 check_clear_deps(mp)
13724 	struct mount *mp;
13725 {
13726 
13727 	/*
13728 	 * If we are suspended, it may be because of our using
13729 	 * too many inodedeps, so help clear them out.
13730 	 */
13731 	if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13732 		clear_inodedeps(mp);
13733 	/*
13734 	 * General requests for cleanup of backed up dependencies
13735 	 */
13736 	ACQUIRE_GBLLOCK(&lk);
13737 	if (req_clear_inodedeps) {
13738 		req_clear_inodedeps -= 1;
13739 		FREE_GBLLOCK(&lk);
13740 		clear_inodedeps(mp);
13741 		ACQUIRE_GBLLOCK(&lk);
13742 		wakeup(&proc_waiting);
13743 	}
13744 	if (req_clear_remove) {
13745 		req_clear_remove -= 1;
13746 		FREE_GBLLOCK(&lk);
13747 		clear_remove(mp);
13748 		ACQUIRE_GBLLOCK(&lk);
13749 		wakeup(&proc_waiting);
13750 	}
13751 	FREE_GBLLOCK(&lk);
13752 }
13753 
13754 /*
13755  * Flush out a directory with at least one removal dependency in an effort to
13756  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13757  */
13758 static void
13759 clear_remove(mp)
13760 	struct mount *mp;
13761 {
13762 	struct pagedep_hashhead *pagedephd;
13763 	struct pagedep *pagedep;
13764 	struct ufsmount *ump;
13765 	struct vnode *vp;
13766 	struct bufobj *bo;
13767 	int error, cnt;
13768 	ino_t ino;
13769 
13770 	ump = VFSTOUFS(mp);
13771 	LOCK_OWNED(ump);
13772 
13773 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13774 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13775 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13776 			ump->pagedep_nextclean = 0;
13777 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13778 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13779 				continue;
13780 			ino = pagedep->pd_ino;
13781 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13782 				continue;
13783 			FREE_LOCK(ump);
13784 
13785 			/*
13786 			 * Let unmount clear deps
13787 			 */
13788 			error = vfs_busy(mp, MBF_NOWAIT);
13789 			if (error != 0)
13790 				goto finish_write;
13791 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13792 			     FFSV_FORCEINSMQ);
13793 			vfs_unbusy(mp);
13794 			if (error != 0) {
13795 				softdep_error("clear_remove: vget", error);
13796 				goto finish_write;
13797 			}
13798 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13799 				softdep_error("clear_remove: fsync", error);
13800 			bo = &vp->v_bufobj;
13801 			BO_LOCK(bo);
13802 			drain_output(vp);
13803 			BO_UNLOCK(bo);
13804 			vput(vp);
13805 		finish_write:
13806 			vn_finished_write(mp);
13807 			ACQUIRE_LOCK(ump);
13808 			return;
13809 		}
13810 	}
13811 }
13812 
13813 /*
13814  * Clear out a block of dirty inodes in an effort to reduce
13815  * the number of inodedep dependency structures.
13816  */
13817 static void
13818 clear_inodedeps(mp)
13819 	struct mount *mp;
13820 {
13821 	struct inodedep_hashhead *inodedephd;
13822 	struct inodedep *inodedep;
13823 	struct ufsmount *ump;
13824 	struct vnode *vp;
13825 	struct fs *fs;
13826 	int error, cnt;
13827 	ino_t firstino, lastino, ino;
13828 
13829 	ump = VFSTOUFS(mp);
13830 	fs = ump->um_fs;
13831 	LOCK_OWNED(ump);
13832 	/*
13833 	 * Pick a random inode dependency to be cleared.
13834 	 * We will then gather up all the inodes in its block
13835 	 * that have dependencies and flush them out.
13836 	 */
13837 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13838 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13839 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13840 			ump->inodedep_nextclean = 0;
13841 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13842 			break;
13843 	}
13844 	if (inodedep == NULL)
13845 		return;
13846 	/*
13847 	 * Find the last inode in the block with dependencies.
13848 	 */
13849 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13850 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13851 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13852 			break;
13853 	/*
13854 	 * Asynchronously push all but the last inode with dependencies.
13855 	 * Synchronously push the last inode with dependencies to ensure
13856 	 * that the inode block gets written to free up the inodedeps.
13857 	 */
13858 	for (ino = firstino; ino <= lastino; ino++) {
13859 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13860 			continue;
13861 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13862 			continue;
13863 		FREE_LOCK(ump);
13864 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13865 		if (error != 0) {
13866 			vn_finished_write(mp);
13867 			ACQUIRE_LOCK(ump);
13868 			return;
13869 		}
13870 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13871 		    FFSV_FORCEINSMQ)) != 0) {
13872 			softdep_error("clear_inodedeps: vget", error);
13873 			vfs_unbusy(mp);
13874 			vn_finished_write(mp);
13875 			ACQUIRE_LOCK(ump);
13876 			return;
13877 		}
13878 		vfs_unbusy(mp);
13879 		if (ino == lastino) {
13880 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13881 				softdep_error("clear_inodedeps: fsync1", error);
13882 		} else {
13883 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13884 				softdep_error("clear_inodedeps: fsync2", error);
13885 			BO_LOCK(&vp->v_bufobj);
13886 			drain_output(vp);
13887 			BO_UNLOCK(&vp->v_bufobj);
13888 		}
13889 		vput(vp);
13890 		vn_finished_write(mp);
13891 		ACQUIRE_LOCK(ump);
13892 	}
13893 }
13894 
13895 void
13896 softdep_buf_append(bp, wkhd)
13897 	struct buf *bp;
13898 	struct workhead *wkhd;
13899 {
13900 	struct worklist *wk;
13901 	struct ufsmount *ump;
13902 
13903 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13904 		return;
13905 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13906 	    ("softdep_buf_append called on non-softdep filesystem"));
13907 	ump = VFSTOUFS(wk->wk_mp);
13908 	ACQUIRE_LOCK(ump);
13909 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13910 		WORKLIST_REMOVE(wk);
13911 		WORKLIST_INSERT(&bp->b_dep, wk);
13912 	}
13913 	FREE_LOCK(ump);
13914 
13915 }
13916 
13917 void
13918 softdep_inode_append(ip, cred, wkhd)
13919 	struct inode *ip;
13920 	struct ucred *cred;
13921 	struct workhead *wkhd;
13922 {
13923 	struct buf *bp;
13924 	struct fs *fs;
13925 	struct ufsmount *ump;
13926 	int error;
13927 
13928 	ump = ITOUMP(ip);
13929 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13930 	    ("softdep_inode_append called on non-softdep filesystem"));
13931 	fs = ump->um_fs;
13932 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13933 	    (int)fs->fs_bsize, cred, &bp);
13934 	if (error) {
13935 		bqrelse(bp);
13936 		softdep_freework(wkhd);
13937 		return;
13938 	}
13939 	softdep_buf_append(bp, wkhd);
13940 	bqrelse(bp);
13941 }
13942 
13943 void
13944 softdep_freework(wkhd)
13945 	struct workhead *wkhd;
13946 {
13947 	struct worklist *wk;
13948 	struct ufsmount *ump;
13949 
13950 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13951 		return;
13952 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13953 	    ("softdep_freework called on non-softdep filesystem"));
13954 	ump = VFSTOUFS(wk->wk_mp);
13955 	ACQUIRE_LOCK(ump);
13956 	handle_jwork(wkhd);
13957 	FREE_LOCK(ump);
13958 }
13959 
13960 static struct ufsmount *
13961 softdep_bp_to_mp(bp)
13962 	struct buf *bp;
13963 {
13964 	struct mount *mp;
13965 	struct vnode *vp;
13966 
13967 	if (LIST_EMPTY(&bp->b_dep))
13968 		return (NULL);
13969 	vp = bp->b_vp;
13970 
13971 	/*
13972 	 * The ump mount point is stable after we get a correct
13973 	 * pointer, since bp is locked and this prevents unmount from
13974 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
13975 	 * head wk_mp, because we do not yet own SU ump lock and
13976 	 * workitem might be freed while dereferenced.
13977 	 */
13978 retry:
13979 	if (vp->v_type == VCHR) {
13980 		VI_LOCK(vp);
13981 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
13982 		VI_UNLOCK(vp);
13983 		if (mp == NULL)
13984 			goto retry;
13985 	} else if (vp->v_type == VREG || vp->v_type == VDIR ||
13986 	    vp->v_type == VLNK || vp->v_type == VFIFO) {
13987 		mp = vp->v_mount;
13988 	} else {
13989 		return (NULL);
13990 	}
13991 	return (VFSTOUFS(mp));
13992 }
13993 
13994 /*
13995  * Function to determine if the buffer has outstanding dependencies
13996  * that will cause a roll-back if the buffer is written. If wantcount
13997  * is set, return number of dependencies, otherwise just yes or no.
13998  */
13999 static int
14000 softdep_count_dependencies(bp, wantcount)
14001 	struct buf *bp;
14002 	int wantcount;
14003 {
14004 	struct worklist *wk;
14005 	struct ufsmount *ump;
14006 	struct bmsafemap *bmsafemap;
14007 	struct freework *freework;
14008 	struct inodedep *inodedep;
14009 	struct indirdep *indirdep;
14010 	struct freeblks *freeblks;
14011 	struct allocindir *aip;
14012 	struct pagedep *pagedep;
14013 	struct dirrem *dirrem;
14014 	struct newblk *newblk;
14015 	struct mkdir *mkdir;
14016 	struct diradd *dap;
14017 	int i, retval;
14018 
14019 	ump = softdep_bp_to_mp(bp);
14020 	if (ump == NULL)
14021 		return (0);
14022 	retval = 0;
14023 	ACQUIRE_LOCK(ump);
14024 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14025 		switch (wk->wk_type) {
14026 
14027 		case D_INODEDEP:
14028 			inodedep = WK_INODEDEP(wk);
14029 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14030 				/* bitmap allocation dependency */
14031 				retval += 1;
14032 				if (!wantcount)
14033 					goto out;
14034 			}
14035 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14036 				/* direct block pointer dependency */
14037 				retval += 1;
14038 				if (!wantcount)
14039 					goto out;
14040 			}
14041 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14042 				/* direct block pointer dependency */
14043 				retval += 1;
14044 				if (!wantcount)
14045 					goto out;
14046 			}
14047 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14048 				/* Add reference dependency. */
14049 				retval += 1;
14050 				if (!wantcount)
14051 					goto out;
14052 			}
14053 			continue;
14054 
14055 		case D_INDIRDEP:
14056 			indirdep = WK_INDIRDEP(wk);
14057 
14058 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14059 				/* indirect truncation dependency */
14060 				retval += 1;
14061 				if (!wantcount)
14062 					goto out;
14063 			}
14064 
14065 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14066 				/* indirect block pointer dependency */
14067 				retval += 1;
14068 				if (!wantcount)
14069 					goto out;
14070 			}
14071 			continue;
14072 
14073 		case D_PAGEDEP:
14074 			pagedep = WK_PAGEDEP(wk);
14075 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14076 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14077 					/* Journal remove ref dependency. */
14078 					retval += 1;
14079 					if (!wantcount)
14080 						goto out;
14081 				}
14082 			}
14083 			for (i = 0; i < DAHASHSZ; i++) {
14084 
14085 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14086 					/* directory entry dependency */
14087 					retval += 1;
14088 					if (!wantcount)
14089 						goto out;
14090 				}
14091 			}
14092 			continue;
14093 
14094 		case D_BMSAFEMAP:
14095 			bmsafemap = WK_BMSAFEMAP(wk);
14096 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14097 				/* Add reference dependency. */
14098 				retval += 1;
14099 				if (!wantcount)
14100 					goto out;
14101 			}
14102 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14103 				/* Allocate block dependency. */
14104 				retval += 1;
14105 				if (!wantcount)
14106 					goto out;
14107 			}
14108 			continue;
14109 
14110 		case D_FREEBLKS:
14111 			freeblks = WK_FREEBLKS(wk);
14112 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14113 				/* Freeblk journal dependency. */
14114 				retval += 1;
14115 				if (!wantcount)
14116 					goto out;
14117 			}
14118 			continue;
14119 
14120 		case D_ALLOCDIRECT:
14121 		case D_ALLOCINDIR:
14122 			newblk = WK_NEWBLK(wk);
14123 			if (newblk->nb_jnewblk) {
14124 				/* Journal allocate dependency. */
14125 				retval += 1;
14126 				if (!wantcount)
14127 					goto out;
14128 			}
14129 			continue;
14130 
14131 		case D_MKDIR:
14132 			mkdir = WK_MKDIR(wk);
14133 			if (mkdir->md_jaddref) {
14134 				/* Journal reference dependency. */
14135 				retval += 1;
14136 				if (!wantcount)
14137 					goto out;
14138 			}
14139 			continue;
14140 
14141 		case D_FREEWORK:
14142 		case D_FREEDEP:
14143 		case D_JSEGDEP:
14144 		case D_JSEG:
14145 		case D_SBDEP:
14146 			/* never a dependency on these blocks */
14147 			continue;
14148 
14149 		default:
14150 			panic("softdep_count_dependencies: Unexpected type %s",
14151 			    TYPENAME(wk->wk_type));
14152 			/* NOTREACHED */
14153 		}
14154 	}
14155 out:
14156 	FREE_LOCK(ump);
14157 	return (retval);
14158 }
14159 
14160 /*
14161  * Acquire exclusive access to a buffer.
14162  * Must be called with a locked mtx parameter.
14163  * Return acquired buffer or NULL on failure.
14164  */
14165 static struct buf *
14166 getdirtybuf(bp, lock, waitfor)
14167 	struct buf *bp;
14168 	struct rwlock *lock;
14169 	int waitfor;
14170 {
14171 	int error;
14172 
14173 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14174 		if (waitfor != MNT_WAIT)
14175 			return (NULL);
14176 		error = BUF_LOCK(bp,
14177 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14178 		/*
14179 		 * Even if we successfully acquire bp here, we have dropped
14180 		 * lock, which may violates our guarantee.
14181 		 */
14182 		if (error == 0)
14183 			BUF_UNLOCK(bp);
14184 		else if (error != ENOLCK)
14185 			panic("getdirtybuf: inconsistent lock: %d", error);
14186 		rw_wlock(lock);
14187 		return (NULL);
14188 	}
14189 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14190 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14191 			rw_wunlock(lock);
14192 			BO_LOCK(bp->b_bufobj);
14193 			BUF_UNLOCK(bp);
14194 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14195 				bp->b_vflags |= BV_BKGRDWAIT;
14196 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14197 				       PRIBIO | PDROP, "getbuf", 0);
14198 			} else
14199 				BO_UNLOCK(bp->b_bufobj);
14200 			rw_wlock(lock);
14201 			return (NULL);
14202 		}
14203 		BUF_UNLOCK(bp);
14204 		if (waitfor != MNT_WAIT)
14205 			return (NULL);
14206 #ifdef DEBUG_VFS_LOCKS
14207 		if (bp->b_vp->v_type != VCHR)
14208 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14209 #endif
14210 		bp->b_vflags |= BV_BKGRDWAIT;
14211 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14212 		return (NULL);
14213 	}
14214 	if ((bp->b_flags & B_DELWRI) == 0) {
14215 		BUF_UNLOCK(bp);
14216 		return (NULL);
14217 	}
14218 	bremfree(bp);
14219 	return (bp);
14220 }
14221 
14222 
14223 /*
14224  * Check if it is safe to suspend the file system now.  On entry,
14225  * the vnode interlock for devvp should be held.  Return 0 with
14226  * the mount interlock held if the file system can be suspended now,
14227  * otherwise return EAGAIN with the mount interlock held.
14228  */
14229 int
14230 softdep_check_suspend(struct mount *mp,
14231 		      struct vnode *devvp,
14232 		      int softdep_depcnt,
14233 		      int softdep_accdepcnt,
14234 		      int secondary_writes,
14235 		      int secondary_accwrites)
14236 {
14237 	struct bufobj *bo;
14238 	struct ufsmount *ump;
14239 	struct inodedep *inodedep;
14240 	int error, unlinked;
14241 
14242 	bo = &devvp->v_bufobj;
14243 	ASSERT_BO_WLOCKED(bo);
14244 
14245 	/*
14246 	 * If we are not running with soft updates, then we need only
14247 	 * deal with secondary writes as we try to suspend.
14248 	 */
14249 	if (MOUNTEDSOFTDEP(mp) == 0) {
14250 		MNT_ILOCK(mp);
14251 		while (mp->mnt_secondary_writes != 0) {
14252 			BO_UNLOCK(bo);
14253 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14254 			    (PUSER - 1) | PDROP, "secwr", 0);
14255 			BO_LOCK(bo);
14256 			MNT_ILOCK(mp);
14257 		}
14258 
14259 		/*
14260 		 * Reasons for needing more work before suspend:
14261 		 * - Dirty buffers on devvp.
14262 		 * - Secondary writes occurred after start of vnode sync loop
14263 		 */
14264 		error = 0;
14265 		if (bo->bo_numoutput > 0 ||
14266 		    bo->bo_dirty.bv_cnt > 0 ||
14267 		    secondary_writes != 0 ||
14268 		    mp->mnt_secondary_writes != 0 ||
14269 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14270 			error = EAGAIN;
14271 		BO_UNLOCK(bo);
14272 		return (error);
14273 	}
14274 
14275 	/*
14276 	 * If we are running with soft updates, then we need to coordinate
14277 	 * with them as we try to suspend.
14278 	 */
14279 	ump = VFSTOUFS(mp);
14280 	for (;;) {
14281 		if (!TRY_ACQUIRE_LOCK(ump)) {
14282 			BO_UNLOCK(bo);
14283 			ACQUIRE_LOCK(ump);
14284 			FREE_LOCK(ump);
14285 			BO_LOCK(bo);
14286 			continue;
14287 		}
14288 		MNT_ILOCK(mp);
14289 		if (mp->mnt_secondary_writes != 0) {
14290 			FREE_LOCK(ump);
14291 			BO_UNLOCK(bo);
14292 			msleep(&mp->mnt_secondary_writes,
14293 			       MNT_MTX(mp),
14294 			       (PUSER - 1) | PDROP, "secwr", 0);
14295 			BO_LOCK(bo);
14296 			continue;
14297 		}
14298 		break;
14299 	}
14300 
14301 	unlinked = 0;
14302 	if (MOUNTEDSUJ(mp)) {
14303 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14304 		    inodedep != NULL;
14305 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14306 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14307 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14308 			    UNLINKONLIST) ||
14309 			    !check_inodedep_free(inodedep))
14310 				continue;
14311 			unlinked++;
14312 		}
14313 	}
14314 
14315 	/*
14316 	 * Reasons for needing more work before suspend:
14317 	 * - Dirty buffers on devvp.
14318 	 * - Softdep activity occurred after start of vnode sync loop
14319 	 * - Secondary writes occurred after start of vnode sync loop
14320 	 */
14321 	error = 0;
14322 	if (bo->bo_numoutput > 0 ||
14323 	    bo->bo_dirty.bv_cnt > 0 ||
14324 	    softdep_depcnt != unlinked ||
14325 	    ump->softdep_deps != unlinked ||
14326 	    softdep_accdepcnt != ump->softdep_accdeps ||
14327 	    secondary_writes != 0 ||
14328 	    mp->mnt_secondary_writes != 0 ||
14329 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14330 		error = EAGAIN;
14331 	FREE_LOCK(ump);
14332 	BO_UNLOCK(bo);
14333 	return (error);
14334 }
14335 
14336 
14337 /*
14338  * Get the number of dependency structures for the file system, both
14339  * the current number and the total number allocated.  These will
14340  * later be used to detect that softdep processing has occurred.
14341  */
14342 void
14343 softdep_get_depcounts(struct mount *mp,
14344 		      int *softdep_depsp,
14345 		      int *softdep_accdepsp)
14346 {
14347 	struct ufsmount *ump;
14348 
14349 	if (MOUNTEDSOFTDEP(mp) == 0) {
14350 		*softdep_depsp = 0;
14351 		*softdep_accdepsp = 0;
14352 		return;
14353 	}
14354 	ump = VFSTOUFS(mp);
14355 	ACQUIRE_LOCK(ump);
14356 	*softdep_depsp = ump->softdep_deps;
14357 	*softdep_accdepsp = ump->softdep_accdeps;
14358 	FREE_LOCK(ump);
14359 }
14360 
14361 /*
14362  * Wait for pending output on a vnode to complete.
14363  */
14364 static void
14365 drain_output(vp)
14366 	struct vnode *vp;
14367 {
14368 
14369 	ASSERT_VOP_LOCKED(vp, "drain_output");
14370 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14371 }
14372 
14373 /*
14374  * Called whenever a buffer that is being invalidated or reallocated
14375  * contains dependencies. This should only happen if an I/O error has
14376  * occurred. The routine is called with the buffer locked.
14377  */
14378 static void
14379 softdep_deallocate_dependencies(bp)
14380 	struct buf *bp;
14381 {
14382 
14383 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14384 		panic("softdep_deallocate_dependencies: dangling deps");
14385 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14386 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14387 	else
14388 		printf("softdep_deallocate_dependencies: "
14389 		    "got error %d while accessing filesystem\n", bp->b_error);
14390 	if (bp->b_error != ENXIO)
14391 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14392 }
14393 
14394 /*
14395  * Function to handle asynchronous write errors in the filesystem.
14396  */
14397 static void
14398 softdep_error(func, error)
14399 	char *func;
14400 	int error;
14401 {
14402 
14403 	/* XXX should do something better! */
14404 	printf("%s: got error %d while accessing filesystem\n", func, error);
14405 }
14406 
14407 #ifdef DDB
14408 
14409 /* exported to ffs_vfsops.c */
14410 extern void db_print_ffs(struct ufsmount *ump);
14411 void
14412 db_print_ffs(struct ufsmount *ump)
14413 {
14414 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14415 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14416 	db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14417 	    ump->um_fs, ump->softdep_on_worklist,
14418 	    ump->softdep_deps, ump->softdep_req);
14419 }
14420 
14421 static void
14422 worklist_print(struct worklist *wk, int verbose)
14423 {
14424 
14425 	if (!verbose) {
14426 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14427 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14428 		return;
14429 	}
14430 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14431 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14432 	    LIST_NEXT(wk, wk_list));
14433 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14434 }
14435 
14436 static void
14437 inodedep_print(struct inodedep *inodedep, int verbose)
14438 {
14439 
14440 	worklist_print(&inodedep->id_list, 0);
14441 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14442 	    inodedep->id_fs,
14443 	    (intmax_t)inodedep->id_ino,
14444 	    (intmax_t)fsbtodb(inodedep->id_fs,
14445 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14446 	    (intmax_t)inodedep->id_nlinkdelta,
14447 	    (intmax_t)inodedep->id_savednlink);
14448 
14449 	if (verbose == 0)
14450 		return;
14451 
14452 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14453 	    inodedep->id_bmsafemap,
14454 	    inodedep->id_mkdiradd,
14455 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14456 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14457 	    LIST_FIRST(&inodedep->id_dirremhd),
14458 	    LIST_FIRST(&inodedep->id_pendinghd),
14459 	    LIST_FIRST(&inodedep->id_bufwait));
14460 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14461 	    LIST_FIRST(&inodedep->id_inowait),
14462 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14463 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14464 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14465 	    TAILQ_FIRST(&inodedep->id_extupdt),
14466 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14467 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14468 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14469 	    inodedep->id_savedino1,
14470 	    (intmax_t)inodedep->id_savedsize,
14471 	    (intmax_t)inodedep->id_savedextsize);
14472 }
14473 
14474 static void
14475 newblk_print(struct newblk *nbp)
14476 {
14477 
14478 	worklist_print(&nbp->nb_list, 0);
14479 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14480 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14481 	    &nbp->nb_jnewblk,
14482 	    &nbp->nb_bmsafemap,
14483 	    &nbp->nb_freefrag);
14484 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14485 	    LIST_FIRST(&nbp->nb_indirdeps),
14486 	    LIST_FIRST(&nbp->nb_newdirblk),
14487 	    LIST_FIRST(&nbp->nb_jwork));
14488 }
14489 
14490 static void
14491 allocdirect_print(struct allocdirect *adp)
14492 {
14493 
14494 	newblk_print(&adp->ad_block);
14495 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14496 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14497 	db_printf("    offset %d, inodedep %p\n",
14498 	    adp->ad_offset, adp->ad_inodedep);
14499 }
14500 
14501 static void
14502 allocindir_print(struct allocindir *aip)
14503 {
14504 
14505 	newblk_print(&aip->ai_block);
14506 	db_printf("    oldblkno %jd, lbn %jd\n",
14507 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14508 	db_printf("    offset %d, indirdep %p\n",
14509 	    aip->ai_offset, aip->ai_indirdep);
14510 }
14511 
14512 static void
14513 mkdir_print(struct mkdir *mkdir)
14514 {
14515 
14516 	worklist_print(&mkdir->md_list, 0);
14517 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14518 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14519 }
14520 
14521 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14522 {
14523 
14524 	if (have_addr == 0) {
14525 		db_printf("inodedep address required\n");
14526 		return;
14527 	}
14528 	inodedep_print((struct inodedep*)addr, 1);
14529 }
14530 
14531 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14532 {
14533 	struct inodedep_hashhead *inodedephd;
14534 	struct inodedep *inodedep;
14535 	struct ufsmount *ump;
14536 	int cnt;
14537 
14538 	if (have_addr == 0) {
14539 		db_printf("ufsmount address required\n");
14540 		return;
14541 	}
14542 	ump = (struct ufsmount *)addr;
14543 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14544 		inodedephd = &ump->inodedep_hashtbl[cnt];
14545 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14546 			inodedep_print(inodedep, 0);
14547 		}
14548 	}
14549 }
14550 
14551 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14552 {
14553 
14554 	if (have_addr == 0) {
14555 		db_printf("worklist address required\n");
14556 		return;
14557 	}
14558 	worklist_print((struct worklist *)addr, 1);
14559 }
14560 
14561 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14562 {
14563 	struct worklist *wk;
14564 	struct workhead *wkhd;
14565 
14566 	if (have_addr == 0) {
14567 		db_printf("worklist address required "
14568 		    "(for example value in bp->b_dep)\n");
14569 		return;
14570 	}
14571 	/*
14572 	 * We often do not have the address of the worklist head but
14573 	 * instead a pointer to its first entry (e.g., we have the
14574 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
14575 	 * pointer of bp->b_dep will point at the head of the list, so
14576 	 * we cheat and use that instead. If we are in the middle of
14577 	 * a list we will still get the same result, so nothing
14578 	 * unexpected will result.
14579 	 */
14580 	wk = (struct worklist *)addr;
14581 	if (wk == NULL)
14582 		return;
14583 	wkhd = (struct workhead *)wk->wk_list.le_prev;
14584 	LIST_FOREACH(wk, wkhd, wk_list) {
14585 		switch(wk->wk_type) {
14586 		case D_INODEDEP:
14587 			inodedep_print(WK_INODEDEP(wk), 0);
14588 			continue;
14589 		case D_ALLOCDIRECT:
14590 			allocdirect_print(WK_ALLOCDIRECT(wk));
14591 			continue;
14592 		case D_ALLOCINDIR:
14593 			allocindir_print(WK_ALLOCINDIR(wk));
14594 			continue;
14595 		case D_MKDIR:
14596 			mkdir_print(WK_MKDIR(wk));
14597 			continue;
14598 		default:
14599 			worklist_print(wk, 0);
14600 			continue;
14601 		}
14602 	}
14603 }
14604 
14605 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14606 {
14607 	if (have_addr == 0) {
14608 		db_printf("mkdir address required\n");
14609 		return;
14610 	}
14611 	mkdir_print((struct mkdir *)addr);
14612 }
14613 
14614 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14615 {
14616 	struct mkdirlist *mkdirlisthd;
14617 	struct mkdir *mkdir;
14618 
14619 	if (have_addr == 0) {
14620 		db_printf("mkdir listhead address required\n");
14621 		return;
14622 	}
14623 	mkdirlisthd = (struct mkdirlist *)addr;
14624 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14625 		mkdir_print(mkdir);
14626 		if (mkdir->md_diradd != NULL) {
14627 			db_printf("    ");
14628 			worklist_print(&mkdir->md_diradd->da_list, 0);
14629 		}
14630 		if (mkdir->md_jaddref != NULL) {
14631 			db_printf("    ");
14632 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
14633 		}
14634 	}
14635 }
14636 
14637 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
14638 {
14639 	if (have_addr == 0) {
14640 		db_printf("allocdirect address required\n");
14641 		return;
14642 	}
14643 	allocdirect_print((struct allocdirect *)addr);
14644 }
14645 
14646 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
14647 {
14648 	if (have_addr == 0) {
14649 		db_printf("allocindir address required\n");
14650 		return;
14651 	}
14652 	allocindir_print((struct allocindir *)addr);
14653 }
14654 
14655 #endif /* DDB */
14656 
14657 #endif /* SOFTUPDATES */
14658