xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 036d2e814bf0f5d88ffb4b24c159320894541757)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1998, 2000 Marshall Kirk McKusick.
5  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
6  * All rights reserved.
7  *
8  * The soft updates code is derived from the appendix of a University
9  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
10  * "Soft Updates: A Solution to the Metadata Update Problem in File
11  * Systems", CSE-TR-254-95, August 1995).
12  *
13  * Further information about soft updates can be obtained from:
14  *
15  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
16  *	1614 Oxford Street		mckusick@mckusick.com
17  *	Berkeley, CA 94709-1608		+1-510-843-9542
18  *	USA
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
35  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
36  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
42  */
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include "opt_ffs.h"
48 #include "opt_quota.h"
49 #include "opt_ddb.h"
50 
51 #include <sys/param.h>
52 #include <sys/kernel.h>
53 #include <sys/systm.h>
54 #include <sys/bio.h>
55 #include <sys/buf.h>
56 #include <sys/kdb.h>
57 #include <sys/kthread.h>
58 #include <sys/ktr.h>
59 #include <sys/limits.h>
60 #include <sys/lock.h>
61 #include <sys/malloc.h>
62 #include <sys/mount.h>
63 #include <sys/mutex.h>
64 #include <sys/namei.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/racct.h>
68 #include <sys/rwlock.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/syslog.h>
72 #include <sys/vnode.h>
73 #include <sys/conf.h>
74 
75 #include <ufs/ufs/dir.h>
76 #include <ufs/ufs/extattr.h>
77 #include <ufs/ufs/quota.h>
78 #include <ufs/ufs/inode.h>
79 #include <ufs/ufs/ufsmount.h>
80 #include <ufs/ffs/fs.h>
81 #include <ufs/ffs/softdep.h>
82 #include <ufs/ffs/ffs_extern.h>
83 #include <ufs/ufs/ufs_extern.h>
84 
85 #include <vm/vm.h>
86 #include <vm/vm_extern.h>
87 #include <vm/vm_object.h>
88 
89 #include <geom/geom.h>
90 
91 #include <ddb/ddb.h>
92 
93 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
94 
95 #ifndef SOFTUPDATES
96 
97 int
98 softdep_flushfiles(oldmnt, flags, td)
99 	struct mount *oldmnt;
100 	int flags;
101 	struct thread *td;
102 {
103 
104 	panic("softdep_flushfiles called");
105 }
106 
107 int
108 softdep_mount(devvp, mp, fs, cred)
109 	struct vnode *devvp;
110 	struct mount *mp;
111 	struct fs *fs;
112 	struct ucred *cred;
113 {
114 
115 	return (0);
116 }
117 
118 void
119 softdep_initialize()
120 {
121 
122 	return;
123 }
124 
125 void
126 softdep_uninitialize()
127 {
128 
129 	return;
130 }
131 
132 void
133 softdep_unmount(mp)
134 	struct mount *mp;
135 {
136 
137 	panic("softdep_unmount called");
138 }
139 
140 void
141 softdep_setup_sbupdate(ump, fs, bp)
142 	struct ufsmount *ump;
143 	struct fs *fs;
144 	struct buf *bp;
145 {
146 
147 	panic("softdep_setup_sbupdate called");
148 }
149 
150 void
151 softdep_setup_inomapdep(bp, ip, newinum, mode)
152 	struct buf *bp;
153 	struct inode *ip;
154 	ino_t newinum;
155 	int mode;
156 {
157 
158 	panic("softdep_setup_inomapdep called");
159 }
160 
161 void
162 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
163 	struct buf *bp;
164 	struct mount *mp;
165 	ufs2_daddr_t newblkno;
166 	int frags;
167 	int oldfrags;
168 {
169 
170 	panic("softdep_setup_blkmapdep called");
171 }
172 
173 void
174 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
175 	struct inode *ip;
176 	ufs_lbn_t lbn;
177 	ufs2_daddr_t newblkno;
178 	ufs2_daddr_t oldblkno;
179 	long newsize;
180 	long oldsize;
181 	struct buf *bp;
182 {
183 
184 	panic("softdep_setup_allocdirect called");
185 }
186 
187 void
188 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
189 	struct inode *ip;
190 	ufs_lbn_t lbn;
191 	ufs2_daddr_t newblkno;
192 	ufs2_daddr_t oldblkno;
193 	long newsize;
194 	long oldsize;
195 	struct buf *bp;
196 {
197 
198 	panic("softdep_setup_allocext called");
199 }
200 
201 void
202 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
203 	struct inode *ip;
204 	ufs_lbn_t lbn;
205 	struct buf *bp;
206 	int ptrno;
207 	ufs2_daddr_t newblkno;
208 	ufs2_daddr_t oldblkno;
209 	struct buf *nbp;
210 {
211 
212 	panic("softdep_setup_allocindir_page called");
213 }
214 
215 void
216 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
217 	struct buf *nbp;
218 	struct inode *ip;
219 	struct buf *bp;
220 	int ptrno;
221 	ufs2_daddr_t newblkno;
222 {
223 
224 	panic("softdep_setup_allocindir_meta called");
225 }
226 
227 void
228 softdep_journal_freeblocks(ip, cred, length, flags)
229 	struct inode *ip;
230 	struct ucred *cred;
231 	off_t length;
232 	int flags;
233 {
234 
235 	panic("softdep_journal_freeblocks called");
236 }
237 
238 void
239 softdep_journal_fsync(ip)
240 	struct inode *ip;
241 {
242 
243 	panic("softdep_journal_fsync called");
244 }
245 
246 void
247 softdep_setup_freeblocks(ip, length, flags)
248 	struct inode *ip;
249 	off_t length;
250 	int flags;
251 {
252 
253 	panic("softdep_setup_freeblocks called");
254 }
255 
256 void
257 softdep_freefile(pvp, ino, mode)
258 		struct vnode *pvp;
259 		ino_t ino;
260 		int mode;
261 {
262 
263 	panic("softdep_freefile called");
264 }
265 
266 int
267 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
268 	struct buf *bp;
269 	struct inode *dp;
270 	off_t diroffset;
271 	ino_t newinum;
272 	struct buf *newdirbp;
273 	int isnewblk;
274 {
275 
276 	panic("softdep_setup_directory_add called");
277 }
278 
279 void
280 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
281 	struct buf *bp;
282 	struct inode *dp;
283 	caddr_t base;
284 	caddr_t oldloc;
285 	caddr_t newloc;
286 	int entrysize;
287 {
288 
289 	panic("softdep_change_directoryentry_offset called");
290 }
291 
292 void
293 softdep_setup_remove(bp, dp, ip, isrmdir)
294 	struct buf *bp;
295 	struct inode *dp;
296 	struct inode *ip;
297 	int isrmdir;
298 {
299 
300 	panic("softdep_setup_remove called");
301 }
302 
303 void
304 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
305 	struct buf *bp;
306 	struct inode *dp;
307 	struct inode *ip;
308 	ino_t newinum;
309 	int isrmdir;
310 {
311 
312 	panic("softdep_setup_directory_change called");
313 }
314 
315 void
316 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
317 	struct mount *mp;
318 	struct buf *bp;
319 	ufs2_daddr_t blkno;
320 	int frags;
321 	struct workhead *wkhd;
322 {
323 
324 	panic("%s called", __FUNCTION__);
325 }
326 
327 void
328 softdep_setup_inofree(mp, bp, ino, wkhd)
329 	struct mount *mp;
330 	struct buf *bp;
331 	ino_t ino;
332 	struct workhead *wkhd;
333 {
334 
335 	panic("%s called", __FUNCTION__);
336 }
337 
338 void
339 softdep_setup_unlink(dp, ip)
340 	struct inode *dp;
341 	struct inode *ip;
342 {
343 
344 	panic("%s called", __FUNCTION__);
345 }
346 
347 void
348 softdep_setup_link(dp, ip)
349 	struct inode *dp;
350 	struct inode *ip;
351 {
352 
353 	panic("%s called", __FUNCTION__);
354 }
355 
356 void
357 softdep_revert_link(dp, ip)
358 	struct inode *dp;
359 	struct inode *ip;
360 {
361 
362 	panic("%s called", __FUNCTION__);
363 }
364 
365 void
366 softdep_setup_rmdir(dp, ip)
367 	struct inode *dp;
368 	struct inode *ip;
369 {
370 
371 	panic("%s called", __FUNCTION__);
372 }
373 
374 void
375 softdep_revert_rmdir(dp, ip)
376 	struct inode *dp;
377 	struct inode *ip;
378 {
379 
380 	panic("%s called", __FUNCTION__);
381 }
382 
383 void
384 softdep_setup_create(dp, ip)
385 	struct inode *dp;
386 	struct inode *ip;
387 {
388 
389 	panic("%s called", __FUNCTION__);
390 }
391 
392 void
393 softdep_revert_create(dp, ip)
394 	struct inode *dp;
395 	struct inode *ip;
396 {
397 
398 	panic("%s called", __FUNCTION__);
399 }
400 
401 void
402 softdep_setup_mkdir(dp, ip)
403 	struct inode *dp;
404 	struct inode *ip;
405 {
406 
407 	panic("%s called", __FUNCTION__);
408 }
409 
410 void
411 softdep_revert_mkdir(dp, ip)
412 	struct inode *dp;
413 	struct inode *ip;
414 {
415 
416 	panic("%s called", __FUNCTION__);
417 }
418 
419 void
420 softdep_setup_dotdot_link(dp, ip)
421 	struct inode *dp;
422 	struct inode *ip;
423 {
424 
425 	panic("%s called", __FUNCTION__);
426 }
427 
428 int
429 softdep_prealloc(vp, waitok)
430 	struct vnode *vp;
431 	int waitok;
432 {
433 
434 	panic("%s called", __FUNCTION__);
435 }
436 
437 int
438 softdep_journal_lookup(mp, vpp)
439 	struct mount *mp;
440 	struct vnode **vpp;
441 {
442 
443 	return (ENOENT);
444 }
445 
446 void
447 softdep_change_linkcnt(ip)
448 	struct inode *ip;
449 {
450 
451 	panic("softdep_change_linkcnt called");
452 }
453 
454 void
455 softdep_load_inodeblock(ip)
456 	struct inode *ip;
457 {
458 
459 	panic("softdep_load_inodeblock called");
460 }
461 
462 void
463 softdep_update_inodeblock(ip, bp, waitfor)
464 	struct inode *ip;
465 	struct buf *bp;
466 	int waitfor;
467 {
468 
469 	panic("softdep_update_inodeblock called");
470 }
471 
472 int
473 softdep_fsync(vp)
474 	struct vnode *vp;	/* the "in_core" copy of the inode */
475 {
476 
477 	return (0);
478 }
479 
480 void
481 softdep_fsync_mountdev(vp)
482 	struct vnode *vp;
483 {
484 
485 	return;
486 }
487 
488 int
489 softdep_flushworklist(oldmnt, countp, td)
490 	struct mount *oldmnt;
491 	int *countp;
492 	struct thread *td;
493 {
494 
495 	*countp = 0;
496 	return (0);
497 }
498 
499 int
500 softdep_sync_metadata(struct vnode *vp)
501 {
502 
503 	panic("softdep_sync_metadata called");
504 }
505 
506 int
507 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
508 {
509 
510 	panic("softdep_sync_buf called");
511 }
512 
513 int
514 softdep_slowdown(vp)
515 	struct vnode *vp;
516 {
517 
518 	panic("softdep_slowdown called");
519 }
520 
521 int
522 softdep_request_cleanup(fs, vp, cred, resource)
523 	struct fs *fs;
524 	struct vnode *vp;
525 	struct ucred *cred;
526 	int resource;
527 {
528 
529 	return (0);
530 }
531 
532 int
533 softdep_check_suspend(struct mount *mp,
534 		      struct vnode *devvp,
535 		      int softdep_depcnt,
536 		      int softdep_accdepcnt,
537 		      int secondary_writes,
538 		      int secondary_accwrites)
539 {
540 	struct bufobj *bo;
541 	int error;
542 
543 	(void) softdep_depcnt,
544 	(void) softdep_accdepcnt;
545 
546 	bo = &devvp->v_bufobj;
547 	ASSERT_BO_WLOCKED(bo);
548 
549 	MNT_ILOCK(mp);
550 	while (mp->mnt_secondary_writes != 0) {
551 		BO_UNLOCK(bo);
552 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
553 		    (PUSER - 1) | PDROP, "secwr", 0);
554 		BO_LOCK(bo);
555 		MNT_ILOCK(mp);
556 	}
557 
558 	/*
559 	 * Reasons for needing more work before suspend:
560 	 * - Dirty buffers on devvp.
561 	 * - Secondary writes occurred after start of vnode sync loop
562 	 */
563 	error = 0;
564 	if (bo->bo_numoutput > 0 ||
565 	    bo->bo_dirty.bv_cnt > 0 ||
566 	    secondary_writes != 0 ||
567 	    mp->mnt_secondary_writes != 0 ||
568 	    secondary_accwrites != mp->mnt_secondary_accwrites)
569 		error = EAGAIN;
570 	BO_UNLOCK(bo);
571 	return (error);
572 }
573 
574 void
575 softdep_get_depcounts(struct mount *mp,
576 		      int *softdepactivep,
577 		      int *softdepactiveaccp)
578 {
579 	(void) mp;
580 	*softdepactivep = 0;
581 	*softdepactiveaccp = 0;
582 }
583 
584 void
585 softdep_buf_append(bp, wkhd)
586 	struct buf *bp;
587 	struct workhead *wkhd;
588 {
589 
590 	panic("softdep_buf_appendwork called");
591 }
592 
593 void
594 softdep_inode_append(ip, cred, wkhd)
595 	struct inode *ip;
596 	struct ucred *cred;
597 	struct workhead *wkhd;
598 {
599 
600 	panic("softdep_inode_appendwork called");
601 }
602 
603 void
604 softdep_freework(wkhd)
605 	struct workhead *wkhd;
606 {
607 
608 	panic("softdep_freework called");
609 }
610 
611 #else
612 
613 FEATURE(softupdates, "FFS soft-updates support");
614 
615 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
616     "soft updates stats");
617 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
618     "total dependencies allocated");
619 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
620     "high use dependencies allocated");
621 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
622     "current dependencies allocated");
623 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
624     "current dependencies written");
625 
626 unsigned long dep_current[D_LAST + 1];
627 unsigned long dep_highuse[D_LAST + 1];
628 unsigned long dep_total[D_LAST + 1];
629 unsigned long dep_write[D_LAST + 1];
630 
631 #define	SOFTDEP_TYPE(type, str, long)					\
632     static MALLOC_DEFINE(M_ ## type, #str, long);			\
633     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
634 	&dep_total[D_ ## type], 0, "");					\
635     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
636 	&dep_current[D_ ## type], 0, "");				\
637     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
638 	&dep_highuse[D_ ## type], 0, "");				\
639     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
640 	&dep_write[D_ ## type], 0, "");
641 
642 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
643 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
644 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
645     "Block or frag allocated from cyl group map");
646 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
647 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
648 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
649 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
650 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
651 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
652 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
653 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
654 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
655 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
656 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
657 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
658 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
659 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
660 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
661 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
662 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
663 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
664 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
665 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
666 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
667 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
668 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
669 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
670 
671 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
672 
673 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
674 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
675 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
676 
677 #define M_SOFTDEP_FLAGS	(M_WAITOK)
678 
679 /*
680  * translate from workitem type to memory type
681  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
682  */
683 static struct malloc_type *memtype[] = {
684 	NULL,
685 	M_PAGEDEP,
686 	M_INODEDEP,
687 	M_BMSAFEMAP,
688 	M_NEWBLK,
689 	M_ALLOCDIRECT,
690 	M_INDIRDEP,
691 	M_ALLOCINDIR,
692 	M_FREEFRAG,
693 	M_FREEBLKS,
694 	M_FREEFILE,
695 	M_DIRADD,
696 	M_MKDIR,
697 	M_DIRREM,
698 	M_NEWDIRBLK,
699 	M_FREEWORK,
700 	M_FREEDEP,
701 	M_JADDREF,
702 	M_JREMREF,
703 	M_JMVREF,
704 	M_JNEWBLK,
705 	M_JFREEBLK,
706 	M_JFREEFRAG,
707 	M_JSEG,
708 	M_JSEGDEP,
709 	M_SBDEP,
710 	M_JTRUNC,
711 	M_JFSYNC,
712 	M_SENTINEL
713 };
714 
715 #define DtoM(type) (memtype[type])
716 
717 /*
718  * Names of malloc types.
719  */
720 #define TYPENAME(type)  \
721 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
722 	memtype[type]->ks_shortdesc : "???")
723 /*
724  * End system adaptation definitions.
725  */
726 
727 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
728 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
729 
730 /*
731  * Internal function prototypes.
732  */
733 static	void check_clear_deps(struct mount *);
734 static	void softdep_error(char *, int);
735 static	int softdep_process_worklist(struct mount *, int);
736 static	int softdep_waitidle(struct mount *, int);
737 static	void drain_output(struct vnode *);
738 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
739 static	int check_inodedep_free(struct inodedep *);
740 static	void clear_remove(struct mount *);
741 static	void clear_inodedeps(struct mount *);
742 static	void unlinked_inodedep(struct mount *, struct inodedep *);
743 static	void clear_unlinked_inodedep(struct inodedep *);
744 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
745 static	int flush_pagedep_deps(struct vnode *, struct mount *,
746 	    struct diraddhd *);
747 static	int free_pagedep(struct pagedep *);
748 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
749 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
750 static	int flush_deplist(struct allocdirectlst *, int, int *);
751 static	int sync_cgs(struct mount *, int);
752 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
753 static	int handle_written_sbdep(struct sbdep *, struct buf *);
754 static	void initiate_write_sbdep(struct sbdep *);
755 static	void diradd_inode_written(struct diradd *, struct inodedep *);
756 static	int handle_written_indirdep(struct indirdep *, struct buf *,
757 	    struct buf**, int);
758 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
759 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
760 	    uint8_t *);
761 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
762 static	void handle_written_jaddref(struct jaddref *);
763 static	void handle_written_jremref(struct jremref *);
764 static	void handle_written_jseg(struct jseg *, struct buf *);
765 static	void handle_written_jnewblk(struct jnewblk *);
766 static	void handle_written_jblkdep(struct jblkdep *);
767 static	void handle_written_jfreefrag(struct jfreefrag *);
768 static	void complete_jseg(struct jseg *);
769 static	void complete_jsegs(struct jseg *);
770 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
771 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
772 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
773 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
774 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
775 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
776 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
777 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
778 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
779 static	inline void inoref_write(struct inoref *, struct jseg *,
780 	    struct jrefrec *);
781 static	void handle_allocdirect_partdone(struct allocdirect *,
782 	    struct workhead *);
783 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
784 	    struct workhead *);
785 static	void indirdep_complete(struct indirdep *);
786 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
787 static	void indirblk_insert(struct freework *);
788 static	void indirblk_remove(struct freework *);
789 static	void handle_allocindir_partdone(struct allocindir *);
790 static	void initiate_write_filepage(struct pagedep *, struct buf *);
791 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
792 static	void handle_written_mkdir(struct mkdir *, int);
793 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
794 	    uint8_t *);
795 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
796 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
797 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
798 static	void handle_workitem_freefile(struct freefile *);
799 static	int handle_workitem_remove(struct dirrem *, int);
800 static	struct dirrem *newdirrem(struct buf *, struct inode *,
801 	    struct inode *, int, struct dirrem **);
802 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
803 	    struct buf *);
804 static	void cancel_indirdep(struct indirdep *, struct buf *,
805 	    struct freeblks *);
806 static	void free_indirdep(struct indirdep *);
807 static	void free_diradd(struct diradd *, struct workhead *);
808 static	void merge_diradd(struct inodedep *, struct diradd *);
809 static	void complete_diradd(struct diradd *);
810 static	struct diradd *diradd_lookup(struct pagedep *, int);
811 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
812 	    struct jremref *);
813 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
814 	    struct jremref *);
815 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
816 	    struct jremref *, struct jremref *);
817 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
818 	    struct jremref *);
819 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
820 	    struct freeblks *, int);
821 static	int setup_trunc_indir(struct freeblks *, struct inode *,
822 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
823 static	void complete_trunc_indir(struct freework *);
824 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
825 	    int);
826 static	void complete_mkdir(struct mkdir *);
827 static	void free_newdirblk(struct newdirblk *);
828 static	void free_jremref(struct jremref *);
829 static	void free_jaddref(struct jaddref *);
830 static	void free_jsegdep(struct jsegdep *);
831 static	void free_jsegs(struct jblocks *);
832 static	void rele_jseg(struct jseg *);
833 static	void free_jseg(struct jseg *, struct jblocks *);
834 static	void free_jnewblk(struct jnewblk *);
835 static	void free_jblkdep(struct jblkdep *);
836 static	void free_jfreefrag(struct jfreefrag *);
837 static	void free_freedep(struct freedep *);
838 static	void journal_jremref(struct dirrem *, struct jremref *,
839 	    struct inodedep *);
840 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
841 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
842 	    struct workhead *);
843 static	void cancel_jfreefrag(struct jfreefrag *);
844 static	inline void setup_freedirect(struct freeblks *, struct inode *,
845 	    int, int);
846 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
847 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
848 	    ufs_lbn_t, int);
849 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
850 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
851 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
852 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
853 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
854 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
855 	    int, int);
856 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
857 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
858 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
859 static	void newblk_freefrag(struct newblk*);
860 static	void free_newblk(struct newblk *);
861 static	void cancel_allocdirect(struct allocdirectlst *,
862 	    struct allocdirect *, struct freeblks *);
863 static	int check_inode_unwritten(struct inodedep *);
864 static	int free_inodedep(struct inodedep *);
865 static	void freework_freeblock(struct freework *, u_long);
866 static	void freework_enqueue(struct freework *);
867 static	int handle_workitem_freeblocks(struct freeblks *, int);
868 static	int handle_complete_freeblocks(struct freeblks *, int);
869 static	void handle_workitem_indirblk(struct freework *);
870 static	void handle_written_freework(struct freework *);
871 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
872 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
873 	    struct workhead *);
874 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
875 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
876 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
877 	    ufs2_daddr_t, ufs_lbn_t);
878 static	void handle_workitem_freefrag(struct freefrag *);
879 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
880 	    ufs_lbn_t, u_long);
881 static	void allocdirect_merge(struct allocdirectlst *,
882 	    struct allocdirect *, struct allocdirect *);
883 static	struct freefrag *allocindir_merge(struct allocindir *,
884 	    struct allocindir *);
885 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
886 	    struct bmsafemap **);
887 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
888 	    int cg, struct bmsafemap *);
889 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
890 	    struct newblk **);
891 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
892 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
893 	    struct inodedep **);
894 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
895 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
896 	    int, struct pagedep **);
897 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
898 	    struct pagedep **);
899 static	void pause_timer(void *);
900 static	int request_cleanup(struct mount *, int);
901 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
902 static	void schedule_cleanup(struct mount *);
903 static void softdep_ast_cleanup_proc(struct thread *);
904 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
905 static	int process_worklist_item(struct mount *, int, int);
906 static	void process_removes(struct vnode *);
907 static	void process_truncates(struct vnode *);
908 static	void jwork_move(struct workhead *, struct workhead *);
909 static	void jwork_insert(struct workhead *, struct jsegdep *);
910 static	void add_to_worklist(struct worklist *, int);
911 static	void wake_worklist(struct worklist *);
912 static	void wait_worklist(struct worklist *, char *);
913 static	void remove_from_worklist(struct worklist *);
914 static	void softdep_flush(void *);
915 static	void softdep_flushjournal(struct mount *);
916 static	int softdep_speedup(struct ufsmount *);
917 static	void worklist_speedup(struct mount *);
918 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
919 static	void journal_unmount(struct ufsmount *);
920 static	int journal_space(struct ufsmount *, int);
921 static	void journal_suspend(struct ufsmount *);
922 static	int journal_unsuspend(struct ufsmount *ump);
923 static	void softdep_prelink(struct vnode *, struct vnode *);
924 static	void add_to_journal(struct worklist *);
925 static	void remove_from_journal(struct worklist *);
926 static	bool softdep_excess_items(struct ufsmount *, int);
927 static	void softdep_process_journal(struct mount *, struct worklist *, int);
928 static	struct jremref *newjremref(struct dirrem *, struct inode *,
929 	    struct inode *ip, off_t, nlink_t);
930 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
931 	    uint16_t);
932 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
933 	    uint16_t);
934 static	inline struct jsegdep *inoref_jseg(struct inoref *);
935 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
936 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
937 	    ufs2_daddr_t, int);
938 static	void adjust_newfreework(struct freeblks *, int);
939 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
940 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
941 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
942 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
943 	    ufs2_daddr_t, long, ufs_lbn_t);
944 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
945 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
946 static	int jwait(struct worklist *, int);
947 static	struct inodedep *inodedep_lookup_ip(struct inode *);
948 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
949 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
950 static	void handle_jwork(struct workhead *);
951 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
952 	    struct mkdir **);
953 static	struct jblocks *jblocks_create(void);
954 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
955 static	void jblocks_free(struct jblocks *, struct mount *, int);
956 static	void jblocks_destroy(struct jblocks *);
957 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
958 
959 /*
960  * Exported softdep operations.
961  */
962 static	void softdep_disk_io_initiation(struct buf *);
963 static	void softdep_disk_write_complete(struct buf *);
964 static	void softdep_deallocate_dependencies(struct buf *);
965 static	int softdep_count_dependencies(struct buf *bp, int);
966 
967 /*
968  * Global lock over all of soft updates.
969  */
970 static struct mtx lk;
971 MTX_SYSINIT(softdep_lock, &lk, "Global Softdep Lock", MTX_DEF);
972 
973 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
974 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
975 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
976 
977 /*
978  * Per-filesystem soft-updates locking.
979  */
980 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
981 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
982 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
983 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
984 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
985 				    RA_WLOCKED)
986 
987 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
988 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
989 
990 /*
991  * Worklist queue management.
992  * These routines require that the lock be held.
993  */
994 #ifndef /* NOT */ INVARIANTS
995 #define WORKLIST_INSERT(head, item) do {	\
996 	(item)->wk_state |= ONWORKLIST;		\
997 	LIST_INSERT_HEAD(head, item, wk_list);	\
998 } while (0)
999 #define WORKLIST_REMOVE(item) do {		\
1000 	(item)->wk_state &= ~ONWORKLIST;	\
1001 	LIST_REMOVE(item, wk_list);		\
1002 } while (0)
1003 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1004 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1005 
1006 #else /* INVARIANTS */
1007 static	void worklist_insert(struct workhead *, struct worklist *, int,
1008 	const char *, int);
1009 static	void worklist_remove(struct worklist *, int, const char *, int);
1010 
1011 #define WORKLIST_INSERT(head, item) \
1012 	worklist_insert(head, item, 1, __func__, __LINE__)
1013 #define WORKLIST_INSERT_UNLOCKED(head, item)\
1014 	worklist_insert(head, item, 0, __func__, __LINE__)
1015 #define WORKLIST_REMOVE(item)\
1016 	worklist_remove(item, 1, __func__, __LINE__)
1017 #define WORKLIST_REMOVE_UNLOCKED(item)\
1018 	worklist_remove(item, 0, __func__, __LINE__)
1019 
1020 static void
1021 worklist_insert(head, item, locked, func, line)
1022 	struct workhead *head;
1023 	struct worklist *item;
1024 	int locked;
1025 	const char *func;
1026 	int line;
1027 {
1028 
1029 	if (locked)
1030 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1031 	if (item->wk_state & ONWORKLIST)
1032 		panic("worklist_insert: %p %s(0x%X) already on list, "
1033 		    "added in function %s at line %d",
1034 		    item, TYPENAME(item->wk_type), item->wk_state,
1035 		    item->wk_func, item->wk_line);
1036 	item->wk_state |= ONWORKLIST;
1037 	item->wk_func = func;
1038 	item->wk_line = line;
1039 	LIST_INSERT_HEAD(head, item, wk_list);
1040 }
1041 
1042 static void
1043 worklist_remove(item, locked, func, line)
1044 	struct worklist *item;
1045 	int locked;
1046 	const char *func;
1047 	int line;
1048 {
1049 
1050 	if (locked)
1051 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1052 	if ((item->wk_state & ONWORKLIST) == 0)
1053 		panic("worklist_remove: %p %s(0x%X) not on list, "
1054 		    "removed in function %s at line %d",
1055 		    item, TYPENAME(item->wk_type), item->wk_state,
1056 		    item->wk_func, item->wk_line);
1057 	item->wk_state &= ~ONWORKLIST;
1058 	item->wk_func = func;
1059 	item->wk_line = line;
1060 	LIST_REMOVE(item, wk_list);
1061 }
1062 #endif /* INVARIANTS */
1063 
1064 /*
1065  * Merge two jsegdeps keeping only the oldest one as newer references
1066  * can't be discarded until after older references.
1067  */
1068 static inline struct jsegdep *
1069 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1070 {
1071 	struct jsegdep *swp;
1072 
1073 	if (two == NULL)
1074 		return (one);
1075 
1076 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1077 		swp = one;
1078 		one = two;
1079 		two = swp;
1080 	}
1081 	WORKLIST_REMOVE(&two->jd_list);
1082 	free_jsegdep(two);
1083 
1084 	return (one);
1085 }
1086 
1087 /*
1088  * If two freedeps are compatible free one to reduce list size.
1089  */
1090 static inline struct freedep *
1091 freedep_merge(struct freedep *one, struct freedep *two)
1092 {
1093 	if (two == NULL)
1094 		return (one);
1095 
1096 	if (one->fd_freework == two->fd_freework) {
1097 		WORKLIST_REMOVE(&two->fd_list);
1098 		free_freedep(two);
1099 	}
1100 	return (one);
1101 }
1102 
1103 /*
1104  * Move journal work from one list to another.  Duplicate freedeps and
1105  * jsegdeps are coalesced to keep the lists as small as possible.
1106  */
1107 static void
1108 jwork_move(dst, src)
1109 	struct workhead *dst;
1110 	struct workhead *src;
1111 {
1112 	struct freedep *freedep;
1113 	struct jsegdep *jsegdep;
1114 	struct worklist *wkn;
1115 	struct worklist *wk;
1116 
1117 	KASSERT(dst != src,
1118 	    ("jwork_move: dst == src"));
1119 	freedep = NULL;
1120 	jsegdep = NULL;
1121 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1122 		if (wk->wk_type == D_JSEGDEP)
1123 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1124 		else if (wk->wk_type == D_FREEDEP)
1125 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1126 	}
1127 
1128 	while ((wk = LIST_FIRST(src)) != NULL) {
1129 		WORKLIST_REMOVE(wk);
1130 		WORKLIST_INSERT(dst, wk);
1131 		if (wk->wk_type == D_JSEGDEP) {
1132 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1133 			continue;
1134 		}
1135 		if (wk->wk_type == D_FREEDEP)
1136 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1137 	}
1138 }
1139 
1140 static void
1141 jwork_insert(dst, jsegdep)
1142 	struct workhead *dst;
1143 	struct jsegdep *jsegdep;
1144 {
1145 	struct jsegdep *jsegdepn;
1146 	struct worklist *wk;
1147 
1148 	LIST_FOREACH(wk, dst, wk_list)
1149 		if (wk->wk_type == D_JSEGDEP)
1150 			break;
1151 	if (wk == NULL) {
1152 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1153 		return;
1154 	}
1155 	jsegdepn = WK_JSEGDEP(wk);
1156 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1157 		WORKLIST_REMOVE(wk);
1158 		free_jsegdep(jsegdepn);
1159 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1160 	} else
1161 		free_jsegdep(jsegdep);
1162 }
1163 
1164 /*
1165  * Routines for tracking and managing workitems.
1166  */
1167 static	void workitem_free(struct worklist *, int);
1168 static	void workitem_alloc(struct worklist *, int, struct mount *);
1169 static	void workitem_reassign(struct worklist *, int);
1170 
1171 #define	WORKITEM_FREE(item, type) \
1172 	workitem_free((struct worklist *)(item), (type))
1173 #define	WORKITEM_REASSIGN(item, type) \
1174 	workitem_reassign((struct worklist *)(item), (type))
1175 
1176 static void
1177 workitem_free(item, type)
1178 	struct worklist *item;
1179 	int type;
1180 {
1181 	struct ufsmount *ump;
1182 
1183 #ifdef INVARIANTS
1184 	if (item->wk_state & ONWORKLIST)
1185 		panic("workitem_free: %s(0x%X) still on list, "
1186 		    "added in function %s at line %d",
1187 		    TYPENAME(item->wk_type), item->wk_state,
1188 		    item->wk_func, item->wk_line);
1189 	if (item->wk_type != type && type != D_NEWBLK)
1190 		panic("workitem_free: type mismatch %s != %s",
1191 		    TYPENAME(item->wk_type), TYPENAME(type));
1192 #endif
1193 	if (item->wk_state & IOWAITING)
1194 		wakeup(item);
1195 	ump = VFSTOUFS(item->wk_mp);
1196 	LOCK_OWNED(ump);
1197 	KASSERT(ump->softdep_deps > 0,
1198 	    ("workitem_free: %s: softdep_deps going negative",
1199 	    ump->um_fs->fs_fsmnt));
1200 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1201 		wakeup(&ump->softdep_deps);
1202 	KASSERT(dep_current[item->wk_type] > 0,
1203 	    ("workitem_free: %s: dep_current[%s] going negative",
1204 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1205 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1206 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1207 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1208 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1209 	ump->softdep_curdeps[item->wk_type] -= 1;
1210 	free(item, DtoM(type));
1211 }
1212 
1213 static void
1214 workitem_alloc(item, type, mp)
1215 	struct worklist *item;
1216 	int type;
1217 	struct mount *mp;
1218 {
1219 	struct ufsmount *ump;
1220 
1221 	item->wk_type = type;
1222 	item->wk_mp = mp;
1223 	item->wk_state = 0;
1224 
1225 	ump = VFSTOUFS(mp);
1226 	ACQUIRE_GBLLOCK(&lk);
1227 	dep_current[type]++;
1228 	if (dep_current[type] > dep_highuse[type])
1229 		dep_highuse[type] = dep_current[type];
1230 	dep_total[type]++;
1231 	FREE_GBLLOCK(&lk);
1232 	ACQUIRE_LOCK(ump);
1233 	ump->softdep_curdeps[type] += 1;
1234 	ump->softdep_deps++;
1235 	ump->softdep_accdeps++;
1236 	FREE_LOCK(ump);
1237 }
1238 
1239 static void
1240 workitem_reassign(item, newtype)
1241 	struct worklist *item;
1242 	int newtype;
1243 {
1244 	struct ufsmount *ump;
1245 
1246 	ump = VFSTOUFS(item->wk_mp);
1247 	LOCK_OWNED(ump);
1248 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1249 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1250 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1251 	ump->softdep_curdeps[item->wk_type] -= 1;
1252 	ump->softdep_curdeps[newtype] += 1;
1253 	KASSERT(dep_current[item->wk_type] > 0,
1254 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1255 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1256 	ACQUIRE_GBLLOCK(&lk);
1257 	dep_current[newtype]++;
1258 	dep_current[item->wk_type]--;
1259 	if (dep_current[newtype] > dep_highuse[newtype])
1260 		dep_highuse[newtype] = dep_current[newtype];
1261 	dep_total[newtype]++;
1262 	FREE_GBLLOCK(&lk);
1263 	item->wk_type = newtype;
1264 }
1265 
1266 /*
1267  * Workitem queue management
1268  */
1269 static int max_softdeps;	/* maximum number of structs before slowdown */
1270 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1271 static int proc_waiting;	/* tracks whether we have a timeout posted */
1272 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1273 static struct callout softdep_callout;
1274 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1275 static int req_clear_remove;	/* syncer process flush some freeblks */
1276 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1277 
1278 /*
1279  * runtime statistics
1280  */
1281 static int stat_flush_threads;	/* number of softdep flushing threads */
1282 static int stat_worklist_push;	/* number of worklist cleanups */
1283 static int stat_blk_limit_push;	/* number of times block limit neared */
1284 static int stat_ino_limit_push;	/* number of times inode limit neared */
1285 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1286 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1287 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1288 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1289 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1290 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1291 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1292 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1293 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1294 static int stat_journal_min;	/* Times hit journal min threshold */
1295 static int stat_journal_low;	/* Times hit journal low threshold */
1296 static int stat_journal_wait;	/* Times blocked in jwait(). */
1297 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1298 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1299 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1300 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1301 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1302 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1303 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1304 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1305 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1306 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1307 
1308 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1309     &max_softdeps, 0, "");
1310 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1311     &tickdelay, 0, "");
1312 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1313     &stat_flush_threads, 0, "");
1314 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1315     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1316 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1317     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1318 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1319     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1320 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1321     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1322 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1323     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1324 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1325     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1326 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1327     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1328 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1329     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1330 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1331     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1332 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1333     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1334 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1335     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1336 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1337     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1338 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1339     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1340 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1341     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1342 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1343     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1344 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1345     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1346 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1347     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1348 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1349     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1350 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1351     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1352 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1353     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1354 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1355     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1356 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1357     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1358 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1359     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1360 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1361     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1362 
1363 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1364     &softdep_flushcache, 0, "");
1365 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1366     &stat_emptyjblocks, 0, "");
1367 
1368 SYSCTL_DECL(_vfs_ffs);
1369 
1370 /* Whether to recompute the summary at mount time */
1371 static int compute_summary_at_mount = 0;
1372 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1373 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1374 static int print_threads = 0;
1375 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1376     &print_threads, 0, "Notify flusher thread start/stop");
1377 
1378 /* List of all filesystems mounted with soft updates */
1379 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1380 
1381 /*
1382  * This function cleans the worklist for a filesystem.
1383  * Each filesystem running with soft dependencies gets its own
1384  * thread to run in this function. The thread is started up in
1385  * softdep_mount and shutdown in softdep_unmount. They show up
1386  * as part of the kernel "bufdaemon" process whose process
1387  * entry is available in bufdaemonproc.
1388  */
1389 static int searchfailed;
1390 extern struct proc *bufdaemonproc;
1391 static void
1392 softdep_flush(addr)
1393 	void *addr;
1394 {
1395 	struct mount *mp;
1396 	struct thread *td;
1397 	struct ufsmount *ump;
1398 
1399 	td = curthread;
1400 	td->td_pflags |= TDP_NORUNNINGBUF;
1401 	mp = (struct mount *)addr;
1402 	ump = VFSTOUFS(mp);
1403 	atomic_add_int(&stat_flush_threads, 1);
1404 	ACQUIRE_LOCK(ump);
1405 	ump->softdep_flags &= ~FLUSH_STARTING;
1406 	wakeup(&ump->softdep_flushtd);
1407 	FREE_LOCK(ump);
1408 	if (print_threads) {
1409 		if (stat_flush_threads == 1)
1410 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1411 			    bufdaemonproc->p_pid);
1412 		printf("Start thread %s\n", td->td_name);
1413 	}
1414 	for (;;) {
1415 		while (softdep_process_worklist(mp, 0) > 0 ||
1416 		    (MOUNTEDSUJ(mp) &&
1417 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1418 			kthread_suspend_check();
1419 		ACQUIRE_LOCK(ump);
1420 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1421 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1422 			    "sdflush", hz / 2);
1423 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1424 		/*
1425 		 * Check to see if we are done and need to exit.
1426 		 */
1427 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1428 			FREE_LOCK(ump);
1429 			continue;
1430 		}
1431 		ump->softdep_flags &= ~FLUSH_EXIT;
1432 		FREE_LOCK(ump);
1433 		wakeup(&ump->softdep_flags);
1434 		if (print_threads)
1435 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1436 		atomic_subtract_int(&stat_flush_threads, 1);
1437 		kthread_exit();
1438 		panic("kthread_exit failed\n");
1439 	}
1440 }
1441 
1442 static void
1443 worklist_speedup(mp)
1444 	struct mount *mp;
1445 {
1446 	struct ufsmount *ump;
1447 
1448 	ump = VFSTOUFS(mp);
1449 	LOCK_OWNED(ump);
1450 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1451 		ump->softdep_flags |= FLUSH_CLEANUP;
1452 	wakeup(&ump->softdep_flushtd);
1453 }
1454 
1455 static int
1456 softdep_speedup(ump)
1457 	struct ufsmount *ump;
1458 {
1459 	struct ufsmount *altump;
1460 	struct mount_softdeps *sdp;
1461 
1462 	LOCK_OWNED(ump);
1463 	worklist_speedup(ump->um_mountp);
1464 	bd_speedup();
1465 	/*
1466 	 * If we have global shortages, then we need other
1467 	 * filesystems to help with the cleanup. Here we wakeup a
1468 	 * flusher thread for a filesystem that is over its fair
1469 	 * share of resources.
1470 	 */
1471 	if (req_clear_inodedeps || req_clear_remove) {
1472 		ACQUIRE_GBLLOCK(&lk);
1473 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1474 			if ((altump = sdp->sd_ump) == ump)
1475 				continue;
1476 			if (((req_clear_inodedeps &&
1477 			    altump->softdep_curdeps[D_INODEDEP] >
1478 			    max_softdeps / stat_flush_threads) ||
1479 			    (req_clear_remove &&
1480 			    altump->softdep_curdeps[D_DIRREM] >
1481 			    (max_softdeps / 2) / stat_flush_threads)) &&
1482 			    TRY_ACQUIRE_LOCK(altump))
1483 				break;
1484 		}
1485 		if (sdp == NULL) {
1486 			searchfailed++;
1487 			FREE_GBLLOCK(&lk);
1488 		} else {
1489 			/*
1490 			 * Move to the end of the list so we pick a
1491 			 * different one on out next try.
1492 			 */
1493 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1494 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1495 			FREE_GBLLOCK(&lk);
1496 			if ((altump->softdep_flags &
1497 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1498 				altump->softdep_flags |= FLUSH_CLEANUP;
1499 			altump->um_softdep->sd_cleanups++;
1500 			wakeup(&altump->softdep_flushtd);
1501 			FREE_LOCK(altump);
1502 		}
1503 	}
1504 	return (speedup_syncer());
1505 }
1506 
1507 /*
1508  * Add an item to the end of the work queue.
1509  * This routine requires that the lock be held.
1510  * This is the only routine that adds items to the list.
1511  * The following routine is the only one that removes items
1512  * and does so in order from first to last.
1513  */
1514 
1515 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1516 #define	WK_NODELAY	0x0002	/* Process immediately. */
1517 
1518 static void
1519 add_to_worklist(wk, flags)
1520 	struct worklist *wk;
1521 	int flags;
1522 {
1523 	struct ufsmount *ump;
1524 
1525 	ump = VFSTOUFS(wk->wk_mp);
1526 	LOCK_OWNED(ump);
1527 	if (wk->wk_state & ONWORKLIST)
1528 		panic("add_to_worklist: %s(0x%X) already on list",
1529 		    TYPENAME(wk->wk_type), wk->wk_state);
1530 	wk->wk_state |= ONWORKLIST;
1531 	if (ump->softdep_on_worklist == 0) {
1532 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1533 		ump->softdep_worklist_tail = wk;
1534 	} else if (flags & WK_HEAD) {
1535 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1536 	} else {
1537 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1538 		ump->softdep_worklist_tail = wk;
1539 	}
1540 	ump->softdep_on_worklist += 1;
1541 	if (flags & WK_NODELAY)
1542 		worklist_speedup(wk->wk_mp);
1543 }
1544 
1545 /*
1546  * Remove the item to be processed. If we are removing the last
1547  * item on the list, we need to recalculate the tail pointer.
1548  */
1549 static void
1550 remove_from_worklist(wk)
1551 	struct worklist *wk;
1552 {
1553 	struct ufsmount *ump;
1554 
1555 	ump = VFSTOUFS(wk->wk_mp);
1556 	if (ump->softdep_worklist_tail == wk)
1557 		ump->softdep_worklist_tail =
1558 		    (struct worklist *)wk->wk_list.le_prev;
1559 	WORKLIST_REMOVE(wk);
1560 	ump->softdep_on_worklist -= 1;
1561 }
1562 
1563 static void
1564 wake_worklist(wk)
1565 	struct worklist *wk;
1566 {
1567 	if (wk->wk_state & IOWAITING) {
1568 		wk->wk_state &= ~IOWAITING;
1569 		wakeup(wk);
1570 	}
1571 }
1572 
1573 static void
1574 wait_worklist(wk, wmesg)
1575 	struct worklist *wk;
1576 	char *wmesg;
1577 {
1578 	struct ufsmount *ump;
1579 
1580 	ump = VFSTOUFS(wk->wk_mp);
1581 	wk->wk_state |= IOWAITING;
1582 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1583 }
1584 
1585 /*
1586  * Process that runs once per second to handle items in the background queue.
1587  *
1588  * Note that we ensure that everything is done in the order in which they
1589  * appear in the queue. The code below depends on this property to ensure
1590  * that blocks of a file are freed before the inode itself is freed. This
1591  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1592  * until all the old ones have been purged from the dependency lists.
1593  */
1594 static int
1595 softdep_process_worklist(mp, full)
1596 	struct mount *mp;
1597 	int full;
1598 {
1599 	int cnt, matchcnt;
1600 	struct ufsmount *ump;
1601 	long starttime;
1602 
1603 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1604 	if (MOUNTEDSOFTDEP(mp) == 0)
1605 		return (0);
1606 	matchcnt = 0;
1607 	ump = VFSTOUFS(mp);
1608 	ACQUIRE_LOCK(ump);
1609 	starttime = time_second;
1610 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1611 	check_clear_deps(mp);
1612 	while (ump->softdep_on_worklist > 0) {
1613 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1614 			break;
1615 		else
1616 			matchcnt += cnt;
1617 		check_clear_deps(mp);
1618 		/*
1619 		 * We do not generally want to stop for buffer space, but if
1620 		 * we are really being a buffer hog, we will stop and wait.
1621 		 */
1622 		if (should_yield()) {
1623 			FREE_LOCK(ump);
1624 			kern_yield(PRI_USER);
1625 			bwillwrite();
1626 			ACQUIRE_LOCK(ump);
1627 		}
1628 		/*
1629 		 * Never allow processing to run for more than one
1630 		 * second. This gives the syncer thread the opportunity
1631 		 * to pause if appropriate.
1632 		 */
1633 		if (!full && starttime != time_second)
1634 			break;
1635 	}
1636 	if (full == 0)
1637 		journal_unsuspend(ump);
1638 	FREE_LOCK(ump);
1639 	return (matchcnt);
1640 }
1641 
1642 /*
1643  * Process all removes associated with a vnode if we are running out of
1644  * journal space.  Any other process which attempts to flush these will
1645  * be unable as we have the vnodes locked.
1646  */
1647 static void
1648 process_removes(vp)
1649 	struct vnode *vp;
1650 {
1651 	struct inodedep *inodedep;
1652 	struct dirrem *dirrem;
1653 	struct ufsmount *ump;
1654 	struct mount *mp;
1655 	ino_t inum;
1656 
1657 	mp = vp->v_mount;
1658 	ump = VFSTOUFS(mp);
1659 	LOCK_OWNED(ump);
1660 	inum = VTOI(vp)->i_number;
1661 	for (;;) {
1662 top:
1663 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1664 			return;
1665 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1666 			/*
1667 			 * If another thread is trying to lock this vnode
1668 			 * it will fail but we must wait for it to do so
1669 			 * before we can proceed.
1670 			 */
1671 			if (dirrem->dm_state & INPROGRESS) {
1672 				wait_worklist(&dirrem->dm_list, "pwrwait");
1673 				goto top;
1674 			}
1675 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1676 			    (COMPLETE | ONWORKLIST))
1677 				break;
1678 		}
1679 		if (dirrem == NULL)
1680 			return;
1681 		remove_from_worklist(&dirrem->dm_list);
1682 		FREE_LOCK(ump);
1683 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1684 			panic("process_removes: suspended filesystem");
1685 		handle_workitem_remove(dirrem, 0);
1686 		vn_finished_secondary_write(mp);
1687 		ACQUIRE_LOCK(ump);
1688 	}
1689 }
1690 
1691 /*
1692  * Process all truncations associated with a vnode if we are running out
1693  * of journal space.  This is called when the vnode lock is already held
1694  * and no other process can clear the truncation.  This function returns
1695  * a value greater than zero if it did any work.
1696  */
1697 static void
1698 process_truncates(vp)
1699 	struct vnode *vp;
1700 {
1701 	struct inodedep *inodedep;
1702 	struct freeblks *freeblks;
1703 	struct ufsmount *ump;
1704 	struct mount *mp;
1705 	ino_t inum;
1706 	int cgwait;
1707 
1708 	mp = vp->v_mount;
1709 	ump = VFSTOUFS(mp);
1710 	LOCK_OWNED(ump);
1711 	inum = VTOI(vp)->i_number;
1712 	for (;;) {
1713 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1714 			return;
1715 		cgwait = 0;
1716 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1717 			/* Journal entries not yet written.  */
1718 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1719 				jwait(&LIST_FIRST(
1720 				    &freeblks->fb_jblkdephd)->jb_list,
1721 				    MNT_WAIT);
1722 				break;
1723 			}
1724 			/* Another thread is executing this item. */
1725 			if (freeblks->fb_state & INPROGRESS) {
1726 				wait_worklist(&freeblks->fb_list, "ptrwait");
1727 				break;
1728 			}
1729 			/* Freeblks is waiting on a inode write. */
1730 			if ((freeblks->fb_state & COMPLETE) == 0) {
1731 				FREE_LOCK(ump);
1732 				ffs_update(vp, 1);
1733 				ACQUIRE_LOCK(ump);
1734 				break;
1735 			}
1736 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1737 			    (ALLCOMPLETE | ONWORKLIST)) {
1738 				remove_from_worklist(&freeblks->fb_list);
1739 				freeblks->fb_state |= INPROGRESS;
1740 				FREE_LOCK(ump);
1741 				if (vn_start_secondary_write(NULL, &mp,
1742 				    V_NOWAIT))
1743 					panic("process_truncates: "
1744 					    "suspended filesystem");
1745 				handle_workitem_freeblocks(freeblks, 0);
1746 				vn_finished_secondary_write(mp);
1747 				ACQUIRE_LOCK(ump);
1748 				break;
1749 			}
1750 			if (freeblks->fb_cgwait)
1751 				cgwait++;
1752 		}
1753 		if (cgwait) {
1754 			FREE_LOCK(ump);
1755 			sync_cgs(mp, MNT_WAIT);
1756 			ffs_sync_snap(mp, MNT_WAIT);
1757 			ACQUIRE_LOCK(ump);
1758 			continue;
1759 		}
1760 		if (freeblks == NULL)
1761 			break;
1762 	}
1763 	return;
1764 }
1765 
1766 /*
1767  * Process one item on the worklist.
1768  */
1769 static int
1770 process_worklist_item(mp, target, flags)
1771 	struct mount *mp;
1772 	int target;
1773 	int flags;
1774 {
1775 	struct worklist sentinel;
1776 	struct worklist *wk;
1777 	struct ufsmount *ump;
1778 	int matchcnt;
1779 	int error;
1780 
1781 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1782 	/*
1783 	 * If we are being called because of a process doing a
1784 	 * copy-on-write, then it is not safe to write as we may
1785 	 * recurse into the copy-on-write routine.
1786 	 */
1787 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1788 		return (-1);
1789 	PHOLD(curproc);	/* Don't let the stack go away. */
1790 	ump = VFSTOUFS(mp);
1791 	LOCK_OWNED(ump);
1792 	matchcnt = 0;
1793 	sentinel.wk_mp = NULL;
1794 	sentinel.wk_type = D_SENTINEL;
1795 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1796 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1797 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1798 		if (wk->wk_type == D_SENTINEL) {
1799 			LIST_REMOVE(&sentinel, wk_list);
1800 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1801 			continue;
1802 		}
1803 		if (wk->wk_state & INPROGRESS)
1804 			panic("process_worklist_item: %p already in progress.",
1805 			    wk);
1806 		wk->wk_state |= INPROGRESS;
1807 		remove_from_worklist(wk);
1808 		FREE_LOCK(ump);
1809 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1810 			panic("process_worklist_item: suspended filesystem");
1811 		switch (wk->wk_type) {
1812 		case D_DIRREM:
1813 			/* removal of a directory entry */
1814 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1815 			break;
1816 
1817 		case D_FREEBLKS:
1818 			/* releasing blocks and/or fragments from a file */
1819 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1820 			    flags);
1821 			break;
1822 
1823 		case D_FREEFRAG:
1824 			/* releasing a fragment when replaced as a file grows */
1825 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1826 			error = 0;
1827 			break;
1828 
1829 		case D_FREEFILE:
1830 			/* releasing an inode when its link count drops to 0 */
1831 			handle_workitem_freefile(WK_FREEFILE(wk));
1832 			error = 0;
1833 			break;
1834 
1835 		default:
1836 			panic("%s_process_worklist: Unknown type %s",
1837 			    "softdep", TYPENAME(wk->wk_type));
1838 			/* NOTREACHED */
1839 		}
1840 		vn_finished_secondary_write(mp);
1841 		ACQUIRE_LOCK(ump);
1842 		if (error == 0) {
1843 			if (++matchcnt == target)
1844 				break;
1845 			continue;
1846 		}
1847 		/*
1848 		 * We have to retry the worklist item later.  Wake up any
1849 		 * waiters who may be able to complete it immediately and
1850 		 * add the item back to the head so we don't try to execute
1851 		 * it again.
1852 		 */
1853 		wk->wk_state &= ~INPROGRESS;
1854 		wake_worklist(wk);
1855 		add_to_worklist(wk, WK_HEAD);
1856 	}
1857 	/* Sentinal could've become the tail from remove_from_worklist. */
1858 	if (ump->softdep_worklist_tail == &sentinel)
1859 		ump->softdep_worklist_tail =
1860 		    (struct worklist *)sentinel.wk_list.le_prev;
1861 	LIST_REMOVE(&sentinel, wk_list);
1862 	PRELE(curproc);
1863 	return (matchcnt);
1864 }
1865 
1866 /*
1867  * Move dependencies from one buffer to another.
1868  */
1869 int
1870 softdep_move_dependencies(oldbp, newbp)
1871 	struct buf *oldbp;
1872 	struct buf *newbp;
1873 {
1874 	struct worklist *wk, *wktail;
1875 	struct ufsmount *ump;
1876 	int dirty;
1877 
1878 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1879 		return (0);
1880 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1881 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1882 	dirty = 0;
1883 	wktail = NULL;
1884 	ump = VFSTOUFS(wk->wk_mp);
1885 	ACQUIRE_LOCK(ump);
1886 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1887 		LIST_REMOVE(wk, wk_list);
1888 		if (wk->wk_type == D_BMSAFEMAP &&
1889 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1890 			dirty = 1;
1891 		if (wktail == NULL)
1892 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1893 		else
1894 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1895 		wktail = wk;
1896 	}
1897 	FREE_LOCK(ump);
1898 
1899 	return (dirty);
1900 }
1901 
1902 /*
1903  * Purge the work list of all items associated with a particular mount point.
1904  */
1905 int
1906 softdep_flushworklist(oldmnt, countp, td)
1907 	struct mount *oldmnt;
1908 	int *countp;
1909 	struct thread *td;
1910 {
1911 	struct vnode *devvp;
1912 	struct ufsmount *ump;
1913 	int count, error;
1914 
1915 	/*
1916 	 * Alternately flush the block device associated with the mount
1917 	 * point and process any dependencies that the flushing
1918 	 * creates. We continue until no more worklist dependencies
1919 	 * are found.
1920 	 */
1921 	*countp = 0;
1922 	error = 0;
1923 	ump = VFSTOUFS(oldmnt);
1924 	devvp = ump->um_devvp;
1925 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1926 		*countp += count;
1927 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1928 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1929 		VOP_UNLOCK(devvp, 0);
1930 		if (error != 0)
1931 			break;
1932 	}
1933 	return (error);
1934 }
1935 
1936 #define	SU_WAITIDLE_RETRIES	20
1937 static int
1938 softdep_waitidle(struct mount *mp, int flags __unused)
1939 {
1940 	struct ufsmount *ump;
1941 	struct vnode *devvp;
1942 	struct thread *td;
1943 	int error, i;
1944 
1945 	ump = VFSTOUFS(mp);
1946 	devvp = ump->um_devvp;
1947 	td = curthread;
1948 	error = 0;
1949 	ACQUIRE_LOCK(ump);
1950 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1951 		ump->softdep_req = 1;
1952 		KASSERT((flags & FORCECLOSE) == 0 ||
1953 		    ump->softdep_on_worklist == 0,
1954 		    ("softdep_waitidle: work added after flush"));
1955 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1956 		    "softdeps", 10 * hz);
1957 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1958 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1959 		VOP_UNLOCK(devvp, 0);
1960 		ACQUIRE_LOCK(ump);
1961 		if (error != 0)
1962 			break;
1963 	}
1964 	ump->softdep_req = 0;
1965 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1966 		error = EBUSY;
1967 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1968 		    mp);
1969 	}
1970 	FREE_LOCK(ump);
1971 	return (error);
1972 }
1973 
1974 /*
1975  * Flush all vnodes and worklist items associated with a specified mount point.
1976  */
1977 int
1978 softdep_flushfiles(oldmnt, flags, td)
1979 	struct mount *oldmnt;
1980 	int flags;
1981 	struct thread *td;
1982 {
1983 #ifdef QUOTA
1984 	struct ufsmount *ump;
1985 	int i;
1986 #endif
1987 	int error, early, depcount, loopcnt, retry_flush_count, retry;
1988 	int morework;
1989 
1990 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1991 	    ("softdep_flushfiles called on non-softdep filesystem"));
1992 	loopcnt = 10;
1993 	retry_flush_count = 3;
1994 retry_flush:
1995 	error = 0;
1996 
1997 	/*
1998 	 * Alternately flush the vnodes associated with the mount
1999 	 * point and process any dependencies that the flushing
2000 	 * creates. In theory, this loop can happen at most twice,
2001 	 * but we give it a few extra just to be sure.
2002 	 */
2003 	for (; loopcnt > 0; loopcnt--) {
2004 		/*
2005 		 * Do another flush in case any vnodes were brought in
2006 		 * as part of the cleanup operations.
2007 		 */
2008 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2009 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2010 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2011 			break;
2012 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2013 		    depcount == 0)
2014 			break;
2015 	}
2016 	/*
2017 	 * If we are unmounting then it is an error to fail. If we
2018 	 * are simply trying to downgrade to read-only, then filesystem
2019 	 * activity can keep us busy forever, so we just fail with EBUSY.
2020 	 */
2021 	if (loopcnt == 0) {
2022 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2023 			panic("softdep_flushfiles: looping");
2024 		error = EBUSY;
2025 	}
2026 	if (!error)
2027 		error = softdep_waitidle(oldmnt, flags);
2028 	if (!error) {
2029 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2030 			retry = 0;
2031 			MNT_ILOCK(oldmnt);
2032 			morework = oldmnt->mnt_nvnodelistsize > 0;
2033 #ifdef QUOTA
2034 			ump = VFSTOUFS(oldmnt);
2035 			UFS_LOCK(ump);
2036 			for (i = 0; i < MAXQUOTAS; i++) {
2037 				if (ump->um_quotas[i] != NULLVP)
2038 					morework = 1;
2039 			}
2040 			UFS_UNLOCK(ump);
2041 #endif
2042 			if (morework) {
2043 				if (--retry_flush_count > 0) {
2044 					retry = 1;
2045 					loopcnt = 3;
2046 				} else
2047 					error = EBUSY;
2048 			}
2049 			MNT_IUNLOCK(oldmnt);
2050 			if (retry)
2051 				goto retry_flush;
2052 		}
2053 	}
2054 	return (error);
2055 }
2056 
2057 /*
2058  * Structure hashing.
2059  *
2060  * There are four types of structures that can be looked up:
2061  *	1) pagedep structures identified by mount point, inode number,
2062  *	   and logical block.
2063  *	2) inodedep structures identified by mount point and inode number.
2064  *	3) newblk structures identified by mount point and
2065  *	   physical block number.
2066  *	4) bmsafemap structures identified by mount point and
2067  *	   cylinder group number.
2068  *
2069  * The "pagedep" and "inodedep" dependency structures are hashed
2070  * separately from the file blocks and inodes to which they correspond.
2071  * This separation helps when the in-memory copy of an inode or
2072  * file block must be replaced. It also obviates the need to access
2073  * an inode or file page when simply updating (or de-allocating)
2074  * dependency structures. Lookup of newblk structures is needed to
2075  * find newly allocated blocks when trying to associate them with
2076  * their allocdirect or allocindir structure.
2077  *
2078  * The lookup routines optionally create and hash a new instance when
2079  * an existing entry is not found. The bmsafemap lookup routine always
2080  * allocates a new structure if an existing one is not found.
2081  */
2082 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2083 
2084 /*
2085  * Structures and routines associated with pagedep caching.
2086  */
2087 #define	PAGEDEP_HASH(ump, inum, lbn) \
2088 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2089 
2090 static int
2091 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2092 	struct pagedep_hashhead *pagedephd;
2093 	ino_t ino;
2094 	ufs_lbn_t lbn;
2095 	struct pagedep **pagedeppp;
2096 {
2097 	struct pagedep *pagedep;
2098 
2099 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2100 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2101 			*pagedeppp = pagedep;
2102 			return (1);
2103 		}
2104 	}
2105 	*pagedeppp = NULL;
2106 	return (0);
2107 }
2108 /*
2109  * Look up a pagedep. Return 1 if found, 0 otherwise.
2110  * If not found, allocate if DEPALLOC flag is passed.
2111  * Found or allocated entry is returned in pagedeppp.
2112  */
2113 static int
2114 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2115 	struct mount *mp;
2116 	struct buf *bp;
2117 	ino_t ino;
2118 	ufs_lbn_t lbn;
2119 	int flags;
2120 	struct pagedep **pagedeppp;
2121 {
2122 	struct pagedep *pagedep;
2123 	struct pagedep_hashhead *pagedephd;
2124 	struct worklist *wk;
2125 	struct ufsmount *ump;
2126 	int ret;
2127 	int i;
2128 
2129 	ump = VFSTOUFS(mp);
2130 	LOCK_OWNED(ump);
2131 	if (bp) {
2132 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2133 			if (wk->wk_type == D_PAGEDEP) {
2134 				*pagedeppp = WK_PAGEDEP(wk);
2135 				return (1);
2136 			}
2137 		}
2138 	}
2139 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2140 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2141 	if (ret) {
2142 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2143 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2144 		return (1);
2145 	}
2146 	if ((flags & DEPALLOC) == 0)
2147 		return (0);
2148 	FREE_LOCK(ump);
2149 	pagedep = malloc(sizeof(struct pagedep),
2150 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2151 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2152 	ACQUIRE_LOCK(ump);
2153 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2154 	if (*pagedeppp) {
2155 		/*
2156 		 * This should never happen since we only create pagedeps
2157 		 * with the vnode lock held.  Could be an assert.
2158 		 */
2159 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2160 		return (ret);
2161 	}
2162 	pagedep->pd_ino = ino;
2163 	pagedep->pd_lbn = lbn;
2164 	LIST_INIT(&pagedep->pd_dirremhd);
2165 	LIST_INIT(&pagedep->pd_pendinghd);
2166 	for (i = 0; i < DAHASHSZ; i++)
2167 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2168 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2169 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2170 	*pagedeppp = pagedep;
2171 	return (0);
2172 }
2173 
2174 /*
2175  * Structures and routines associated with inodedep caching.
2176  */
2177 #define	INODEDEP_HASH(ump, inum) \
2178       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2179 
2180 static int
2181 inodedep_find(inodedephd, inum, inodedeppp)
2182 	struct inodedep_hashhead *inodedephd;
2183 	ino_t inum;
2184 	struct inodedep **inodedeppp;
2185 {
2186 	struct inodedep *inodedep;
2187 
2188 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2189 		if (inum == inodedep->id_ino)
2190 			break;
2191 	if (inodedep) {
2192 		*inodedeppp = inodedep;
2193 		return (1);
2194 	}
2195 	*inodedeppp = NULL;
2196 
2197 	return (0);
2198 }
2199 /*
2200  * Look up an inodedep. Return 1 if found, 0 if not found.
2201  * If not found, allocate if DEPALLOC flag is passed.
2202  * Found or allocated entry is returned in inodedeppp.
2203  */
2204 static int
2205 inodedep_lookup(mp, inum, flags, inodedeppp)
2206 	struct mount *mp;
2207 	ino_t inum;
2208 	int flags;
2209 	struct inodedep **inodedeppp;
2210 {
2211 	struct inodedep *inodedep;
2212 	struct inodedep_hashhead *inodedephd;
2213 	struct ufsmount *ump;
2214 	struct fs *fs;
2215 
2216 	ump = VFSTOUFS(mp);
2217 	LOCK_OWNED(ump);
2218 	fs = ump->um_fs;
2219 	inodedephd = INODEDEP_HASH(ump, inum);
2220 
2221 	if (inodedep_find(inodedephd, inum, inodedeppp))
2222 		return (1);
2223 	if ((flags & DEPALLOC) == 0)
2224 		return (0);
2225 	/*
2226 	 * If the system is over its limit and our filesystem is
2227 	 * responsible for more than our share of that usage and
2228 	 * we are not in a rush, request some inodedep cleanup.
2229 	 */
2230 	if (softdep_excess_items(ump, D_INODEDEP))
2231 		schedule_cleanup(mp);
2232 	else
2233 		FREE_LOCK(ump);
2234 	inodedep = malloc(sizeof(struct inodedep),
2235 		M_INODEDEP, M_SOFTDEP_FLAGS);
2236 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2237 	ACQUIRE_LOCK(ump);
2238 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2239 		WORKITEM_FREE(inodedep, D_INODEDEP);
2240 		return (1);
2241 	}
2242 	inodedep->id_fs = fs;
2243 	inodedep->id_ino = inum;
2244 	inodedep->id_state = ALLCOMPLETE;
2245 	inodedep->id_nlinkdelta = 0;
2246 	inodedep->id_savedino1 = NULL;
2247 	inodedep->id_savedsize = -1;
2248 	inodedep->id_savedextsize = -1;
2249 	inodedep->id_savednlink = -1;
2250 	inodedep->id_bmsafemap = NULL;
2251 	inodedep->id_mkdiradd = NULL;
2252 	LIST_INIT(&inodedep->id_dirremhd);
2253 	LIST_INIT(&inodedep->id_pendinghd);
2254 	LIST_INIT(&inodedep->id_inowait);
2255 	LIST_INIT(&inodedep->id_bufwait);
2256 	TAILQ_INIT(&inodedep->id_inoreflst);
2257 	TAILQ_INIT(&inodedep->id_inoupdt);
2258 	TAILQ_INIT(&inodedep->id_newinoupdt);
2259 	TAILQ_INIT(&inodedep->id_extupdt);
2260 	TAILQ_INIT(&inodedep->id_newextupdt);
2261 	TAILQ_INIT(&inodedep->id_freeblklst);
2262 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2263 	*inodedeppp = inodedep;
2264 	return (0);
2265 }
2266 
2267 /*
2268  * Structures and routines associated with newblk caching.
2269  */
2270 #define	NEWBLK_HASH(ump, inum) \
2271 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2272 
2273 static int
2274 newblk_find(newblkhd, newblkno, flags, newblkpp)
2275 	struct newblk_hashhead *newblkhd;
2276 	ufs2_daddr_t newblkno;
2277 	int flags;
2278 	struct newblk **newblkpp;
2279 {
2280 	struct newblk *newblk;
2281 
2282 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2283 		if (newblkno != newblk->nb_newblkno)
2284 			continue;
2285 		/*
2286 		 * If we're creating a new dependency don't match those that
2287 		 * have already been converted to allocdirects.  This is for
2288 		 * a frag extend.
2289 		 */
2290 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2291 			continue;
2292 		break;
2293 	}
2294 	if (newblk) {
2295 		*newblkpp = newblk;
2296 		return (1);
2297 	}
2298 	*newblkpp = NULL;
2299 	return (0);
2300 }
2301 
2302 /*
2303  * Look up a newblk. Return 1 if found, 0 if not found.
2304  * If not found, allocate if DEPALLOC flag is passed.
2305  * Found or allocated entry is returned in newblkpp.
2306  */
2307 static int
2308 newblk_lookup(mp, newblkno, flags, newblkpp)
2309 	struct mount *mp;
2310 	ufs2_daddr_t newblkno;
2311 	int flags;
2312 	struct newblk **newblkpp;
2313 {
2314 	struct newblk *newblk;
2315 	struct newblk_hashhead *newblkhd;
2316 	struct ufsmount *ump;
2317 
2318 	ump = VFSTOUFS(mp);
2319 	LOCK_OWNED(ump);
2320 	newblkhd = NEWBLK_HASH(ump, newblkno);
2321 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2322 		return (1);
2323 	if ((flags & DEPALLOC) == 0)
2324 		return (0);
2325 	if (softdep_excess_items(ump, D_NEWBLK) ||
2326 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2327 	    softdep_excess_items(ump, D_ALLOCINDIR))
2328 		schedule_cleanup(mp);
2329 	else
2330 		FREE_LOCK(ump);
2331 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2332 	    M_SOFTDEP_FLAGS | M_ZERO);
2333 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2334 	ACQUIRE_LOCK(ump);
2335 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2336 		WORKITEM_FREE(newblk, D_NEWBLK);
2337 		return (1);
2338 	}
2339 	newblk->nb_freefrag = NULL;
2340 	LIST_INIT(&newblk->nb_indirdeps);
2341 	LIST_INIT(&newblk->nb_newdirblk);
2342 	LIST_INIT(&newblk->nb_jwork);
2343 	newblk->nb_state = ATTACHED;
2344 	newblk->nb_newblkno = newblkno;
2345 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2346 	*newblkpp = newblk;
2347 	return (0);
2348 }
2349 
2350 /*
2351  * Structures and routines associated with freed indirect block caching.
2352  */
2353 #define	INDIR_HASH(ump, blkno) \
2354 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2355 
2356 /*
2357  * Lookup an indirect block in the indir hash table.  The freework is
2358  * removed and potentially freed.  The caller must do a blocking journal
2359  * write before writing to the blkno.
2360  */
2361 static int
2362 indirblk_lookup(mp, blkno)
2363 	struct mount *mp;
2364 	ufs2_daddr_t blkno;
2365 {
2366 	struct freework *freework;
2367 	struct indir_hashhead *wkhd;
2368 	struct ufsmount *ump;
2369 
2370 	ump = VFSTOUFS(mp);
2371 	wkhd = INDIR_HASH(ump, blkno);
2372 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2373 		if (freework->fw_blkno != blkno)
2374 			continue;
2375 		indirblk_remove(freework);
2376 		return (1);
2377 	}
2378 	return (0);
2379 }
2380 
2381 /*
2382  * Insert an indirect block represented by freework into the indirblk
2383  * hash table so that it may prevent the block from being re-used prior
2384  * to the journal being written.
2385  */
2386 static void
2387 indirblk_insert(freework)
2388 	struct freework *freework;
2389 {
2390 	struct jblocks *jblocks;
2391 	struct jseg *jseg;
2392 	struct ufsmount *ump;
2393 
2394 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2395 	jblocks = ump->softdep_jblocks;
2396 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2397 	if (jseg == NULL)
2398 		return;
2399 
2400 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2401 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2402 	    fw_next);
2403 	freework->fw_state &= ~DEPCOMPLETE;
2404 }
2405 
2406 static void
2407 indirblk_remove(freework)
2408 	struct freework *freework;
2409 {
2410 	struct ufsmount *ump;
2411 
2412 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2413 	LIST_REMOVE(freework, fw_segs);
2414 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2415 	freework->fw_state |= DEPCOMPLETE;
2416 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2417 		WORKITEM_FREE(freework, D_FREEWORK);
2418 }
2419 
2420 /*
2421  * Executed during filesystem system initialization before
2422  * mounting any filesystems.
2423  */
2424 void
2425 softdep_initialize()
2426 {
2427 
2428 	TAILQ_INIT(&softdepmounts);
2429 #ifdef __LP64__
2430 	max_softdeps = desiredvnodes * 4;
2431 #else
2432 	max_softdeps = desiredvnodes * 2;
2433 #endif
2434 
2435 	/* initialise bioops hack */
2436 	bioops.io_start = softdep_disk_io_initiation;
2437 	bioops.io_complete = softdep_disk_write_complete;
2438 	bioops.io_deallocate = softdep_deallocate_dependencies;
2439 	bioops.io_countdeps = softdep_count_dependencies;
2440 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2441 
2442 	/* Initialize the callout with an mtx. */
2443 	callout_init_mtx(&softdep_callout, &lk, 0);
2444 }
2445 
2446 /*
2447  * Executed after all filesystems have been unmounted during
2448  * filesystem module unload.
2449  */
2450 void
2451 softdep_uninitialize()
2452 {
2453 
2454 	/* clear bioops hack */
2455 	bioops.io_start = NULL;
2456 	bioops.io_complete = NULL;
2457 	bioops.io_deallocate = NULL;
2458 	bioops.io_countdeps = NULL;
2459 	softdep_ast_cleanup = NULL;
2460 
2461 	callout_drain(&softdep_callout);
2462 }
2463 
2464 /*
2465  * Called at mount time to notify the dependency code that a
2466  * filesystem wishes to use it.
2467  */
2468 int
2469 softdep_mount(devvp, mp, fs, cred)
2470 	struct vnode *devvp;
2471 	struct mount *mp;
2472 	struct fs *fs;
2473 	struct ucred *cred;
2474 {
2475 	struct csum_total cstotal;
2476 	struct mount_softdeps *sdp;
2477 	struct ufsmount *ump;
2478 	struct cg *cgp;
2479 	struct buf *bp;
2480 	u_int cyl, i;
2481 	int error;
2482 
2483 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2484 	    M_WAITOK | M_ZERO);
2485 	MNT_ILOCK(mp);
2486 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2487 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2488 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2489 			MNTK_SOFTDEP | MNTK_NOASYNC;
2490 	}
2491 	ump = VFSTOUFS(mp);
2492 	ump->um_softdep = sdp;
2493 	MNT_IUNLOCK(mp);
2494 	rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2495 	sdp->sd_ump = ump;
2496 	LIST_INIT(&ump->softdep_workitem_pending);
2497 	LIST_INIT(&ump->softdep_journal_pending);
2498 	TAILQ_INIT(&ump->softdep_unlinked);
2499 	LIST_INIT(&ump->softdep_dirtycg);
2500 	ump->softdep_worklist_tail = NULL;
2501 	ump->softdep_on_worklist = 0;
2502 	ump->softdep_deps = 0;
2503 	LIST_INIT(&ump->softdep_mkdirlisthd);
2504 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2505 	    &ump->pagedep_hash_size);
2506 	ump->pagedep_nextclean = 0;
2507 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2508 	    &ump->inodedep_hash_size);
2509 	ump->inodedep_nextclean = 0;
2510 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2511 	    &ump->newblk_hash_size);
2512 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2513 	    &ump->bmsafemap_hash_size);
2514 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2515 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2516 	    M_FREEWORK, M_WAITOK);
2517 	ump->indir_hash_size = i - 1;
2518 	for (i = 0; i <= ump->indir_hash_size; i++)
2519 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2520 	ACQUIRE_GBLLOCK(&lk);
2521 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2522 	FREE_GBLLOCK(&lk);
2523 	if ((fs->fs_flags & FS_SUJ) &&
2524 	    (error = journal_mount(mp, fs, cred)) != 0) {
2525 		printf("Failed to start journal: %d\n", error);
2526 		softdep_unmount(mp);
2527 		return (error);
2528 	}
2529 	/*
2530 	 * Start our flushing thread in the bufdaemon process.
2531 	 */
2532 	ACQUIRE_LOCK(ump);
2533 	ump->softdep_flags |= FLUSH_STARTING;
2534 	FREE_LOCK(ump);
2535 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2536 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2537 	    mp->mnt_stat.f_mntonname);
2538 	ACQUIRE_LOCK(ump);
2539 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2540 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2541 		    hz / 2);
2542 	}
2543 	FREE_LOCK(ump);
2544 	/*
2545 	 * When doing soft updates, the counters in the
2546 	 * superblock may have gotten out of sync. Recomputation
2547 	 * can take a long time and can be deferred for background
2548 	 * fsck.  However, the old behavior of scanning the cylinder
2549 	 * groups and recalculating them at mount time is available
2550 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2551 	 */
2552 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2553 		return (0);
2554 	bzero(&cstotal, sizeof cstotal);
2555 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2556 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2557 		    fs->fs_cgsize, cred, &bp)) != 0) {
2558 			brelse(bp);
2559 			softdep_unmount(mp);
2560 			return (error);
2561 		}
2562 		cgp = (struct cg *)bp->b_data;
2563 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2564 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2565 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2566 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2567 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2568 		brelse(bp);
2569 	}
2570 #ifdef INVARIANTS
2571 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2572 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2573 #endif
2574 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2575 	return (0);
2576 }
2577 
2578 void
2579 softdep_unmount(mp)
2580 	struct mount *mp;
2581 {
2582 	struct ufsmount *ump;
2583 #ifdef INVARIANTS
2584 	int i;
2585 #endif
2586 
2587 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2588 	    ("softdep_unmount called on non-softdep filesystem"));
2589 	ump = VFSTOUFS(mp);
2590 	MNT_ILOCK(mp);
2591 	mp->mnt_flag &= ~MNT_SOFTDEP;
2592 	if (MOUNTEDSUJ(mp) == 0) {
2593 		MNT_IUNLOCK(mp);
2594 	} else {
2595 		mp->mnt_flag &= ~MNT_SUJ;
2596 		MNT_IUNLOCK(mp);
2597 		journal_unmount(ump);
2598 	}
2599 	/*
2600 	 * Shut down our flushing thread. Check for NULL is if
2601 	 * softdep_mount errors out before the thread has been created.
2602 	 */
2603 	if (ump->softdep_flushtd != NULL) {
2604 		ACQUIRE_LOCK(ump);
2605 		ump->softdep_flags |= FLUSH_EXIT;
2606 		wakeup(&ump->softdep_flushtd);
2607 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2608 		    "sdwait", 0);
2609 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2610 		    ("Thread shutdown failed"));
2611 	}
2612 	/*
2613 	 * Free up our resources.
2614 	 */
2615 	ACQUIRE_GBLLOCK(&lk);
2616 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2617 	FREE_GBLLOCK(&lk);
2618 	rw_destroy(LOCK_PTR(ump));
2619 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2620 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2621 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2622 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2623 	    ump->bmsafemap_hash_size);
2624 	free(ump->indir_hashtbl, M_FREEWORK);
2625 #ifdef INVARIANTS
2626 	for (i = 0; i <= D_LAST; i++)
2627 		KASSERT(ump->softdep_curdeps[i] == 0,
2628 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2629 		    TYPENAME(i), ump->softdep_curdeps[i]));
2630 #endif
2631 	free(ump->um_softdep, M_MOUNTDATA);
2632 }
2633 
2634 static struct jblocks *
2635 jblocks_create(void)
2636 {
2637 	struct jblocks *jblocks;
2638 
2639 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2640 	TAILQ_INIT(&jblocks->jb_segs);
2641 	jblocks->jb_avail = 10;
2642 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2643 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2644 
2645 	return (jblocks);
2646 }
2647 
2648 static ufs2_daddr_t
2649 jblocks_alloc(jblocks, bytes, actual)
2650 	struct jblocks *jblocks;
2651 	int bytes;
2652 	int *actual;
2653 {
2654 	ufs2_daddr_t daddr;
2655 	struct jextent *jext;
2656 	int freecnt;
2657 	int blocks;
2658 
2659 	blocks = bytes / DEV_BSIZE;
2660 	jext = &jblocks->jb_extent[jblocks->jb_head];
2661 	freecnt = jext->je_blocks - jblocks->jb_off;
2662 	if (freecnt == 0) {
2663 		jblocks->jb_off = 0;
2664 		if (++jblocks->jb_head > jblocks->jb_used)
2665 			jblocks->jb_head = 0;
2666 		jext = &jblocks->jb_extent[jblocks->jb_head];
2667 		freecnt = jext->je_blocks;
2668 	}
2669 	if (freecnt > blocks)
2670 		freecnt = blocks;
2671 	*actual = freecnt * DEV_BSIZE;
2672 	daddr = jext->je_daddr + jblocks->jb_off;
2673 	jblocks->jb_off += freecnt;
2674 	jblocks->jb_free -= freecnt;
2675 
2676 	return (daddr);
2677 }
2678 
2679 static void
2680 jblocks_free(jblocks, mp, bytes)
2681 	struct jblocks *jblocks;
2682 	struct mount *mp;
2683 	int bytes;
2684 {
2685 
2686 	LOCK_OWNED(VFSTOUFS(mp));
2687 	jblocks->jb_free += bytes / DEV_BSIZE;
2688 	if (jblocks->jb_suspended)
2689 		worklist_speedup(mp);
2690 	wakeup(jblocks);
2691 }
2692 
2693 static void
2694 jblocks_destroy(jblocks)
2695 	struct jblocks *jblocks;
2696 {
2697 
2698 	if (jblocks->jb_extent)
2699 		free(jblocks->jb_extent, M_JBLOCKS);
2700 	free(jblocks, M_JBLOCKS);
2701 }
2702 
2703 static void
2704 jblocks_add(jblocks, daddr, blocks)
2705 	struct jblocks *jblocks;
2706 	ufs2_daddr_t daddr;
2707 	int blocks;
2708 {
2709 	struct jextent *jext;
2710 
2711 	jblocks->jb_blocks += blocks;
2712 	jblocks->jb_free += blocks;
2713 	jext = &jblocks->jb_extent[jblocks->jb_used];
2714 	/* Adding the first block. */
2715 	if (jext->je_daddr == 0) {
2716 		jext->je_daddr = daddr;
2717 		jext->je_blocks = blocks;
2718 		return;
2719 	}
2720 	/* Extending the last extent. */
2721 	if (jext->je_daddr + jext->je_blocks == daddr) {
2722 		jext->je_blocks += blocks;
2723 		return;
2724 	}
2725 	/* Adding a new extent. */
2726 	if (++jblocks->jb_used == jblocks->jb_avail) {
2727 		jblocks->jb_avail *= 2;
2728 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2729 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2730 		memcpy(jext, jblocks->jb_extent,
2731 		    sizeof(struct jextent) * jblocks->jb_used);
2732 		free(jblocks->jb_extent, M_JBLOCKS);
2733 		jblocks->jb_extent = jext;
2734 	}
2735 	jext = &jblocks->jb_extent[jblocks->jb_used];
2736 	jext->je_daddr = daddr;
2737 	jext->je_blocks = blocks;
2738 	return;
2739 }
2740 
2741 int
2742 softdep_journal_lookup(mp, vpp)
2743 	struct mount *mp;
2744 	struct vnode **vpp;
2745 {
2746 	struct componentname cnp;
2747 	struct vnode *dvp;
2748 	ino_t sujournal;
2749 	int error;
2750 
2751 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2752 	if (error)
2753 		return (error);
2754 	bzero(&cnp, sizeof(cnp));
2755 	cnp.cn_nameiop = LOOKUP;
2756 	cnp.cn_flags = ISLASTCN;
2757 	cnp.cn_thread = curthread;
2758 	cnp.cn_cred = curthread->td_ucred;
2759 	cnp.cn_pnbuf = SUJ_FILE;
2760 	cnp.cn_nameptr = SUJ_FILE;
2761 	cnp.cn_namelen = strlen(SUJ_FILE);
2762 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2763 	vput(dvp);
2764 	if (error != 0)
2765 		return (error);
2766 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2767 	return (error);
2768 }
2769 
2770 /*
2771  * Open and verify the journal file.
2772  */
2773 static int
2774 journal_mount(mp, fs, cred)
2775 	struct mount *mp;
2776 	struct fs *fs;
2777 	struct ucred *cred;
2778 {
2779 	struct jblocks *jblocks;
2780 	struct ufsmount *ump;
2781 	struct vnode *vp;
2782 	struct inode *ip;
2783 	ufs2_daddr_t blkno;
2784 	int bcount;
2785 	int error;
2786 	int i;
2787 
2788 	ump = VFSTOUFS(mp);
2789 	ump->softdep_journal_tail = NULL;
2790 	ump->softdep_on_journal = 0;
2791 	ump->softdep_accdeps = 0;
2792 	ump->softdep_req = 0;
2793 	ump->softdep_jblocks = NULL;
2794 	error = softdep_journal_lookup(mp, &vp);
2795 	if (error != 0) {
2796 		printf("Failed to find journal.  Use tunefs to create one\n");
2797 		return (error);
2798 	}
2799 	ip = VTOI(vp);
2800 	if (ip->i_size < SUJ_MIN) {
2801 		error = ENOSPC;
2802 		goto out;
2803 	}
2804 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2805 	jblocks = jblocks_create();
2806 	for (i = 0; i < bcount; i++) {
2807 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2808 		if (error)
2809 			break;
2810 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2811 	}
2812 	if (error) {
2813 		jblocks_destroy(jblocks);
2814 		goto out;
2815 	}
2816 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2817 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2818 	ump->softdep_jblocks = jblocks;
2819 out:
2820 	if (error == 0) {
2821 		MNT_ILOCK(mp);
2822 		mp->mnt_flag |= MNT_SUJ;
2823 		mp->mnt_flag &= ~MNT_SOFTDEP;
2824 		MNT_IUNLOCK(mp);
2825 		/*
2826 		 * Only validate the journal contents if the
2827 		 * filesystem is clean, otherwise we write the logs
2828 		 * but they'll never be used.  If the filesystem was
2829 		 * still dirty when we mounted it the journal is
2830 		 * invalid and a new journal can only be valid if it
2831 		 * starts from a clean mount.
2832 		 */
2833 		if (fs->fs_clean) {
2834 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2835 			ip->i_flags |= IN_MODIFIED;
2836 			ffs_update(vp, 1);
2837 		}
2838 	}
2839 	vput(vp);
2840 	return (error);
2841 }
2842 
2843 static void
2844 journal_unmount(ump)
2845 	struct ufsmount *ump;
2846 {
2847 
2848 	if (ump->softdep_jblocks)
2849 		jblocks_destroy(ump->softdep_jblocks);
2850 	ump->softdep_jblocks = NULL;
2851 }
2852 
2853 /*
2854  * Called when a journal record is ready to be written.  Space is allocated
2855  * and the journal entry is created when the journal is flushed to stable
2856  * store.
2857  */
2858 static void
2859 add_to_journal(wk)
2860 	struct worklist *wk;
2861 {
2862 	struct ufsmount *ump;
2863 
2864 	ump = VFSTOUFS(wk->wk_mp);
2865 	LOCK_OWNED(ump);
2866 	if (wk->wk_state & ONWORKLIST)
2867 		panic("add_to_journal: %s(0x%X) already on list",
2868 		    TYPENAME(wk->wk_type), wk->wk_state);
2869 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2870 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2871 		ump->softdep_jblocks->jb_age = ticks;
2872 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2873 	} else
2874 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2875 	ump->softdep_journal_tail = wk;
2876 	ump->softdep_on_journal += 1;
2877 }
2878 
2879 /*
2880  * Remove an arbitrary item for the journal worklist maintain the tail
2881  * pointer.  This happens when a new operation obviates the need to
2882  * journal an old operation.
2883  */
2884 static void
2885 remove_from_journal(wk)
2886 	struct worklist *wk;
2887 {
2888 	struct ufsmount *ump;
2889 
2890 	ump = VFSTOUFS(wk->wk_mp);
2891 	LOCK_OWNED(ump);
2892 #ifdef INVARIANTS
2893 	{
2894 		struct worklist *wkn;
2895 
2896 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2897 			if (wkn == wk)
2898 				break;
2899 		if (wkn == NULL)
2900 			panic("remove_from_journal: %p is not in journal", wk);
2901 	}
2902 #endif
2903 	/*
2904 	 * We emulate a TAILQ to save space in most structures which do not
2905 	 * require TAILQ semantics.  Here we must update the tail position
2906 	 * when removing the tail which is not the final entry. This works
2907 	 * only if the worklist linkage are at the beginning of the structure.
2908 	 */
2909 	if (ump->softdep_journal_tail == wk)
2910 		ump->softdep_journal_tail =
2911 		    (struct worklist *)wk->wk_list.le_prev;
2912 	WORKLIST_REMOVE(wk);
2913 	ump->softdep_on_journal -= 1;
2914 }
2915 
2916 /*
2917  * Check for journal space as well as dependency limits so the prelink
2918  * code can throttle both journaled and non-journaled filesystems.
2919  * Threshold is 0 for low and 1 for min.
2920  */
2921 static int
2922 journal_space(ump, thresh)
2923 	struct ufsmount *ump;
2924 	int thresh;
2925 {
2926 	struct jblocks *jblocks;
2927 	int limit, avail;
2928 
2929 	jblocks = ump->softdep_jblocks;
2930 	if (jblocks == NULL)
2931 		return (1);
2932 	/*
2933 	 * We use a tighter restriction here to prevent request_cleanup()
2934 	 * running in threads from running into locks we currently hold.
2935 	 * We have to be over the limit and our filesystem has to be
2936 	 * responsible for more than our share of that usage.
2937 	 */
2938 	limit = (max_softdeps / 10) * 9;
2939 	if (dep_current[D_INODEDEP] > limit &&
2940 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2941 		return (0);
2942 	if (thresh)
2943 		thresh = jblocks->jb_min;
2944 	else
2945 		thresh = jblocks->jb_low;
2946 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2947 	avail = jblocks->jb_free - avail;
2948 
2949 	return (avail > thresh);
2950 }
2951 
2952 static void
2953 journal_suspend(ump)
2954 	struct ufsmount *ump;
2955 {
2956 	struct jblocks *jblocks;
2957 	struct mount *mp;
2958 	bool set;
2959 
2960 	mp = UFSTOVFS(ump);
2961 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
2962 		return;
2963 
2964 	jblocks = ump->softdep_jblocks;
2965 	vfs_op_enter(mp);
2966 	set = false;
2967 	MNT_ILOCK(mp);
2968 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2969 		stat_journal_min++;
2970 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2971 		mp->mnt_susp_owner = ump->softdep_flushtd;
2972 		set = true;
2973 	}
2974 	jblocks->jb_suspended = 1;
2975 	MNT_IUNLOCK(mp);
2976 	if (!set)
2977 		vfs_op_exit(mp);
2978 }
2979 
2980 static int
2981 journal_unsuspend(struct ufsmount *ump)
2982 {
2983 	struct jblocks *jblocks;
2984 	struct mount *mp;
2985 
2986 	mp = UFSTOVFS(ump);
2987 	jblocks = ump->softdep_jblocks;
2988 
2989 	if (jblocks != NULL && jblocks->jb_suspended &&
2990 	    journal_space(ump, jblocks->jb_min)) {
2991 		jblocks->jb_suspended = 0;
2992 		FREE_LOCK(ump);
2993 		mp->mnt_susp_owner = curthread;
2994 		vfs_write_resume(mp, 0);
2995 		ACQUIRE_LOCK(ump);
2996 		return (1);
2997 	}
2998 	return (0);
2999 }
3000 
3001 /*
3002  * Called before any allocation function to be certain that there is
3003  * sufficient space in the journal prior to creating any new records.
3004  * Since in the case of block allocation we may have multiple locked
3005  * buffers at the time of the actual allocation we can not block
3006  * when the journal records are created.  Doing so would create a deadlock
3007  * if any of these buffers needed to be flushed to reclaim space.  Instead
3008  * we require a sufficiently large amount of available space such that
3009  * each thread in the system could have passed this allocation check and
3010  * still have sufficient free space.  With 20% of a minimum journal size
3011  * of 1MB we have 6553 records available.
3012  */
3013 int
3014 softdep_prealloc(vp, waitok)
3015 	struct vnode *vp;
3016 	int waitok;
3017 {
3018 	struct ufsmount *ump;
3019 
3020 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3021 	    ("softdep_prealloc called on non-softdep filesystem"));
3022 	/*
3023 	 * Nothing to do if we are not running journaled soft updates.
3024 	 * If we currently hold the snapshot lock, we must avoid
3025 	 * handling other resources that could cause deadlock.  Do not
3026 	 * touch quotas vnode since it is typically recursed with
3027 	 * other vnode locks held.
3028 	 */
3029 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3030 	    (vp->v_vflag & VV_SYSTEM) != 0)
3031 		return (0);
3032 	ump = VFSTOUFS(vp->v_mount);
3033 	ACQUIRE_LOCK(ump);
3034 	if (journal_space(ump, 0)) {
3035 		FREE_LOCK(ump);
3036 		return (0);
3037 	}
3038 	stat_journal_low++;
3039 	FREE_LOCK(ump);
3040 	if (waitok == MNT_NOWAIT)
3041 		return (ENOSPC);
3042 	/*
3043 	 * Attempt to sync this vnode once to flush any journal
3044 	 * work attached to it.
3045 	 */
3046 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3047 		ffs_syncvnode(vp, waitok, 0);
3048 	ACQUIRE_LOCK(ump);
3049 	process_removes(vp);
3050 	process_truncates(vp);
3051 	if (journal_space(ump, 0) == 0) {
3052 		softdep_speedup(ump);
3053 		if (journal_space(ump, 1) == 0)
3054 			journal_suspend(ump);
3055 	}
3056 	FREE_LOCK(ump);
3057 
3058 	return (0);
3059 }
3060 
3061 /*
3062  * Before adjusting a link count on a vnode verify that we have sufficient
3063  * journal space.  If not, process operations that depend on the currently
3064  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3065  * and softdep flush threads can not acquire these locks to reclaim space.
3066  */
3067 static void
3068 softdep_prelink(dvp, vp)
3069 	struct vnode *dvp;
3070 	struct vnode *vp;
3071 {
3072 	struct ufsmount *ump;
3073 
3074 	ump = VFSTOUFS(dvp->v_mount);
3075 	LOCK_OWNED(ump);
3076 	/*
3077 	 * Nothing to do if we have sufficient journal space.
3078 	 * If we currently hold the snapshot lock, we must avoid
3079 	 * handling other resources that could cause deadlock.
3080 	 */
3081 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3082 		return;
3083 	stat_journal_low++;
3084 	FREE_LOCK(ump);
3085 	if (vp)
3086 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3087 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3088 	ACQUIRE_LOCK(ump);
3089 	/* Process vp before dvp as it may create .. removes. */
3090 	if (vp) {
3091 		process_removes(vp);
3092 		process_truncates(vp);
3093 	}
3094 	process_removes(dvp);
3095 	process_truncates(dvp);
3096 	softdep_speedup(ump);
3097 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3098 	if (journal_space(ump, 0) == 0) {
3099 		softdep_speedup(ump);
3100 		if (journal_space(ump, 1) == 0)
3101 			journal_suspend(ump);
3102 	}
3103 }
3104 
3105 static void
3106 jseg_write(ump, jseg, data)
3107 	struct ufsmount *ump;
3108 	struct jseg *jseg;
3109 	uint8_t *data;
3110 {
3111 	struct jsegrec *rec;
3112 
3113 	rec = (struct jsegrec *)data;
3114 	rec->jsr_seq = jseg->js_seq;
3115 	rec->jsr_oldest = jseg->js_oldseq;
3116 	rec->jsr_cnt = jseg->js_cnt;
3117 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3118 	rec->jsr_crc = 0;
3119 	rec->jsr_time = ump->um_fs->fs_mtime;
3120 }
3121 
3122 static inline void
3123 inoref_write(inoref, jseg, rec)
3124 	struct inoref *inoref;
3125 	struct jseg *jseg;
3126 	struct jrefrec *rec;
3127 {
3128 
3129 	inoref->if_jsegdep->jd_seg = jseg;
3130 	rec->jr_ino = inoref->if_ino;
3131 	rec->jr_parent = inoref->if_parent;
3132 	rec->jr_nlink = inoref->if_nlink;
3133 	rec->jr_mode = inoref->if_mode;
3134 	rec->jr_diroff = inoref->if_diroff;
3135 }
3136 
3137 static void
3138 jaddref_write(jaddref, jseg, data)
3139 	struct jaddref *jaddref;
3140 	struct jseg *jseg;
3141 	uint8_t *data;
3142 {
3143 	struct jrefrec *rec;
3144 
3145 	rec = (struct jrefrec *)data;
3146 	rec->jr_op = JOP_ADDREF;
3147 	inoref_write(&jaddref->ja_ref, jseg, rec);
3148 }
3149 
3150 static void
3151 jremref_write(jremref, jseg, data)
3152 	struct jremref *jremref;
3153 	struct jseg *jseg;
3154 	uint8_t *data;
3155 {
3156 	struct jrefrec *rec;
3157 
3158 	rec = (struct jrefrec *)data;
3159 	rec->jr_op = JOP_REMREF;
3160 	inoref_write(&jremref->jr_ref, jseg, rec);
3161 }
3162 
3163 static void
3164 jmvref_write(jmvref, jseg, data)
3165 	struct jmvref *jmvref;
3166 	struct jseg *jseg;
3167 	uint8_t *data;
3168 {
3169 	struct jmvrec *rec;
3170 
3171 	rec = (struct jmvrec *)data;
3172 	rec->jm_op = JOP_MVREF;
3173 	rec->jm_ino = jmvref->jm_ino;
3174 	rec->jm_parent = jmvref->jm_parent;
3175 	rec->jm_oldoff = jmvref->jm_oldoff;
3176 	rec->jm_newoff = jmvref->jm_newoff;
3177 }
3178 
3179 static void
3180 jnewblk_write(jnewblk, jseg, data)
3181 	struct jnewblk *jnewblk;
3182 	struct jseg *jseg;
3183 	uint8_t *data;
3184 {
3185 	struct jblkrec *rec;
3186 
3187 	jnewblk->jn_jsegdep->jd_seg = jseg;
3188 	rec = (struct jblkrec *)data;
3189 	rec->jb_op = JOP_NEWBLK;
3190 	rec->jb_ino = jnewblk->jn_ino;
3191 	rec->jb_blkno = jnewblk->jn_blkno;
3192 	rec->jb_lbn = jnewblk->jn_lbn;
3193 	rec->jb_frags = jnewblk->jn_frags;
3194 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3195 }
3196 
3197 static void
3198 jfreeblk_write(jfreeblk, jseg, data)
3199 	struct jfreeblk *jfreeblk;
3200 	struct jseg *jseg;
3201 	uint8_t *data;
3202 {
3203 	struct jblkrec *rec;
3204 
3205 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3206 	rec = (struct jblkrec *)data;
3207 	rec->jb_op = JOP_FREEBLK;
3208 	rec->jb_ino = jfreeblk->jf_ino;
3209 	rec->jb_blkno = jfreeblk->jf_blkno;
3210 	rec->jb_lbn = jfreeblk->jf_lbn;
3211 	rec->jb_frags = jfreeblk->jf_frags;
3212 	rec->jb_oldfrags = 0;
3213 }
3214 
3215 static void
3216 jfreefrag_write(jfreefrag, jseg, data)
3217 	struct jfreefrag *jfreefrag;
3218 	struct jseg *jseg;
3219 	uint8_t *data;
3220 {
3221 	struct jblkrec *rec;
3222 
3223 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3224 	rec = (struct jblkrec *)data;
3225 	rec->jb_op = JOP_FREEBLK;
3226 	rec->jb_ino = jfreefrag->fr_ino;
3227 	rec->jb_blkno = jfreefrag->fr_blkno;
3228 	rec->jb_lbn = jfreefrag->fr_lbn;
3229 	rec->jb_frags = jfreefrag->fr_frags;
3230 	rec->jb_oldfrags = 0;
3231 }
3232 
3233 static void
3234 jtrunc_write(jtrunc, jseg, data)
3235 	struct jtrunc *jtrunc;
3236 	struct jseg *jseg;
3237 	uint8_t *data;
3238 {
3239 	struct jtrncrec *rec;
3240 
3241 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3242 	rec = (struct jtrncrec *)data;
3243 	rec->jt_op = JOP_TRUNC;
3244 	rec->jt_ino = jtrunc->jt_ino;
3245 	rec->jt_size = jtrunc->jt_size;
3246 	rec->jt_extsize = jtrunc->jt_extsize;
3247 }
3248 
3249 static void
3250 jfsync_write(jfsync, jseg, data)
3251 	struct jfsync *jfsync;
3252 	struct jseg *jseg;
3253 	uint8_t *data;
3254 {
3255 	struct jtrncrec *rec;
3256 
3257 	rec = (struct jtrncrec *)data;
3258 	rec->jt_op = JOP_SYNC;
3259 	rec->jt_ino = jfsync->jfs_ino;
3260 	rec->jt_size = jfsync->jfs_size;
3261 	rec->jt_extsize = jfsync->jfs_extsize;
3262 }
3263 
3264 static void
3265 softdep_flushjournal(mp)
3266 	struct mount *mp;
3267 {
3268 	struct jblocks *jblocks;
3269 	struct ufsmount *ump;
3270 
3271 	if (MOUNTEDSUJ(mp) == 0)
3272 		return;
3273 	ump = VFSTOUFS(mp);
3274 	jblocks = ump->softdep_jblocks;
3275 	ACQUIRE_LOCK(ump);
3276 	while (ump->softdep_on_journal) {
3277 		jblocks->jb_needseg = 1;
3278 		softdep_process_journal(mp, NULL, MNT_WAIT);
3279 	}
3280 	FREE_LOCK(ump);
3281 }
3282 
3283 static void softdep_synchronize_completed(struct bio *);
3284 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3285 
3286 static void
3287 softdep_synchronize_completed(bp)
3288         struct bio *bp;
3289 {
3290 	struct jseg *oldest;
3291 	struct jseg *jseg;
3292 	struct ufsmount *ump;
3293 
3294 	/*
3295 	 * caller1 marks the last segment written before we issued the
3296 	 * synchronize cache.
3297 	 */
3298 	jseg = bp->bio_caller1;
3299 	if (jseg == NULL) {
3300 		g_destroy_bio(bp);
3301 		return;
3302 	}
3303 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3304 	ACQUIRE_LOCK(ump);
3305 	oldest = NULL;
3306 	/*
3307 	 * Mark all the journal entries waiting on the synchronize cache
3308 	 * as completed so they may continue on.
3309 	 */
3310 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3311 		jseg->js_state |= COMPLETE;
3312 		oldest = jseg;
3313 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3314 	}
3315 	/*
3316 	 * Restart deferred journal entry processing from the oldest
3317 	 * completed jseg.
3318 	 */
3319 	if (oldest)
3320 		complete_jsegs(oldest);
3321 
3322 	FREE_LOCK(ump);
3323 	g_destroy_bio(bp);
3324 }
3325 
3326 /*
3327  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3328  * barriers.  The journal must be written prior to any blocks that depend
3329  * on it and the journal can not be released until the blocks have be
3330  * written.  This code handles both barriers simultaneously.
3331  */
3332 static void
3333 softdep_synchronize(bp, ump, caller1)
3334 	struct bio *bp;
3335 	struct ufsmount *ump;
3336 	void *caller1;
3337 {
3338 
3339 	bp->bio_cmd = BIO_FLUSH;
3340 	bp->bio_flags |= BIO_ORDERED;
3341 	bp->bio_data = NULL;
3342 	bp->bio_offset = ump->um_cp->provider->mediasize;
3343 	bp->bio_length = 0;
3344 	bp->bio_done = softdep_synchronize_completed;
3345 	bp->bio_caller1 = caller1;
3346 	g_io_request(bp,
3347 	    (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3348 }
3349 
3350 /*
3351  * Flush some journal records to disk.
3352  */
3353 static void
3354 softdep_process_journal(mp, needwk, flags)
3355 	struct mount *mp;
3356 	struct worklist *needwk;
3357 	int flags;
3358 {
3359 	struct jblocks *jblocks;
3360 	struct ufsmount *ump;
3361 	struct worklist *wk;
3362 	struct jseg *jseg;
3363 	struct buf *bp;
3364 	struct bio *bio;
3365 	uint8_t *data;
3366 	struct fs *fs;
3367 	int shouldflush;
3368 	int segwritten;
3369 	int jrecmin;	/* Minimum records per block. */
3370 	int jrecmax;	/* Maximum records per block. */
3371 	int size;
3372 	int cnt;
3373 	int off;
3374 	int devbsize;
3375 
3376 	if (MOUNTEDSUJ(mp) == 0)
3377 		return;
3378 	shouldflush = softdep_flushcache;
3379 	bio = NULL;
3380 	jseg = NULL;
3381 	ump = VFSTOUFS(mp);
3382 	LOCK_OWNED(ump);
3383 	fs = ump->um_fs;
3384 	jblocks = ump->softdep_jblocks;
3385 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3386 	/*
3387 	 * We write anywhere between a disk block and fs block.  The upper
3388 	 * bound is picked to prevent buffer cache fragmentation and limit
3389 	 * processing time per I/O.
3390 	 */
3391 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3392 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3393 	segwritten = 0;
3394 	for (;;) {
3395 		cnt = ump->softdep_on_journal;
3396 		/*
3397 		 * Criteria for writing a segment:
3398 		 * 1) We have a full block.
3399 		 * 2) We're called from jwait() and haven't found the
3400 		 *    journal item yet.
3401 		 * 3) Always write if needseg is set.
3402 		 * 4) If we are called from process_worklist and have
3403 		 *    not yet written anything we write a partial block
3404 		 *    to enforce a 1 second maximum latency on journal
3405 		 *    entries.
3406 		 */
3407 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3408 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3409 			break;
3410 		cnt++;
3411 		/*
3412 		 * Verify some free journal space.  softdep_prealloc() should
3413 		 * guarantee that we don't run out so this is indicative of
3414 		 * a problem with the flow control.  Try to recover
3415 		 * gracefully in any event.
3416 		 */
3417 		while (jblocks->jb_free == 0) {
3418 			if (flags != MNT_WAIT)
3419 				break;
3420 			printf("softdep: Out of journal space!\n");
3421 			softdep_speedup(ump);
3422 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3423 		}
3424 		FREE_LOCK(ump);
3425 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3426 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3427 		LIST_INIT(&jseg->js_entries);
3428 		LIST_INIT(&jseg->js_indirs);
3429 		jseg->js_state = ATTACHED;
3430 		if (shouldflush == 0)
3431 			jseg->js_state |= COMPLETE;
3432 		else if (bio == NULL)
3433 			bio = g_alloc_bio();
3434 		jseg->js_jblocks = jblocks;
3435 		bp = geteblk(fs->fs_bsize, 0);
3436 		ACQUIRE_LOCK(ump);
3437 		/*
3438 		 * If there was a race while we were allocating the block
3439 		 * and jseg the entry we care about was likely written.
3440 		 * We bail out in both the WAIT and NOWAIT case and assume
3441 		 * the caller will loop if the entry it cares about is
3442 		 * not written.
3443 		 */
3444 		cnt = ump->softdep_on_journal;
3445 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3446 			bp->b_flags |= B_INVAL | B_NOCACHE;
3447 			WORKITEM_FREE(jseg, D_JSEG);
3448 			FREE_LOCK(ump);
3449 			brelse(bp);
3450 			ACQUIRE_LOCK(ump);
3451 			break;
3452 		}
3453 		/*
3454 		 * Calculate the disk block size required for the available
3455 		 * records rounded to the min size.
3456 		 */
3457 		if (cnt == 0)
3458 			size = devbsize;
3459 		else if (cnt < jrecmax)
3460 			size = howmany(cnt, jrecmin) * devbsize;
3461 		else
3462 			size = fs->fs_bsize;
3463 		/*
3464 		 * Allocate a disk block for this journal data and account
3465 		 * for truncation of the requested size if enough contiguous
3466 		 * space was not available.
3467 		 */
3468 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3469 		bp->b_lblkno = bp->b_blkno;
3470 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3471 		bp->b_bcount = size;
3472 		bp->b_flags &= ~B_INVAL;
3473 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3474 		/*
3475 		 * Initialize our jseg with cnt records.  Assign the next
3476 		 * sequence number to it and link it in-order.
3477 		 */
3478 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3479 		jseg->js_buf = bp;
3480 		jseg->js_cnt = cnt;
3481 		jseg->js_refs = cnt + 1;	/* Self ref. */
3482 		jseg->js_size = size;
3483 		jseg->js_seq = jblocks->jb_nextseq++;
3484 		if (jblocks->jb_oldestseg == NULL)
3485 			jblocks->jb_oldestseg = jseg;
3486 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3487 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3488 		if (jblocks->jb_writeseg == NULL)
3489 			jblocks->jb_writeseg = jseg;
3490 		/*
3491 		 * Start filling in records from the pending list.
3492 		 */
3493 		data = bp->b_data;
3494 		off = 0;
3495 
3496 		/*
3497 		 * Always put a header on the first block.
3498 		 * XXX As with below, there might not be a chance to get
3499 		 * into the loop.  Ensure that something valid is written.
3500 		 */
3501 		jseg_write(ump, jseg, data);
3502 		off += JREC_SIZE;
3503 		data = bp->b_data + off;
3504 
3505 		/*
3506 		 * XXX Something is wrong here.  There's no work to do,
3507 		 * but we need to perform and I/O and allow it to complete
3508 		 * anyways.
3509 		 */
3510 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3511 			stat_emptyjblocks++;
3512 
3513 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3514 		    != NULL) {
3515 			if (cnt == 0)
3516 				break;
3517 			/* Place a segment header on every device block. */
3518 			if ((off % devbsize) == 0) {
3519 				jseg_write(ump, jseg, data);
3520 				off += JREC_SIZE;
3521 				data = bp->b_data + off;
3522 			}
3523 			if (wk == needwk)
3524 				needwk = NULL;
3525 			remove_from_journal(wk);
3526 			wk->wk_state |= INPROGRESS;
3527 			WORKLIST_INSERT(&jseg->js_entries, wk);
3528 			switch (wk->wk_type) {
3529 			case D_JADDREF:
3530 				jaddref_write(WK_JADDREF(wk), jseg, data);
3531 				break;
3532 			case D_JREMREF:
3533 				jremref_write(WK_JREMREF(wk), jseg, data);
3534 				break;
3535 			case D_JMVREF:
3536 				jmvref_write(WK_JMVREF(wk), jseg, data);
3537 				break;
3538 			case D_JNEWBLK:
3539 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3540 				break;
3541 			case D_JFREEBLK:
3542 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3543 				break;
3544 			case D_JFREEFRAG:
3545 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3546 				break;
3547 			case D_JTRUNC:
3548 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3549 				break;
3550 			case D_JFSYNC:
3551 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3552 				break;
3553 			default:
3554 				panic("process_journal: Unknown type %s",
3555 				    TYPENAME(wk->wk_type));
3556 				/* NOTREACHED */
3557 			}
3558 			off += JREC_SIZE;
3559 			data = bp->b_data + off;
3560 			cnt--;
3561 		}
3562 
3563 		/* Clear any remaining space so we don't leak kernel data */
3564 		if (size > off)
3565 			bzero(data, size - off);
3566 
3567 		/*
3568 		 * Write this one buffer and continue.
3569 		 */
3570 		segwritten = 1;
3571 		jblocks->jb_needseg = 0;
3572 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3573 		FREE_LOCK(ump);
3574 		pbgetvp(ump->um_devvp, bp);
3575 		/*
3576 		 * We only do the blocking wait once we find the journal
3577 		 * entry we're looking for.
3578 		 */
3579 		if (needwk == NULL && flags == MNT_WAIT)
3580 			bwrite(bp);
3581 		else
3582 			bawrite(bp);
3583 		ACQUIRE_LOCK(ump);
3584 	}
3585 	/*
3586 	 * If we wrote a segment issue a synchronize cache so the journal
3587 	 * is reflected on disk before the data is written.  Since reclaiming
3588 	 * journal space also requires writing a journal record this
3589 	 * process also enforces a barrier before reclamation.
3590 	 */
3591 	if (segwritten && shouldflush) {
3592 		softdep_synchronize(bio, ump,
3593 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3594 	} else if (bio)
3595 		g_destroy_bio(bio);
3596 	/*
3597 	 * If we've suspended the filesystem because we ran out of journal
3598 	 * space either try to sync it here to make some progress or
3599 	 * unsuspend it if we already have.
3600 	 */
3601 	if (flags == 0 && jblocks->jb_suspended) {
3602 		if (journal_unsuspend(ump))
3603 			return;
3604 		FREE_LOCK(ump);
3605 		VFS_SYNC(mp, MNT_NOWAIT);
3606 		ffs_sbupdate(ump, MNT_WAIT, 0);
3607 		ACQUIRE_LOCK(ump);
3608 	}
3609 }
3610 
3611 /*
3612  * Complete a jseg, allowing all dependencies awaiting journal writes
3613  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3614  * structures so that the journal segment can be freed to reclaim space.
3615  */
3616 static void
3617 complete_jseg(jseg)
3618 	struct jseg *jseg;
3619 {
3620 	struct worklist *wk;
3621 	struct jmvref *jmvref;
3622 #ifdef INVARIANTS
3623 	int i = 0;
3624 #endif
3625 
3626 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3627 		WORKLIST_REMOVE(wk);
3628 		wk->wk_state &= ~INPROGRESS;
3629 		wk->wk_state |= COMPLETE;
3630 		KASSERT(i++ < jseg->js_cnt,
3631 		    ("handle_written_jseg: overflow %d >= %d",
3632 		    i - 1, jseg->js_cnt));
3633 		switch (wk->wk_type) {
3634 		case D_JADDREF:
3635 			handle_written_jaddref(WK_JADDREF(wk));
3636 			break;
3637 		case D_JREMREF:
3638 			handle_written_jremref(WK_JREMREF(wk));
3639 			break;
3640 		case D_JMVREF:
3641 			rele_jseg(jseg);	/* No jsegdep. */
3642 			jmvref = WK_JMVREF(wk);
3643 			LIST_REMOVE(jmvref, jm_deps);
3644 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3645 				free_pagedep(jmvref->jm_pagedep);
3646 			WORKITEM_FREE(jmvref, D_JMVREF);
3647 			break;
3648 		case D_JNEWBLK:
3649 			handle_written_jnewblk(WK_JNEWBLK(wk));
3650 			break;
3651 		case D_JFREEBLK:
3652 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3653 			break;
3654 		case D_JTRUNC:
3655 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3656 			break;
3657 		case D_JFSYNC:
3658 			rele_jseg(jseg);	/* No jsegdep. */
3659 			WORKITEM_FREE(wk, D_JFSYNC);
3660 			break;
3661 		case D_JFREEFRAG:
3662 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3663 			break;
3664 		default:
3665 			panic("handle_written_jseg: Unknown type %s",
3666 			    TYPENAME(wk->wk_type));
3667 			/* NOTREACHED */
3668 		}
3669 	}
3670 	/* Release the self reference so the structure may be freed. */
3671 	rele_jseg(jseg);
3672 }
3673 
3674 /*
3675  * Determine which jsegs are ready for completion processing.  Waits for
3676  * synchronize cache to complete as well as forcing in-order completion
3677  * of journal entries.
3678  */
3679 static void
3680 complete_jsegs(jseg)
3681 	struct jseg *jseg;
3682 {
3683 	struct jblocks *jblocks;
3684 	struct jseg *jsegn;
3685 
3686 	jblocks = jseg->js_jblocks;
3687 	/*
3688 	 * Don't allow out of order completions.  If this isn't the first
3689 	 * block wait for it to write before we're done.
3690 	 */
3691 	if (jseg != jblocks->jb_writeseg)
3692 		return;
3693 	/* Iterate through available jsegs processing their entries. */
3694 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3695 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3696 		jsegn = TAILQ_NEXT(jseg, js_next);
3697 		complete_jseg(jseg);
3698 		jseg = jsegn;
3699 	}
3700 	jblocks->jb_writeseg = jseg;
3701 	/*
3702 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3703 	 */
3704 	free_jsegs(jblocks);
3705 }
3706 
3707 /*
3708  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3709  * the final completions.
3710  */
3711 static void
3712 handle_written_jseg(jseg, bp)
3713 	struct jseg *jseg;
3714 	struct buf *bp;
3715 {
3716 
3717 	if (jseg->js_refs == 0)
3718 		panic("handle_written_jseg: No self-reference on %p", jseg);
3719 	jseg->js_state |= DEPCOMPLETE;
3720 	/*
3721 	 * We'll never need this buffer again, set flags so it will be
3722 	 * discarded.
3723 	 */
3724 	bp->b_flags |= B_INVAL | B_NOCACHE;
3725 	pbrelvp(bp);
3726 	complete_jsegs(jseg);
3727 }
3728 
3729 static inline struct jsegdep *
3730 inoref_jseg(inoref)
3731 	struct inoref *inoref;
3732 {
3733 	struct jsegdep *jsegdep;
3734 
3735 	jsegdep = inoref->if_jsegdep;
3736 	inoref->if_jsegdep = NULL;
3737 
3738 	return (jsegdep);
3739 }
3740 
3741 /*
3742  * Called once a jremref has made it to stable store.  The jremref is marked
3743  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3744  * for the jremref to complete will be awoken by free_jremref.
3745  */
3746 static void
3747 handle_written_jremref(jremref)
3748 	struct jremref *jremref;
3749 {
3750 	struct inodedep *inodedep;
3751 	struct jsegdep *jsegdep;
3752 	struct dirrem *dirrem;
3753 
3754 	/* Grab the jsegdep. */
3755 	jsegdep = inoref_jseg(&jremref->jr_ref);
3756 	/*
3757 	 * Remove us from the inoref list.
3758 	 */
3759 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3760 	    0, &inodedep) == 0)
3761 		panic("handle_written_jremref: Lost inodedep");
3762 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3763 	/*
3764 	 * Complete the dirrem.
3765 	 */
3766 	dirrem = jremref->jr_dirrem;
3767 	jremref->jr_dirrem = NULL;
3768 	LIST_REMOVE(jremref, jr_deps);
3769 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3770 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3771 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3772 	    (dirrem->dm_state & COMPLETE) != 0)
3773 		add_to_worklist(&dirrem->dm_list, 0);
3774 	free_jremref(jremref);
3775 }
3776 
3777 /*
3778  * Called once a jaddref has made it to stable store.  The dependency is
3779  * marked complete and any dependent structures are added to the inode
3780  * bufwait list to be completed as soon as it is written.  If a bitmap write
3781  * depends on this entry we move the inode into the inodedephd of the
3782  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3783  */
3784 static void
3785 handle_written_jaddref(jaddref)
3786 	struct jaddref *jaddref;
3787 {
3788 	struct jsegdep *jsegdep;
3789 	struct inodedep *inodedep;
3790 	struct diradd *diradd;
3791 	struct mkdir *mkdir;
3792 
3793 	/* Grab the jsegdep. */
3794 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3795 	mkdir = NULL;
3796 	diradd = NULL;
3797 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3798 	    0, &inodedep) == 0)
3799 		panic("handle_written_jaddref: Lost inodedep.");
3800 	if (jaddref->ja_diradd == NULL)
3801 		panic("handle_written_jaddref: No dependency");
3802 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3803 		diradd = jaddref->ja_diradd;
3804 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3805 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3806 		mkdir = jaddref->ja_mkdir;
3807 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3808 	} else if (jaddref->ja_state & MKDIR_BODY)
3809 		mkdir = jaddref->ja_mkdir;
3810 	else
3811 		panic("handle_written_jaddref: Unknown dependency %p",
3812 		    jaddref->ja_diradd);
3813 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3814 	/*
3815 	 * Remove us from the inode list.
3816 	 */
3817 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3818 	/*
3819 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3820 	 */
3821 	if (mkdir) {
3822 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3823 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3824 		    TYPENAME(mkdir->md_list.wk_type)));
3825 		mkdir->md_jaddref = NULL;
3826 		diradd = mkdir->md_diradd;
3827 		mkdir->md_state |= DEPCOMPLETE;
3828 		complete_mkdir(mkdir);
3829 	}
3830 	jwork_insert(&diradd->da_jwork, jsegdep);
3831 	if (jaddref->ja_state & NEWBLOCK) {
3832 		inodedep->id_state |= ONDEPLIST;
3833 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3834 		    inodedep, id_deps);
3835 	}
3836 	free_jaddref(jaddref);
3837 }
3838 
3839 /*
3840  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3841  * is placed in the bmsafemap to await notification of a written bitmap.  If
3842  * the operation was canceled we add the segdep to the appropriate
3843  * dependency to free the journal space once the canceling operation
3844  * completes.
3845  */
3846 static void
3847 handle_written_jnewblk(jnewblk)
3848 	struct jnewblk *jnewblk;
3849 {
3850 	struct bmsafemap *bmsafemap;
3851 	struct freefrag *freefrag;
3852 	struct freework *freework;
3853 	struct jsegdep *jsegdep;
3854 	struct newblk *newblk;
3855 
3856 	/* Grab the jsegdep. */
3857 	jsegdep = jnewblk->jn_jsegdep;
3858 	jnewblk->jn_jsegdep = NULL;
3859 	if (jnewblk->jn_dep == NULL)
3860 		panic("handle_written_jnewblk: No dependency for the segdep.");
3861 	switch (jnewblk->jn_dep->wk_type) {
3862 	case D_NEWBLK:
3863 	case D_ALLOCDIRECT:
3864 	case D_ALLOCINDIR:
3865 		/*
3866 		 * Add the written block to the bmsafemap so it can
3867 		 * be notified when the bitmap is on disk.
3868 		 */
3869 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3870 		newblk->nb_jnewblk = NULL;
3871 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3872 			bmsafemap = newblk->nb_bmsafemap;
3873 			newblk->nb_state |= ONDEPLIST;
3874 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3875 			    nb_deps);
3876 		}
3877 		jwork_insert(&newblk->nb_jwork, jsegdep);
3878 		break;
3879 	case D_FREEFRAG:
3880 		/*
3881 		 * A newblock being removed by a freefrag when replaced by
3882 		 * frag extension.
3883 		 */
3884 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3885 		freefrag->ff_jdep = NULL;
3886 		jwork_insert(&freefrag->ff_jwork, jsegdep);
3887 		break;
3888 	case D_FREEWORK:
3889 		/*
3890 		 * A direct block was removed by truncate.
3891 		 */
3892 		freework = WK_FREEWORK(jnewblk->jn_dep);
3893 		freework->fw_jnewblk = NULL;
3894 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3895 		break;
3896 	default:
3897 		panic("handle_written_jnewblk: Unknown type %d.",
3898 		    jnewblk->jn_dep->wk_type);
3899 	}
3900 	jnewblk->jn_dep = NULL;
3901 	free_jnewblk(jnewblk);
3902 }
3903 
3904 /*
3905  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3906  * an in-flight allocation that has not yet been committed.  Divorce us
3907  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3908  * to the worklist.
3909  */
3910 static void
3911 cancel_jfreefrag(jfreefrag)
3912 	struct jfreefrag *jfreefrag;
3913 {
3914 	struct freefrag *freefrag;
3915 
3916 	if (jfreefrag->fr_jsegdep) {
3917 		free_jsegdep(jfreefrag->fr_jsegdep);
3918 		jfreefrag->fr_jsegdep = NULL;
3919 	}
3920 	freefrag = jfreefrag->fr_freefrag;
3921 	jfreefrag->fr_freefrag = NULL;
3922 	free_jfreefrag(jfreefrag);
3923 	freefrag->ff_state |= DEPCOMPLETE;
3924 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3925 }
3926 
3927 /*
3928  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3929  */
3930 static void
3931 free_jfreefrag(jfreefrag)
3932 	struct jfreefrag *jfreefrag;
3933 {
3934 
3935 	if (jfreefrag->fr_state & INPROGRESS)
3936 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3937 	else if (jfreefrag->fr_state & ONWORKLIST)
3938 		remove_from_journal(&jfreefrag->fr_list);
3939 	if (jfreefrag->fr_freefrag != NULL)
3940 		panic("free_jfreefrag:  Still attached to a freefrag.");
3941 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3942 }
3943 
3944 /*
3945  * Called when the journal write for a jfreefrag completes.  The parent
3946  * freefrag is added to the worklist if this completes its dependencies.
3947  */
3948 static void
3949 handle_written_jfreefrag(jfreefrag)
3950 	struct jfreefrag *jfreefrag;
3951 {
3952 	struct jsegdep *jsegdep;
3953 	struct freefrag *freefrag;
3954 
3955 	/* Grab the jsegdep. */
3956 	jsegdep = jfreefrag->fr_jsegdep;
3957 	jfreefrag->fr_jsegdep = NULL;
3958 	freefrag = jfreefrag->fr_freefrag;
3959 	if (freefrag == NULL)
3960 		panic("handle_written_jfreefrag: No freefrag.");
3961 	freefrag->ff_state |= DEPCOMPLETE;
3962 	freefrag->ff_jdep = NULL;
3963 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3964 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3965 		add_to_worklist(&freefrag->ff_list, 0);
3966 	jfreefrag->fr_freefrag = NULL;
3967 	free_jfreefrag(jfreefrag);
3968 }
3969 
3970 /*
3971  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3972  * is removed from the freeblks list of pending journal writes and the
3973  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3974  * have been reclaimed.
3975  */
3976 static void
3977 handle_written_jblkdep(jblkdep)
3978 	struct jblkdep *jblkdep;
3979 {
3980 	struct freeblks *freeblks;
3981 	struct jsegdep *jsegdep;
3982 
3983 	/* Grab the jsegdep. */
3984 	jsegdep = jblkdep->jb_jsegdep;
3985 	jblkdep->jb_jsegdep = NULL;
3986 	freeblks = jblkdep->jb_freeblks;
3987 	LIST_REMOVE(jblkdep, jb_deps);
3988 	jwork_insert(&freeblks->fb_jwork, jsegdep);
3989 	/*
3990 	 * If the freeblks is all journaled, we can add it to the worklist.
3991 	 */
3992 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3993 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3994 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3995 
3996 	free_jblkdep(jblkdep);
3997 }
3998 
3999 static struct jsegdep *
4000 newjsegdep(struct worklist *wk)
4001 {
4002 	struct jsegdep *jsegdep;
4003 
4004 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4005 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4006 	jsegdep->jd_seg = NULL;
4007 
4008 	return (jsegdep);
4009 }
4010 
4011 static struct jmvref *
4012 newjmvref(dp, ino, oldoff, newoff)
4013 	struct inode *dp;
4014 	ino_t ino;
4015 	off_t oldoff;
4016 	off_t newoff;
4017 {
4018 	struct jmvref *jmvref;
4019 
4020 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4021 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4022 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4023 	jmvref->jm_parent = dp->i_number;
4024 	jmvref->jm_ino = ino;
4025 	jmvref->jm_oldoff = oldoff;
4026 	jmvref->jm_newoff = newoff;
4027 
4028 	return (jmvref);
4029 }
4030 
4031 /*
4032  * Allocate a new jremref that tracks the removal of ip from dp with the
4033  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4034  * DEPCOMPLETE as we have all the information required for the journal write
4035  * and the directory has already been removed from the buffer.  The caller
4036  * is responsible for linking the jremref into the pagedep and adding it
4037  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4038  * a DOTDOT addition so handle_workitem_remove() can properly assign
4039  * the jsegdep when we're done.
4040  */
4041 static struct jremref *
4042 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4043     off_t diroff, nlink_t nlink)
4044 {
4045 	struct jremref *jremref;
4046 
4047 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4048 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4049 	jremref->jr_state = ATTACHED;
4050 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4051 	   nlink, ip->i_mode);
4052 	jremref->jr_dirrem = dirrem;
4053 
4054 	return (jremref);
4055 }
4056 
4057 static inline void
4058 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4059     nlink_t nlink, uint16_t mode)
4060 {
4061 
4062 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4063 	inoref->if_diroff = diroff;
4064 	inoref->if_ino = ino;
4065 	inoref->if_parent = parent;
4066 	inoref->if_nlink = nlink;
4067 	inoref->if_mode = mode;
4068 }
4069 
4070 /*
4071  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4072  * directory offset may not be known until later.  The caller is responsible
4073  * adding the entry to the journal when this information is available.  nlink
4074  * should be the link count prior to the addition and mode is only required
4075  * to have the correct FMT.
4076  */
4077 static struct jaddref *
4078 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4079     uint16_t mode)
4080 {
4081 	struct jaddref *jaddref;
4082 
4083 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4084 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4085 	jaddref->ja_state = ATTACHED;
4086 	jaddref->ja_mkdir = NULL;
4087 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4088 
4089 	return (jaddref);
4090 }
4091 
4092 /*
4093  * Create a new free dependency for a freework.  The caller is responsible
4094  * for adjusting the reference count when it has the lock held.  The freedep
4095  * will track an outstanding bitmap write that will ultimately clear the
4096  * freework to continue.
4097  */
4098 static struct freedep *
4099 newfreedep(struct freework *freework)
4100 {
4101 	struct freedep *freedep;
4102 
4103 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4104 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4105 	freedep->fd_freework = freework;
4106 
4107 	return (freedep);
4108 }
4109 
4110 /*
4111  * Free a freedep structure once the buffer it is linked to is written.  If
4112  * this is the last reference to the freework schedule it for completion.
4113  */
4114 static void
4115 free_freedep(freedep)
4116 	struct freedep *freedep;
4117 {
4118 	struct freework *freework;
4119 
4120 	freework = freedep->fd_freework;
4121 	freework->fw_freeblks->fb_cgwait--;
4122 	if (--freework->fw_ref == 0)
4123 		freework_enqueue(freework);
4124 	WORKITEM_FREE(freedep, D_FREEDEP);
4125 }
4126 
4127 /*
4128  * Allocate a new freework structure that may be a level in an indirect
4129  * when parent is not NULL or a top level block when it is.  The top level
4130  * freework structures are allocated without the per-filesystem lock held
4131  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4132  */
4133 static struct freework *
4134 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4135 	struct ufsmount *ump;
4136 	struct freeblks *freeblks;
4137 	struct freework *parent;
4138 	ufs_lbn_t lbn;
4139 	ufs2_daddr_t nb;
4140 	int frags;
4141 	int off;
4142 	int journal;
4143 {
4144 	struct freework *freework;
4145 
4146 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4147 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4148 	freework->fw_state = ATTACHED;
4149 	freework->fw_jnewblk = NULL;
4150 	freework->fw_freeblks = freeblks;
4151 	freework->fw_parent = parent;
4152 	freework->fw_lbn = lbn;
4153 	freework->fw_blkno = nb;
4154 	freework->fw_frags = frags;
4155 	freework->fw_indir = NULL;
4156 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4157 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4158 	freework->fw_start = freework->fw_off = off;
4159 	if (journal)
4160 		newjfreeblk(freeblks, lbn, nb, frags);
4161 	if (parent == NULL) {
4162 		ACQUIRE_LOCK(ump);
4163 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4164 		freeblks->fb_ref++;
4165 		FREE_LOCK(ump);
4166 	}
4167 
4168 	return (freework);
4169 }
4170 
4171 /*
4172  * Eliminate a jfreeblk for a block that does not need journaling.
4173  */
4174 static void
4175 cancel_jfreeblk(freeblks, blkno)
4176 	struct freeblks *freeblks;
4177 	ufs2_daddr_t blkno;
4178 {
4179 	struct jfreeblk *jfreeblk;
4180 	struct jblkdep *jblkdep;
4181 
4182 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4183 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4184 			continue;
4185 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4186 		if (jfreeblk->jf_blkno == blkno)
4187 			break;
4188 	}
4189 	if (jblkdep == NULL)
4190 		return;
4191 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4192 	free_jsegdep(jblkdep->jb_jsegdep);
4193 	LIST_REMOVE(jblkdep, jb_deps);
4194 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4195 }
4196 
4197 /*
4198  * Allocate a new jfreeblk to journal top level block pointer when truncating
4199  * a file.  The caller must add this to the worklist when the per-filesystem
4200  * lock is held.
4201  */
4202 static struct jfreeblk *
4203 newjfreeblk(freeblks, lbn, blkno, frags)
4204 	struct freeblks *freeblks;
4205 	ufs_lbn_t lbn;
4206 	ufs2_daddr_t blkno;
4207 	int frags;
4208 {
4209 	struct jfreeblk *jfreeblk;
4210 
4211 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4212 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4213 	    freeblks->fb_list.wk_mp);
4214 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4215 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4216 	jfreeblk->jf_ino = freeblks->fb_inum;
4217 	jfreeblk->jf_lbn = lbn;
4218 	jfreeblk->jf_blkno = blkno;
4219 	jfreeblk->jf_frags = frags;
4220 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4221 
4222 	return (jfreeblk);
4223 }
4224 
4225 /*
4226  * The journal is only prepared to handle full-size block numbers, so we
4227  * have to adjust the record to reflect the change to a full-size block.
4228  * For example, suppose we have a block made up of fragments 8-15 and
4229  * want to free its last two fragments. We are given a request that says:
4230  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4231  * where frags are the number of fragments to free and oldfrags are the
4232  * number of fragments to keep. To block align it, we have to change it to
4233  * have a valid full-size blkno, so it becomes:
4234  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4235  */
4236 static void
4237 adjust_newfreework(freeblks, frag_offset)
4238 	struct freeblks *freeblks;
4239 	int frag_offset;
4240 {
4241 	struct jfreeblk *jfreeblk;
4242 
4243 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4244 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4245 	    ("adjust_newfreework: Missing freeblks dependency"));
4246 
4247 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4248 	jfreeblk->jf_blkno -= frag_offset;
4249 	jfreeblk->jf_frags += frag_offset;
4250 }
4251 
4252 /*
4253  * Allocate a new jtrunc to track a partial truncation.
4254  */
4255 static struct jtrunc *
4256 newjtrunc(freeblks, size, extsize)
4257 	struct freeblks *freeblks;
4258 	off_t size;
4259 	int extsize;
4260 {
4261 	struct jtrunc *jtrunc;
4262 
4263 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4264 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4265 	    freeblks->fb_list.wk_mp);
4266 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4267 	jtrunc->jt_dep.jb_freeblks = freeblks;
4268 	jtrunc->jt_ino = freeblks->fb_inum;
4269 	jtrunc->jt_size = size;
4270 	jtrunc->jt_extsize = extsize;
4271 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4272 
4273 	return (jtrunc);
4274 }
4275 
4276 /*
4277  * If we're canceling a new bitmap we have to search for another ref
4278  * to move into the bmsafemap dep.  This might be better expressed
4279  * with another structure.
4280  */
4281 static void
4282 move_newblock_dep(jaddref, inodedep)
4283 	struct jaddref *jaddref;
4284 	struct inodedep *inodedep;
4285 {
4286 	struct inoref *inoref;
4287 	struct jaddref *jaddrefn;
4288 
4289 	jaddrefn = NULL;
4290 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4291 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4292 		if ((jaddref->ja_state & NEWBLOCK) &&
4293 		    inoref->if_list.wk_type == D_JADDREF) {
4294 			jaddrefn = (struct jaddref *)inoref;
4295 			break;
4296 		}
4297 	}
4298 	if (jaddrefn == NULL)
4299 		return;
4300 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4301 	jaddrefn->ja_state |= jaddref->ja_state &
4302 	    (ATTACHED | UNDONE | NEWBLOCK);
4303 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4304 	jaddref->ja_state |= ATTACHED;
4305 	LIST_REMOVE(jaddref, ja_bmdeps);
4306 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4307 	    ja_bmdeps);
4308 }
4309 
4310 /*
4311  * Cancel a jaddref either before it has been written or while it is being
4312  * written.  This happens when a link is removed before the add reaches
4313  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4314  * and inode to prevent the link count or bitmap from reaching the disk
4315  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4316  * required.
4317  *
4318  * Returns 1 if the canceled addref requires journaling of the remove and
4319  * 0 otherwise.
4320  */
4321 static int
4322 cancel_jaddref(jaddref, inodedep, wkhd)
4323 	struct jaddref *jaddref;
4324 	struct inodedep *inodedep;
4325 	struct workhead *wkhd;
4326 {
4327 	struct inoref *inoref;
4328 	struct jsegdep *jsegdep;
4329 	int needsj;
4330 
4331 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4332 	    ("cancel_jaddref: Canceling complete jaddref"));
4333 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4334 		needsj = 1;
4335 	else
4336 		needsj = 0;
4337 	if (inodedep == NULL)
4338 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4339 		    0, &inodedep) == 0)
4340 			panic("cancel_jaddref: Lost inodedep");
4341 	/*
4342 	 * We must adjust the nlink of any reference operation that follows
4343 	 * us so that it is consistent with the in-memory reference.  This
4344 	 * ensures that inode nlink rollbacks always have the correct link.
4345 	 */
4346 	if (needsj == 0) {
4347 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4348 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4349 			if (inoref->if_state & GOINGAWAY)
4350 				break;
4351 			inoref->if_nlink--;
4352 		}
4353 	}
4354 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4355 	if (jaddref->ja_state & NEWBLOCK)
4356 		move_newblock_dep(jaddref, inodedep);
4357 	wake_worklist(&jaddref->ja_list);
4358 	jaddref->ja_mkdir = NULL;
4359 	if (jaddref->ja_state & INPROGRESS) {
4360 		jaddref->ja_state &= ~INPROGRESS;
4361 		WORKLIST_REMOVE(&jaddref->ja_list);
4362 		jwork_insert(wkhd, jsegdep);
4363 	} else {
4364 		free_jsegdep(jsegdep);
4365 		if (jaddref->ja_state & DEPCOMPLETE)
4366 			remove_from_journal(&jaddref->ja_list);
4367 	}
4368 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4369 	/*
4370 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4371 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4372 	 * no longer need this addref attached to the inoreflst and it
4373 	 * will incorrectly adjust nlink if we leave it.
4374 	 */
4375 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4376 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4377 		    if_deps);
4378 		jaddref->ja_state |= COMPLETE;
4379 		free_jaddref(jaddref);
4380 		return (needsj);
4381 	}
4382 	/*
4383 	 * Leave the head of the list for jsegdeps for fast merging.
4384 	 */
4385 	if (LIST_FIRST(wkhd) != NULL) {
4386 		jaddref->ja_state |= ONWORKLIST;
4387 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4388 	} else
4389 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4390 
4391 	return (needsj);
4392 }
4393 
4394 /*
4395  * Attempt to free a jaddref structure when some work completes.  This
4396  * should only succeed once the entry is written and all dependencies have
4397  * been notified.
4398  */
4399 static void
4400 free_jaddref(jaddref)
4401 	struct jaddref *jaddref;
4402 {
4403 
4404 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4405 		return;
4406 	if (jaddref->ja_ref.if_jsegdep)
4407 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4408 		    jaddref, jaddref->ja_state);
4409 	if (jaddref->ja_state & NEWBLOCK)
4410 		LIST_REMOVE(jaddref, ja_bmdeps);
4411 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4412 		panic("free_jaddref: Bad state %p(0x%X)",
4413 		    jaddref, jaddref->ja_state);
4414 	if (jaddref->ja_mkdir != NULL)
4415 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4416 	WORKITEM_FREE(jaddref, D_JADDREF);
4417 }
4418 
4419 /*
4420  * Free a jremref structure once it has been written or discarded.
4421  */
4422 static void
4423 free_jremref(jremref)
4424 	struct jremref *jremref;
4425 {
4426 
4427 	if (jremref->jr_ref.if_jsegdep)
4428 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4429 	if (jremref->jr_state & INPROGRESS)
4430 		panic("free_jremref: IO still pending");
4431 	WORKITEM_FREE(jremref, D_JREMREF);
4432 }
4433 
4434 /*
4435  * Free a jnewblk structure.
4436  */
4437 static void
4438 free_jnewblk(jnewblk)
4439 	struct jnewblk *jnewblk;
4440 {
4441 
4442 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4443 		return;
4444 	LIST_REMOVE(jnewblk, jn_deps);
4445 	if (jnewblk->jn_dep != NULL)
4446 		panic("free_jnewblk: Dependency still attached.");
4447 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4448 }
4449 
4450 /*
4451  * Cancel a jnewblk which has been been made redundant by frag extension.
4452  */
4453 static void
4454 cancel_jnewblk(jnewblk, wkhd)
4455 	struct jnewblk *jnewblk;
4456 	struct workhead *wkhd;
4457 {
4458 	struct jsegdep *jsegdep;
4459 
4460 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4461 	jsegdep = jnewblk->jn_jsegdep;
4462 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4463 		panic("cancel_jnewblk: Invalid state");
4464 	jnewblk->jn_jsegdep  = NULL;
4465 	jnewblk->jn_dep = NULL;
4466 	jnewblk->jn_state |= GOINGAWAY;
4467 	if (jnewblk->jn_state & INPROGRESS) {
4468 		jnewblk->jn_state &= ~INPROGRESS;
4469 		WORKLIST_REMOVE(&jnewblk->jn_list);
4470 		jwork_insert(wkhd, jsegdep);
4471 	} else {
4472 		free_jsegdep(jsegdep);
4473 		remove_from_journal(&jnewblk->jn_list);
4474 	}
4475 	wake_worklist(&jnewblk->jn_list);
4476 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4477 }
4478 
4479 static void
4480 free_jblkdep(jblkdep)
4481 	struct jblkdep *jblkdep;
4482 {
4483 
4484 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4485 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4486 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4487 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4488 	else
4489 		panic("free_jblkdep: Unexpected type %s",
4490 		    TYPENAME(jblkdep->jb_list.wk_type));
4491 }
4492 
4493 /*
4494  * Free a single jseg once it is no longer referenced in memory or on
4495  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4496  * to disappear.
4497  */
4498 static void
4499 free_jseg(jseg, jblocks)
4500 	struct jseg *jseg;
4501 	struct jblocks *jblocks;
4502 {
4503 	struct freework *freework;
4504 
4505 	/*
4506 	 * Free freework structures that were lingering to indicate freed
4507 	 * indirect blocks that forced journal write ordering on reallocate.
4508 	 */
4509 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4510 		indirblk_remove(freework);
4511 	if (jblocks->jb_oldestseg == jseg)
4512 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4513 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4514 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4515 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4516 	    ("free_jseg: Freed jseg has valid entries."));
4517 	WORKITEM_FREE(jseg, D_JSEG);
4518 }
4519 
4520 /*
4521  * Free all jsegs that meet the criteria for being reclaimed and update
4522  * oldestseg.
4523  */
4524 static void
4525 free_jsegs(jblocks)
4526 	struct jblocks *jblocks;
4527 {
4528 	struct jseg *jseg;
4529 
4530 	/*
4531 	 * Free only those jsegs which have none allocated before them to
4532 	 * preserve the journal space ordering.
4533 	 */
4534 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4535 		/*
4536 		 * Only reclaim space when nothing depends on this journal
4537 		 * set and another set has written that it is no longer
4538 		 * valid.
4539 		 */
4540 		if (jseg->js_refs != 0) {
4541 			jblocks->jb_oldestseg = jseg;
4542 			return;
4543 		}
4544 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4545 			break;
4546 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4547 			break;
4548 		/*
4549 		 * We can free jsegs that didn't write entries when
4550 		 * oldestwrseq == js_seq.
4551 		 */
4552 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4553 		    jseg->js_cnt != 0)
4554 			break;
4555 		free_jseg(jseg, jblocks);
4556 	}
4557 	/*
4558 	 * If we exited the loop above we still must discover the
4559 	 * oldest valid segment.
4560 	 */
4561 	if (jseg)
4562 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4563 		     jseg = TAILQ_NEXT(jseg, js_next))
4564 			if (jseg->js_refs != 0)
4565 				break;
4566 	jblocks->jb_oldestseg = jseg;
4567 	/*
4568 	 * The journal has no valid records but some jsegs may still be
4569 	 * waiting on oldestwrseq to advance.  We force a small record
4570 	 * out to permit these lingering records to be reclaimed.
4571 	 */
4572 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4573 		jblocks->jb_needseg = 1;
4574 }
4575 
4576 /*
4577  * Release one reference to a jseg and free it if the count reaches 0.  This
4578  * should eventually reclaim journal space as well.
4579  */
4580 static void
4581 rele_jseg(jseg)
4582 	struct jseg *jseg;
4583 {
4584 
4585 	KASSERT(jseg->js_refs > 0,
4586 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4587 	if (--jseg->js_refs != 0)
4588 		return;
4589 	free_jsegs(jseg->js_jblocks);
4590 }
4591 
4592 /*
4593  * Release a jsegdep and decrement the jseg count.
4594  */
4595 static void
4596 free_jsegdep(jsegdep)
4597 	struct jsegdep *jsegdep;
4598 {
4599 
4600 	if (jsegdep->jd_seg)
4601 		rele_jseg(jsegdep->jd_seg);
4602 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4603 }
4604 
4605 /*
4606  * Wait for a journal item to make it to disk.  Initiate journal processing
4607  * if required.
4608  */
4609 static int
4610 jwait(wk, waitfor)
4611 	struct worklist *wk;
4612 	int waitfor;
4613 {
4614 
4615 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4616 	/*
4617 	 * Blocking journal waits cause slow synchronous behavior.  Record
4618 	 * stats on the frequency of these blocking operations.
4619 	 */
4620 	if (waitfor == MNT_WAIT) {
4621 		stat_journal_wait++;
4622 		switch (wk->wk_type) {
4623 		case D_JREMREF:
4624 		case D_JMVREF:
4625 			stat_jwait_filepage++;
4626 			break;
4627 		case D_JTRUNC:
4628 		case D_JFREEBLK:
4629 			stat_jwait_freeblks++;
4630 			break;
4631 		case D_JNEWBLK:
4632 			stat_jwait_newblk++;
4633 			break;
4634 		case D_JADDREF:
4635 			stat_jwait_inode++;
4636 			break;
4637 		default:
4638 			break;
4639 		}
4640 	}
4641 	/*
4642 	 * If IO has not started we process the journal.  We can't mark the
4643 	 * worklist item as IOWAITING because we drop the lock while
4644 	 * processing the journal and the worklist entry may be freed after
4645 	 * this point.  The caller may call back in and re-issue the request.
4646 	 */
4647 	if ((wk->wk_state & INPROGRESS) == 0) {
4648 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4649 		if (waitfor != MNT_WAIT)
4650 			return (EBUSY);
4651 		return (0);
4652 	}
4653 	if (waitfor != MNT_WAIT)
4654 		return (EBUSY);
4655 	wait_worklist(wk, "jwait");
4656 	return (0);
4657 }
4658 
4659 /*
4660  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4661  * appropriate.  This is a convenience function to reduce duplicate code
4662  * for the setup and revert functions below.
4663  */
4664 static struct inodedep *
4665 inodedep_lookup_ip(ip)
4666 	struct inode *ip;
4667 {
4668 	struct inodedep *inodedep;
4669 
4670 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4671 	    ("inodedep_lookup_ip: bad delta"));
4672 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4673 	    &inodedep);
4674 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4675 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4676 
4677 	return (inodedep);
4678 }
4679 
4680 /*
4681  * Called prior to creating a new inode and linking it to a directory.  The
4682  * jaddref structure must already be allocated by softdep_setup_inomapdep
4683  * and it is discovered here so we can initialize the mode and update
4684  * nlinkdelta.
4685  */
4686 void
4687 softdep_setup_create(dp, ip)
4688 	struct inode *dp;
4689 	struct inode *ip;
4690 {
4691 	struct inodedep *inodedep;
4692 	struct jaddref *jaddref;
4693 	struct vnode *dvp;
4694 
4695 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4696 	    ("softdep_setup_create called on non-softdep filesystem"));
4697 	KASSERT(ip->i_nlink == 1,
4698 	    ("softdep_setup_create: Invalid link count."));
4699 	dvp = ITOV(dp);
4700 	ACQUIRE_LOCK(ITOUMP(dp));
4701 	inodedep = inodedep_lookup_ip(ip);
4702 	if (DOINGSUJ(dvp)) {
4703 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4704 		    inoreflst);
4705 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4706 		    ("softdep_setup_create: No addref structure present."));
4707 	}
4708 	softdep_prelink(dvp, NULL);
4709 	FREE_LOCK(ITOUMP(dp));
4710 }
4711 
4712 /*
4713  * Create a jaddref structure to track the addition of a DOTDOT link when
4714  * we are reparenting an inode as part of a rename.  This jaddref will be
4715  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4716  * non-journaling softdep.
4717  */
4718 void
4719 softdep_setup_dotdot_link(dp, ip)
4720 	struct inode *dp;
4721 	struct inode *ip;
4722 {
4723 	struct inodedep *inodedep;
4724 	struct jaddref *jaddref;
4725 	struct vnode *dvp;
4726 
4727 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4728 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4729 	dvp = ITOV(dp);
4730 	jaddref = NULL;
4731 	/*
4732 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4733 	 * is used as a normal link would be.
4734 	 */
4735 	if (DOINGSUJ(dvp))
4736 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4737 		    dp->i_effnlink - 1, dp->i_mode);
4738 	ACQUIRE_LOCK(ITOUMP(dp));
4739 	inodedep = inodedep_lookup_ip(dp);
4740 	if (jaddref)
4741 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4742 		    if_deps);
4743 	softdep_prelink(dvp, ITOV(ip));
4744 	FREE_LOCK(ITOUMP(dp));
4745 }
4746 
4747 /*
4748  * Create a jaddref structure to track a new link to an inode.  The directory
4749  * offset is not known until softdep_setup_directory_add or
4750  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4751  * softdep.
4752  */
4753 void
4754 softdep_setup_link(dp, ip)
4755 	struct inode *dp;
4756 	struct inode *ip;
4757 {
4758 	struct inodedep *inodedep;
4759 	struct jaddref *jaddref;
4760 	struct vnode *dvp;
4761 
4762 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4763 	    ("softdep_setup_link called on non-softdep filesystem"));
4764 	dvp = ITOV(dp);
4765 	jaddref = NULL;
4766 	if (DOINGSUJ(dvp))
4767 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4768 		    ip->i_mode);
4769 	ACQUIRE_LOCK(ITOUMP(dp));
4770 	inodedep = inodedep_lookup_ip(ip);
4771 	if (jaddref)
4772 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4773 		    if_deps);
4774 	softdep_prelink(dvp, ITOV(ip));
4775 	FREE_LOCK(ITOUMP(dp));
4776 }
4777 
4778 /*
4779  * Called to create the jaddref structures to track . and .. references as
4780  * well as lookup and further initialize the incomplete jaddref created
4781  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4782  * nlinkdelta for non-journaling softdep.
4783  */
4784 void
4785 softdep_setup_mkdir(dp, ip)
4786 	struct inode *dp;
4787 	struct inode *ip;
4788 {
4789 	struct inodedep *inodedep;
4790 	struct jaddref *dotdotaddref;
4791 	struct jaddref *dotaddref;
4792 	struct jaddref *jaddref;
4793 	struct vnode *dvp;
4794 
4795 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4796 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
4797 	dvp = ITOV(dp);
4798 	dotaddref = dotdotaddref = NULL;
4799 	if (DOINGSUJ(dvp)) {
4800 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4801 		    ip->i_mode);
4802 		dotaddref->ja_state |= MKDIR_BODY;
4803 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4804 		    dp->i_effnlink - 1, dp->i_mode);
4805 		dotdotaddref->ja_state |= MKDIR_PARENT;
4806 	}
4807 	ACQUIRE_LOCK(ITOUMP(dp));
4808 	inodedep = inodedep_lookup_ip(ip);
4809 	if (DOINGSUJ(dvp)) {
4810 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4811 		    inoreflst);
4812 		KASSERT(jaddref != NULL,
4813 		    ("softdep_setup_mkdir: No addref structure present."));
4814 		KASSERT(jaddref->ja_parent == dp->i_number,
4815 		    ("softdep_setup_mkdir: bad parent %ju",
4816 		    (uintmax_t)jaddref->ja_parent));
4817 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4818 		    if_deps);
4819 	}
4820 	inodedep = inodedep_lookup_ip(dp);
4821 	if (DOINGSUJ(dvp))
4822 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4823 		    &dotdotaddref->ja_ref, if_deps);
4824 	softdep_prelink(ITOV(dp), NULL);
4825 	FREE_LOCK(ITOUMP(dp));
4826 }
4827 
4828 /*
4829  * Called to track nlinkdelta of the inode and parent directories prior to
4830  * unlinking a directory.
4831  */
4832 void
4833 softdep_setup_rmdir(dp, ip)
4834 	struct inode *dp;
4835 	struct inode *ip;
4836 {
4837 	struct vnode *dvp;
4838 
4839 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4840 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4841 	dvp = ITOV(dp);
4842 	ACQUIRE_LOCK(ITOUMP(dp));
4843 	(void) inodedep_lookup_ip(ip);
4844 	(void) inodedep_lookup_ip(dp);
4845 	softdep_prelink(dvp, ITOV(ip));
4846 	FREE_LOCK(ITOUMP(dp));
4847 }
4848 
4849 /*
4850  * Called to track nlinkdelta of the inode and parent directories prior to
4851  * unlink.
4852  */
4853 void
4854 softdep_setup_unlink(dp, ip)
4855 	struct inode *dp;
4856 	struct inode *ip;
4857 {
4858 	struct vnode *dvp;
4859 
4860 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4861 	    ("softdep_setup_unlink called on non-softdep filesystem"));
4862 	dvp = ITOV(dp);
4863 	ACQUIRE_LOCK(ITOUMP(dp));
4864 	(void) inodedep_lookup_ip(ip);
4865 	(void) inodedep_lookup_ip(dp);
4866 	softdep_prelink(dvp, ITOV(ip));
4867 	FREE_LOCK(ITOUMP(dp));
4868 }
4869 
4870 /*
4871  * Called to release the journal structures created by a failed non-directory
4872  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4873  */
4874 void
4875 softdep_revert_create(dp, ip)
4876 	struct inode *dp;
4877 	struct inode *ip;
4878 {
4879 	struct inodedep *inodedep;
4880 	struct jaddref *jaddref;
4881 	struct vnode *dvp;
4882 
4883 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4884 	    ("softdep_revert_create called on non-softdep filesystem"));
4885 	dvp = ITOV(dp);
4886 	ACQUIRE_LOCK(ITOUMP(dp));
4887 	inodedep = inodedep_lookup_ip(ip);
4888 	if (DOINGSUJ(dvp)) {
4889 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4890 		    inoreflst);
4891 		KASSERT(jaddref->ja_parent == dp->i_number,
4892 		    ("softdep_revert_create: addref parent mismatch"));
4893 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4894 	}
4895 	FREE_LOCK(ITOUMP(dp));
4896 }
4897 
4898 /*
4899  * Called to release the journal structures created by a failed link
4900  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4901  */
4902 void
4903 softdep_revert_link(dp, ip)
4904 	struct inode *dp;
4905 	struct inode *ip;
4906 {
4907 	struct inodedep *inodedep;
4908 	struct jaddref *jaddref;
4909 	struct vnode *dvp;
4910 
4911 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4912 	    ("softdep_revert_link called on non-softdep filesystem"));
4913 	dvp = ITOV(dp);
4914 	ACQUIRE_LOCK(ITOUMP(dp));
4915 	inodedep = inodedep_lookup_ip(ip);
4916 	if (DOINGSUJ(dvp)) {
4917 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4918 		    inoreflst);
4919 		KASSERT(jaddref->ja_parent == dp->i_number,
4920 		    ("softdep_revert_link: addref parent mismatch"));
4921 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4922 	}
4923 	FREE_LOCK(ITOUMP(dp));
4924 }
4925 
4926 /*
4927  * Called to release the journal structures created by a failed mkdir
4928  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4929  */
4930 void
4931 softdep_revert_mkdir(dp, ip)
4932 	struct inode *dp;
4933 	struct inode *ip;
4934 {
4935 	struct inodedep *inodedep;
4936 	struct jaddref *jaddref;
4937 	struct jaddref *dotaddref;
4938 	struct vnode *dvp;
4939 
4940 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4941 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4942 	dvp = ITOV(dp);
4943 
4944 	ACQUIRE_LOCK(ITOUMP(dp));
4945 	inodedep = inodedep_lookup_ip(dp);
4946 	if (DOINGSUJ(dvp)) {
4947 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4948 		    inoreflst);
4949 		KASSERT(jaddref->ja_parent == ip->i_number,
4950 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4951 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4952 	}
4953 	inodedep = inodedep_lookup_ip(ip);
4954 	if (DOINGSUJ(dvp)) {
4955 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4956 		    inoreflst);
4957 		KASSERT(jaddref->ja_parent == dp->i_number,
4958 		    ("softdep_revert_mkdir: addref parent mismatch"));
4959 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4960 		    inoreflst, if_deps);
4961 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4962 		KASSERT(dotaddref->ja_parent == ip->i_number,
4963 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4964 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4965 	}
4966 	FREE_LOCK(ITOUMP(dp));
4967 }
4968 
4969 /*
4970  * Called to correct nlinkdelta after a failed rmdir.
4971  */
4972 void
4973 softdep_revert_rmdir(dp, ip)
4974 	struct inode *dp;
4975 	struct inode *ip;
4976 {
4977 
4978 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4979 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
4980 	ACQUIRE_LOCK(ITOUMP(dp));
4981 	(void) inodedep_lookup_ip(ip);
4982 	(void) inodedep_lookup_ip(dp);
4983 	FREE_LOCK(ITOUMP(dp));
4984 }
4985 
4986 /*
4987  * Protecting the freemaps (or bitmaps).
4988  *
4989  * To eliminate the need to execute fsck before mounting a filesystem
4990  * after a power failure, one must (conservatively) guarantee that the
4991  * on-disk copy of the bitmaps never indicate that a live inode or block is
4992  * free.  So, when a block or inode is allocated, the bitmap should be
4993  * updated (on disk) before any new pointers.  When a block or inode is
4994  * freed, the bitmap should not be updated until all pointers have been
4995  * reset.  The latter dependency is handled by the delayed de-allocation
4996  * approach described below for block and inode de-allocation.  The former
4997  * dependency is handled by calling the following procedure when a block or
4998  * inode is allocated. When an inode is allocated an "inodedep" is created
4999  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5000  * Each "inodedep" is also inserted into the hash indexing structure so
5001  * that any additional link additions can be made dependent on the inode
5002  * allocation.
5003  *
5004  * The ufs filesystem maintains a number of free block counts (e.g., per
5005  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5006  * in addition to the bitmaps.  These counts are used to improve efficiency
5007  * during allocation and therefore must be consistent with the bitmaps.
5008  * There is no convenient way to guarantee post-crash consistency of these
5009  * counts with simple update ordering, for two main reasons: (1) The counts
5010  * and bitmaps for a single cylinder group block are not in the same disk
5011  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5012  * be written and the other not.  (2) Some of the counts are located in the
5013  * superblock rather than the cylinder group block. So, we focus our soft
5014  * updates implementation on protecting the bitmaps. When mounting a
5015  * filesystem, we recompute the auxiliary counts from the bitmaps.
5016  */
5017 
5018 /*
5019  * Called just after updating the cylinder group block to allocate an inode.
5020  */
5021 void
5022 softdep_setup_inomapdep(bp, ip, newinum, mode)
5023 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5024 	struct inode *ip;	/* inode related to allocation */
5025 	ino_t newinum;		/* new inode number being allocated */
5026 	int mode;
5027 {
5028 	struct inodedep *inodedep;
5029 	struct bmsafemap *bmsafemap;
5030 	struct jaddref *jaddref;
5031 	struct mount *mp;
5032 	struct fs *fs;
5033 
5034 	mp = ITOVFS(ip);
5035 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5036 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5037 	fs = VFSTOUFS(mp)->um_fs;
5038 	jaddref = NULL;
5039 
5040 	/*
5041 	 * Allocate the journal reference add structure so that the bitmap
5042 	 * can be dependent on it.
5043 	 */
5044 	if (MOUNTEDSUJ(mp)) {
5045 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5046 		jaddref->ja_state |= NEWBLOCK;
5047 	}
5048 
5049 	/*
5050 	 * Create a dependency for the newly allocated inode.
5051 	 * Panic if it already exists as something is seriously wrong.
5052 	 * Otherwise add it to the dependency list for the buffer holding
5053 	 * the cylinder group map from which it was allocated.
5054 	 *
5055 	 * We have to preallocate a bmsafemap entry in case it is needed
5056 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5057 	 * have to finish initializing it before we can FREE_LOCK().
5058 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5059 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5060 	 * creating the inodedep as it can be freed during the time
5061 	 * that we FREE_LOCK() while allocating the inodedep. We must
5062 	 * call workitem_alloc() before entering the locked section as
5063 	 * it also acquires the lock and we must avoid trying doing so
5064 	 * recursively.
5065 	 */
5066 	bmsafemap = malloc(sizeof(struct bmsafemap),
5067 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5068 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5069 	ACQUIRE_LOCK(ITOUMP(ip));
5070 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5071 		panic("softdep_setup_inomapdep: dependency %p for new"
5072 		    "inode already exists", inodedep);
5073 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5074 	if (jaddref) {
5075 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5076 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5077 		    if_deps);
5078 	} else {
5079 		inodedep->id_state |= ONDEPLIST;
5080 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5081 	}
5082 	inodedep->id_bmsafemap = bmsafemap;
5083 	inodedep->id_state &= ~DEPCOMPLETE;
5084 	FREE_LOCK(ITOUMP(ip));
5085 }
5086 
5087 /*
5088  * Called just after updating the cylinder group block to
5089  * allocate block or fragment.
5090  */
5091 void
5092 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5093 	struct buf *bp;		/* buffer for cylgroup block with block map */
5094 	struct mount *mp;	/* filesystem doing allocation */
5095 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5096 	int frags;		/* Number of fragments. */
5097 	int oldfrags;		/* Previous number of fragments for extend. */
5098 {
5099 	struct newblk *newblk;
5100 	struct bmsafemap *bmsafemap;
5101 	struct jnewblk *jnewblk;
5102 	struct ufsmount *ump;
5103 	struct fs *fs;
5104 
5105 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5106 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5107 	ump = VFSTOUFS(mp);
5108 	fs = ump->um_fs;
5109 	jnewblk = NULL;
5110 	/*
5111 	 * Create a dependency for the newly allocated block.
5112 	 * Add it to the dependency list for the buffer holding
5113 	 * the cylinder group map from which it was allocated.
5114 	 */
5115 	if (MOUNTEDSUJ(mp)) {
5116 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5117 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5118 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5119 		jnewblk->jn_state = ATTACHED;
5120 		jnewblk->jn_blkno = newblkno;
5121 		jnewblk->jn_frags = frags;
5122 		jnewblk->jn_oldfrags = oldfrags;
5123 #ifdef INVARIANTS
5124 		{
5125 			struct cg *cgp;
5126 			uint8_t *blksfree;
5127 			long bno;
5128 			int i;
5129 
5130 			cgp = (struct cg *)bp->b_data;
5131 			blksfree = cg_blksfree(cgp);
5132 			bno = dtogd(fs, jnewblk->jn_blkno);
5133 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5134 			    i++) {
5135 				if (isset(blksfree, bno + i))
5136 					panic("softdep_setup_blkmapdep: "
5137 					    "free fragment %d from %d-%d "
5138 					    "state 0x%X dep %p", i,
5139 					    jnewblk->jn_oldfrags,
5140 					    jnewblk->jn_frags,
5141 					    jnewblk->jn_state,
5142 					    jnewblk->jn_dep);
5143 			}
5144 		}
5145 #endif
5146 	}
5147 
5148 	CTR3(KTR_SUJ,
5149 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5150 	    newblkno, frags, oldfrags);
5151 	ACQUIRE_LOCK(ump);
5152 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5153 		panic("softdep_setup_blkmapdep: found block");
5154 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5155 	    dtog(fs, newblkno), NULL);
5156 	if (jnewblk) {
5157 		jnewblk->jn_dep = (struct worklist *)newblk;
5158 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5159 	} else {
5160 		newblk->nb_state |= ONDEPLIST;
5161 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5162 	}
5163 	newblk->nb_bmsafemap = bmsafemap;
5164 	newblk->nb_jnewblk = jnewblk;
5165 	FREE_LOCK(ump);
5166 }
5167 
5168 #define	BMSAFEMAP_HASH(ump, cg) \
5169       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5170 
5171 static int
5172 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5173 	struct bmsafemap_hashhead *bmsafemaphd;
5174 	int cg;
5175 	struct bmsafemap **bmsafemapp;
5176 {
5177 	struct bmsafemap *bmsafemap;
5178 
5179 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5180 		if (bmsafemap->sm_cg == cg)
5181 			break;
5182 	if (bmsafemap) {
5183 		*bmsafemapp = bmsafemap;
5184 		return (1);
5185 	}
5186 	*bmsafemapp = NULL;
5187 
5188 	return (0);
5189 }
5190 
5191 /*
5192  * Find the bmsafemap associated with a cylinder group buffer.
5193  * If none exists, create one. The buffer must be locked when
5194  * this routine is called and this routine must be called with
5195  * the softdep lock held. To avoid giving up the lock while
5196  * allocating a new bmsafemap, a preallocated bmsafemap may be
5197  * provided. If it is provided but not needed, it is freed.
5198  */
5199 static struct bmsafemap *
5200 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5201 	struct mount *mp;
5202 	struct buf *bp;
5203 	int cg;
5204 	struct bmsafemap *newbmsafemap;
5205 {
5206 	struct bmsafemap_hashhead *bmsafemaphd;
5207 	struct bmsafemap *bmsafemap, *collision;
5208 	struct worklist *wk;
5209 	struct ufsmount *ump;
5210 
5211 	ump = VFSTOUFS(mp);
5212 	LOCK_OWNED(ump);
5213 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5214 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5215 		if (wk->wk_type == D_BMSAFEMAP) {
5216 			if (newbmsafemap)
5217 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5218 			return (WK_BMSAFEMAP(wk));
5219 		}
5220 	}
5221 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5222 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5223 		if (newbmsafemap)
5224 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5225 		return (bmsafemap);
5226 	}
5227 	if (newbmsafemap) {
5228 		bmsafemap = newbmsafemap;
5229 	} else {
5230 		FREE_LOCK(ump);
5231 		bmsafemap = malloc(sizeof(struct bmsafemap),
5232 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5233 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5234 		ACQUIRE_LOCK(ump);
5235 	}
5236 	bmsafemap->sm_buf = bp;
5237 	LIST_INIT(&bmsafemap->sm_inodedephd);
5238 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5239 	LIST_INIT(&bmsafemap->sm_newblkhd);
5240 	LIST_INIT(&bmsafemap->sm_newblkwr);
5241 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5242 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5243 	LIST_INIT(&bmsafemap->sm_freehd);
5244 	LIST_INIT(&bmsafemap->sm_freewr);
5245 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5246 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5247 		return (collision);
5248 	}
5249 	bmsafemap->sm_cg = cg;
5250 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5251 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5252 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5253 	return (bmsafemap);
5254 }
5255 
5256 /*
5257  * Direct block allocation dependencies.
5258  *
5259  * When a new block is allocated, the corresponding disk locations must be
5260  * initialized (with zeros or new data) before the on-disk inode points to
5261  * them.  Also, the freemap from which the block was allocated must be
5262  * updated (on disk) before the inode's pointer. These two dependencies are
5263  * independent of each other and are needed for all file blocks and indirect
5264  * blocks that are pointed to directly by the inode.  Just before the
5265  * "in-core" version of the inode is updated with a newly allocated block
5266  * number, a procedure (below) is called to setup allocation dependency
5267  * structures.  These structures are removed when the corresponding
5268  * dependencies are satisfied or when the block allocation becomes obsolete
5269  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5270  * fragment that gets upgraded).  All of these cases are handled in
5271  * procedures described later.
5272  *
5273  * When a file extension causes a fragment to be upgraded, either to a larger
5274  * fragment or to a full block, the on-disk location may change (if the
5275  * previous fragment could not simply be extended). In this case, the old
5276  * fragment must be de-allocated, but not until after the inode's pointer has
5277  * been updated. In most cases, this is handled by later procedures, which
5278  * will construct a "freefrag" structure to be added to the workitem queue
5279  * when the inode update is complete (or obsolete).  The main exception to
5280  * this is when an allocation occurs while a pending allocation dependency
5281  * (for the same block pointer) remains.  This case is handled in the main
5282  * allocation dependency setup procedure by immediately freeing the
5283  * unreferenced fragments.
5284  */
5285 void
5286 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5287 	struct inode *ip;	/* inode to which block is being added */
5288 	ufs_lbn_t off;		/* block pointer within inode */
5289 	ufs2_daddr_t newblkno;	/* disk block number being added */
5290 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5291 	long newsize;		/* size of new block */
5292 	long oldsize;		/* size of new block */
5293 	struct buf *bp;		/* bp for allocated block */
5294 {
5295 	struct allocdirect *adp, *oldadp;
5296 	struct allocdirectlst *adphead;
5297 	struct freefrag *freefrag;
5298 	struct inodedep *inodedep;
5299 	struct pagedep *pagedep;
5300 	struct jnewblk *jnewblk;
5301 	struct newblk *newblk;
5302 	struct mount *mp;
5303 	ufs_lbn_t lbn;
5304 
5305 	lbn = bp->b_lblkno;
5306 	mp = ITOVFS(ip);
5307 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5308 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5309 	if (oldblkno && oldblkno != newblkno)
5310 		/*
5311 		 * The usual case is that a smaller fragment that
5312 		 * was just allocated has been replaced with a bigger
5313 		 * fragment or a full-size block. If it is marked as
5314 		 * B_DELWRI, the current contents have not been written
5315 		 * to disk. It is possible that the block was written
5316 		 * earlier, but very uncommon. If the block has never
5317 		 * been written, there is no need to send a BIO_DELETE
5318 		 * for it when it is freed. The gain from avoiding the
5319 		 * TRIMs for the common case of unwritten blocks far
5320 		 * exceeds the cost of the write amplification for the
5321 		 * uncommon case of failing to send a TRIM for a block
5322 		 * that had been written.
5323 		 */
5324 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5325 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5326 	else
5327 		freefrag = NULL;
5328 
5329 	CTR6(KTR_SUJ,
5330 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5331 	    "off %jd newsize %ld oldsize %d",
5332 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5333 	ACQUIRE_LOCK(ITOUMP(ip));
5334 	if (off >= UFS_NDADDR) {
5335 		if (lbn > 0)
5336 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5337 			    lbn, off);
5338 		/* allocating an indirect block */
5339 		if (oldblkno != 0)
5340 			panic("softdep_setup_allocdirect: non-zero indir");
5341 	} else {
5342 		if (off != lbn)
5343 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5344 			    lbn, off);
5345 		/*
5346 		 * Allocating a direct block.
5347 		 *
5348 		 * If we are allocating a directory block, then we must
5349 		 * allocate an associated pagedep to track additions and
5350 		 * deletions.
5351 		 */
5352 		if ((ip->i_mode & IFMT) == IFDIR)
5353 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5354 			    &pagedep);
5355 	}
5356 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5357 		panic("softdep_setup_allocdirect: lost block");
5358 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5359 	    ("softdep_setup_allocdirect: newblk already initialized"));
5360 	/*
5361 	 * Convert the newblk to an allocdirect.
5362 	 */
5363 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5364 	adp = (struct allocdirect *)newblk;
5365 	newblk->nb_freefrag = freefrag;
5366 	adp->ad_offset = off;
5367 	adp->ad_oldblkno = oldblkno;
5368 	adp->ad_newsize = newsize;
5369 	adp->ad_oldsize = oldsize;
5370 
5371 	/*
5372 	 * Finish initializing the journal.
5373 	 */
5374 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5375 		jnewblk->jn_ino = ip->i_number;
5376 		jnewblk->jn_lbn = lbn;
5377 		add_to_journal(&jnewblk->jn_list);
5378 	}
5379 	if (freefrag && freefrag->ff_jdep != NULL &&
5380 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5381 		add_to_journal(freefrag->ff_jdep);
5382 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5383 	adp->ad_inodedep = inodedep;
5384 
5385 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5386 	/*
5387 	 * The list of allocdirects must be kept in sorted and ascending
5388 	 * order so that the rollback routines can quickly determine the
5389 	 * first uncommitted block (the size of the file stored on disk
5390 	 * ends at the end of the lowest committed fragment, or if there
5391 	 * are no fragments, at the end of the highest committed block).
5392 	 * Since files generally grow, the typical case is that the new
5393 	 * block is to be added at the end of the list. We speed this
5394 	 * special case by checking against the last allocdirect in the
5395 	 * list before laboriously traversing the list looking for the
5396 	 * insertion point.
5397 	 */
5398 	adphead = &inodedep->id_newinoupdt;
5399 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5400 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5401 		/* insert at end of list */
5402 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5403 		if (oldadp != NULL && oldadp->ad_offset == off)
5404 			allocdirect_merge(adphead, adp, oldadp);
5405 		FREE_LOCK(ITOUMP(ip));
5406 		return;
5407 	}
5408 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5409 		if (oldadp->ad_offset >= off)
5410 			break;
5411 	}
5412 	if (oldadp == NULL)
5413 		panic("softdep_setup_allocdirect: lost entry");
5414 	/* insert in middle of list */
5415 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5416 	if (oldadp->ad_offset == off)
5417 		allocdirect_merge(adphead, adp, oldadp);
5418 
5419 	FREE_LOCK(ITOUMP(ip));
5420 }
5421 
5422 /*
5423  * Merge a newer and older journal record to be stored either in a
5424  * newblock or freefrag.  This handles aggregating journal records for
5425  * fragment allocation into a second record as well as replacing a
5426  * journal free with an aborted journal allocation.  A segment for the
5427  * oldest record will be placed on wkhd if it has been written.  If not
5428  * the segment for the newer record will suffice.
5429  */
5430 static struct worklist *
5431 jnewblk_merge(new, old, wkhd)
5432 	struct worklist *new;
5433 	struct worklist *old;
5434 	struct workhead *wkhd;
5435 {
5436 	struct jnewblk *njnewblk;
5437 	struct jnewblk *jnewblk;
5438 
5439 	/* Handle NULLs to simplify callers. */
5440 	if (new == NULL)
5441 		return (old);
5442 	if (old == NULL)
5443 		return (new);
5444 	/* Replace a jfreefrag with a jnewblk. */
5445 	if (new->wk_type == D_JFREEFRAG) {
5446 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5447 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5448 			    old, new);
5449 		cancel_jfreefrag(WK_JFREEFRAG(new));
5450 		return (old);
5451 	}
5452 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5453 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5454 		    old->wk_type, new->wk_type);
5455 	/*
5456 	 * Handle merging of two jnewblk records that describe
5457 	 * different sets of fragments in the same block.
5458 	 */
5459 	jnewblk = WK_JNEWBLK(old);
5460 	njnewblk = WK_JNEWBLK(new);
5461 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5462 		panic("jnewblk_merge: Merging disparate blocks.");
5463 	/*
5464 	 * The record may be rolled back in the cg.
5465 	 */
5466 	if (jnewblk->jn_state & UNDONE) {
5467 		jnewblk->jn_state &= ~UNDONE;
5468 		njnewblk->jn_state |= UNDONE;
5469 		njnewblk->jn_state &= ~ATTACHED;
5470 	}
5471 	/*
5472 	 * We modify the newer addref and free the older so that if neither
5473 	 * has been written the most up-to-date copy will be on disk.  If
5474 	 * both have been written but rolled back we only temporarily need
5475 	 * one of them to fix the bits when the cg write completes.
5476 	 */
5477 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5478 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5479 	cancel_jnewblk(jnewblk, wkhd);
5480 	WORKLIST_REMOVE(&jnewblk->jn_list);
5481 	free_jnewblk(jnewblk);
5482 	return (new);
5483 }
5484 
5485 /*
5486  * Replace an old allocdirect dependency with a newer one.
5487  */
5488 static void
5489 allocdirect_merge(adphead, newadp, oldadp)
5490 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5491 	struct allocdirect *newadp;	/* allocdirect being added */
5492 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5493 {
5494 	struct worklist *wk;
5495 	struct freefrag *freefrag;
5496 
5497 	freefrag = NULL;
5498 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5499 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5500 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5501 	    newadp->ad_offset >= UFS_NDADDR)
5502 		panic("%s %jd != new %jd || old size %ld != new %ld",
5503 		    "allocdirect_merge: old blkno",
5504 		    (intmax_t)newadp->ad_oldblkno,
5505 		    (intmax_t)oldadp->ad_newblkno,
5506 		    newadp->ad_oldsize, oldadp->ad_newsize);
5507 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5508 	newadp->ad_oldsize = oldadp->ad_oldsize;
5509 	/*
5510 	 * If the old dependency had a fragment to free or had never
5511 	 * previously had a block allocated, then the new dependency
5512 	 * can immediately post its freefrag and adopt the old freefrag.
5513 	 * This action is done by swapping the freefrag dependencies.
5514 	 * The new dependency gains the old one's freefrag, and the
5515 	 * old one gets the new one and then immediately puts it on
5516 	 * the worklist when it is freed by free_newblk. It is
5517 	 * not possible to do this swap when the old dependency had a
5518 	 * non-zero size but no previous fragment to free. This condition
5519 	 * arises when the new block is an extension of the old block.
5520 	 * Here, the first part of the fragment allocated to the new
5521 	 * dependency is part of the block currently claimed on disk by
5522 	 * the old dependency, so cannot legitimately be freed until the
5523 	 * conditions for the new dependency are fulfilled.
5524 	 */
5525 	freefrag = newadp->ad_freefrag;
5526 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5527 		newadp->ad_freefrag = oldadp->ad_freefrag;
5528 		oldadp->ad_freefrag = freefrag;
5529 	}
5530 	/*
5531 	 * If we are tracking a new directory-block allocation,
5532 	 * move it from the old allocdirect to the new allocdirect.
5533 	 */
5534 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5535 		WORKLIST_REMOVE(wk);
5536 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5537 			panic("allocdirect_merge: extra newdirblk");
5538 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5539 	}
5540 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5541 	/*
5542 	 * We need to move any journal dependencies over to the freefrag
5543 	 * that releases this block if it exists.  Otherwise we are
5544 	 * extending an existing block and we'll wait until that is
5545 	 * complete to release the journal space and extend the
5546 	 * new journal to cover this old space as well.
5547 	 */
5548 	if (freefrag == NULL) {
5549 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5550 			panic("allocdirect_merge: %jd != %jd",
5551 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5552 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5553 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5554 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5555 		    &newadp->ad_block.nb_jwork);
5556 		oldadp->ad_block.nb_jnewblk = NULL;
5557 		cancel_newblk(&oldadp->ad_block, NULL,
5558 		    &newadp->ad_block.nb_jwork);
5559 	} else {
5560 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5561 		    &freefrag->ff_list, &freefrag->ff_jwork);
5562 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5563 		    &freefrag->ff_jwork);
5564 	}
5565 	free_newblk(&oldadp->ad_block);
5566 }
5567 
5568 /*
5569  * Allocate a jfreefrag structure to journal a single block free.
5570  */
5571 static struct jfreefrag *
5572 newjfreefrag(freefrag, ip, blkno, size, lbn)
5573 	struct freefrag *freefrag;
5574 	struct inode *ip;
5575 	ufs2_daddr_t blkno;
5576 	long size;
5577 	ufs_lbn_t lbn;
5578 {
5579 	struct jfreefrag *jfreefrag;
5580 	struct fs *fs;
5581 
5582 	fs = ITOFS(ip);
5583 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5584 	    M_SOFTDEP_FLAGS);
5585 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5586 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5587 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5588 	jfreefrag->fr_ino = ip->i_number;
5589 	jfreefrag->fr_lbn = lbn;
5590 	jfreefrag->fr_blkno = blkno;
5591 	jfreefrag->fr_frags = numfrags(fs, size);
5592 	jfreefrag->fr_freefrag = freefrag;
5593 
5594 	return (jfreefrag);
5595 }
5596 
5597 /*
5598  * Allocate a new freefrag structure.
5599  */
5600 static struct freefrag *
5601 newfreefrag(ip, blkno, size, lbn, key)
5602 	struct inode *ip;
5603 	ufs2_daddr_t blkno;
5604 	long size;
5605 	ufs_lbn_t lbn;
5606 	u_long key;
5607 {
5608 	struct freefrag *freefrag;
5609 	struct ufsmount *ump;
5610 	struct fs *fs;
5611 
5612 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5613 	    ip->i_number, blkno, size, lbn);
5614 	ump = ITOUMP(ip);
5615 	fs = ump->um_fs;
5616 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5617 		panic("newfreefrag: frag size");
5618 	freefrag = malloc(sizeof(struct freefrag),
5619 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5620 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5621 	freefrag->ff_state = ATTACHED;
5622 	LIST_INIT(&freefrag->ff_jwork);
5623 	freefrag->ff_inum = ip->i_number;
5624 	freefrag->ff_vtype = ITOV(ip)->v_type;
5625 	freefrag->ff_blkno = blkno;
5626 	freefrag->ff_fragsize = size;
5627 	freefrag->ff_key = key;
5628 
5629 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5630 		freefrag->ff_jdep = (struct worklist *)
5631 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5632 	} else {
5633 		freefrag->ff_state |= DEPCOMPLETE;
5634 		freefrag->ff_jdep = NULL;
5635 	}
5636 
5637 	return (freefrag);
5638 }
5639 
5640 /*
5641  * This workitem de-allocates fragments that were replaced during
5642  * file block allocation.
5643  */
5644 static void
5645 handle_workitem_freefrag(freefrag)
5646 	struct freefrag *freefrag;
5647 {
5648 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5649 	struct workhead wkhd;
5650 
5651 	CTR3(KTR_SUJ,
5652 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5653 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5654 	/*
5655 	 * It would be illegal to add new completion items to the
5656 	 * freefrag after it was schedule to be done so it must be
5657 	 * safe to modify the list head here.
5658 	 */
5659 	LIST_INIT(&wkhd);
5660 	ACQUIRE_LOCK(ump);
5661 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5662 	/*
5663 	 * If the journal has not been written we must cancel it here.
5664 	 */
5665 	if (freefrag->ff_jdep) {
5666 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5667 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5668 			    freefrag->ff_jdep->wk_type);
5669 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5670 	}
5671 	FREE_LOCK(ump);
5672 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5673 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5674 	   &wkhd, freefrag->ff_key);
5675 	ACQUIRE_LOCK(ump);
5676 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5677 	FREE_LOCK(ump);
5678 }
5679 
5680 /*
5681  * Set up a dependency structure for an external attributes data block.
5682  * This routine follows much of the structure of softdep_setup_allocdirect.
5683  * See the description of softdep_setup_allocdirect above for details.
5684  */
5685 void
5686 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5687 	struct inode *ip;
5688 	ufs_lbn_t off;
5689 	ufs2_daddr_t newblkno;
5690 	ufs2_daddr_t oldblkno;
5691 	long newsize;
5692 	long oldsize;
5693 	struct buf *bp;
5694 {
5695 	struct allocdirect *adp, *oldadp;
5696 	struct allocdirectlst *adphead;
5697 	struct freefrag *freefrag;
5698 	struct inodedep *inodedep;
5699 	struct jnewblk *jnewblk;
5700 	struct newblk *newblk;
5701 	struct mount *mp;
5702 	struct ufsmount *ump;
5703 	ufs_lbn_t lbn;
5704 
5705 	mp = ITOVFS(ip);
5706 	ump = VFSTOUFS(mp);
5707 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5708 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5709 	KASSERT(off < UFS_NXADDR,
5710 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5711 
5712 	lbn = bp->b_lblkno;
5713 	if (oldblkno && oldblkno != newblkno)
5714 		/*
5715 		 * The usual case is that a smaller fragment that
5716 		 * was just allocated has been replaced with a bigger
5717 		 * fragment or a full-size block. If it is marked as
5718 		 * B_DELWRI, the current contents have not been written
5719 		 * to disk. It is possible that the block was written
5720 		 * earlier, but very uncommon. If the block has never
5721 		 * been written, there is no need to send a BIO_DELETE
5722 		 * for it when it is freed. The gain from avoiding the
5723 		 * TRIMs for the common case of unwritten blocks far
5724 		 * exceeds the cost of the write amplification for the
5725 		 * uncommon case of failing to send a TRIM for a block
5726 		 * that had been written.
5727 		 */
5728 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5729 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5730 	else
5731 		freefrag = NULL;
5732 
5733 	ACQUIRE_LOCK(ump);
5734 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5735 		panic("softdep_setup_allocext: lost block");
5736 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5737 	    ("softdep_setup_allocext: newblk already initialized"));
5738 	/*
5739 	 * Convert the newblk to an allocdirect.
5740 	 */
5741 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5742 	adp = (struct allocdirect *)newblk;
5743 	newblk->nb_freefrag = freefrag;
5744 	adp->ad_offset = off;
5745 	adp->ad_oldblkno = oldblkno;
5746 	adp->ad_newsize = newsize;
5747 	adp->ad_oldsize = oldsize;
5748 	adp->ad_state |=  EXTDATA;
5749 
5750 	/*
5751 	 * Finish initializing the journal.
5752 	 */
5753 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5754 		jnewblk->jn_ino = ip->i_number;
5755 		jnewblk->jn_lbn = lbn;
5756 		add_to_journal(&jnewblk->jn_list);
5757 	}
5758 	if (freefrag && freefrag->ff_jdep != NULL &&
5759 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5760 		add_to_journal(freefrag->ff_jdep);
5761 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5762 	adp->ad_inodedep = inodedep;
5763 
5764 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5765 	/*
5766 	 * The list of allocdirects must be kept in sorted and ascending
5767 	 * order so that the rollback routines can quickly determine the
5768 	 * first uncommitted block (the size of the file stored on disk
5769 	 * ends at the end of the lowest committed fragment, or if there
5770 	 * are no fragments, at the end of the highest committed block).
5771 	 * Since files generally grow, the typical case is that the new
5772 	 * block is to be added at the end of the list. We speed this
5773 	 * special case by checking against the last allocdirect in the
5774 	 * list before laboriously traversing the list looking for the
5775 	 * insertion point.
5776 	 */
5777 	adphead = &inodedep->id_newextupdt;
5778 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5779 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5780 		/* insert at end of list */
5781 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5782 		if (oldadp != NULL && oldadp->ad_offset == off)
5783 			allocdirect_merge(adphead, adp, oldadp);
5784 		FREE_LOCK(ump);
5785 		return;
5786 	}
5787 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5788 		if (oldadp->ad_offset >= off)
5789 			break;
5790 	}
5791 	if (oldadp == NULL)
5792 		panic("softdep_setup_allocext: lost entry");
5793 	/* insert in middle of list */
5794 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5795 	if (oldadp->ad_offset == off)
5796 		allocdirect_merge(adphead, adp, oldadp);
5797 	FREE_LOCK(ump);
5798 }
5799 
5800 /*
5801  * Indirect block allocation dependencies.
5802  *
5803  * The same dependencies that exist for a direct block also exist when
5804  * a new block is allocated and pointed to by an entry in a block of
5805  * indirect pointers. The undo/redo states described above are also
5806  * used here. Because an indirect block contains many pointers that
5807  * may have dependencies, a second copy of the entire in-memory indirect
5808  * block is kept. The buffer cache copy is always completely up-to-date.
5809  * The second copy, which is used only as a source for disk writes,
5810  * contains only the safe pointers (i.e., those that have no remaining
5811  * update dependencies). The second copy is freed when all pointers
5812  * are safe. The cache is not allowed to replace indirect blocks with
5813  * pending update dependencies. If a buffer containing an indirect
5814  * block with dependencies is written, these routines will mark it
5815  * dirty again. It can only be successfully written once all the
5816  * dependencies are removed. The ffs_fsync routine in conjunction with
5817  * softdep_sync_metadata work together to get all the dependencies
5818  * removed so that a file can be successfully written to disk. Three
5819  * procedures are used when setting up indirect block pointer
5820  * dependencies. The division is necessary because of the organization
5821  * of the "balloc" routine and because of the distinction between file
5822  * pages and file metadata blocks.
5823  */
5824 
5825 /*
5826  * Allocate a new allocindir structure.
5827  */
5828 static struct allocindir *
5829 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5830 	struct inode *ip;	/* inode for file being extended */
5831 	int ptrno;		/* offset of pointer in indirect block */
5832 	ufs2_daddr_t newblkno;	/* disk block number being added */
5833 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5834 	ufs_lbn_t lbn;
5835 {
5836 	struct newblk *newblk;
5837 	struct allocindir *aip;
5838 	struct freefrag *freefrag;
5839 	struct jnewblk *jnewblk;
5840 
5841 	if (oldblkno)
5842 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
5843 		    SINGLETON_KEY);
5844 	else
5845 		freefrag = NULL;
5846 	ACQUIRE_LOCK(ITOUMP(ip));
5847 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5848 		panic("new_allocindir: lost block");
5849 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5850 	    ("newallocindir: newblk already initialized"));
5851 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5852 	newblk->nb_freefrag = freefrag;
5853 	aip = (struct allocindir *)newblk;
5854 	aip->ai_offset = ptrno;
5855 	aip->ai_oldblkno = oldblkno;
5856 	aip->ai_lbn = lbn;
5857 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5858 		jnewblk->jn_ino = ip->i_number;
5859 		jnewblk->jn_lbn = lbn;
5860 		add_to_journal(&jnewblk->jn_list);
5861 	}
5862 	if (freefrag && freefrag->ff_jdep != NULL &&
5863 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5864 		add_to_journal(freefrag->ff_jdep);
5865 	return (aip);
5866 }
5867 
5868 /*
5869  * Called just before setting an indirect block pointer
5870  * to a newly allocated file page.
5871  */
5872 void
5873 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5874 	struct inode *ip;	/* inode for file being extended */
5875 	ufs_lbn_t lbn;		/* allocated block number within file */
5876 	struct buf *bp;		/* buffer with indirect blk referencing page */
5877 	int ptrno;		/* offset of pointer in indirect block */
5878 	ufs2_daddr_t newblkno;	/* disk block number being added */
5879 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5880 	struct buf *nbp;	/* buffer holding allocated page */
5881 {
5882 	struct inodedep *inodedep;
5883 	struct freefrag *freefrag;
5884 	struct allocindir *aip;
5885 	struct pagedep *pagedep;
5886 	struct mount *mp;
5887 	struct ufsmount *ump;
5888 
5889 	mp = ITOVFS(ip);
5890 	ump = VFSTOUFS(mp);
5891 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5892 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5893 	KASSERT(lbn == nbp->b_lblkno,
5894 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5895 	    lbn, bp->b_lblkno));
5896 	CTR4(KTR_SUJ,
5897 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5898 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5899 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5900 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5901 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5902 	/*
5903 	 * If we are allocating a directory page, then we must
5904 	 * allocate an associated pagedep to track additions and
5905 	 * deletions.
5906 	 */
5907 	if ((ip->i_mode & IFMT) == IFDIR)
5908 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5909 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5910 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5911 	FREE_LOCK(ump);
5912 	if (freefrag)
5913 		handle_workitem_freefrag(freefrag);
5914 }
5915 
5916 /*
5917  * Called just before setting an indirect block pointer to a
5918  * newly allocated indirect block.
5919  */
5920 void
5921 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5922 	struct buf *nbp;	/* newly allocated indirect block */
5923 	struct inode *ip;	/* inode for file being extended */
5924 	struct buf *bp;		/* indirect block referencing allocated block */
5925 	int ptrno;		/* offset of pointer in indirect block */
5926 	ufs2_daddr_t newblkno;	/* disk block number being added */
5927 {
5928 	struct inodedep *inodedep;
5929 	struct allocindir *aip;
5930 	struct ufsmount *ump;
5931 	ufs_lbn_t lbn;
5932 
5933 	ump = ITOUMP(ip);
5934 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5935 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5936 	CTR3(KTR_SUJ,
5937 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5938 	    ip->i_number, newblkno, ptrno);
5939 	lbn = nbp->b_lblkno;
5940 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5941 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5942 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5943 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5944 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5945 		panic("softdep_setup_allocindir_meta: Block already existed");
5946 	FREE_LOCK(ump);
5947 }
5948 
5949 static void
5950 indirdep_complete(indirdep)
5951 	struct indirdep *indirdep;
5952 {
5953 	struct allocindir *aip;
5954 
5955 	LIST_REMOVE(indirdep, ir_next);
5956 	indirdep->ir_state |= DEPCOMPLETE;
5957 
5958 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5959 		LIST_REMOVE(aip, ai_next);
5960 		free_newblk(&aip->ai_block);
5961 	}
5962 	/*
5963 	 * If this indirdep is not attached to a buf it was simply waiting
5964 	 * on completion to clear completehd.  free_indirdep() asserts
5965 	 * that nothing is dangling.
5966 	 */
5967 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5968 		free_indirdep(indirdep);
5969 }
5970 
5971 static struct indirdep *
5972 indirdep_lookup(mp, ip, bp)
5973 	struct mount *mp;
5974 	struct inode *ip;
5975 	struct buf *bp;
5976 {
5977 	struct indirdep *indirdep, *newindirdep;
5978 	struct newblk *newblk;
5979 	struct ufsmount *ump;
5980 	struct worklist *wk;
5981 	struct fs *fs;
5982 	ufs2_daddr_t blkno;
5983 
5984 	ump = VFSTOUFS(mp);
5985 	LOCK_OWNED(ump);
5986 	indirdep = NULL;
5987 	newindirdep = NULL;
5988 	fs = ump->um_fs;
5989 	for (;;) {
5990 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5991 			if (wk->wk_type != D_INDIRDEP)
5992 				continue;
5993 			indirdep = WK_INDIRDEP(wk);
5994 			break;
5995 		}
5996 		/* Found on the buffer worklist, no new structure to free. */
5997 		if (indirdep != NULL && newindirdep == NULL)
5998 			return (indirdep);
5999 		if (indirdep != NULL && newindirdep != NULL)
6000 			panic("indirdep_lookup: simultaneous create");
6001 		/* None found on the buffer and a new structure is ready. */
6002 		if (indirdep == NULL && newindirdep != NULL)
6003 			break;
6004 		/* None found and no new structure available. */
6005 		FREE_LOCK(ump);
6006 		newindirdep = malloc(sizeof(struct indirdep),
6007 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
6008 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6009 		newindirdep->ir_state = ATTACHED;
6010 		if (I_IS_UFS1(ip))
6011 			newindirdep->ir_state |= UFS1FMT;
6012 		TAILQ_INIT(&newindirdep->ir_trunc);
6013 		newindirdep->ir_saveddata = NULL;
6014 		LIST_INIT(&newindirdep->ir_deplisthd);
6015 		LIST_INIT(&newindirdep->ir_donehd);
6016 		LIST_INIT(&newindirdep->ir_writehd);
6017 		LIST_INIT(&newindirdep->ir_completehd);
6018 		if (bp->b_blkno == bp->b_lblkno) {
6019 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6020 			    NULL, NULL);
6021 			bp->b_blkno = blkno;
6022 		}
6023 		newindirdep->ir_freeblks = NULL;
6024 		newindirdep->ir_savebp =
6025 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6026 		newindirdep->ir_bp = bp;
6027 		BUF_KERNPROC(newindirdep->ir_savebp);
6028 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6029 		ACQUIRE_LOCK(ump);
6030 	}
6031 	indirdep = newindirdep;
6032 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6033 	/*
6034 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6035 	 * that we don't free dependencies until the pointers are valid.
6036 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6037 	 * than using the hash.
6038 	 */
6039 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6040 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6041 	else
6042 		indirdep->ir_state |= DEPCOMPLETE;
6043 	return (indirdep);
6044 }
6045 
6046 /*
6047  * Called to finish the allocation of the "aip" allocated
6048  * by one of the two routines above.
6049  */
6050 static struct freefrag *
6051 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6052 	struct buf *bp;		/* in-memory copy of the indirect block */
6053 	struct inode *ip;	/* inode for file being extended */
6054 	struct inodedep *inodedep; /* Inodedep for ip */
6055 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6056 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6057 {
6058 	struct fs *fs;
6059 	struct indirdep *indirdep;
6060 	struct allocindir *oldaip;
6061 	struct freefrag *freefrag;
6062 	struct mount *mp;
6063 	struct ufsmount *ump;
6064 
6065 	mp = ITOVFS(ip);
6066 	ump = VFSTOUFS(mp);
6067 	LOCK_OWNED(ump);
6068 	fs = ump->um_fs;
6069 	if (bp->b_lblkno >= 0)
6070 		panic("setup_allocindir_phase2: not indir blk");
6071 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6072 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6073 	indirdep = indirdep_lookup(mp, ip, bp);
6074 	KASSERT(indirdep->ir_savebp != NULL,
6075 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6076 	aip->ai_indirdep = indirdep;
6077 	/*
6078 	 * Check for an unwritten dependency for this indirect offset.  If
6079 	 * there is, merge the old dependency into the new one.  This happens
6080 	 * as a result of reallocblk only.
6081 	 */
6082 	freefrag = NULL;
6083 	if (aip->ai_oldblkno != 0) {
6084 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6085 			if (oldaip->ai_offset == aip->ai_offset) {
6086 				freefrag = allocindir_merge(aip, oldaip);
6087 				goto done;
6088 			}
6089 		}
6090 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6091 			if (oldaip->ai_offset == aip->ai_offset) {
6092 				freefrag = allocindir_merge(aip, oldaip);
6093 				goto done;
6094 			}
6095 		}
6096 	}
6097 done:
6098 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6099 	return (freefrag);
6100 }
6101 
6102 /*
6103  * Merge two allocindirs which refer to the same block.  Move newblock
6104  * dependencies and setup the freefrags appropriately.
6105  */
6106 static struct freefrag *
6107 allocindir_merge(aip, oldaip)
6108 	struct allocindir *aip;
6109 	struct allocindir *oldaip;
6110 {
6111 	struct freefrag *freefrag;
6112 	struct worklist *wk;
6113 
6114 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6115 		panic("allocindir_merge: blkno");
6116 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6117 	freefrag = aip->ai_freefrag;
6118 	aip->ai_freefrag = oldaip->ai_freefrag;
6119 	oldaip->ai_freefrag = NULL;
6120 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6121 	/*
6122 	 * If we are tracking a new directory-block allocation,
6123 	 * move it from the old allocindir to the new allocindir.
6124 	 */
6125 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6126 		WORKLIST_REMOVE(wk);
6127 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6128 			panic("allocindir_merge: extra newdirblk");
6129 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6130 	}
6131 	/*
6132 	 * We can skip journaling for this freefrag and just complete
6133 	 * any pending journal work for the allocindir that is being
6134 	 * removed after the freefrag completes.
6135 	 */
6136 	if (freefrag->ff_jdep)
6137 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6138 	LIST_REMOVE(oldaip, ai_next);
6139 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6140 	    &freefrag->ff_list, &freefrag->ff_jwork);
6141 	free_newblk(&oldaip->ai_block);
6142 
6143 	return (freefrag);
6144 }
6145 
6146 static inline void
6147 setup_freedirect(freeblks, ip, i, needj)
6148 	struct freeblks *freeblks;
6149 	struct inode *ip;
6150 	int i;
6151 	int needj;
6152 {
6153 	struct ufsmount *ump;
6154 	ufs2_daddr_t blkno;
6155 	int frags;
6156 
6157 	blkno = DIP(ip, i_db[i]);
6158 	if (blkno == 0)
6159 		return;
6160 	DIP_SET(ip, i_db[i], 0);
6161 	ump = ITOUMP(ip);
6162 	frags = sblksize(ump->um_fs, ip->i_size, i);
6163 	frags = numfrags(ump->um_fs, frags);
6164 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6165 }
6166 
6167 static inline void
6168 setup_freeext(freeblks, ip, i, needj)
6169 	struct freeblks *freeblks;
6170 	struct inode *ip;
6171 	int i;
6172 	int needj;
6173 {
6174 	struct ufsmount *ump;
6175 	ufs2_daddr_t blkno;
6176 	int frags;
6177 
6178 	blkno = ip->i_din2->di_extb[i];
6179 	if (blkno == 0)
6180 		return;
6181 	ip->i_din2->di_extb[i] = 0;
6182 	ump = ITOUMP(ip);
6183 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6184 	frags = numfrags(ump->um_fs, frags);
6185 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6186 }
6187 
6188 static inline void
6189 setup_freeindir(freeblks, ip, i, lbn, needj)
6190 	struct freeblks *freeblks;
6191 	struct inode *ip;
6192 	int i;
6193 	ufs_lbn_t lbn;
6194 	int needj;
6195 {
6196 	struct ufsmount *ump;
6197 	ufs2_daddr_t blkno;
6198 
6199 	blkno = DIP(ip, i_ib[i]);
6200 	if (blkno == 0)
6201 		return;
6202 	DIP_SET(ip, i_ib[i], 0);
6203 	ump = ITOUMP(ip);
6204 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6205 	    0, needj);
6206 }
6207 
6208 static inline struct freeblks *
6209 newfreeblks(mp, ip)
6210 	struct mount *mp;
6211 	struct inode *ip;
6212 {
6213 	struct freeblks *freeblks;
6214 
6215 	freeblks = malloc(sizeof(struct freeblks),
6216 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6217 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6218 	LIST_INIT(&freeblks->fb_jblkdephd);
6219 	LIST_INIT(&freeblks->fb_jwork);
6220 	freeblks->fb_ref = 0;
6221 	freeblks->fb_cgwait = 0;
6222 	freeblks->fb_state = ATTACHED;
6223 	freeblks->fb_uid = ip->i_uid;
6224 	freeblks->fb_inum = ip->i_number;
6225 	freeblks->fb_vtype = ITOV(ip)->v_type;
6226 	freeblks->fb_modrev = DIP(ip, i_modrev);
6227 	freeblks->fb_devvp = ITODEVVP(ip);
6228 	freeblks->fb_chkcnt = 0;
6229 	freeblks->fb_len = 0;
6230 
6231 	return (freeblks);
6232 }
6233 
6234 static void
6235 trunc_indirdep(indirdep, freeblks, bp, off)
6236 	struct indirdep *indirdep;
6237 	struct freeblks *freeblks;
6238 	struct buf *bp;
6239 	int off;
6240 {
6241 	struct allocindir *aip, *aipn;
6242 
6243 	/*
6244 	 * The first set of allocindirs won't be in savedbp.
6245 	 */
6246 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6247 		if (aip->ai_offset > off)
6248 			cancel_allocindir(aip, bp, freeblks, 1);
6249 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6250 		if (aip->ai_offset > off)
6251 			cancel_allocindir(aip, bp, freeblks, 1);
6252 	/*
6253 	 * These will exist in savedbp.
6254 	 */
6255 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6256 		if (aip->ai_offset > off)
6257 			cancel_allocindir(aip, NULL, freeblks, 0);
6258 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6259 		if (aip->ai_offset > off)
6260 			cancel_allocindir(aip, NULL, freeblks, 0);
6261 }
6262 
6263 /*
6264  * Follow the chain of indirects down to lastlbn creating a freework
6265  * structure for each.  This will be used to start indir_trunc() at
6266  * the right offset and create the journal records for the parrtial
6267  * truncation.  A second step will handle the truncated dependencies.
6268  */
6269 static int
6270 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6271 	struct freeblks *freeblks;
6272 	struct inode *ip;
6273 	ufs_lbn_t lbn;
6274 	ufs_lbn_t lastlbn;
6275 	ufs2_daddr_t blkno;
6276 {
6277 	struct indirdep *indirdep;
6278 	struct indirdep *indirn;
6279 	struct freework *freework;
6280 	struct newblk *newblk;
6281 	struct mount *mp;
6282 	struct ufsmount *ump;
6283 	struct buf *bp;
6284 	uint8_t *start;
6285 	uint8_t *end;
6286 	ufs_lbn_t lbnadd;
6287 	int level;
6288 	int error;
6289 	int off;
6290 
6291 
6292 	freework = NULL;
6293 	if (blkno == 0)
6294 		return (0);
6295 	mp = freeblks->fb_list.wk_mp;
6296 	ump = VFSTOUFS(mp);
6297 	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6298 	if ((bp->b_flags & B_CACHE) == 0) {
6299 		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6300 		bp->b_iocmd = BIO_READ;
6301 		bp->b_flags &= ~B_INVAL;
6302 		bp->b_ioflags &= ~BIO_ERROR;
6303 		vfs_busy_pages(bp, 0);
6304 		bp->b_iooffset = dbtob(bp->b_blkno);
6305 		bstrategy(bp);
6306 #ifdef RACCT
6307 		if (racct_enable) {
6308 			PROC_LOCK(curproc);
6309 			racct_add_buf(curproc, bp, 0);
6310 			PROC_UNLOCK(curproc);
6311 		}
6312 #endif /* RACCT */
6313 		curthread->td_ru.ru_inblock++;
6314 		error = bufwait(bp);
6315 		if (error) {
6316 			brelse(bp);
6317 			return (error);
6318 		}
6319 	}
6320 	level = lbn_level(lbn);
6321 	lbnadd = lbn_offset(ump->um_fs, level);
6322 	/*
6323 	 * Compute the offset of the last block we want to keep.  Store
6324 	 * in the freework the first block we want to completely free.
6325 	 */
6326 	off = (lastlbn - -(lbn + level)) / lbnadd;
6327 	if (off + 1 == NINDIR(ump->um_fs))
6328 		goto nowork;
6329 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6330 	/*
6331 	 * Link the freework into the indirdep.  This will prevent any new
6332 	 * allocations from proceeding until we are finished with the
6333 	 * truncate and the block is written.
6334 	 */
6335 	ACQUIRE_LOCK(ump);
6336 	indirdep = indirdep_lookup(mp, ip, bp);
6337 	if (indirdep->ir_freeblks)
6338 		panic("setup_trunc_indir: indirdep already truncated.");
6339 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6340 	freework->fw_indir = indirdep;
6341 	/*
6342 	 * Cancel any allocindirs that will not make it to disk.
6343 	 * We have to do this for all copies of the indirdep that
6344 	 * live on this newblk.
6345 	 */
6346 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6347 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6348 		    &newblk) == 0)
6349 			panic("setup_trunc_indir: lost block");
6350 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6351 			trunc_indirdep(indirn, freeblks, bp, off);
6352 	} else
6353 		trunc_indirdep(indirdep, freeblks, bp, off);
6354 	FREE_LOCK(ump);
6355 	/*
6356 	 * Creation is protected by the buf lock. The saveddata is only
6357 	 * needed if a full truncation follows a partial truncation but it
6358 	 * is difficult to allocate in that case so we fetch it anyway.
6359 	 */
6360 	if (indirdep->ir_saveddata == NULL)
6361 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6362 		    M_SOFTDEP_FLAGS);
6363 nowork:
6364 	/* Fetch the blkno of the child and the zero start offset. */
6365 	if (I_IS_UFS1(ip)) {
6366 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6367 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6368 	} else {
6369 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6370 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6371 	}
6372 	if (freework) {
6373 		/* Zero the truncated pointers. */
6374 		end = bp->b_data + bp->b_bcount;
6375 		bzero(start, end - start);
6376 		bdwrite(bp);
6377 	} else
6378 		bqrelse(bp);
6379 	if (level == 0)
6380 		return (0);
6381 	lbn++; /* adjust level */
6382 	lbn -= (off * lbnadd);
6383 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6384 }
6385 
6386 /*
6387  * Complete the partial truncation of an indirect block setup by
6388  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6389  * copy and writes them to disk before the freeblks is allowed to complete.
6390  */
6391 static void
6392 complete_trunc_indir(freework)
6393 	struct freework *freework;
6394 {
6395 	struct freework *fwn;
6396 	struct indirdep *indirdep;
6397 	struct ufsmount *ump;
6398 	struct buf *bp;
6399 	uintptr_t start;
6400 	int count;
6401 
6402 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6403 	LOCK_OWNED(ump);
6404 	indirdep = freework->fw_indir;
6405 	for (;;) {
6406 		bp = indirdep->ir_bp;
6407 		/* See if the block was discarded. */
6408 		if (bp == NULL)
6409 			break;
6410 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6411 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6412 			break;
6413 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6414 		    LOCK_PTR(ump)) == 0)
6415 			BUF_UNLOCK(bp);
6416 		ACQUIRE_LOCK(ump);
6417 	}
6418 	freework->fw_state |= DEPCOMPLETE;
6419 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6420 	/*
6421 	 * Zero the pointers in the saved copy.
6422 	 */
6423 	if (indirdep->ir_state & UFS1FMT)
6424 		start = sizeof(ufs1_daddr_t);
6425 	else
6426 		start = sizeof(ufs2_daddr_t);
6427 	start *= freework->fw_start;
6428 	count = indirdep->ir_savebp->b_bcount - start;
6429 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6430 	bzero((char *)start, count);
6431 	/*
6432 	 * We need to start the next truncation in the list if it has not
6433 	 * been started yet.
6434 	 */
6435 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6436 	if (fwn != NULL) {
6437 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6438 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6439 		if ((fwn->fw_state & ONWORKLIST) == 0)
6440 			freework_enqueue(fwn);
6441 	}
6442 	/*
6443 	 * If bp is NULL the block was fully truncated, restore
6444 	 * the saved block list otherwise free it if it is no
6445 	 * longer needed.
6446 	 */
6447 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6448 		if (bp == NULL)
6449 			bcopy(indirdep->ir_saveddata,
6450 			    indirdep->ir_savebp->b_data,
6451 			    indirdep->ir_savebp->b_bcount);
6452 		free(indirdep->ir_saveddata, M_INDIRDEP);
6453 		indirdep->ir_saveddata = NULL;
6454 	}
6455 	/*
6456 	 * When bp is NULL there is a full truncation pending.  We
6457 	 * must wait for this full truncation to be journaled before
6458 	 * we can release this freework because the disk pointers will
6459 	 * never be written as zero.
6460 	 */
6461 	if (bp == NULL)  {
6462 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6463 			handle_written_freework(freework);
6464 		else
6465 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6466 			   &freework->fw_list);
6467 	} else {
6468 		/* Complete when the real copy is written. */
6469 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6470 		BUF_UNLOCK(bp);
6471 	}
6472 }
6473 
6474 /*
6475  * Calculate the number of blocks we are going to release where datablocks
6476  * is the current total and length is the new file size.
6477  */
6478 static ufs2_daddr_t
6479 blkcount(fs, datablocks, length)
6480 	struct fs *fs;
6481 	ufs2_daddr_t datablocks;
6482 	off_t length;
6483 {
6484 	off_t totblks, numblks;
6485 
6486 	totblks = 0;
6487 	numblks = howmany(length, fs->fs_bsize);
6488 	if (numblks <= UFS_NDADDR) {
6489 		totblks = howmany(length, fs->fs_fsize);
6490 		goto out;
6491 	}
6492         totblks = blkstofrags(fs, numblks);
6493 	numblks -= UFS_NDADDR;
6494 	/*
6495 	 * Count all single, then double, then triple indirects required.
6496 	 * Subtracting one indirects worth of blocks for each pass
6497 	 * acknowledges one of each pointed to by the inode.
6498 	 */
6499 	for (;;) {
6500 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6501 		numblks -= NINDIR(fs);
6502 		if (numblks <= 0)
6503 			break;
6504 		numblks = howmany(numblks, NINDIR(fs));
6505 	}
6506 out:
6507 	totblks = fsbtodb(fs, totblks);
6508 	/*
6509 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6510 	 * references.  We will correct it later in handle_complete_freeblks()
6511 	 * when we know the real count.
6512 	 */
6513 	if (totblks > datablocks)
6514 		return (0);
6515 	return (datablocks - totblks);
6516 }
6517 
6518 /*
6519  * Handle freeblocks for journaled softupdate filesystems.
6520  *
6521  * Contrary to normal softupdates, we must preserve the block pointers in
6522  * indirects until their subordinates are free.  This is to avoid journaling
6523  * every block that is freed which may consume more space than the journal
6524  * itself.  The recovery program will see the free block journals at the
6525  * base of the truncated area and traverse them to reclaim space.  The
6526  * pointers in the inode may be cleared immediately after the journal
6527  * records are written because each direct and indirect pointer in the
6528  * inode is recorded in a journal.  This permits full truncation to proceed
6529  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6530  *
6531  * The algorithm is as follows:
6532  * 1) Traverse the in-memory state and create journal entries to release
6533  *    the relevant blocks and full indirect trees.
6534  * 2) Traverse the indirect block chain adding partial truncation freework
6535  *    records to indirects in the path to lastlbn.  The freework will
6536  *    prevent new allocation dependencies from being satisfied in this
6537  *    indirect until the truncation completes.
6538  * 3) Read and lock the inode block, performing an update with the new size
6539  *    and pointers.  This prevents truncated data from becoming valid on
6540  *    disk through step 4.
6541  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6542  *    eliminate journal work for those records that do not require it.
6543  * 5) Schedule the journal records to be written followed by the inode block.
6544  * 6) Allocate any necessary frags for the end of file.
6545  * 7) Zero any partially truncated blocks.
6546  *
6547  * From this truncation proceeds asynchronously using the freework and
6548  * indir_trunc machinery.  The file will not be extended again into a
6549  * partially truncated indirect block until all work is completed but
6550  * the normal dependency mechanism ensures that it is rolled back/forward
6551  * as appropriate.  Further truncation may occur without delay and is
6552  * serialized in indir_trunc().
6553  */
6554 void
6555 softdep_journal_freeblocks(ip, cred, length, flags)
6556 	struct inode *ip;	/* The inode whose length is to be reduced */
6557 	struct ucred *cred;
6558 	off_t length;		/* The new length for the file */
6559 	int flags;		/* IO_EXT and/or IO_NORMAL */
6560 {
6561 	struct freeblks *freeblks, *fbn;
6562 	struct worklist *wk, *wkn;
6563 	struct inodedep *inodedep;
6564 	struct jblkdep *jblkdep;
6565 	struct allocdirect *adp, *adpn;
6566 	struct ufsmount *ump;
6567 	struct fs *fs;
6568 	struct buf *bp;
6569 	struct vnode *vp;
6570 	struct mount *mp;
6571 	ufs2_daddr_t extblocks, datablocks;
6572 	ufs_lbn_t tmpval, lbn, lastlbn;
6573 	int frags, lastoff, iboff, allocblock, needj, error, i;
6574 
6575 	ump = ITOUMP(ip);
6576 	mp = UFSTOVFS(ump);
6577 	fs = ump->um_fs;
6578 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6579 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6580 	vp = ITOV(ip);
6581 	needj = 1;
6582 	iboff = -1;
6583 	allocblock = 0;
6584 	extblocks = 0;
6585 	datablocks = 0;
6586 	frags = 0;
6587 	freeblks = newfreeblks(mp, ip);
6588 	ACQUIRE_LOCK(ump);
6589 	/*
6590 	 * If we're truncating a removed file that will never be written
6591 	 * we don't need to journal the block frees.  The canceled journals
6592 	 * for the allocations will suffice.
6593 	 */
6594 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6595 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6596 	    length == 0)
6597 		needj = 0;
6598 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6599 	    ip->i_number, length, needj);
6600 	FREE_LOCK(ump);
6601 	/*
6602 	 * Calculate the lbn that we are truncating to.  This results in -1
6603 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6604 	 * to keep, not the first lbn we want to truncate.
6605 	 */
6606 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6607 	lastoff = blkoff(fs, length);
6608 	/*
6609 	 * Compute frags we are keeping in lastlbn.  0 means all.
6610 	 */
6611 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6612 		frags = fragroundup(fs, lastoff);
6613 		/* adp offset of last valid allocdirect. */
6614 		iboff = lastlbn;
6615 	} else if (lastlbn > 0)
6616 		iboff = UFS_NDADDR;
6617 	if (fs->fs_magic == FS_UFS2_MAGIC)
6618 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6619 	/*
6620 	 * Handle normal data blocks and indirects.  This section saves
6621 	 * values used after the inode update to complete frag and indirect
6622 	 * truncation.
6623 	 */
6624 	if ((flags & IO_NORMAL) != 0) {
6625 		/*
6626 		 * Handle truncation of whole direct and indirect blocks.
6627 		 */
6628 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6629 			setup_freedirect(freeblks, ip, i, needj);
6630 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6631 		    i < UFS_NIADDR;
6632 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6633 			/* Release a whole indirect tree. */
6634 			if (lbn > lastlbn) {
6635 				setup_freeindir(freeblks, ip, i, -lbn -i,
6636 				    needj);
6637 				continue;
6638 			}
6639 			iboff = i + UFS_NDADDR;
6640 			/*
6641 			 * Traverse partially truncated indirect tree.
6642 			 */
6643 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6644 				setup_trunc_indir(freeblks, ip, -lbn - i,
6645 				    lastlbn, DIP(ip, i_ib[i]));
6646 		}
6647 		/*
6648 		 * Handle partial truncation to a frag boundary.
6649 		 */
6650 		if (frags) {
6651 			ufs2_daddr_t blkno;
6652 			long oldfrags;
6653 
6654 			oldfrags = blksize(fs, ip, lastlbn);
6655 			blkno = DIP(ip, i_db[lastlbn]);
6656 			if (blkno && oldfrags != frags) {
6657 				oldfrags -= frags;
6658 				oldfrags = numfrags(fs, oldfrags);
6659 				blkno += numfrags(fs, frags);
6660 				newfreework(ump, freeblks, NULL, lastlbn,
6661 				    blkno, oldfrags, 0, needj);
6662 				if (needj)
6663 					adjust_newfreework(freeblks,
6664 					    numfrags(fs, frags));
6665 			} else if (blkno == 0)
6666 				allocblock = 1;
6667 		}
6668 		/*
6669 		 * Add a journal record for partial truncate if we are
6670 		 * handling indirect blocks.  Non-indirects need no extra
6671 		 * journaling.
6672 		 */
6673 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6674 			ip->i_flag |= IN_TRUNCATED;
6675 			newjtrunc(freeblks, length, 0);
6676 		}
6677 		ip->i_size = length;
6678 		DIP_SET(ip, i_size, ip->i_size);
6679 		datablocks = DIP(ip, i_blocks) - extblocks;
6680 		if (length != 0)
6681 			datablocks = blkcount(fs, datablocks, length);
6682 		freeblks->fb_len = length;
6683 	}
6684 	if ((flags & IO_EXT) != 0) {
6685 		for (i = 0; i < UFS_NXADDR; i++)
6686 			setup_freeext(freeblks, ip, i, needj);
6687 		ip->i_din2->di_extsize = 0;
6688 		datablocks += extblocks;
6689 	}
6690 #ifdef QUOTA
6691 	/* Reference the quotas in case the block count is wrong in the end. */
6692 	quotaref(vp, freeblks->fb_quota);
6693 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6694 #endif
6695 	freeblks->fb_chkcnt = -datablocks;
6696 	UFS_LOCK(ump);
6697 	fs->fs_pendingblocks += datablocks;
6698 	UFS_UNLOCK(ump);
6699 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6700 	/*
6701 	 * Handle truncation of incomplete alloc direct dependencies.  We
6702 	 * hold the inode block locked to prevent incomplete dependencies
6703 	 * from reaching the disk while we are eliminating those that
6704 	 * have been truncated.  This is a partially inlined ffs_update().
6705 	 */
6706 	ufs_itimes(vp);
6707 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6708 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6709 	    (int)fs->fs_bsize, cred, &bp);
6710 	if (error) {
6711 		softdep_error("softdep_journal_freeblocks", error);
6712 		return;
6713 	}
6714 	if (bp->b_bufsize == fs->fs_bsize)
6715 		bp->b_flags |= B_CLUSTEROK;
6716 	softdep_update_inodeblock(ip, bp, 0);
6717 	if (ump->um_fstype == UFS1) {
6718 		*((struct ufs1_dinode *)bp->b_data +
6719 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6720 	} else {
6721 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6722 		*((struct ufs2_dinode *)bp->b_data +
6723 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6724 	}
6725 	ACQUIRE_LOCK(ump);
6726 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6727 	if ((inodedep->id_state & IOSTARTED) != 0)
6728 		panic("softdep_setup_freeblocks: inode busy");
6729 	/*
6730 	 * Add the freeblks structure to the list of operations that
6731 	 * must await the zero'ed inode being written to disk. If we
6732 	 * still have a bitmap dependency (needj), then the inode
6733 	 * has never been written to disk, so we can process the
6734 	 * freeblks below once we have deleted the dependencies.
6735 	 */
6736 	if (needj)
6737 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6738 	else
6739 		freeblks->fb_state |= COMPLETE;
6740 	if ((flags & IO_NORMAL) != 0) {
6741 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6742 			if (adp->ad_offset > iboff)
6743 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6744 				    freeblks);
6745 			/*
6746 			 * Truncate the allocdirect.  We could eliminate
6747 			 * or modify journal records as well.
6748 			 */
6749 			else if (adp->ad_offset == iboff && frags)
6750 				adp->ad_newsize = frags;
6751 		}
6752 	}
6753 	if ((flags & IO_EXT) != 0)
6754 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6755 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6756 			    freeblks);
6757 	/*
6758 	 * Scan the bufwait list for newblock dependencies that will never
6759 	 * make it to disk.
6760 	 */
6761 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6762 		if (wk->wk_type != D_ALLOCDIRECT)
6763 			continue;
6764 		adp = WK_ALLOCDIRECT(wk);
6765 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6766 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6767 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6768 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6769 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6770 		}
6771 	}
6772 	/*
6773 	 * Add journal work.
6774 	 */
6775 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6776 		add_to_journal(&jblkdep->jb_list);
6777 	FREE_LOCK(ump);
6778 	bdwrite(bp);
6779 	/*
6780 	 * Truncate dependency structures beyond length.
6781 	 */
6782 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6783 	/*
6784 	 * This is only set when we need to allocate a fragment because
6785 	 * none existed at the end of a frag-sized file.  It handles only
6786 	 * allocating a new, zero filled block.
6787 	 */
6788 	if (allocblock) {
6789 		ip->i_size = length - lastoff;
6790 		DIP_SET(ip, i_size, ip->i_size);
6791 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6792 		if (error != 0) {
6793 			softdep_error("softdep_journal_freeblks", error);
6794 			return;
6795 		}
6796 		ip->i_size = length;
6797 		DIP_SET(ip, i_size, length);
6798 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6799 		allocbuf(bp, frags);
6800 		ffs_update(vp, 0);
6801 		bawrite(bp);
6802 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6803 		int size;
6804 
6805 		/*
6806 		 * Zero the end of a truncated frag or block.
6807 		 */
6808 		size = sblksize(fs, length, lastlbn);
6809 		error = bread(vp, lastlbn, size, cred, &bp);
6810 		if (error) {
6811 			softdep_error("softdep_journal_freeblks", error);
6812 			return;
6813 		}
6814 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6815 		bawrite(bp);
6816 
6817 	}
6818 	ACQUIRE_LOCK(ump);
6819 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6820 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6821 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6822 	/*
6823 	 * We zero earlier truncations so they don't erroneously
6824 	 * update i_blocks.
6825 	 */
6826 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6827 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6828 			fbn->fb_len = 0;
6829 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6830 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6831 		freeblks->fb_state |= INPROGRESS;
6832 	else
6833 		freeblks = NULL;
6834 	FREE_LOCK(ump);
6835 	if (freeblks)
6836 		handle_workitem_freeblocks(freeblks, 0);
6837 	trunc_pages(ip, length, extblocks, flags);
6838 
6839 }
6840 
6841 /*
6842  * Flush a JOP_SYNC to the journal.
6843  */
6844 void
6845 softdep_journal_fsync(ip)
6846 	struct inode *ip;
6847 {
6848 	struct jfsync *jfsync;
6849 	struct ufsmount *ump;
6850 
6851 	ump = ITOUMP(ip);
6852 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6853 	    ("softdep_journal_fsync called on non-softdep filesystem"));
6854 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6855 		return;
6856 	ip->i_flag &= ~IN_TRUNCATED;
6857 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6858 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6859 	jfsync->jfs_size = ip->i_size;
6860 	jfsync->jfs_ino = ip->i_number;
6861 	ACQUIRE_LOCK(ump);
6862 	add_to_journal(&jfsync->jfs_list);
6863 	jwait(&jfsync->jfs_list, MNT_WAIT);
6864 	FREE_LOCK(ump);
6865 }
6866 
6867 /*
6868  * Block de-allocation dependencies.
6869  *
6870  * When blocks are de-allocated, the on-disk pointers must be nullified before
6871  * the blocks are made available for use by other files.  (The true
6872  * requirement is that old pointers must be nullified before new on-disk
6873  * pointers are set.  We chose this slightly more stringent requirement to
6874  * reduce complexity.) Our implementation handles this dependency by updating
6875  * the inode (or indirect block) appropriately but delaying the actual block
6876  * de-allocation (i.e., freemap and free space count manipulation) until
6877  * after the updated versions reach stable storage.  After the disk is
6878  * updated, the blocks can be safely de-allocated whenever it is convenient.
6879  * This implementation handles only the common case of reducing a file's
6880  * length to zero. Other cases are handled by the conventional synchronous
6881  * write approach.
6882  *
6883  * The ffs implementation with which we worked double-checks
6884  * the state of the block pointers and file size as it reduces
6885  * a file's length.  Some of this code is replicated here in our
6886  * soft updates implementation.  The freeblks->fb_chkcnt field is
6887  * used to transfer a part of this information to the procedure
6888  * that eventually de-allocates the blocks.
6889  *
6890  * This routine should be called from the routine that shortens
6891  * a file's length, before the inode's size or block pointers
6892  * are modified. It will save the block pointer information for
6893  * later release and zero the inode so that the calling routine
6894  * can release it.
6895  */
6896 void
6897 softdep_setup_freeblocks(ip, length, flags)
6898 	struct inode *ip;	/* The inode whose length is to be reduced */
6899 	off_t length;		/* The new length for the file */
6900 	int flags;		/* IO_EXT and/or IO_NORMAL */
6901 {
6902 	struct ufs1_dinode *dp1;
6903 	struct ufs2_dinode *dp2;
6904 	struct freeblks *freeblks;
6905 	struct inodedep *inodedep;
6906 	struct allocdirect *adp;
6907 	struct ufsmount *ump;
6908 	struct buf *bp;
6909 	struct fs *fs;
6910 	ufs2_daddr_t extblocks, datablocks;
6911 	struct mount *mp;
6912 	int i, delay, error;
6913 	ufs_lbn_t tmpval;
6914 	ufs_lbn_t lbn;
6915 
6916 	ump = ITOUMP(ip);
6917 	mp = UFSTOVFS(ump);
6918 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6919 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6920 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6921 	    ip->i_number, length);
6922 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6923 	fs = ump->um_fs;
6924 	if ((error = bread(ump->um_devvp,
6925 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6926 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6927 		brelse(bp);
6928 		softdep_error("softdep_setup_freeblocks", error);
6929 		return;
6930 	}
6931 	freeblks = newfreeblks(mp, ip);
6932 	extblocks = 0;
6933 	datablocks = 0;
6934 	if (fs->fs_magic == FS_UFS2_MAGIC)
6935 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6936 	if ((flags & IO_NORMAL) != 0) {
6937 		for (i = 0; i < UFS_NDADDR; i++)
6938 			setup_freedirect(freeblks, ip, i, 0);
6939 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6940 		    i < UFS_NIADDR;
6941 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6942 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6943 		ip->i_size = 0;
6944 		DIP_SET(ip, i_size, 0);
6945 		datablocks = DIP(ip, i_blocks) - extblocks;
6946 	}
6947 	if ((flags & IO_EXT) != 0) {
6948 		for (i = 0; i < UFS_NXADDR; i++)
6949 			setup_freeext(freeblks, ip, i, 0);
6950 		ip->i_din2->di_extsize = 0;
6951 		datablocks += extblocks;
6952 	}
6953 #ifdef QUOTA
6954 	/* Reference the quotas in case the block count is wrong in the end. */
6955 	quotaref(ITOV(ip), freeblks->fb_quota);
6956 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6957 #endif
6958 	freeblks->fb_chkcnt = -datablocks;
6959 	UFS_LOCK(ump);
6960 	fs->fs_pendingblocks += datablocks;
6961 	UFS_UNLOCK(ump);
6962 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6963 	/*
6964 	 * Push the zero'ed inode to its disk buffer so that we are free
6965 	 * to delete its dependencies below. Once the dependencies are gone
6966 	 * the buffer can be safely released.
6967 	 */
6968 	if (ump->um_fstype == UFS1) {
6969 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6970 		    ino_to_fsbo(fs, ip->i_number));
6971 		ip->i_din1->di_freelink = dp1->di_freelink;
6972 		*dp1 = *ip->i_din1;
6973 	} else {
6974 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6975 		    ino_to_fsbo(fs, ip->i_number));
6976 		ip->i_din2->di_freelink = dp2->di_freelink;
6977 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6978 		*dp2 = *ip->i_din2;
6979 	}
6980 	/*
6981 	 * Find and eliminate any inode dependencies.
6982 	 */
6983 	ACQUIRE_LOCK(ump);
6984 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6985 	if ((inodedep->id_state & IOSTARTED) != 0)
6986 		panic("softdep_setup_freeblocks: inode busy");
6987 	/*
6988 	 * Add the freeblks structure to the list of operations that
6989 	 * must await the zero'ed inode being written to disk. If we
6990 	 * still have a bitmap dependency (delay == 0), then the inode
6991 	 * has never been written to disk, so we can process the
6992 	 * freeblks below once we have deleted the dependencies.
6993 	 */
6994 	delay = (inodedep->id_state & DEPCOMPLETE);
6995 	if (delay)
6996 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6997 	else
6998 		freeblks->fb_state |= COMPLETE;
6999 	/*
7000 	 * Because the file length has been truncated to zero, any
7001 	 * pending block allocation dependency structures associated
7002 	 * with this inode are obsolete and can simply be de-allocated.
7003 	 * We must first merge the two dependency lists to get rid of
7004 	 * any duplicate freefrag structures, then purge the merged list.
7005 	 * If we still have a bitmap dependency, then the inode has never
7006 	 * been written to disk, so we can free any fragments without delay.
7007 	 */
7008 	if (flags & IO_NORMAL) {
7009 		merge_inode_lists(&inodedep->id_newinoupdt,
7010 		    &inodedep->id_inoupdt);
7011 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7012 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7013 			    freeblks);
7014 	}
7015 	if (flags & IO_EXT) {
7016 		merge_inode_lists(&inodedep->id_newextupdt,
7017 		    &inodedep->id_extupdt);
7018 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7019 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7020 			    freeblks);
7021 	}
7022 	FREE_LOCK(ump);
7023 	bdwrite(bp);
7024 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7025 	ACQUIRE_LOCK(ump);
7026 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7027 		(void) free_inodedep(inodedep);
7028 	freeblks->fb_state |= DEPCOMPLETE;
7029 	/*
7030 	 * If the inode with zeroed block pointers is now on disk
7031 	 * we can start freeing blocks.
7032 	 */
7033 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7034 		freeblks->fb_state |= INPROGRESS;
7035 	else
7036 		freeblks = NULL;
7037 	FREE_LOCK(ump);
7038 	if (freeblks)
7039 		handle_workitem_freeblocks(freeblks, 0);
7040 	trunc_pages(ip, length, extblocks, flags);
7041 }
7042 
7043 /*
7044  * Eliminate pages from the page cache that back parts of this inode and
7045  * adjust the vnode pager's idea of our size.  This prevents stale data
7046  * from hanging around in the page cache.
7047  */
7048 static void
7049 trunc_pages(ip, length, extblocks, flags)
7050 	struct inode *ip;
7051 	off_t length;
7052 	ufs2_daddr_t extblocks;
7053 	int flags;
7054 {
7055 	struct vnode *vp;
7056 	struct fs *fs;
7057 	ufs_lbn_t lbn;
7058 	off_t end, extend;
7059 
7060 	vp = ITOV(ip);
7061 	fs = ITOFS(ip);
7062 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7063 	if ((flags & IO_EXT) != 0)
7064 		vn_pages_remove(vp, extend, 0);
7065 	if ((flags & IO_NORMAL) == 0)
7066 		return;
7067 	BO_LOCK(&vp->v_bufobj);
7068 	drain_output(vp);
7069 	BO_UNLOCK(&vp->v_bufobj);
7070 	/*
7071 	 * The vnode pager eliminates file pages we eliminate indirects
7072 	 * below.
7073 	 */
7074 	vnode_pager_setsize(vp, length);
7075 	/*
7076 	 * Calculate the end based on the last indirect we want to keep.  If
7077 	 * the block extends into indirects we can just use the negative of
7078 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7079 	 * be careful not to remove those, if they exist.  double and triple
7080 	 * indirect lbns do not overlap with others so it is not important
7081 	 * to verify how many levels are required.
7082 	 */
7083 	lbn = lblkno(fs, length);
7084 	if (lbn >= UFS_NDADDR) {
7085 		/* Calculate the virtual lbn of the triple indirect. */
7086 		lbn = -lbn - (UFS_NIADDR - 1);
7087 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7088 	} else
7089 		end = extend;
7090 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7091 }
7092 
7093 /*
7094  * See if the buf bp is in the range eliminated by truncation.
7095  */
7096 static int
7097 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7098 	struct buf *bp;
7099 	int *blkoffp;
7100 	ufs_lbn_t lastlbn;
7101 	int lastoff;
7102 	int flags;
7103 {
7104 	ufs_lbn_t lbn;
7105 
7106 	*blkoffp = 0;
7107 	/* Only match ext/normal blocks as appropriate. */
7108 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7109 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7110 		return (0);
7111 	/* ALTDATA is always a full truncation. */
7112 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7113 		return (1);
7114 	/* -1 is full truncation. */
7115 	if (lastlbn == -1)
7116 		return (1);
7117 	/*
7118 	 * If this is a partial truncate we only want those
7119 	 * blocks and indirect blocks that cover the range
7120 	 * we're after.
7121 	 */
7122 	lbn = bp->b_lblkno;
7123 	if (lbn < 0)
7124 		lbn = -(lbn + lbn_level(lbn));
7125 	if (lbn < lastlbn)
7126 		return (0);
7127 	/* Here we only truncate lblkno if it's partial. */
7128 	if (lbn == lastlbn) {
7129 		if (lastoff == 0)
7130 			return (0);
7131 		*blkoffp = lastoff;
7132 	}
7133 	return (1);
7134 }
7135 
7136 /*
7137  * Eliminate any dependencies that exist in memory beyond lblkno:off
7138  */
7139 static void
7140 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7141 	struct inode *ip;
7142 	struct freeblks *freeblks;
7143 	ufs_lbn_t lastlbn;
7144 	int lastoff;
7145 	int flags;
7146 {
7147 	struct bufobj *bo;
7148 	struct vnode *vp;
7149 	struct buf *bp;
7150 	int blkoff;
7151 
7152 	/*
7153 	 * We must wait for any I/O in progress to finish so that
7154 	 * all potential buffers on the dirty list will be visible.
7155 	 * Once they are all there, walk the list and get rid of
7156 	 * any dependencies.
7157 	 */
7158 	vp = ITOV(ip);
7159 	bo = &vp->v_bufobj;
7160 	BO_LOCK(bo);
7161 	drain_output(vp);
7162 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7163 		bp->b_vflags &= ~BV_SCANNED;
7164 restart:
7165 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7166 		if (bp->b_vflags & BV_SCANNED)
7167 			continue;
7168 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7169 			bp->b_vflags |= BV_SCANNED;
7170 			continue;
7171 		}
7172 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7173 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7174 			goto restart;
7175 		BO_UNLOCK(bo);
7176 		if (deallocate_dependencies(bp, freeblks, blkoff))
7177 			bqrelse(bp);
7178 		else
7179 			brelse(bp);
7180 		BO_LOCK(bo);
7181 		goto restart;
7182 	}
7183 	/*
7184 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7185 	 */
7186 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7187 		bp->b_vflags &= ~BV_SCANNED;
7188 cleanrestart:
7189 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7190 		if (bp->b_vflags & BV_SCANNED)
7191 			continue;
7192 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7193 			bp->b_vflags |= BV_SCANNED;
7194 			continue;
7195 		}
7196 		if (BUF_LOCK(bp,
7197 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7198 		    BO_LOCKPTR(bo)) == ENOLCK) {
7199 			BO_LOCK(bo);
7200 			goto cleanrestart;
7201 		}
7202 		bp->b_vflags |= BV_SCANNED;
7203 		bremfree(bp);
7204 		if (blkoff != 0) {
7205 			allocbuf(bp, blkoff);
7206 			bqrelse(bp);
7207 		} else {
7208 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7209 			brelse(bp);
7210 		}
7211 		BO_LOCK(bo);
7212 		goto cleanrestart;
7213 	}
7214 	drain_output(vp);
7215 	BO_UNLOCK(bo);
7216 }
7217 
7218 static int
7219 cancel_pagedep(pagedep, freeblks, blkoff)
7220 	struct pagedep *pagedep;
7221 	struct freeblks *freeblks;
7222 	int blkoff;
7223 {
7224 	struct jremref *jremref;
7225 	struct jmvref *jmvref;
7226 	struct dirrem *dirrem, *tmp;
7227 	int i;
7228 
7229 	/*
7230 	 * Copy any directory remove dependencies to the list
7231 	 * to be processed after the freeblks proceeds.  If
7232 	 * directory entry never made it to disk they
7233 	 * can be dumped directly onto the work list.
7234 	 */
7235 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7236 		/* Skip this directory removal if it is intended to remain. */
7237 		if (dirrem->dm_offset < blkoff)
7238 			continue;
7239 		/*
7240 		 * If there are any dirrems we wait for the journal write
7241 		 * to complete and then restart the buf scan as the lock
7242 		 * has been dropped.
7243 		 */
7244 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7245 			jwait(&jremref->jr_list, MNT_WAIT);
7246 			return (ERESTART);
7247 		}
7248 		LIST_REMOVE(dirrem, dm_next);
7249 		dirrem->dm_dirinum = pagedep->pd_ino;
7250 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7251 	}
7252 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7253 		jwait(&jmvref->jm_list, MNT_WAIT);
7254 		return (ERESTART);
7255 	}
7256 	/*
7257 	 * When we're partially truncating a pagedep we just want to flush
7258 	 * journal entries and return.  There can not be any adds in the
7259 	 * truncated portion of the directory and newblk must remain if
7260 	 * part of the block remains.
7261 	 */
7262 	if (blkoff != 0) {
7263 		struct diradd *dap;
7264 
7265 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7266 			if (dap->da_offset > blkoff)
7267 				panic("cancel_pagedep: diradd %p off %d > %d",
7268 				    dap, dap->da_offset, blkoff);
7269 		for (i = 0; i < DAHASHSZ; i++)
7270 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7271 				if (dap->da_offset > blkoff)
7272 					panic("cancel_pagedep: diradd %p off %d > %d",
7273 					    dap, dap->da_offset, blkoff);
7274 		return (0);
7275 	}
7276 	/*
7277 	 * There should be no directory add dependencies present
7278 	 * as the directory could not be truncated until all
7279 	 * children were removed.
7280 	 */
7281 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7282 	    ("deallocate_dependencies: pendinghd != NULL"));
7283 	for (i = 0; i < DAHASHSZ; i++)
7284 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7285 		    ("deallocate_dependencies: diraddhd != NULL"));
7286 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7287 		free_newdirblk(pagedep->pd_newdirblk);
7288 	if (free_pagedep(pagedep) == 0)
7289 		panic("Failed to free pagedep %p", pagedep);
7290 	return (0);
7291 }
7292 
7293 /*
7294  * Reclaim any dependency structures from a buffer that is about to
7295  * be reallocated to a new vnode. The buffer must be locked, thus,
7296  * no I/O completion operations can occur while we are manipulating
7297  * its associated dependencies. The mutex is held so that other I/O's
7298  * associated with related dependencies do not occur.
7299  */
7300 static int
7301 deallocate_dependencies(bp, freeblks, off)
7302 	struct buf *bp;
7303 	struct freeblks *freeblks;
7304 	int off;
7305 {
7306 	struct indirdep *indirdep;
7307 	struct pagedep *pagedep;
7308 	struct worklist *wk, *wkn;
7309 	struct ufsmount *ump;
7310 
7311 	ump = softdep_bp_to_mp(bp);
7312 	if (ump == NULL)
7313 		goto done;
7314 	ACQUIRE_LOCK(ump);
7315 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7316 		switch (wk->wk_type) {
7317 		case D_INDIRDEP:
7318 			indirdep = WK_INDIRDEP(wk);
7319 			if (bp->b_lblkno >= 0 ||
7320 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7321 				panic("deallocate_dependencies: not indir");
7322 			cancel_indirdep(indirdep, bp, freeblks);
7323 			continue;
7324 
7325 		case D_PAGEDEP:
7326 			pagedep = WK_PAGEDEP(wk);
7327 			if (cancel_pagedep(pagedep, freeblks, off)) {
7328 				FREE_LOCK(ump);
7329 				return (ERESTART);
7330 			}
7331 			continue;
7332 
7333 		case D_ALLOCINDIR:
7334 			/*
7335 			 * Simply remove the allocindir, we'll find it via
7336 			 * the indirdep where we can clear pointers if
7337 			 * needed.
7338 			 */
7339 			WORKLIST_REMOVE(wk);
7340 			continue;
7341 
7342 		case D_FREEWORK:
7343 			/*
7344 			 * A truncation is waiting for the zero'd pointers
7345 			 * to be written.  It can be freed when the freeblks
7346 			 * is journaled.
7347 			 */
7348 			WORKLIST_REMOVE(wk);
7349 			wk->wk_state |= ONDEPLIST;
7350 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7351 			break;
7352 
7353 		case D_ALLOCDIRECT:
7354 			if (off != 0)
7355 				continue;
7356 			/* FALLTHROUGH */
7357 		default:
7358 			panic("deallocate_dependencies: Unexpected type %s",
7359 			    TYPENAME(wk->wk_type));
7360 			/* NOTREACHED */
7361 		}
7362 	}
7363 	FREE_LOCK(ump);
7364 done:
7365 	/*
7366 	 * Don't throw away this buf, we were partially truncating and
7367 	 * some deps may always remain.
7368 	 */
7369 	if (off) {
7370 		allocbuf(bp, off);
7371 		bp->b_vflags |= BV_SCANNED;
7372 		return (EBUSY);
7373 	}
7374 	bp->b_flags |= B_INVAL | B_NOCACHE;
7375 
7376 	return (0);
7377 }
7378 
7379 /*
7380  * An allocdirect is being canceled due to a truncate.  We must make sure
7381  * the journal entry is released in concert with the blkfree that releases
7382  * the storage.  Completed journal entries must not be released until the
7383  * space is no longer pointed to by the inode or in the bitmap.
7384  */
7385 static void
7386 cancel_allocdirect(adphead, adp, freeblks)
7387 	struct allocdirectlst *adphead;
7388 	struct allocdirect *adp;
7389 	struct freeblks *freeblks;
7390 {
7391 	struct freework *freework;
7392 	struct newblk *newblk;
7393 	struct worklist *wk;
7394 
7395 	TAILQ_REMOVE(adphead, adp, ad_next);
7396 	newblk = (struct newblk *)adp;
7397 	freework = NULL;
7398 	/*
7399 	 * Find the correct freework structure.
7400 	 */
7401 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7402 		if (wk->wk_type != D_FREEWORK)
7403 			continue;
7404 		freework = WK_FREEWORK(wk);
7405 		if (freework->fw_blkno == newblk->nb_newblkno)
7406 			break;
7407 	}
7408 	if (freework == NULL)
7409 		panic("cancel_allocdirect: Freework not found");
7410 	/*
7411 	 * If a newblk exists at all we still have the journal entry that
7412 	 * initiated the allocation so we do not need to journal the free.
7413 	 */
7414 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7415 	/*
7416 	 * If the journal hasn't been written the jnewblk must be passed
7417 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7418 	 * this by linking the journal dependency into the freework to be
7419 	 * freed when freework_freeblock() is called.  If the journal has
7420 	 * been written we can simply reclaim the journal space when the
7421 	 * freeblks work is complete.
7422 	 */
7423 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7424 	    &freeblks->fb_jwork);
7425 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7426 }
7427 
7428 
7429 /*
7430  * Cancel a new block allocation.  May be an indirect or direct block.  We
7431  * remove it from various lists and return any journal record that needs to
7432  * be resolved by the caller.
7433  *
7434  * A special consideration is made for indirects which were never pointed
7435  * at on disk and will never be found once this block is released.
7436  */
7437 static struct jnewblk *
7438 cancel_newblk(newblk, wk, wkhd)
7439 	struct newblk *newblk;
7440 	struct worklist *wk;
7441 	struct workhead *wkhd;
7442 {
7443 	struct jnewblk *jnewblk;
7444 
7445 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7446 
7447 	newblk->nb_state |= GOINGAWAY;
7448 	/*
7449 	 * Previously we traversed the completedhd on each indirdep
7450 	 * attached to this newblk to cancel them and gather journal
7451 	 * work.  Since we need only the oldest journal segment and
7452 	 * the lowest point on the tree will always have the oldest
7453 	 * journal segment we are free to release the segments
7454 	 * of any subordinates and may leave the indirdep list to
7455 	 * indirdep_complete() when this newblk is freed.
7456 	 */
7457 	if (newblk->nb_state & ONDEPLIST) {
7458 		newblk->nb_state &= ~ONDEPLIST;
7459 		LIST_REMOVE(newblk, nb_deps);
7460 	}
7461 	if (newblk->nb_state & ONWORKLIST)
7462 		WORKLIST_REMOVE(&newblk->nb_list);
7463 	/*
7464 	 * If the journal entry hasn't been written we save a pointer to
7465 	 * the dependency that frees it until it is written or the
7466 	 * superseding operation completes.
7467 	 */
7468 	jnewblk = newblk->nb_jnewblk;
7469 	if (jnewblk != NULL && wk != NULL) {
7470 		newblk->nb_jnewblk = NULL;
7471 		jnewblk->jn_dep = wk;
7472 	}
7473 	if (!LIST_EMPTY(&newblk->nb_jwork))
7474 		jwork_move(wkhd, &newblk->nb_jwork);
7475 	/*
7476 	 * When truncating we must free the newdirblk early to remove
7477 	 * the pagedep from the hash before returning.
7478 	 */
7479 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7480 		free_newdirblk(WK_NEWDIRBLK(wk));
7481 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7482 		panic("cancel_newblk: extra newdirblk");
7483 
7484 	return (jnewblk);
7485 }
7486 
7487 /*
7488  * Schedule the freefrag associated with a newblk to be released once
7489  * the pointers are written and the previous block is no longer needed.
7490  */
7491 static void
7492 newblk_freefrag(newblk)
7493 	struct newblk *newblk;
7494 {
7495 	struct freefrag *freefrag;
7496 
7497 	if (newblk->nb_freefrag == NULL)
7498 		return;
7499 	freefrag = newblk->nb_freefrag;
7500 	newblk->nb_freefrag = NULL;
7501 	freefrag->ff_state |= COMPLETE;
7502 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7503 		add_to_worklist(&freefrag->ff_list, 0);
7504 }
7505 
7506 /*
7507  * Free a newblk. Generate a new freefrag work request if appropriate.
7508  * This must be called after the inode pointer and any direct block pointers
7509  * are valid or fully removed via truncate or frag extension.
7510  */
7511 static void
7512 free_newblk(newblk)
7513 	struct newblk *newblk;
7514 {
7515 	struct indirdep *indirdep;
7516 	struct worklist *wk;
7517 
7518 	KASSERT(newblk->nb_jnewblk == NULL,
7519 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7520 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7521 	    ("free_newblk: unclaimed newblk"));
7522 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7523 	newblk_freefrag(newblk);
7524 	if (newblk->nb_state & ONDEPLIST)
7525 		LIST_REMOVE(newblk, nb_deps);
7526 	if (newblk->nb_state & ONWORKLIST)
7527 		WORKLIST_REMOVE(&newblk->nb_list);
7528 	LIST_REMOVE(newblk, nb_hash);
7529 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7530 		free_newdirblk(WK_NEWDIRBLK(wk));
7531 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7532 		panic("free_newblk: extra newdirblk");
7533 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7534 		indirdep_complete(indirdep);
7535 	handle_jwork(&newblk->nb_jwork);
7536 	WORKITEM_FREE(newblk, D_NEWBLK);
7537 }
7538 
7539 /*
7540  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7541  */
7542 static void
7543 free_newdirblk(newdirblk)
7544 	struct newdirblk *newdirblk;
7545 {
7546 	struct pagedep *pagedep;
7547 	struct diradd *dap;
7548 	struct worklist *wk;
7549 
7550 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7551 	WORKLIST_REMOVE(&newdirblk->db_list);
7552 	/*
7553 	 * If the pagedep is still linked onto the directory buffer
7554 	 * dependency chain, then some of the entries on the
7555 	 * pd_pendinghd list may not be committed to disk yet. In
7556 	 * this case, we will simply clear the NEWBLOCK flag and
7557 	 * let the pd_pendinghd list be processed when the pagedep
7558 	 * is next written. If the pagedep is no longer on the buffer
7559 	 * dependency chain, then all the entries on the pd_pending
7560 	 * list are committed to disk and we can free them here.
7561 	 */
7562 	pagedep = newdirblk->db_pagedep;
7563 	pagedep->pd_state &= ~NEWBLOCK;
7564 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7565 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7566 			free_diradd(dap, NULL);
7567 		/*
7568 		 * If no dependencies remain, the pagedep will be freed.
7569 		 */
7570 		free_pagedep(pagedep);
7571 	}
7572 	/* Should only ever be one item in the list. */
7573 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7574 		WORKLIST_REMOVE(wk);
7575 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7576 	}
7577 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7578 }
7579 
7580 /*
7581  * Prepare an inode to be freed. The actual free operation is not
7582  * done until the zero'ed inode has been written to disk.
7583  */
7584 void
7585 softdep_freefile(pvp, ino, mode)
7586 	struct vnode *pvp;
7587 	ino_t ino;
7588 	int mode;
7589 {
7590 	struct inode *ip = VTOI(pvp);
7591 	struct inodedep *inodedep;
7592 	struct freefile *freefile;
7593 	struct freeblks *freeblks;
7594 	struct ufsmount *ump;
7595 
7596 	ump = ITOUMP(ip);
7597 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7598 	    ("softdep_freefile called on non-softdep filesystem"));
7599 	/*
7600 	 * This sets up the inode de-allocation dependency.
7601 	 */
7602 	freefile = malloc(sizeof(struct freefile),
7603 		M_FREEFILE, M_SOFTDEP_FLAGS);
7604 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7605 	freefile->fx_mode = mode;
7606 	freefile->fx_oldinum = ino;
7607 	freefile->fx_devvp = ump->um_devvp;
7608 	LIST_INIT(&freefile->fx_jwork);
7609 	UFS_LOCK(ump);
7610 	ump->um_fs->fs_pendinginodes += 1;
7611 	UFS_UNLOCK(ump);
7612 
7613 	/*
7614 	 * If the inodedep does not exist, then the zero'ed inode has
7615 	 * been written to disk. If the allocated inode has never been
7616 	 * written to disk, then the on-disk inode is zero'ed. In either
7617 	 * case we can free the file immediately.  If the journal was
7618 	 * canceled before being written the inode will never make it to
7619 	 * disk and we must send the canceled journal entrys to
7620 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7621 	 * Any blocks waiting on the inode to write can be safely freed
7622 	 * here as it will never been written.
7623 	 */
7624 	ACQUIRE_LOCK(ump);
7625 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7626 	if (inodedep) {
7627 		/*
7628 		 * Clear out freeblks that no longer need to reference
7629 		 * this inode.
7630 		 */
7631 		while ((freeblks =
7632 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7633 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7634 			    fb_next);
7635 			freeblks->fb_state &= ~ONDEPLIST;
7636 		}
7637 		/*
7638 		 * Remove this inode from the unlinked list.
7639 		 */
7640 		if (inodedep->id_state & UNLINKED) {
7641 			/*
7642 			 * Save the journal work to be freed with the bitmap
7643 			 * before we clear UNLINKED.  Otherwise it can be lost
7644 			 * if the inode block is written.
7645 			 */
7646 			handle_bufwait(inodedep, &freefile->fx_jwork);
7647 			clear_unlinked_inodedep(inodedep);
7648 			/*
7649 			 * Re-acquire inodedep as we've dropped the
7650 			 * per-filesystem lock in clear_unlinked_inodedep().
7651 			 */
7652 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7653 		}
7654 	}
7655 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7656 		FREE_LOCK(ump);
7657 		handle_workitem_freefile(freefile);
7658 		return;
7659 	}
7660 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7661 		inodedep->id_state |= GOINGAWAY;
7662 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7663 	FREE_LOCK(ump);
7664 	if (ip->i_number == ino)
7665 		ip->i_flag |= IN_MODIFIED;
7666 }
7667 
7668 /*
7669  * Check to see if an inode has never been written to disk. If
7670  * so free the inodedep and return success, otherwise return failure.
7671  *
7672  * If we still have a bitmap dependency, then the inode has never
7673  * been written to disk. Drop the dependency as it is no longer
7674  * necessary since the inode is being deallocated. We set the
7675  * ALLCOMPLETE flags since the bitmap now properly shows that the
7676  * inode is not allocated. Even if the inode is actively being
7677  * written, it has been rolled back to its zero'ed state, so we
7678  * are ensured that a zero inode is what is on the disk. For short
7679  * lived files, this change will usually result in removing all the
7680  * dependencies from the inode so that it can be freed immediately.
7681  */
7682 static int
7683 check_inode_unwritten(inodedep)
7684 	struct inodedep *inodedep;
7685 {
7686 
7687 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7688 
7689 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7690 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7691 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7692 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7693 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7694 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7695 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7696 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7697 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7698 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7699 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7700 	    inodedep->id_mkdiradd != NULL ||
7701 	    inodedep->id_nlinkdelta != 0)
7702 		return (0);
7703 	/*
7704 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7705 	 * trying to allocate memory without holding "Softdep Lock".
7706 	 */
7707 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7708 	    inodedep->id_savedino1 == NULL)
7709 		return (0);
7710 
7711 	if (inodedep->id_state & ONDEPLIST)
7712 		LIST_REMOVE(inodedep, id_deps);
7713 	inodedep->id_state &= ~ONDEPLIST;
7714 	inodedep->id_state |= ALLCOMPLETE;
7715 	inodedep->id_bmsafemap = NULL;
7716 	if (inodedep->id_state & ONWORKLIST)
7717 		WORKLIST_REMOVE(&inodedep->id_list);
7718 	if (inodedep->id_savedino1 != NULL) {
7719 		free(inodedep->id_savedino1, M_SAVEDINO);
7720 		inodedep->id_savedino1 = NULL;
7721 	}
7722 	if (free_inodedep(inodedep) == 0)
7723 		panic("check_inode_unwritten: busy inode");
7724 	return (1);
7725 }
7726 
7727 static int
7728 check_inodedep_free(inodedep)
7729 	struct inodedep *inodedep;
7730 {
7731 
7732 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7733 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7734 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7735 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7736 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7737 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7738 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7739 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7740 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7741 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7742 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7743 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7744 	    inodedep->id_mkdiradd != NULL ||
7745 	    inodedep->id_nlinkdelta != 0 ||
7746 	    inodedep->id_savedino1 != NULL)
7747 		return (0);
7748 	return (1);
7749 }
7750 
7751 /*
7752  * Try to free an inodedep structure. Return 1 if it could be freed.
7753  */
7754 static int
7755 free_inodedep(inodedep)
7756 	struct inodedep *inodedep;
7757 {
7758 
7759 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7760 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7761 	    !check_inodedep_free(inodedep))
7762 		return (0);
7763 	if (inodedep->id_state & ONDEPLIST)
7764 		LIST_REMOVE(inodedep, id_deps);
7765 	LIST_REMOVE(inodedep, id_hash);
7766 	WORKITEM_FREE(inodedep, D_INODEDEP);
7767 	return (1);
7768 }
7769 
7770 /*
7771  * Free the block referenced by a freework structure.  The parent freeblks
7772  * structure is released and completed when the final cg bitmap reaches
7773  * the disk.  This routine may be freeing a jnewblk which never made it to
7774  * disk in which case we do not have to wait as the operation is undone
7775  * in memory immediately.
7776  */
7777 static void
7778 freework_freeblock(freework, key)
7779 	struct freework *freework;
7780 	u_long key;
7781 {
7782 	struct freeblks *freeblks;
7783 	struct jnewblk *jnewblk;
7784 	struct ufsmount *ump;
7785 	struct workhead wkhd;
7786 	struct fs *fs;
7787 	int bsize;
7788 	int needj;
7789 
7790 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7791 	LOCK_OWNED(ump);
7792 	/*
7793 	 * Handle partial truncate separately.
7794 	 */
7795 	if (freework->fw_indir) {
7796 		complete_trunc_indir(freework);
7797 		return;
7798 	}
7799 	freeblks = freework->fw_freeblks;
7800 	fs = ump->um_fs;
7801 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7802 	bsize = lfragtosize(fs, freework->fw_frags);
7803 	LIST_INIT(&wkhd);
7804 	/*
7805 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7806 	 * on the indirblk hashtable and prevents premature freeing.
7807 	 */
7808 	freework->fw_state |= DEPCOMPLETE;
7809 	/*
7810 	 * SUJ needs to wait for the segment referencing freed indirect
7811 	 * blocks to expire so that we know the checker will not confuse
7812 	 * a re-allocated indirect block with its old contents.
7813 	 */
7814 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7815 		indirblk_insert(freework);
7816 	/*
7817 	 * If we are canceling an existing jnewblk pass it to the free
7818 	 * routine, otherwise pass the freeblk which will ultimately
7819 	 * release the freeblks.  If we're not journaling, we can just
7820 	 * free the freeblks immediately.
7821 	 */
7822 	jnewblk = freework->fw_jnewblk;
7823 	if (jnewblk != NULL) {
7824 		cancel_jnewblk(jnewblk, &wkhd);
7825 		needj = 0;
7826 	} else if (needj) {
7827 		freework->fw_state |= DELAYEDFREE;
7828 		freeblks->fb_cgwait++;
7829 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7830 	}
7831 	FREE_LOCK(ump);
7832 	freeblks_free(ump, freeblks, btodb(bsize));
7833 	CTR4(KTR_SUJ,
7834 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
7835 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7836 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7837 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
7838 	ACQUIRE_LOCK(ump);
7839 	/*
7840 	 * The jnewblk will be discarded and the bits in the map never
7841 	 * made it to disk.  We can immediately free the freeblk.
7842 	 */
7843 	if (needj == 0)
7844 		handle_written_freework(freework);
7845 }
7846 
7847 /*
7848  * We enqueue freework items that need processing back on the freeblks and
7849  * add the freeblks to the worklist.  This makes it easier to find all work
7850  * required to flush a truncation in process_truncates().
7851  */
7852 static void
7853 freework_enqueue(freework)
7854 	struct freework *freework;
7855 {
7856 	struct freeblks *freeblks;
7857 
7858 	freeblks = freework->fw_freeblks;
7859 	if ((freework->fw_state & INPROGRESS) == 0)
7860 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7861 	if ((freeblks->fb_state &
7862 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7863 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7864 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7865 }
7866 
7867 /*
7868  * Start, continue, or finish the process of freeing an indirect block tree.
7869  * The free operation may be paused at any point with fw_off containing the
7870  * offset to restart from.  This enables us to implement some flow control
7871  * for large truncates which may fan out and generate a huge number of
7872  * dependencies.
7873  */
7874 static void
7875 handle_workitem_indirblk(freework)
7876 	struct freework *freework;
7877 {
7878 	struct freeblks *freeblks;
7879 	struct ufsmount *ump;
7880 	struct fs *fs;
7881 
7882 	freeblks = freework->fw_freeblks;
7883 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7884 	fs = ump->um_fs;
7885 	if (freework->fw_state & DEPCOMPLETE) {
7886 		handle_written_freework(freework);
7887 		return;
7888 	}
7889 	if (freework->fw_off == NINDIR(fs)) {
7890 		freework_freeblock(freework, SINGLETON_KEY);
7891 		return;
7892 	}
7893 	freework->fw_state |= INPROGRESS;
7894 	FREE_LOCK(ump);
7895 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7896 	    freework->fw_lbn);
7897 	ACQUIRE_LOCK(ump);
7898 }
7899 
7900 /*
7901  * Called when a freework structure attached to a cg buf is written.  The
7902  * ref on either the parent or the freeblks structure is released and
7903  * the freeblks is added back to the worklist if there is more work to do.
7904  */
7905 static void
7906 handle_written_freework(freework)
7907 	struct freework *freework;
7908 {
7909 	struct freeblks *freeblks;
7910 	struct freework *parent;
7911 
7912 	freeblks = freework->fw_freeblks;
7913 	parent = freework->fw_parent;
7914 	if (freework->fw_state & DELAYEDFREE)
7915 		freeblks->fb_cgwait--;
7916 	freework->fw_state |= COMPLETE;
7917 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7918 		WORKITEM_FREE(freework, D_FREEWORK);
7919 	if (parent) {
7920 		if (--parent->fw_ref == 0)
7921 			freework_enqueue(parent);
7922 		return;
7923 	}
7924 	if (--freeblks->fb_ref != 0)
7925 		return;
7926 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7927 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7928 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7929 }
7930 
7931 /*
7932  * This workitem routine performs the block de-allocation.
7933  * The workitem is added to the pending list after the updated
7934  * inode block has been written to disk.  As mentioned above,
7935  * checks regarding the number of blocks de-allocated (compared
7936  * to the number of blocks allocated for the file) are also
7937  * performed in this function.
7938  */
7939 static int
7940 handle_workitem_freeblocks(freeblks, flags)
7941 	struct freeblks *freeblks;
7942 	int flags;
7943 {
7944 	struct freework *freework;
7945 	struct newblk *newblk;
7946 	struct allocindir *aip;
7947 	struct ufsmount *ump;
7948 	struct worklist *wk;
7949 	u_long key;
7950 
7951 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7952 	    ("handle_workitem_freeblocks: Journal entries not written."));
7953 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7954 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
7955 	ACQUIRE_LOCK(ump);
7956 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7957 		WORKLIST_REMOVE(wk);
7958 		switch (wk->wk_type) {
7959 		case D_DIRREM:
7960 			wk->wk_state |= COMPLETE;
7961 			add_to_worklist(wk, 0);
7962 			continue;
7963 
7964 		case D_ALLOCDIRECT:
7965 			free_newblk(WK_NEWBLK(wk));
7966 			continue;
7967 
7968 		case D_ALLOCINDIR:
7969 			aip = WK_ALLOCINDIR(wk);
7970 			freework = NULL;
7971 			if (aip->ai_state & DELAYEDFREE) {
7972 				FREE_LOCK(ump);
7973 				freework = newfreework(ump, freeblks, NULL,
7974 				    aip->ai_lbn, aip->ai_newblkno,
7975 				    ump->um_fs->fs_frag, 0, 0);
7976 				ACQUIRE_LOCK(ump);
7977 			}
7978 			newblk = WK_NEWBLK(wk);
7979 			if (newblk->nb_jnewblk) {
7980 				freework->fw_jnewblk = newblk->nb_jnewblk;
7981 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7982 				newblk->nb_jnewblk = NULL;
7983 			}
7984 			free_newblk(newblk);
7985 			continue;
7986 
7987 		case D_FREEWORK:
7988 			freework = WK_FREEWORK(wk);
7989 			if (freework->fw_lbn <= -UFS_NDADDR)
7990 				handle_workitem_indirblk(freework);
7991 			else
7992 				freework_freeblock(freework, key);
7993 			continue;
7994 		default:
7995 			panic("handle_workitem_freeblocks: Unknown type %s",
7996 			    TYPENAME(wk->wk_type));
7997 		}
7998 	}
7999 	if (freeblks->fb_ref != 0) {
8000 		freeblks->fb_state &= ~INPROGRESS;
8001 		wake_worklist(&freeblks->fb_list);
8002 		freeblks = NULL;
8003 	}
8004 	FREE_LOCK(ump);
8005 	ffs_blkrelease_finish(ump, key);
8006 	if (freeblks)
8007 		return handle_complete_freeblocks(freeblks, flags);
8008 	return (0);
8009 }
8010 
8011 /*
8012  * Handle completion of block free via truncate.  This allows fs_pending
8013  * to track the actual free block count more closely than if we only updated
8014  * it at the end.  We must be careful to handle cases where the block count
8015  * on free was incorrect.
8016  */
8017 static void
8018 freeblks_free(ump, freeblks, blocks)
8019 	struct ufsmount *ump;
8020 	struct freeblks *freeblks;
8021 	int blocks;
8022 {
8023 	struct fs *fs;
8024 	ufs2_daddr_t remain;
8025 
8026 	UFS_LOCK(ump);
8027 	remain = -freeblks->fb_chkcnt;
8028 	freeblks->fb_chkcnt += blocks;
8029 	if (remain > 0) {
8030 		if (remain < blocks)
8031 			blocks = remain;
8032 		fs = ump->um_fs;
8033 		fs->fs_pendingblocks -= blocks;
8034 	}
8035 	UFS_UNLOCK(ump);
8036 }
8037 
8038 /*
8039  * Once all of the freework workitems are complete we can retire the
8040  * freeblocks dependency and any journal work awaiting completion.  This
8041  * can not be called until all other dependencies are stable on disk.
8042  */
8043 static int
8044 handle_complete_freeblocks(freeblks, flags)
8045 	struct freeblks *freeblks;
8046 	int flags;
8047 {
8048 	struct inodedep *inodedep;
8049 	struct inode *ip;
8050 	struct vnode *vp;
8051 	struct fs *fs;
8052 	struct ufsmount *ump;
8053 	ufs2_daddr_t spare;
8054 
8055 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8056 	fs = ump->um_fs;
8057 	flags = LK_EXCLUSIVE | flags;
8058 	spare = freeblks->fb_chkcnt;
8059 
8060 	/*
8061 	 * If we did not release the expected number of blocks we may have
8062 	 * to adjust the inode block count here.  Only do so if it wasn't
8063 	 * a truncation to zero and the modrev still matches.
8064 	 */
8065 	if (spare && freeblks->fb_len != 0) {
8066 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8067 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8068 			return (EBUSY);
8069 		ip = VTOI(vp);
8070 		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8071 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8072 			ip->i_flag |= IN_CHANGE;
8073 			/*
8074 			 * We must wait so this happens before the
8075 			 * journal is reclaimed.
8076 			 */
8077 			ffs_update(vp, 1);
8078 		}
8079 		vput(vp);
8080 	}
8081 	if (spare < 0) {
8082 		UFS_LOCK(ump);
8083 		fs->fs_pendingblocks += spare;
8084 		UFS_UNLOCK(ump);
8085 	}
8086 #ifdef QUOTA
8087 	/* Handle spare. */
8088 	if (spare)
8089 		quotaadj(freeblks->fb_quota, ump, -spare);
8090 	quotarele(freeblks->fb_quota);
8091 #endif
8092 	ACQUIRE_LOCK(ump);
8093 	if (freeblks->fb_state & ONDEPLIST) {
8094 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8095 		    0, &inodedep);
8096 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8097 		freeblks->fb_state &= ~ONDEPLIST;
8098 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8099 			free_inodedep(inodedep);
8100 	}
8101 	/*
8102 	 * All of the freeblock deps must be complete prior to this call
8103 	 * so it's now safe to complete earlier outstanding journal entries.
8104 	 */
8105 	handle_jwork(&freeblks->fb_jwork);
8106 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8107 	FREE_LOCK(ump);
8108 	return (0);
8109 }
8110 
8111 /*
8112  * Release blocks associated with the freeblks and stored in the indirect
8113  * block dbn. If level is greater than SINGLE, the block is an indirect block
8114  * and recursive calls to indirtrunc must be used to cleanse other indirect
8115  * blocks.
8116  *
8117  * This handles partial and complete truncation of blocks.  Partial is noted
8118  * with goingaway == 0.  In this case the freework is completed after the
8119  * zero'd indirects are written to disk.  For full truncation the freework
8120  * is completed after the block is freed.
8121  */
8122 static void
8123 indir_trunc(freework, dbn, lbn)
8124 	struct freework *freework;
8125 	ufs2_daddr_t dbn;
8126 	ufs_lbn_t lbn;
8127 {
8128 	struct freework *nfreework;
8129 	struct workhead wkhd;
8130 	struct freeblks *freeblks;
8131 	struct buf *bp;
8132 	struct fs *fs;
8133 	struct indirdep *indirdep;
8134 	struct mount *mp;
8135 	struct ufsmount *ump;
8136 	ufs1_daddr_t *bap1;
8137 	ufs2_daddr_t nb, nnb, *bap2;
8138 	ufs_lbn_t lbnadd, nlbn;
8139 	u_long key;
8140 	int nblocks, ufs1fmt, freedblocks;
8141 	int goingaway, freedeps, needj, level, cnt, i;
8142 
8143 	freeblks = freework->fw_freeblks;
8144 	mp = freeblks->fb_list.wk_mp;
8145 	ump = VFSTOUFS(mp);
8146 	fs = ump->um_fs;
8147 	/*
8148 	 * Get buffer of block pointers to be freed.  There are three cases:
8149 	 *
8150 	 * 1) Partial truncate caches the indirdep pointer in the freework
8151 	 *    which provides us a back copy to the save bp which holds the
8152 	 *    pointers we want to clear.  When this completes the zero
8153 	 *    pointers are written to the real copy.
8154 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8155 	 *    eliminated the real copy and placed the indirdep on the saved
8156 	 *    copy.  The indirdep and buf are discarded when this completes.
8157 	 * 3) The indirect was not in memory, we read a copy off of the disk
8158 	 *    using the devvp and drop and invalidate the buffer when we're
8159 	 *    done.
8160 	 */
8161 	goingaway = 1;
8162 	indirdep = NULL;
8163 	if (freework->fw_indir != NULL) {
8164 		goingaway = 0;
8165 		indirdep = freework->fw_indir;
8166 		bp = indirdep->ir_savebp;
8167 		if (bp == NULL || bp->b_blkno != dbn)
8168 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8169 			    bp, (intmax_t)dbn);
8170 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8171 		/*
8172 		 * The lock prevents the buf dep list from changing and
8173 	 	 * indirects on devvp should only ever have one dependency.
8174 		 */
8175 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8176 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8177 			panic("indir_trunc: Bad indirdep %p from buf %p",
8178 			    indirdep, bp);
8179 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8180 	    NOCRED, &bp) != 0) {
8181 		brelse(bp);
8182 		return;
8183 	}
8184 	ACQUIRE_LOCK(ump);
8185 	/* Protects against a race with complete_trunc_indir(). */
8186 	freework->fw_state &= ~INPROGRESS;
8187 	/*
8188 	 * If we have an indirdep we need to enforce the truncation order
8189 	 * and discard it when it is complete.
8190 	 */
8191 	if (indirdep) {
8192 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8193 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8194 			/*
8195 			 * Add the complete truncate to the list on the
8196 			 * indirdep to enforce in-order processing.
8197 			 */
8198 			if (freework->fw_indir == NULL)
8199 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8200 				    freework, fw_next);
8201 			FREE_LOCK(ump);
8202 			return;
8203 		}
8204 		/*
8205 		 * If we're goingaway, free the indirdep.  Otherwise it will
8206 		 * linger until the write completes.
8207 		 */
8208 		if (goingaway)
8209 			free_indirdep(indirdep);
8210 	}
8211 	FREE_LOCK(ump);
8212 	/* Initialize pointers depending on block size. */
8213 	if (ump->um_fstype == UFS1) {
8214 		bap1 = (ufs1_daddr_t *)bp->b_data;
8215 		nb = bap1[freework->fw_off];
8216 		ufs1fmt = 1;
8217 		bap2 = NULL;
8218 	} else {
8219 		bap2 = (ufs2_daddr_t *)bp->b_data;
8220 		nb = bap2[freework->fw_off];
8221 		ufs1fmt = 0;
8222 		bap1 = NULL;
8223 	}
8224 	level = lbn_level(lbn);
8225 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8226 	lbnadd = lbn_offset(fs, level);
8227 	nblocks = btodb(fs->fs_bsize);
8228 	nfreework = freework;
8229 	freedeps = 0;
8230 	cnt = 0;
8231 	/*
8232 	 * Reclaim blocks.  Traverses into nested indirect levels and
8233 	 * arranges for the current level to be freed when subordinates
8234 	 * are free when journaling.
8235 	 */
8236 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8237 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8238 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8239 		    fs->fs_bsize) != 0)
8240 			nb = 0;
8241 		if (i != NINDIR(fs) - 1) {
8242 			if (ufs1fmt)
8243 				nnb = bap1[i+1];
8244 			else
8245 				nnb = bap2[i+1];
8246 		} else
8247 			nnb = 0;
8248 		if (nb == 0)
8249 			continue;
8250 		cnt++;
8251 		if (level != 0) {
8252 			nlbn = (lbn + 1) - (i * lbnadd);
8253 			if (needj != 0) {
8254 				nfreework = newfreework(ump, freeblks, freework,
8255 				    nlbn, nb, fs->fs_frag, 0, 0);
8256 				freedeps++;
8257 			}
8258 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8259 		} else {
8260 			struct freedep *freedep;
8261 
8262 			/*
8263 			 * Attempt to aggregate freedep dependencies for
8264 			 * all blocks being released to the same CG.
8265 			 */
8266 			LIST_INIT(&wkhd);
8267 			if (needj != 0 &&
8268 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8269 				freedep = newfreedep(freework);
8270 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8271 				    &freedep->fd_list);
8272 				freedeps++;
8273 			}
8274 			CTR3(KTR_SUJ,
8275 			    "indir_trunc: ino %jd blkno %jd size %d",
8276 			    freeblks->fb_inum, nb, fs->fs_bsize);
8277 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8278 			    fs->fs_bsize, freeblks->fb_inum,
8279 			    freeblks->fb_vtype, &wkhd, key);
8280 		}
8281 	}
8282 	ffs_blkrelease_finish(ump, key);
8283 	if (goingaway) {
8284 		bp->b_flags |= B_INVAL | B_NOCACHE;
8285 		brelse(bp);
8286 	}
8287 	freedblocks = 0;
8288 	if (level == 0)
8289 		freedblocks = (nblocks * cnt);
8290 	if (needj == 0)
8291 		freedblocks += nblocks;
8292 	freeblks_free(ump, freeblks, freedblocks);
8293 	/*
8294 	 * If we are journaling set up the ref counts and offset so this
8295 	 * indirect can be completed when its children are free.
8296 	 */
8297 	if (needj) {
8298 		ACQUIRE_LOCK(ump);
8299 		freework->fw_off = i;
8300 		freework->fw_ref += freedeps;
8301 		freework->fw_ref -= NINDIR(fs) + 1;
8302 		if (level == 0)
8303 			freeblks->fb_cgwait += freedeps;
8304 		if (freework->fw_ref == 0)
8305 			freework_freeblock(freework, SINGLETON_KEY);
8306 		FREE_LOCK(ump);
8307 		return;
8308 	}
8309 	/*
8310 	 * If we're not journaling we can free the indirect now.
8311 	 */
8312 	dbn = dbtofsb(fs, dbn);
8313 	CTR3(KTR_SUJ,
8314 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8315 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8316 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8317 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8318 	/* Non SUJ softdep does single-threaded truncations. */
8319 	if (freework->fw_blkno == dbn) {
8320 		freework->fw_state |= ALLCOMPLETE;
8321 		ACQUIRE_LOCK(ump);
8322 		handle_written_freework(freework);
8323 		FREE_LOCK(ump);
8324 	}
8325 	return;
8326 }
8327 
8328 /*
8329  * Cancel an allocindir when it is removed via truncation.  When bp is not
8330  * NULL the indirect never appeared on disk and is scheduled to be freed
8331  * independently of the indir so we can more easily track journal work.
8332  */
8333 static void
8334 cancel_allocindir(aip, bp, freeblks, trunc)
8335 	struct allocindir *aip;
8336 	struct buf *bp;
8337 	struct freeblks *freeblks;
8338 	int trunc;
8339 {
8340 	struct indirdep *indirdep;
8341 	struct freefrag *freefrag;
8342 	struct newblk *newblk;
8343 
8344 	newblk = (struct newblk *)aip;
8345 	LIST_REMOVE(aip, ai_next);
8346 	/*
8347 	 * We must eliminate the pointer in bp if it must be freed on its
8348 	 * own due to partial truncate or pending journal work.
8349 	 */
8350 	if (bp && (trunc || newblk->nb_jnewblk)) {
8351 		/*
8352 		 * Clear the pointer and mark the aip to be freed
8353 		 * directly if it never existed on disk.
8354 		 */
8355 		aip->ai_state |= DELAYEDFREE;
8356 		indirdep = aip->ai_indirdep;
8357 		if (indirdep->ir_state & UFS1FMT)
8358 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8359 		else
8360 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8361 	}
8362 	/*
8363 	 * When truncating the previous pointer will be freed via
8364 	 * savedbp.  Eliminate the freefrag which would dup free.
8365 	 */
8366 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8367 		newblk->nb_freefrag = NULL;
8368 		if (freefrag->ff_jdep)
8369 			cancel_jfreefrag(
8370 			    WK_JFREEFRAG(freefrag->ff_jdep));
8371 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8372 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8373 	}
8374 	/*
8375 	 * If the journal hasn't been written the jnewblk must be passed
8376 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8377 	 * this by leaving the journal dependency on the newblk to be freed
8378 	 * when a freework is created in handle_workitem_freeblocks().
8379 	 */
8380 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8381 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8382 }
8383 
8384 /*
8385  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8386  * in to a newdirblk so any subsequent additions are tracked properly.  The
8387  * caller is responsible for adding the mkdir1 dependency to the journal
8388  * and updating id_mkdiradd.  This function returns with the per-filesystem
8389  * lock held.
8390  */
8391 static struct mkdir *
8392 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8393 	struct diradd *dap;
8394 	ino_t newinum;
8395 	ino_t dinum;
8396 	struct buf *newdirbp;
8397 	struct mkdir **mkdirp;
8398 {
8399 	struct newblk *newblk;
8400 	struct pagedep *pagedep;
8401 	struct inodedep *inodedep;
8402 	struct newdirblk *newdirblk;
8403 	struct mkdir *mkdir1, *mkdir2;
8404 	struct worklist *wk;
8405 	struct jaddref *jaddref;
8406 	struct ufsmount *ump;
8407 	struct mount *mp;
8408 
8409 	mp = dap->da_list.wk_mp;
8410 	ump = VFSTOUFS(mp);
8411 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8412 	    M_SOFTDEP_FLAGS);
8413 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8414 	LIST_INIT(&newdirblk->db_mkdir);
8415 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8416 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8417 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8418 	mkdir1->md_diradd = dap;
8419 	mkdir1->md_jaddref = NULL;
8420 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8421 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8422 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8423 	mkdir2->md_diradd = dap;
8424 	mkdir2->md_jaddref = NULL;
8425 	if (MOUNTEDSUJ(mp) == 0) {
8426 		mkdir1->md_state |= DEPCOMPLETE;
8427 		mkdir2->md_state |= DEPCOMPLETE;
8428 	}
8429 	/*
8430 	 * Dependency on "." and ".." being written to disk.
8431 	 */
8432 	mkdir1->md_buf = newdirbp;
8433 	ACQUIRE_LOCK(VFSTOUFS(mp));
8434 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8435 	/*
8436 	 * We must link the pagedep, allocdirect, and newdirblk for
8437 	 * the initial file page so the pointer to the new directory
8438 	 * is not written until the directory contents are live and
8439 	 * any subsequent additions are not marked live until the
8440 	 * block is reachable via the inode.
8441 	 */
8442 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8443 		panic("setup_newdir: lost pagedep");
8444 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8445 		if (wk->wk_type == D_ALLOCDIRECT)
8446 			break;
8447 	if (wk == NULL)
8448 		panic("setup_newdir: lost allocdirect");
8449 	if (pagedep->pd_state & NEWBLOCK)
8450 		panic("setup_newdir: NEWBLOCK already set");
8451 	newblk = WK_NEWBLK(wk);
8452 	pagedep->pd_state |= NEWBLOCK;
8453 	pagedep->pd_newdirblk = newdirblk;
8454 	newdirblk->db_pagedep = pagedep;
8455 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8456 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8457 	/*
8458 	 * Look up the inodedep for the parent directory so that we
8459 	 * can link mkdir2 into the pending dotdot jaddref or
8460 	 * the inode write if there is none.  If the inode is
8461 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8462 	 * been satisfied and mkdir2 can be freed.
8463 	 */
8464 	inodedep_lookup(mp, dinum, 0, &inodedep);
8465 	if (MOUNTEDSUJ(mp)) {
8466 		if (inodedep == NULL)
8467 			panic("setup_newdir: Lost parent.");
8468 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8469 		    inoreflst);
8470 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8471 		    (jaddref->ja_state & MKDIR_PARENT),
8472 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8473 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8474 		mkdir2->md_jaddref = jaddref;
8475 		jaddref->ja_mkdir = mkdir2;
8476 	} else if (inodedep == NULL ||
8477 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8478 		dap->da_state &= ~MKDIR_PARENT;
8479 		WORKITEM_FREE(mkdir2, D_MKDIR);
8480 		mkdir2 = NULL;
8481 	} else {
8482 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8483 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8484 	}
8485 	*mkdirp = mkdir2;
8486 
8487 	return (mkdir1);
8488 }
8489 
8490 /*
8491  * Directory entry addition dependencies.
8492  *
8493  * When adding a new directory entry, the inode (with its incremented link
8494  * count) must be written to disk before the directory entry's pointer to it.
8495  * Also, if the inode is newly allocated, the corresponding freemap must be
8496  * updated (on disk) before the directory entry's pointer. These requirements
8497  * are met via undo/redo on the directory entry's pointer, which consists
8498  * simply of the inode number.
8499  *
8500  * As directory entries are added and deleted, the free space within a
8501  * directory block can become fragmented.  The ufs filesystem will compact
8502  * a fragmented directory block to make space for a new entry. When this
8503  * occurs, the offsets of previously added entries change. Any "diradd"
8504  * dependency structures corresponding to these entries must be updated with
8505  * the new offsets.
8506  */
8507 
8508 /*
8509  * This routine is called after the in-memory inode's link
8510  * count has been incremented, but before the directory entry's
8511  * pointer to the inode has been set.
8512  */
8513 int
8514 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8515 	struct buf *bp;		/* buffer containing directory block */
8516 	struct inode *dp;	/* inode for directory */
8517 	off_t diroffset;	/* offset of new entry in directory */
8518 	ino_t newinum;		/* inode referenced by new directory entry */
8519 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8520 	int isnewblk;		/* entry is in a newly allocated block */
8521 {
8522 	int offset;		/* offset of new entry within directory block */
8523 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8524 	struct fs *fs;
8525 	struct diradd *dap;
8526 	struct newblk *newblk;
8527 	struct pagedep *pagedep;
8528 	struct inodedep *inodedep;
8529 	struct newdirblk *newdirblk;
8530 	struct mkdir *mkdir1, *mkdir2;
8531 	struct jaddref *jaddref;
8532 	struct ufsmount *ump;
8533 	struct mount *mp;
8534 	int isindir;
8535 
8536 	mp = ITOVFS(dp);
8537 	ump = VFSTOUFS(mp);
8538 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8539 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8540 	/*
8541 	 * Whiteouts have no dependencies.
8542 	 */
8543 	if (newinum == UFS_WINO) {
8544 		if (newdirbp != NULL)
8545 			bdwrite(newdirbp);
8546 		return (0);
8547 	}
8548 	jaddref = NULL;
8549 	mkdir1 = mkdir2 = NULL;
8550 	fs = ump->um_fs;
8551 	lbn = lblkno(fs, diroffset);
8552 	offset = blkoff(fs, diroffset);
8553 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8554 		M_SOFTDEP_FLAGS|M_ZERO);
8555 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8556 	dap->da_offset = offset;
8557 	dap->da_newinum = newinum;
8558 	dap->da_state = ATTACHED;
8559 	LIST_INIT(&dap->da_jwork);
8560 	isindir = bp->b_lblkno >= UFS_NDADDR;
8561 	newdirblk = NULL;
8562 	if (isnewblk &&
8563 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8564 		newdirblk = malloc(sizeof(struct newdirblk),
8565 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8566 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8567 		LIST_INIT(&newdirblk->db_mkdir);
8568 	}
8569 	/*
8570 	 * If we're creating a new directory setup the dependencies and set
8571 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8572 	 * we can move on.
8573 	 */
8574 	if (newdirbp == NULL) {
8575 		dap->da_state |= DEPCOMPLETE;
8576 		ACQUIRE_LOCK(ump);
8577 	} else {
8578 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8579 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8580 		    &mkdir2);
8581 	}
8582 	/*
8583 	 * Link into parent directory pagedep to await its being written.
8584 	 */
8585 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8586 #ifdef INVARIANTS
8587 	if (diradd_lookup(pagedep, offset) != NULL)
8588 		panic("softdep_setup_directory_add: %p already at off %d\n",
8589 		    diradd_lookup(pagedep, offset), offset);
8590 #endif
8591 	dap->da_pagedep = pagedep;
8592 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8593 	    da_pdlist);
8594 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8595 	/*
8596 	 * If we're journaling, link the diradd into the jaddref so it
8597 	 * may be completed after the journal entry is written.  Otherwise,
8598 	 * link the diradd into its inodedep.  If the inode is not yet
8599 	 * written place it on the bufwait list, otherwise do the post-inode
8600 	 * write processing to put it on the id_pendinghd list.
8601 	 */
8602 	if (MOUNTEDSUJ(mp)) {
8603 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8604 		    inoreflst);
8605 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8606 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8607 		jaddref->ja_diroff = diroffset;
8608 		jaddref->ja_diradd = dap;
8609 		add_to_journal(&jaddref->ja_list);
8610 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8611 		diradd_inode_written(dap, inodedep);
8612 	else
8613 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8614 	/*
8615 	 * Add the journal entries for . and .. links now that the primary
8616 	 * link is written.
8617 	 */
8618 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8619 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8620 		    inoreflst, if_deps);
8621 		KASSERT(jaddref != NULL &&
8622 		    jaddref->ja_ino == jaddref->ja_parent &&
8623 		    (jaddref->ja_state & MKDIR_BODY),
8624 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8625 		    jaddref));
8626 		mkdir1->md_jaddref = jaddref;
8627 		jaddref->ja_mkdir = mkdir1;
8628 		/*
8629 		 * It is important that the dotdot journal entry
8630 		 * is added prior to the dot entry since dot writes
8631 		 * both the dot and dotdot links.  These both must
8632 		 * be added after the primary link for the journal
8633 		 * to remain consistent.
8634 		 */
8635 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8636 		add_to_journal(&jaddref->ja_list);
8637 	}
8638 	/*
8639 	 * If we are adding a new directory remember this diradd so that if
8640 	 * we rename it we can keep the dot and dotdot dependencies.  If
8641 	 * we are adding a new name for an inode that has a mkdiradd we
8642 	 * must be in rename and we have to move the dot and dotdot
8643 	 * dependencies to this new name.  The old name is being orphaned
8644 	 * soon.
8645 	 */
8646 	if (mkdir1 != NULL) {
8647 		if (inodedep->id_mkdiradd != NULL)
8648 			panic("softdep_setup_directory_add: Existing mkdir");
8649 		inodedep->id_mkdiradd = dap;
8650 	} else if (inodedep->id_mkdiradd)
8651 		merge_diradd(inodedep, dap);
8652 	if (newdirblk != NULL) {
8653 		/*
8654 		 * There is nothing to do if we are already tracking
8655 		 * this block.
8656 		 */
8657 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8658 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8659 			FREE_LOCK(ump);
8660 			return (0);
8661 		}
8662 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8663 		    == 0)
8664 			panic("softdep_setup_directory_add: lost entry");
8665 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8666 		pagedep->pd_state |= NEWBLOCK;
8667 		pagedep->pd_newdirblk = newdirblk;
8668 		newdirblk->db_pagedep = pagedep;
8669 		FREE_LOCK(ump);
8670 		/*
8671 		 * If we extended into an indirect signal direnter to sync.
8672 		 */
8673 		if (isindir)
8674 			return (1);
8675 		return (0);
8676 	}
8677 	FREE_LOCK(ump);
8678 	return (0);
8679 }
8680 
8681 /*
8682  * This procedure is called to change the offset of a directory
8683  * entry when compacting a directory block which must be owned
8684  * exclusively by the caller. Note that the actual entry movement
8685  * must be done in this procedure to ensure that no I/O completions
8686  * occur while the move is in progress.
8687  */
8688 void
8689 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8690 	struct buf *bp;		/* Buffer holding directory block. */
8691 	struct inode *dp;	/* inode for directory */
8692 	caddr_t base;		/* address of dp->i_offset */
8693 	caddr_t oldloc;		/* address of old directory location */
8694 	caddr_t newloc;		/* address of new directory location */
8695 	int entrysize;		/* size of directory entry */
8696 {
8697 	int offset, oldoffset, newoffset;
8698 	struct pagedep *pagedep;
8699 	struct jmvref *jmvref;
8700 	struct diradd *dap;
8701 	struct direct *de;
8702 	struct mount *mp;
8703 	struct ufsmount *ump;
8704 	ufs_lbn_t lbn;
8705 	int flags;
8706 
8707 	mp = ITOVFS(dp);
8708 	ump = VFSTOUFS(mp);
8709 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8710 	    ("softdep_change_directoryentry_offset called on "
8711 	     "non-softdep filesystem"));
8712 	de = (struct direct *)oldloc;
8713 	jmvref = NULL;
8714 	flags = 0;
8715 	/*
8716 	 * Moves are always journaled as it would be too complex to
8717 	 * determine if any affected adds or removes are present in the
8718 	 * journal.
8719 	 */
8720 	if (MOUNTEDSUJ(mp)) {
8721 		flags = DEPALLOC;
8722 		jmvref = newjmvref(dp, de->d_ino,
8723 		    dp->i_offset + (oldloc - base),
8724 		    dp->i_offset + (newloc - base));
8725 	}
8726 	lbn = lblkno(ump->um_fs, dp->i_offset);
8727 	offset = blkoff(ump->um_fs, dp->i_offset);
8728 	oldoffset = offset + (oldloc - base);
8729 	newoffset = offset + (newloc - base);
8730 	ACQUIRE_LOCK(ump);
8731 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8732 		goto done;
8733 	dap = diradd_lookup(pagedep, oldoffset);
8734 	if (dap) {
8735 		dap->da_offset = newoffset;
8736 		newoffset = DIRADDHASH(newoffset);
8737 		oldoffset = DIRADDHASH(oldoffset);
8738 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8739 		    newoffset != oldoffset) {
8740 			LIST_REMOVE(dap, da_pdlist);
8741 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8742 			    dap, da_pdlist);
8743 		}
8744 	}
8745 done:
8746 	if (jmvref) {
8747 		jmvref->jm_pagedep = pagedep;
8748 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8749 		add_to_journal(&jmvref->jm_list);
8750 	}
8751 	bcopy(oldloc, newloc, entrysize);
8752 	FREE_LOCK(ump);
8753 }
8754 
8755 /*
8756  * Move the mkdir dependencies and journal work from one diradd to another
8757  * when renaming a directory.  The new name must depend on the mkdir deps
8758  * completing as the old name did.  Directories can only have one valid link
8759  * at a time so one must be canonical.
8760  */
8761 static void
8762 merge_diradd(inodedep, newdap)
8763 	struct inodedep *inodedep;
8764 	struct diradd *newdap;
8765 {
8766 	struct diradd *olddap;
8767 	struct mkdir *mkdir, *nextmd;
8768 	struct ufsmount *ump;
8769 	short state;
8770 
8771 	olddap = inodedep->id_mkdiradd;
8772 	inodedep->id_mkdiradd = newdap;
8773 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8774 		newdap->da_state &= ~DEPCOMPLETE;
8775 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8776 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8777 		     mkdir = nextmd) {
8778 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8779 			if (mkdir->md_diradd != olddap)
8780 				continue;
8781 			mkdir->md_diradd = newdap;
8782 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8783 			newdap->da_state |= state;
8784 			olddap->da_state &= ~state;
8785 			if ((olddap->da_state &
8786 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8787 				break;
8788 		}
8789 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8790 			panic("merge_diradd: unfound ref");
8791 	}
8792 	/*
8793 	 * Any mkdir related journal items are not safe to be freed until
8794 	 * the new name is stable.
8795 	 */
8796 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8797 	olddap->da_state |= DEPCOMPLETE;
8798 	complete_diradd(olddap);
8799 }
8800 
8801 /*
8802  * Move the diradd to the pending list when all diradd dependencies are
8803  * complete.
8804  */
8805 static void
8806 complete_diradd(dap)
8807 	struct diradd *dap;
8808 {
8809 	struct pagedep *pagedep;
8810 
8811 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8812 		if (dap->da_state & DIRCHG)
8813 			pagedep = dap->da_previous->dm_pagedep;
8814 		else
8815 			pagedep = dap->da_pagedep;
8816 		LIST_REMOVE(dap, da_pdlist);
8817 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8818 	}
8819 }
8820 
8821 /*
8822  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8823  * add entries and conditonally journal the remove.
8824  */
8825 static void
8826 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8827 	struct diradd *dap;
8828 	struct dirrem *dirrem;
8829 	struct jremref *jremref;
8830 	struct jremref *dotremref;
8831 	struct jremref *dotdotremref;
8832 {
8833 	struct inodedep *inodedep;
8834 	struct jaddref *jaddref;
8835 	struct inoref *inoref;
8836 	struct ufsmount *ump;
8837 	struct mkdir *mkdir;
8838 
8839 	/*
8840 	 * If no remove references were allocated we're on a non-journaled
8841 	 * filesystem and can skip the cancel step.
8842 	 */
8843 	if (jremref == NULL) {
8844 		free_diradd(dap, NULL);
8845 		return;
8846 	}
8847 	/*
8848 	 * Cancel the primary name an free it if it does not require
8849 	 * journaling.
8850 	 */
8851 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8852 	    0, &inodedep) != 0) {
8853 		/* Abort the addref that reference this diradd.  */
8854 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8855 			if (inoref->if_list.wk_type != D_JADDREF)
8856 				continue;
8857 			jaddref = (struct jaddref *)inoref;
8858 			if (jaddref->ja_diradd != dap)
8859 				continue;
8860 			if (cancel_jaddref(jaddref, inodedep,
8861 			    &dirrem->dm_jwork) == 0) {
8862 				free_jremref(jremref);
8863 				jremref = NULL;
8864 			}
8865 			break;
8866 		}
8867 	}
8868 	/*
8869 	 * Cancel subordinate names and free them if they do not require
8870 	 * journaling.
8871 	 */
8872 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8873 		ump = VFSTOUFS(dap->da_list.wk_mp);
8874 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8875 			if (mkdir->md_diradd != dap)
8876 				continue;
8877 			if ((jaddref = mkdir->md_jaddref) == NULL)
8878 				continue;
8879 			mkdir->md_jaddref = NULL;
8880 			if (mkdir->md_state & MKDIR_PARENT) {
8881 				if (cancel_jaddref(jaddref, NULL,
8882 				    &dirrem->dm_jwork) == 0) {
8883 					free_jremref(dotdotremref);
8884 					dotdotremref = NULL;
8885 				}
8886 			} else {
8887 				if (cancel_jaddref(jaddref, inodedep,
8888 				    &dirrem->dm_jwork) == 0) {
8889 					free_jremref(dotremref);
8890 					dotremref = NULL;
8891 				}
8892 			}
8893 		}
8894 	}
8895 
8896 	if (jremref)
8897 		journal_jremref(dirrem, jremref, inodedep);
8898 	if (dotremref)
8899 		journal_jremref(dirrem, dotremref, inodedep);
8900 	if (dotdotremref)
8901 		journal_jremref(dirrem, dotdotremref, NULL);
8902 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8903 	free_diradd(dap, &dirrem->dm_jwork);
8904 }
8905 
8906 /*
8907  * Free a diradd dependency structure.
8908  */
8909 static void
8910 free_diradd(dap, wkhd)
8911 	struct diradd *dap;
8912 	struct workhead *wkhd;
8913 {
8914 	struct dirrem *dirrem;
8915 	struct pagedep *pagedep;
8916 	struct inodedep *inodedep;
8917 	struct mkdir *mkdir, *nextmd;
8918 	struct ufsmount *ump;
8919 
8920 	ump = VFSTOUFS(dap->da_list.wk_mp);
8921 	LOCK_OWNED(ump);
8922 	LIST_REMOVE(dap, da_pdlist);
8923 	if (dap->da_state & ONWORKLIST)
8924 		WORKLIST_REMOVE(&dap->da_list);
8925 	if ((dap->da_state & DIRCHG) == 0) {
8926 		pagedep = dap->da_pagedep;
8927 	} else {
8928 		dirrem = dap->da_previous;
8929 		pagedep = dirrem->dm_pagedep;
8930 		dirrem->dm_dirinum = pagedep->pd_ino;
8931 		dirrem->dm_state |= COMPLETE;
8932 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8933 			add_to_worklist(&dirrem->dm_list, 0);
8934 	}
8935 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8936 	    0, &inodedep) != 0)
8937 		if (inodedep->id_mkdiradd == dap)
8938 			inodedep->id_mkdiradd = NULL;
8939 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8940 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8941 		     mkdir = nextmd) {
8942 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8943 			if (mkdir->md_diradd != dap)
8944 				continue;
8945 			dap->da_state &=
8946 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8947 			LIST_REMOVE(mkdir, md_mkdirs);
8948 			if (mkdir->md_state & ONWORKLIST)
8949 				WORKLIST_REMOVE(&mkdir->md_list);
8950 			if (mkdir->md_jaddref != NULL)
8951 				panic("free_diradd: Unexpected jaddref");
8952 			WORKITEM_FREE(mkdir, D_MKDIR);
8953 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8954 				break;
8955 		}
8956 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8957 			panic("free_diradd: unfound ref");
8958 	}
8959 	if (inodedep)
8960 		free_inodedep(inodedep);
8961 	/*
8962 	 * Free any journal segments waiting for the directory write.
8963 	 */
8964 	handle_jwork(&dap->da_jwork);
8965 	WORKITEM_FREE(dap, D_DIRADD);
8966 }
8967 
8968 /*
8969  * Directory entry removal dependencies.
8970  *
8971  * When removing a directory entry, the entry's inode pointer must be
8972  * zero'ed on disk before the corresponding inode's link count is decremented
8973  * (possibly freeing the inode for re-use). This dependency is handled by
8974  * updating the directory entry but delaying the inode count reduction until
8975  * after the directory block has been written to disk. After this point, the
8976  * inode count can be decremented whenever it is convenient.
8977  */
8978 
8979 /*
8980  * This routine should be called immediately after removing
8981  * a directory entry.  The inode's link count should not be
8982  * decremented by the calling procedure -- the soft updates
8983  * code will do this task when it is safe.
8984  */
8985 void
8986 softdep_setup_remove(bp, dp, ip, isrmdir)
8987 	struct buf *bp;		/* buffer containing directory block */
8988 	struct inode *dp;	/* inode for the directory being modified */
8989 	struct inode *ip;	/* inode for directory entry being removed */
8990 	int isrmdir;		/* indicates if doing RMDIR */
8991 {
8992 	struct dirrem *dirrem, *prevdirrem;
8993 	struct inodedep *inodedep;
8994 	struct ufsmount *ump;
8995 	int direct;
8996 
8997 	ump = ITOUMP(ip);
8998 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8999 	    ("softdep_setup_remove called on non-softdep filesystem"));
9000 	/*
9001 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9002 	 * newdirrem() to setup the full directory remove which requires
9003 	 * isrmdir > 1.
9004 	 */
9005 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9006 	/*
9007 	 * Add the dirrem to the inodedep's pending remove list for quick
9008 	 * discovery later.
9009 	 */
9010 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9011 		panic("softdep_setup_remove: Lost inodedep.");
9012 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9013 	dirrem->dm_state |= ONDEPLIST;
9014 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9015 
9016 	/*
9017 	 * If the COMPLETE flag is clear, then there were no active
9018 	 * entries and we want to roll back to a zeroed entry until
9019 	 * the new inode is committed to disk. If the COMPLETE flag is
9020 	 * set then we have deleted an entry that never made it to
9021 	 * disk. If the entry we deleted resulted from a name change,
9022 	 * then the old name still resides on disk. We cannot delete
9023 	 * its inode (returned to us in prevdirrem) until the zeroed
9024 	 * directory entry gets to disk. The new inode has never been
9025 	 * referenced on the disk, so can be deleted immediately.
9026 	 */
9027 	if ((dirrem->dm_state & COMPLETE) == 0) {
9028 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9029 		    dm_next);
9030 		FREE_LOCK(ump);
9031 	} else {
9032 		if (prevdirrem != NULL)
9033 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9034 			    prevdirrem, dm_next);
9035 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9036 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9037 		FREE_LOCK(ump);
9038 		if (direct)
9039 			handle_workitem_remove(dirrem, 0);
9040 	}
9041 }
9042 
9043 /*
9044  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9045  * pd_pendinghd list of a pagedep.
9046  */
9047 static struct diradd *
9048 diradd_lookup(pagedep, offset)
9049 	struct pagedep *pagedep;
9050 	int offset;
9051 {
9052 	struct diradd *dap;
9053 
9054 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9055 		if (dap->da_offset == offset)
9056 			return (dap);
9057 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9058 		if (dap->da_offset == offset)
9059 			return (dap);
9060 	return (NULL);
9061 }
9062 
9063 /*
9064  * Search for a .. diradd dependency in a directory that is being removed.
9065  * If the directory was renamed to a new parent we have a diradd rather
9066  * than a mkdir for the .. entry.  We need to cancel it now before
9067  * it is found in truncate().
9068  */
9069 static struct jremref *
9070 cancel_diradd_dotdot(ip, dirrem, jremref)
9071 	struct inode *ip;
9072 	struct dirrem *dirrem;
9073 	struct jremref *jremref;
9074 {
9075 	struct pagedep *pagedep;
9076 	struct diradd *dap;
9077 	struct worklist *wk;
9078 
9079 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9080 		return (jremref);
9081 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9082 	if (dap == NULL)
9083 		return (jremref);
9084 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9085 	/*
9086 	 * Mark any journal work as belonging to the parent so it is freed
9087 	 * with the .. reference.
9088 	 */
9089 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9090 		wk->wk_state |= MKDIR_PARENT;
9091 	return (NULL);
9092 }
9093 
9094 /*
9095  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9096  * replace it with a dirrem/diradd pair as a result of re-parenting a
9097  * directory.  This ensures that we don't simultaneously have a mkdir and
9098  * a diradd for the same .. entry.
9099  */
9100 static struct jremref *
9101 cancel_mkdir_dotdot(ip, dirrem, jremref)
9102 	struct inode *ip;
9103 	struct dirrem *dirrem;
9104 	struct jremref *jremref;
9105 {
9106 	struct inodedep *inodedep;
9107 	struct jaddref *jaddref;
9108 	struct ufsmount *ump;
9109 	struct mkdir *mkdir;
9110 	struct diradd *dap;
9111 	struct mount *mp;
9112 
9113 	mp = ITOVFS(ip);
9114 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9115 		return (jremref);
9116 	dap = inodedep->id_mkdiradd;
9117 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9118 		return (jremref);
9119 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9120 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9121 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9122 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9123 			break;
9124 	if (mkdir == NULL)
9125 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9126 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9127 		mkdir->md_jaddref = NULL;
9128 		jaddref->ja_state &= ~MKDIR_PARENT;
9129 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9130 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9131 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9132 			journal_jremref(dirrem, jremref, inodedep);
9133 			jremref = NULL;
9134 		}
9135 	}
9136 	if (mkdir->md_state & ONWORKLIST)
9137 		WORKLIST_REMOVE(&mkdir->md_list);
9138 	mkdir->md_state |= ALLCOMPLETE;
9139 	complete_mkdir(mkdir);
9140 	return (jremref);
9141 }
9142 
9143 static void
9144 journal_jremref(dirrem, jremref, inodedep)
9145 	struct dirrem *dirrem;
9146 	struct jremref *jremref;
9147 	struct inodedep *inodedep;
9148 {
9149 
9150 	if (inodedep == NULL)
9151 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9152 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9153 			panic("journal_jremref: Lost inodedep");
9154 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9155 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9156 	add_to_journal(&jremref->jr_list);
9157 }
9158 
9159 static void
9160 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9161 	struct dirrem *dirrem;
9162 	struct jremref *jremref;
9163 	struct jremref *dotremref;
9164 	struct jremref *dotdotremref;
9165 {
9166 	struct inodedep *inodedep;
9167 
9168 
9169 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9170 	    &inodedep) == 0)
9171 		panic("dirrem_journal: Lost inodedep");
9172 	journal_jremref(dirrem, jremref, inodedep);
9173 	if (dotremref)
9174 		journal_jremref(dirrem, dotremref, inodedep);
9175 	if (dotdotremref)
9176 		journal_jremref(dirrem, dotdotremref, NULL);
9177 }
9178 
9179 /*
9180  * Allocate a new dirrem if appropriate and return it along with
9181  * its associated pagedep. Called without a lock, returns with lock.
9182  */
9183 static struct dirrem *
9184 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9185 	struct buf *bp;		/* buffer containing directory block */
9186 	struct inode *dp;	/* inode for the directory being modified */
9187 	struct inode *ip;	/* inode for directory entry being removed */
9188 	int isrmdir;		/* indicates if doing RMDIR */
9189 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9190 {
9191 	int offset;
9192 	ufs_lbn_t lbn;
9193 	struct diradd *dap;
9194 	struct dirrem *dirrem;
9195 	struct pagedep *pagedep;
9196 	struct jremref *jremref;
9197 	struct jremref *dotremref;
9198 	struct jremref *dotdotremref;
9199 	struct vnode *dvp;
9200 	struct ufsmount *ump;
9201 
9202 	/*
9203 	 * Whiteouts have no deletion dependencies.
9204 	 */
9205 	if (ip == NULL)
9206 		panic("newdirrem: whiteout");
9207 	dvp = ITOV(dp);
9208 	ump = ITOUMP(dp);
9209 
9210 	/*
9211 	 * If the system is over its limit and our filesystem is
9212 	 * responsible for more than our share of that usage and
9213 	 * we are not a snapshot, request some inodedep cleanup.
9214 	 * Limiting the number of dirrem structures will also limit
9215 	 * the number of freefile and freeblks structures.
9216 	 */
9217 	ACQUIRE_LOCK(ump);
9218 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9219 		schedule_cleanup(UFSTOVFS(ump));
9220 	else
9221 		FREE_LOCK(ump);
9222 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9223 	    M_ZERO);
9224 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9225 	LIST_INIT(&dirrem->dm_jremrefhd);
9226 	LIST_INIT(&dirrem->dm_jwork);
9227 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9228 	dirrem->dm_oldinum = ip->i_number;
9229 	*prevdirremp = NULL;
9230 	/*
9231 	 * Allocate remove reference structures to track journal write
9232 	 * dependencies.  We will always have one for the link and
9233 	 * when doing directories we will always have one more for dot.
9234 	 * When renaming a directory we skip the dotdot link change so
9235 	 * this is not needed.
9236 	 */
9237 	jremref = dotremref = dotdotremref = NULL;
9238 	if (DOINGSUJ(dvp)) {
9239 		if (isrmdir) {
9240 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9241 			    ip->i_effnlink + 2);
9242 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9243 			    ip->i_effnlink + 1);
9244 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9245 			    dp->i_effnlink + 1);
9246 			dotdotremref->jr_state |= MKDIR_PARENT;
9247 		} else
9248 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9249 			    ip->i_effnlink + 1);
9250 	}
9251 	ACQUIRE_LOCK(ump);
9252 	lbn = lblkno(ump->um_fs, dp->i_offset);
9253 	offset = blkoff(ump->um_fs, dp->i_offset);
9254 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9255 	    &pagedep);
9256 	dirrem->dm_pagedep = pagedep;
9257 	dirrem->dm_offset = offset;
9258 	/*
9259 	 * If we're renaming a .. link to a new directory, cancel any
9260 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9261 	 * the jremref is preserved for any potential diradd in this
9262 	 * location.  This can not coincide with a rmdir.
9263 	 */
9264 	if (dp->i_offset == DOTDOT_OFFSET) {
9265 		if (isrmdir)
9266 			panic("newdirrem: .. directory change during remove?");
9267 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9268 	}
9269 	/*
9270 	 * If we're removing a directory search for the .. dependency now and
9271 	 * cancel it.  Any pending journal work will be added to the dirrem
9272 	 * to be completed when the workitem remove completes.
9273 	 */
9274 	if (isrmdir)
9275 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9276 	/*
9277 	 * Check for a diradd dependency for the same directory entry.
9278 	 * If present, then both dependencies become obsolete and can
9279 	 * be de-allocated.
9280 	 */
9281 	dap = diradd_lookup(pagedep, offset);
9282 	if (dap == NULL) {
9283 		/*
9284 		 * Link the jremref structures into the dirrem so they are
9285 		 * written prior to the pagedep.
9286 		 */
9287 		if (jremref)
9288 			dirrem_journal(dirrem, jremref, dotremref,
9289 			    dotdotremref);
9290 		return (dirrem);
9291 	}
9292 	/*
9293 	 * Must be ATTACHED at this point.
9294 	 */
9295 	if ((dap->da_state & ATTACHED) == 0)
9296 		panic("newdirrem: not ATTACHED");
9297 	if (dap->da_newinum != ip->i_number)
9298 		panic("newdirrem: inum %ju should be %ju",
9299 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9300 	/*
9301 	 * If we are deleting a changed name that never made it to disk,
9302 	 * then return the dirrem describing the previous inode (which
9303 	 * represents the inode currently referenced from this entry on disk).
9304 	 */
9305 	if ((dap->da_state & DIRCHG) != 0) {
9306 		*prevdirremp = dap->da_previous;
9307 		dap->da_state &= ~DIRCHG;
9308 		dap->da_pagedep = pagedep;
9309 	}
9310 	/*
9311 	 * We are deleting an entry that never made it to disk.
9312 	 * Mark it COMPLETE so we can delete its inode immediately.
9313 	 */
9314 	dirrem->dm_state |= COMPLETE;
9315 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9316 #ifdef INVARIANTS
9317 	if (isrmdir == 0) {
9318 		struct worklist *wk;
9319 
9320 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9321 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9322 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9323 	}
9324 #endif
9325 
9326 	return (dirrem);
9327 }
9328 
9329 /*
9330  * Directory entry change dependencies.
9331  *
9332  * Changing an existing directory entry requires that an add operation
9333  * be completed first followed by a deletion. The semantics for the addition
9334  * are identical to the description of adding a new entry above except
9335  * that the rollback is to the old inode number rather than zero. Once
9336  * the addition dependency is completed, the removal is done as described
9337  * in the removal routine above.
9338  */
9339 
9340 /*
9341  * This routine should be called immediately after changing
9342  * a directory entry.  The inode's link count should not be
9343  * decremented by the calling procedure -- the soft updates
9344  * code will perform this task when it is safe.
9345  */
9346 void
9347 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9348 	struct buf *bp;		/* buffer containing directory block */
9349 	struct inode *dp;	/* inode for the directory being modified */
9350 	struct inode *ip;	/* inode for directory entry being removed */
9351 	ino_t newinum;		/* new inode number for changed entry */
9352 	int isrmdir;		/* indicates if doing RMDIR */
9353 {
9354 	int offset;
9355 	struct diradd *dap = NULL;
9356 	struct dirrem *dirrem, *prevdirrem;
9357 	struct pagedep *pagedep;
9358 	struct inodedep *inodedep;
9359 	struct jaddref *jaddref;
9360 	struct mount *mp;
9361 	struct ufsmount *ump;
9362 
9363 	mp = ITOVFS(dp);
9364 	ump = VFSTOUFS(mp);
9365 	offset = blkoff(ump->um_fs, dp->i_offset);
9366 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9367 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9368 
9369 	/*
9370 	 * Whiteouts do not need diradd dependencies.
9371 	 */
9372 	if (newinum != UFS_WINO) {
9373 		dap = malloc(sizeof(struct diradd),
9374 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9375 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9376 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9377 		dap->da_offset = offset;
9378 		dap->da_newinum = newinum;
9379 		LIST_INIT(&dap->da_jwork);
9380 	}
9381 
9382 	/*
9383 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9384 	 */
9385 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9386 	pagedep = dirrem->dm_pagedep;
9387 	/*
9388 	 * The possible values for isrmdir:
9389 	 *	0 - non-directory file rename
9390 	 *	1 - directory rename within same directory
9391 	 *   inum - directory rename to new directory of given inode number
9392 	 * When renaming to a new directory, we are both deleting and
9393 	 * creating a new directory entry, so the link count on the new
9394 	 * directory should not change. Thus we do not need the followup
9395 	 * dirrem which is usually done in handle_workitem_remove. We set
9396 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9397 	 * followup dirrem.
9398 	 */
9399 	if (isrmdir > 1)
9400 		dirrem->dm_state |= DIRCHG;
9401 
9402 	/*
9403 	 * Whiteouts have no additional dependencies,
9404 	 * so just put the dirrem on the correct list.
9405 	 */
9406 	if (newinum == UFS_WINO) {
9407 		if ((dirrem->dm_state & COMPLETE) == 0) {
9408 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9409 			    dm_next);
9410 		} else {
9411 			dirrem->dm_dirinum = pagedep->pd_ino;
9412 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9413 				add_to_worklist(&dirrem->dm_list, 0);
9414 		}
9415 		FREE_LOCK(ump);
9416 		return;
9417 	}
9418 	/*
9419 	 * Add the dirrem to the inodedep's pending remove list for quick
9420 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9421 	 * will not fail.
9422 	 */
9423 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9424 		panic("softdep_setup_directory_change: Lost inodedep.");
9425 	dirrem->dm_state |= ONDEPLIST;
9426 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9427 
9428 	/*
9429 	 * If the COMPLETE flag is clear, then there were no active
9430 	 * entries and we want to roll back to the previous inode until
9431 	 * the new inode is committed to disk. If the COMPLETE flag is
9432 	 * set, then we have deleted an entry that never made it to disk.
9433 	 * If the entry we deleted resulted from a name change, then the old
9434 	 * inode reference still resides on disk. Any rollback that we do
9435 	 * needs to be to that old inode (returned to us in prevdirrem). If
9436 	 * the entry we deleted resulted from a create, then there is
9437 	 * no entry on the disk, so we want to roll back to zero rather
9438 	 * than the uncommitted inode. In either of the COMPLETE cases we
9439 	 * want to immediately free the unwritten and unreferenced inode.
9440 	 */
9441 	if ((dirrem->dm_state & COMPLETE) == 0) {
9442 		dap->da_previous = dirrem;
9443 	} else {
9444 		if (prevdirrem != NULL) {
9445 			dap->da_previous = prevdirrem;
9446 		} else {
9447 			dap->da_state &= ~DIRCHG;
9448 			dap->da_pagedep = pagedep;
9449 		}
9450 		dirrem->dm_dirinum = pagedep->pd_ino;
9451 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9452 			add_to_worklist(&dirrem->dm_list, 0);
9453 	}
9454 	/*
9455 	 * Lookup the jaddref for this journal entry.  We must finish
9456 	 * initializing it and make the diradd write dependent on it.
9457 	 * If we're not journaling, put it on the id_bufwait list if the
9458 	 * inode is not yet written. If it is written, do the post-inode
9459 	 * write processing to put it on the id_pendinghd list.
9460 	 */
9461 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9462 	if (MOUNTEDSUJ(mp)) {
9463 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9464 		    inoreflst);
9465 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9466 		    ("softdep_setup_directory_change: bad jaddref %p",
9467 		    jaddref));
9468 		jaddref->ja_diroff = dp->i_offset;
9469 		jaddref->ja_diradd = dap;
9470 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9471 		    dap, da_pdlist);
9472 		add_to_journal(&jaddref->ja_list);
9473 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9474 		dap->da_state |= COMPLETE;
9475 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9476 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9477 	} else {
9478 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9479 		    dap, da_pdlist);
9480 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9481 	}
9482 	/*
9483 	 * If we're making a new name for a directory that has not been
9484 	 * committed when need to move the dot and dotdot references to
9485 	 * this new name.
9486 	 */
9487 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9488 		merge_diradd(inodedep, dap);
9489 	FREE_LOCK(ump);
9490 }
9491 
9492 /*
9493  * Called whenever the link count on an inode is changed.
9494  * It creates an inode dependency so that the new reference(s)
9495  * to the inode cannot be committed to disk until the updated
9496  * inode has been written.
9497  */
9498 void
9499 softdep_change_linkcnt(ip)
9500 	struct inode *ip;	/* the inode with the increased link count */
9501 {
9502 	struct inodedep *inodedep;
9503 	struct ufsmount *ump;
9504 
9505 	ump = ITOUMP(ip);
9506 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9507 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9508 	ACQUIRE_LOCK(ump);
9509 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9510 	if (ip->i_nlink < ip->i_effnlink)
9511 		panic("softdep_change_linkcnt: bad delta");
9512 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9513 	FREE_LOCK(ump);
9514 }
9515 
9516 /*
9517  * Attach a sbdep dependency to the superblock buf so that we can keep
9518  * track of the head of the linked list of referenced but unlinked inodes.
9519  */
9520 void
9521 softdep_setup_sbupdate(ump, fs, bp)
9522 	struct ufsmount *ump;
9523 	struct fs *fs;
9524 	struct buf *bp;
9525 {
9526 	struct sbdep *sbdep;
9527 	struct worklist *wk;
9528 
9529 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9530 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9531 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9532 		if (wk->wk_type == D_SBDEP)
9533 			break;
9534 	if (wk != NULL)
9535 		return;
9536 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9537 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9538 	sbdep->sb_fs = fs;
9539 	sbdep->sb_ump = ump;
9540 	ACQUIRE_LOCK(ump);
9541 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9542 	FREE_LOCK(ump);
9543 }
9544 
9545 /*
9546  * Return the first unlinked inodedep which is ready to be the head of the
9547  * list.  The inodedep and all those after it must have valid next pointers.
9548  */
9549 static struct inodedep *
9550 first_unlinked_inodedep(ump)
9551 	struct ufsmount *ump;
9552 {
9553 	struct inodedep *inodedep;
9554 	struct inodedep *idp;
9555 
9556 	LOCK_OWNED(ump);
9557 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9558 	    inodedep; inodedep = idp) {
9559 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9560 			return (NULL);
9561 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9562 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9563 			break;
9564 		if ((inodedep->id_state & UNLINKPREV) == 0)
9565 			break;
9566 	}
9567 	return (inodedep);
9568 }
9569 
9570 /*
9571  * Set the sujfree unlinked head pointer prior to writing a superblock.
9572  */
9573 static void
9574 initiate_write_sbdep(sbdep)
9575 	struct sbdep *sbdep;
9576 {
9577 	struct inodedep *inodedep;
9578 	struct fs *bpfs;
9579 	struct fs *fs;
9580 
9581 	bpfs = sbdep->sb_fs;
9582 	fs = sbdep->sb_ump->um_fs;
9583 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9584 	if (inodedep) {
9585 		fs->fs_sujfree = inodedep->id_ino;
9586 		inodedep->id_state |= UNLINKPREV;
9587 	} else
9588 		fs->fs_sujfree = 0;
9589 	bpfs->fs_sujfree = fs->fs_sujfree;
9590 }
9591 
9592 /*
9593  * After a superblock is written determine whether it must be written again
9594  * due to a changing unlinked list head.
9595  */
9596 static int
9597 handle_written_sbdep(sbdep, bp)
9598 	struct sbdep *sbdep;
9599 	struct buf *bp;
9600 {
9601 	struct inodedep *inodedep;
9602 	struct fs *fs;
9603 
9604 	LOCK_OWNED(sbdep->sb_ump);
9605 	fs = sbdep->sb_fs;
9606 	/*
9607 	 * If the superblock doesn't match the in-memory list start over.
9608 	 */
9609 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9610 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9611 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9612 		bdirty(bp);
9613 		return (1);
9614 	}
9615 	WORKITEM_FREE(sbdep, D_SBDEP);
9616 	if (fs->fs_sujfree == 0)
9617 		return (0);
9618 	/*
9619 	 * Now that we have a record of this inode in stable store allow it
9620 	 * to be written to free up pending work.  Inodes may see a lot of
9621 	 * write activity after they are unlinked which we must not hold up.
9622 	 */
9623 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9624 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9625 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9626 			    inodedep, inodedep->id_state);
9627 		if (inodedep->id_state & UNLINKONLIST)
9628 			break;
9629 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9630 	}
9631 
9632 	return (0);
9633 }
9634 
9635 /*
9636  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9637  */
9638 static void
9639 unlinked_inodedep(mp, inodedep)
9640 	struct mount *mp;
9641 	struct inodedep *inodedep;
9642 {
9643 	struct ufsmount *ump;
9644 
9645 	ump = VFSTOUFS(mp);
9646 	LOCK_OWNED(ump);
9647 	if (MOUNTEDSUJ(mp) == 0)
9648 		return;
9649 	ump->um_fs->fs_fmod = 1;
9650 	if (inodedep->id_state & UNLINKED)
9651 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9652 	inodedep->id_state |= UNLINKED;
9653 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9654 }
9655 
9656 /*
9657  * Remove an inodedep from the unlinked inodedep list.  This may require
9658  * disk writes if the inode has made it that far.
9659  */
9660 static void
9661 clear_unlinked_inodedep(inodedep)
9662 	struct inodedep *inodedep;
9663 {
9664 	struct ufs2_dinode *dip;
9665 	struct ufsmount *ump;
9666 	struct inodedep *idp;
9667 	struct inodedep *idn;
9668 	struct fs *fs;
9669 	struct buf *bp;
9670 	ino_t ino;
9671 	ino_t nino;
9672 	ino_t pino;
9673 	int error;
9674 
9675 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9676 	fs = ump->um_fs;
9677 	ino = inodedep->id_ino;
9678 	error = 0;
9679 	for (;;) {
9680 		LOCK_OWNED(ump);
9681 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9682 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9683 		    inodedep));
9684 		/*
9685 		 * If nothing has yet been written simply remove us from
9686 		 * the in memory list and return.  This is the most common
9687 		 * case where handle_workitem_remove() loses the final
9688 		 * reference.
9689 		 */
9690 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9691 			break;
9692 		/*
9693 		 * If we have a NEXT pointer and no PREV pointer we can simply
9694 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9695 		 * careful not to clear PREV if the superblock points at
9696 		 * next as well.
9697 		 */
9698 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9699 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9700 			if (idn && fs->fs_sujfree != idn->id_ino)
9701 				idn->id_state &= ~UNLINKPREV;
9702 			break;
9703 		}
9704 		/*
9705 		 * Here we have an inodedep which is actually linked into
9706 		 * the list.  We must remove it by forcing a write to the
9707 		 * link before us, whether it be the superblock or an inode.
9708 		 * Unfortunately the list may change while we're waiting
9709 		 * on the buf lock for either resource so we must loop until
9710 		 * we lock the right one.  If both the superblock and an
9711 		 * inode point to this inode we must clear the inode first
9712 		 * followed by the superblock.
9713 		 */
9714 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9715 		pino = 0;
9716 		if (idp && (idp->id_state & UNLINKNEXT))
9717 			pino = idp->id_ino;
9718 		FREE_LOCK(ump);
9719 		if (pino == 0) {
9720 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9721 			    (int)fs->fs_sbsize, 0, 0, 0);
9722 		} else {
9723 			error = bread(ump->um_devvp,
9724 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9725 			    (int)fs->fs_bsize, NOCRED, &bp);
9726 			if (error)
9727 				brelse(bp);
9728 		}
9729 		ACQUIRE_LOCK(ump);
9730 		if (error)
9731 			break;
9732 		/* If the list has changed restart the loop. */
9733 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9734 		nino = 0;
9735 		if (idp && (idp->id_state & UNLINKNEXT))
9736 			nino = idp->id_ino;
9737 		if (nino != pino ||
9738 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9739 			FREE_LOCK(ump);
9740 			brelse(bp);
9741 			ACQUIRE_LOCK(ump);
9742 			continue;
9743 		}
9744 		nino = 0;
9745 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9746 		if (idn)
9747 			nino = idn->id_ino;
9748 		/*
9749 		 * Remove us from the in memory list.  After this we cannot
9750 		 * access the inodedep.
9751 		 */
9752 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9753 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9754 		    inodedep));
9755 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9756 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9757 		FREE_LOCK(ump);
9758 		/*
9759 		 * The predecessor's next pointer is manually updated here
9760 		 * so that the NEXT flag is never cleared for an element
9761 		 * that is in the list.
9762 		 */
9763 		if (pino == 0) {
9764 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9765 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9766 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9767 			    bp);
9768 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
9769 			((struct ufs1_dinode *)bp->b_data +
9770 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9771 		} else {
9772 			dip = (struct ufs2_dinode *)bp->b_data +
9773 			    ino_to_fsbo(fs, pino);
9774 			dip->di_freelink = nino;
9775 			ffs_update_dinode_ckhash(fs, dip);
9776 		}
9777 		/*
9778 		 * If the bwrite fails we have no recourse to recover.  The
9779 		 * filesystem is corrupted already.
9780 		 */
9781 		bwrite(bp);
9782 		ACQUIRE_LOCK(ump);
9783 		/*
9784 		 * If the superblock pointer still needs to be cleared force
9785 		 * a write here.
9786 		 */
9787 		if (fs->fs_sujfree == ino) {
9788 			FREE_LOCK(ump);
9789 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9790 			    (int)fs->fs_sbsize, 0, 0, 0);
9791 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9792 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9793 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9794 			    bp);
9795 			bwrite(bp);
9796 			ACQUIRE_LOCK(ump);
9797 		}
9798 
9799 		if (fs->fs_sujfree != ino)
9800 			return;
9801 		panic("clear_unlinked_inodedep: Failed to clear free head");
9802 	}
9803 	if (inodedep->id_ino == fs->fs_sujfree)
9804 		panic("clear_unlinked_inodedep: Freeing head of free list");
9805 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9806 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9807 	return;
9808 }
9809 
9810 /*
9811  * This workitem decrements the inode's link count.
9812  * If the link count reaches zero, the file is removed.
9813  */
9814 static int
9815 handle_workitem_remove(dirrem, flags)
9816 	struct dirrem *dirrem;
9817 	int flags;
9818 {
9819 	struct inodedep *inodedep;
9820 	struct workhead dotdotwk;
9821 	struct worklist *wk;
9822 	struct ufsmount *ump;
9823 	struct mount *mp;
9824 	struct vnode *vp;
9825 	struct inode *ip;
9826 	ino_t oldinum;
9827 
9828 	if (dirrem->dm_state & ONWORKLIST)
9829 		panic("handle_workitem_remove: dirrem %p still on worklist",
9830 		    dirrem);
9831 	oldinum = dirrem->dm_oldinum;
9832 	mp = dirrem->dm_list.wk_mp;
9833 	ump = VFSTOUFS(mp);
9834 	flags |= LK_EXCLUSIVE;
9835 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9836 		return (EBUSY);
9837 	ip = VTOI(vp);
9838 	ACQUIRE_LOCK(ump);
9839 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9840 		panic("handle_workitem_remove: lost inodedep");
9841 	if (dirrem->dm_state & ONDEPLIST)
9842 		LIST_REMOVE(dirrem, dm_inonext);
9843 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9844 	    ("handle_workitem_remove:  Journal entries not written."));
9845 
9846 	/*
9847 	 * Move all dependencies waiting on the remove to complete
9848 	 * from the dirrem to the inode inowait list to be completed
9849 	 * after the inode has been updated and written to disk.  Any
9850 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9851 	 * is removed.
9852 	 */
9853 	LIST_INIT(&dotdotwk);
9854 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9855 		WORKLIST_REMOVE(wk);
9856 		if (wk->wk_state & MKDIR_PARENT) {
9857 			wk->wk_state &= ~MKDIR_PARENT;
9858 			WORKLIST_INSERT(&dotdotwk, wk);
9859 			continue;
9860 		}
9861 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9862 	}
9863 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9864 	/*
9865 	 * Normal file deletion.
9866 	 */
9867 	if ((dirrem->dm_state & RMDIR) == 0) {
9868 		ip->i_nlink--;
9869 		DIP_SET(ip, i_nlink, ip->i_nlink);
9870 		ip->i_flag |= IN_CHANGE;
9871 		if (ip->i_nlink < ip->i_effnlink)
9872 			panic("handle_workitem_remove: bad file delta");
9873 		if (ip->i_nlink == 0)
9874 			unlinked_inodedep(mp, inodedep);
9875 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9876 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9877 		    ("handle_workitem_remove: worklist not empty. %s",
9878 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9879 		WORKITEM_FREE(dirrem, D_DIRREM);
9880 		FREE_LOCK(ump);
9881 		goto out;
9882 	}
9883 	/*
9884 	 * Directory deletion. Decrement reference count for both the
9885 	 * just deleted parent directory entry and the reference for ".".
9886 	 * Arrange to have the reference count on the parent decremented
9887 	 * to account for the loss of "..".
9888 	 */
9889 	ip->i_nlink -= 2;
9890 	DIP_SET(ip, i_nlink, ip->i_nlink);
9891 	ip->i_flag |= IN_CHANGE;
9892 	if (ip->i_nlink < ip->i_effnlink)
9893 		panic("handle_workitem_remove: bad dir delta");
9894 	if (ip->i_nlink == 0)
9895 		unlinked_inodedep(mp, inodedep);
9896 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9897 	/*
9898 	 * Rename a directory to a new parent. Since, we are both deleting
9899 	 * and creating a new directory entry, the link count on the new
9900 	 * directory should not change. Thus we skip the followup dirrem.
9901 	 */
9902 	if (dirrem->dm_state & DIRCHG) {
9903 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9904 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9905 		WORKITEM_FREE(dirrem, D_DIRREM);
9906 		FREE_LOCK(ump);
9907 		goto out;
9908 	}
9909 	dirrem->dm_state = ONDEPLIST;
9910 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9911 	/*
9912 	 * Place the dirrem on the parent's diremhd list.
9913 	 */
9914 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9915 		panic("handle_workitem_remove: lost dir inodedep");
9916 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9917 	/*
9918 	 * If the allocated inode has never been written to disk, then
9919 	 * the on-disk inode is zero'ed and we can remove the file
9920 	 * immediately.  When journaling if the inode has been marked
9921 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9922 	 */
9923 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9924 	if (inodedep == NULL ||
9925 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9926 	    check_inode_unwritten(inodedep)) {
9927 		FREE_LOCK(ump);
9928 		vput(vp);
9929 		return handle_workitem_remove(dirrem, flags);
9930 	}
9931 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9932 	FREE_LOCK(ump);
9933 	ip->i_flag |= IN_CHANGE;
9934 out:
9935 	ffs_update(vp, 0);
9936 	vput(vp);
9937 	return (0);
9938 }
9939 
9940 /*
9941  * Inode de-allocation dependencies.
9942  *
9943  * When an inode's link count is reduced to zero, it can be de-allocated. We
9944  * found it convenient to postpone de-allocation until after the inode is
9945  * written to disk with its new link count (zero).  At this point, all of the
9946  * on-disk inode's block pointers are nullified and, with careful dependency
9947  * list ordering, all dependencies related to the inode will be satisfied and
9948  * the corresponding dependency structures de-allocated.  So, if/when the
9949  * inode is reused, there will be no mixing of old dependencies with new
9950  * ones.  This artificial dependency is set up by the block de-allocation
9951  * procedure above (softdep_setup_freeblocks) and completed by the
9952  * following procedure.
9953  */
9954 static void
9955 handle_workitem_freefile(freefile)
9956 	struct freefile *freefile;
9957 {
9958 	struct workhead wkhd;
9959 	struct fs *fs;
9960 	struct ufsmount *ump;
9961 	int error;
9962 #ifdef INVARIANTS
9963 	struct inodedep *idp;
9964 #endif
9965 
9966 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9967 	fs = ump->um_fs;
9968 #ifdef INVARIANTS
9969 	ACQUIRE_LOCK(ump);
9970 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9971 	FREE_LOCK(ump);
9972 	if (error)
9973 		panic("handle_workitem_freefile: inodedep %p survived", idp);
9974 #endif
9975 	UFS_LOCK(ump);
9976 	fs->fs_pendinginodes -= 1;
9977 	UFS_UNLOCK(ump);
9978 	LIST_INIT(&wkhd);
9979 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9980 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9981 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9982 		softdep_error("handle_workitem_freefile", error);
9983 	ACQUIRE_LOCK(ump);
9984 	WORKITEM_FREE(freefile, D_FREEFILE);
9985 	FREE_LOCK(ump);
9986 }
9987 
9988 
9989 /*
9990  * Helper function which unlinks marker element from work list and returns
9991  * the next element on the list.
9992  */
9993 static __inline struct worklist *
9994 markernext(struct worklist *marker)
9995 {
9996 	struct worklist *next;
9997 
9998 	next = LIST_NEXT(marker, wk_list);
9999 	LIST_REMOVE(marker, wk_list);
10000 	return next;
10001 }
10002 
10003 /*
10004  * Disk writes.
10005  *
10006  * The dependency structures constructed above are most actively used when file
10007  * system blocks are written to disk.  No constraints are placed on when a
10008  * block can be written, but unsatisfied update dependencies are made safe by
10009  * modifying (or replacing) the source memory for the duration of the disk
10010  * write.  When the disk write completes, the memory block is again brought
10011  * up-to-date.
10012  *
10013  * In-core inode structure reclamation.
10014  *
10015  * Because there are a finite number of "in-core" inode structures, they are
10016  * reused regularly.  By transferring all inode-related dependencies to the
10017  * in-memory inode block and indexing them separately (via "inodedep"s), we
10018  * can allow "in-core" inode structures to be reused at any time and avoid
10019  * any increase in contention.
10020  *
10021  * Called just before entering the device driver to initiate a new disk I/O.
10022  * The buffer must be locked, thus, no I/O completion operations can occur
10023  * while we are manipulating its associated dependencies.
10024  */
10025 static void
10026 softdep_disk_io_initiation(bp)
10027 	struct buf *bp;		/* structure describing disk write to occur */
10028 {
10029 	struct worklist *wk;
10030 	struct worklist marker;
10031 	struct inodedep *inodedep;
10032 	struct freeblks *freeblks;
10033 	struct jblkdep *jblkdep;
10034 	struct newblk *newblk;
10035 	struct ufsmount *ump;
10036 
10037 	/*
10038 	 * We only care about write operations. There should never
10039 	 * be dependencies for reads.
10040 	 */
10041 	if (bp->b_iocmd != BIO_WRITE)
10042 		panic("softdep_disk_io_initiation: not write");
10043 
10044 	if (bp->b_vflags & BV_BKGRDINPROG)
10045 		panic("softdep_disk_io_initiation: Writing buffer with "
10046 		    "background write in progress: %p", bp);
10047 
10048 	ump = softdep_bp_to_mp(bp);
10049 	if (ump == NULL)
10050 		return;
10051 
10052 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10053 	PHOLD(curproc);			/* Don't swap out kernel stack */
10054 	ACQUIRE_LOCK(ump);
10055 	/*
10056 	 * Do any necessary pre-I/O processing.
10057 	 */
10058 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10059 	     wk = markernext(&marker)) {
10060 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10061 		switch (wk->wk_type) {
10062 
10063 		case D_PAGEDEP:
10064 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10065 			continue;
10066 
10067 		case D_INODEDEP:
10068 			inodedep = WK_INODEDEP(wk);
10069 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10070 				initiate_write_inodeblock_ufs1(inodedep, bp);
10071 			else
10072 				initiate_write_inodeblock_ufs2(inodedep, bp);
10073 			continue;
10074 
10075 		case D_INDIRDEP:
10076 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10077 			continue;
10078 
10079 		case D_BMSAFEMAP:
10080 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10081 			continue;
10082 
10083 		case D_JSEG:
10084 			WK_JSEG(wk)->js_buf = NULL;
10085 			continue;
10086 
10087 		case D_FREEBLKS:
10088 			freeblks = WK_FREEBLKS(wk);
10089 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10090 			/*
10091 			 * We have to wait for the freeblks to be journaled
10092 			 * before we can write an inodeblock with updated
10093 			 * pointers.  Be careful to arrange the marker so
10094 			 * we revisit the freeblks if it's not removed by
10095 			 * the first jwait().
10096 			 */
10097 			if (jblkdep != NULL) {
10098 				LIST_REMOVE(&marker, wk_list);
10099 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10100 				jwait(&jblkdep->jb_list, MNT_WAIT);
10101 			}
10102 			continue;
10103 		case D_ALLOCDIRECT:
10104 		case D_ALLOCINDIR:
10105 			/*
10106 			 * We have to wait for the jnewblk to be journaled
10107 			 * before we can write to a block if the contents
10108 			 * may be confused with an earlier file's indirect
10109 			 * at recovery time.  Handle the marker as described
10110 			 * above.
10111 			 */
10112 			newblk = WK_NEWBLK(wk);
10113 			if (newblk->nb_jnewblk != NULL &&
10114 			    indirblk_lookup(newblk->nb_list.wk_mp,
10115 			    newblk->nb_newblkno)) {
10116 				LIST_REMOVE(&marker, wk_list);
10117 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10118 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10119 			}
10120 			continue;
10121 
10122 		case D_SBDEP:
10123 			initiate_write_sbdep(WK_SBDEP(wk));
10124 			continue;
10125 
10126 		case D_MKDIR:
10127 		case D_FREEWORK:
10128 		case D_FREEDEP:
10129 		case D_JSEGDEP:
10130 			continue;
10131 
10132 		default:
10133 			panic("handle_disk_io_initiation: Unexpected type %s",
10134 			    TYPENAME(wk->wk_type));
10135 			/* NOTREACHED */
10136 		}
10137 	}
10138 	FREE_LOCK(ump);
10139 	PRELE(curproc);			/* Allow swapout of kernel stack */
10140 }
10141 
10142 /*
10143  * Called from within the procedure above to deal with unsatisfied
10144  * allocation dependencies in a directory. The buffer must be locked,
10145  * thus, no I/O completion operations can occur while we are
10146  * manipulating its associated dependencies.
10147  */
10148 static void
10149 initiate_write_filepage(pagedep, bp)
10150 	struct pagedep *pagedep;
10151 	struct buf *bp;
10152 {
10153 	struct jremref *jremref;
10154 	struct jmvref *jmvref;
10155 	struct dirrem *dirrem;
10156 	struct diradd *dap;
10157 	struct direct *ep;
10158 	int i;
10159 
10160 	if (pagedep->pd_state & IOSTARTED) {
10161 		/*
10162 		 * This can only happen if there is a driver that does not
10163 		 * understand chaining. Here biodone will reissue the call
10164 		 * to strategy for the incomplete buffers.
10165 		 */
10166 		printf("initiate_write_filepage: already started\n");
10167 		return;
10168 	}
10169 	pagedep->pd_state |= IOSTARTED;
10170 	/*
10171 	 * Wait for all journal remove dependencies to hit the disk.
10172 	 * We can not allow any potentially conflicting directory adds
10173 	 * to be visible before removes and rollback is too difficult.
10174 	 * The per-filesystem lock may be dropped and re-acquired, however
10175 	 * we hold the buf locked so the dependency can not go away.
10176 	 */
10177 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10178 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10179 			jwait(&jremref->jr_list, MNT_WAIT);
10180 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10181 		jwait(&jmvref->jm_list, MNT_WAIT);
10182 	for (i = 0; i < DAHASHSZ; i++) {
10183 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10184 			ep = (struct direct *)
10185 			    ((char *)bp->b_data + dap->da_offset);
10186 			if (ep->d_ino != dap->da_newinum)
10187 				panic("%s: dir inum %ju != new %ju",
10188 				    "initiate_write_filepage",
10189 				    (uintmax_t)ep->d_ino,
10190 				    (uintmax_t)dap->da_newinum);
10191 			if (dap->da_state & DIRCHG)
10192 				ep->d_ino = dap->da_previous->dm_oldinum;
10193 			else
10194 				ep->d_ino = 0;
10195 			dap->da_state &= ~ATTACHED;
10196 			dap->da_state |= UNDONE;
10197 		}
10198 	}
10199 }
10200 
10201 /*
10202  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10203  * Note that any bug fixes made to this routine must be done in the
10204  * version found below.
10205  *
10206  * Called from within the procedure above to deal with unsatisfied
10207  * allocation dependencies in an inodeblock. The buffer must be
10208  * locked, thus, no I/O completion operations can occur while we
10209  * are manipulating its associated dependencies.
10210  */
10211 static void
10212 initiate_write_inodeblock_ufs1(inodedep, bp)
10213 	struct inodedep *inodedep;
10214 	struct buf *bp;			/* The inode block */
10215 {
10216 	struct allocdirect *adp, *lastadp;
10217 	struct ufs1_dinode *dp;
10218 	struct ufs1_dinode *sip;
10219 	struct inoref *inoref;
10220 	struct ufsmount *ump;
10221 	struct fs *fs;
10222 	ufs_lbn_t i;
10223 #ifdef INVARIANTS
10224 	ufs_lbn_t prevlbn = 0;
10225 #endif
10226 	int deplist;
10227 
10228 	if (inodedep->id_state & IOSTARTED)
10229 		panic("initiate_write_inodeblock_ufs1: already started");
10230 	inodedep->id_state |= IOSTARTED;
10231 	fs = inodedep->id_fs;
10232 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10233 	LOCK_OWNED(ump);
10234 	dp = (struct ufs1_dinode *)bp->b_data +
10235 	    ino_to_fsbo(fs, inodedep->id_ino);
10236 
10237 	/*
10238 	 * If we're on the unlinked list but have not yet written our
10239 	 * next pointer initialize it here.
10240 	 */
10241 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10242 		struct inodedep *inon;
10243 
10244 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10245 		dp->di_freelink = inon ? inon->id_ino : 0;
10246 	}
10247 	/*
10248 	 * If the bitmap is not yet written, then the allocated
10249 	 * inode cannot be written to disk.
10250 	 */
10251 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10252 		if (inodedep->id_savedino1 != NULL)
10253 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10254 		FREE_LOCK(ump);
10255 		sip = malloc(sizeof(struct ufs1_dinode),
10256 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10257 		ACQUIRE_LOCK(ump);
10258 		inodedep->id_savedino1 = sip;
10259 		*inodedep->id_savedino1 = *dp;
10260 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10261 		dp->di_gen = inodedep->id_savedino1->di_gen;
10262 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10263 		return;
10264 	}
10265 	/*
10266 	 * If no dependencies, then there is nothing to roll back.
10267 	 */
10268 	inodedep->id_savedsize = dp->di_size;
10269 	inodedep->id_savedextsize = 0;
10270 	inodedep->id_savednlink = dp->di_nlink;
10271 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10272 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10273 		return;
10274 	/*
10275 	 * Revert the link count to that of the first unwritten journal entry.
10276 	 */
10277 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10278 	if (inoref)
10279 		dp->di_nlink = inoref->if_nlink;
10280 	/*
10281 	 * Set the dependencies to busy.
10282 	 */
10283 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10284 	     adp = TAILQ_NEXT(adp, ad_next)) {
10285 #ifdef INVARIANTS
10286 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10287 			panic("softdep_write_inodeblock: lbn order");
10288 		prevlbn = adp->ad_offset;
10289 		if (adp->ad_offset < UFS_NDADDR &&
10290 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10291 			panic("initiate_write_inodeblock_ufs1: "
10292 			    "direct pointer #%jd mismatch %d != %jd",
10293 			    (intmax_t)adp->ad_offset,
10294 			    dp->di_db[adp->ad_offset],
10295 			    (intmax_t)adp->ad_newblkno);
10296 		if (adp->ad_offset >= UFS_NDADDR &&
10297 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10298 			panic("initiate_write_inodeblock_ufs1: "
10299 			    "indirect pointer #%jd mismatch %d != %jd",
10300 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10301 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10302 			    (intmax_t)adp->ad_newblkno);
10303 		deplist |= 1 << adp->ad_offset;
10304 		if ((adp->ad_state & ATTACHED) == 0)
10305 			panic("initiate_write_inodeblock_ufs1: "
10306 			    "Unknown state 0x%x", adp->ad_state);
10307 #endif /* INVARIANTS */
10308 		adp->ad_state &= ~ATTACHED;
10309 		adp->ad_state |= UNDONE;
10310 	}
10311 	/*
10312 	 * The on-disk inode cannot claim to be any larger than the last
10313 	 * fragment that has been written. Otherwise, the on-disk inode
10314 	 * might have fragments that were not the last block in the file
10315 	 * which would corrupt the filesystem.
10316 	 */
10317 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10318 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10319 		if (adp->ad_offset >= UFS_NDADDR)
10320 			break;
10321 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10322 		/* keep going until hitting a rollback to a frag */
10323 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10324 			continue;
10325 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10326 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10327 #ifdef INVARIANTS
10328 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10329 				panic("initiate_write_inodeblock_ufs1: "
10330 				    "lost dep1");
10331 #endif /* INVARIANTS */
10332 			dp->di_db[i] = 0;
10333 		}
10334 		for (i = 0; i < UFS_NIADDR; i++) {
10335 #ifdef INVARIANTS
10336 			if (dp->di_ib[i] != 0 &&
10337 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10338 				panic("initiate_write_inodeblock_ufs1: "
10339 				    "lost dep2");
10340 #endif /* INVARIANTS */
10341 			dp->di_ib[i] = 0;
10342 		}
10343 		return;
10344 	}
10345 	/*
10346 	 * If we have zero'ed out the last allocated block of the file,
10347 	 * roll back the size to the last currently allocated block.
10348 	 * We know that this last allocated block is a full-sized as
10349 	 * we already checked for fragments in the loop above.
10350 	 */
10351 	if (lastadp != NULL &&
10352 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10353 		for (i = lastadp->ad_offset; i >= 0; i--)
10354 			if (dp->di_db[i] != 0)
10355 				break;
10356 		dp->di_size = (i + 1) * fs->fs_bsize;
10357 	}
10358 	/*
10359 	 * The only dependencies are for indirect blocks.
10360 	 *
10361 	 * The file size for indirect block additions is not guaranteed.
10362 	 * Such a guarantee would be non-trivial to achieve. The conventional
10363 	 * synchronous write implementation also does not make this guarantee.
10364 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10365 	 * can be over-estimated without destroying integrity when the file
10366 	 * moves into the indirect blocks (i.e., is large). If we want to
10367 	 * postpone fsck, we are stuck with this argument.
10368 	 */
10369 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10370 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10371 }
10372 
10373 /*
10374  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10375  * Note that any bug fixes made to this routine must be done in the
10376  * version found above.
10377  *
10378  * Called from within the procedure above to deal with unsatisfied
10379  * allocation dependencies in an inodeblock. The buffer must be
10380  * locked, thus, no I/O completion operations can occur while we
10381  * are manipulating its associated dependencies.
10382  */
10383 static void
10384 initiate_write_inodeblock_ufs2(inodedep, bp)
10385 	struct inodedep *inodedep;
10386 	struct buf *bp;			/* The inode block */
10387 {
10388 	struct allocdirect *adp, *lastadp;
10389 	struct ufs2_dinode *dp;
10390 	struct ufs2_dinode *sip;
10391 	struct inoref *inoref;
10392 	struct ufsmount *ump;
10393 	struct fs *fs;
10394 	ufs_lbn_t i;
10395 #ifdef INVARIANTS
10396 	ufs_lbn_t prevlbn = 0;
10397 #endif
10398 	int deplist;
10399 
10400 	if (inodedep->id_state & IOSTARTED)
10401 		panic("initiate_write_inodeblock_ufs2: already started");
10402 	inodedep->id_state |= IOSTARTED;
10403 	fs = inodedep->id_fs;
10404 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10405 	LOCK_OWNED(ump);
10406 	dp = (struct ufs2_dinode *)bp->b_data +
10407 	    ino_to_fsbo(fs, inodedep->id_ino);
10408 
10409 	/*
10410 	 * If we're on the unlinked list but have not yet written our
10411 	 * next pointer initialize it here.
10412 	 */
10413 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10414 		struct inodedep *inon;
10415 
10416 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10417 		dp->di_freelink = inon ? inon->id_ino : 0;
10418 		ffs_update_dinode_ckhash(fs, dp);
10419 	}
10420 	/*
10421 	 * If the bitmap is not yet written, then the allocated
10422 	 * inode cannot be written to disk.
10423 	 */
10424 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10425 		if (inodedep->id_savedino2 != NULL)
10426 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10427 		FREE_LOCK(ump);
10428 		sip = malloc(sizeof(struct ufs2_dinode),
10429 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10430 		ACQUIRE_LOCK(ump);
10431 		inodedep->id_savedino2 = sip;
10432 		*inodedep->id_savedino2 = *dp;
10433 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10434 		dp->di_gen = inodedep->id_savedino2->di_gen;
10435 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10436 		return;
10437 	}
10438 	/*
10439 	 * If no dependencies, then there is nothing to roll back.
10440 	 */
10441 	inodedep->id_savedsize = dp->di_size;
10442 	inodedep->id_savedextsize = dp->di_extsize;
10443 	inodedep->id_savednlink = dp->di_nlink;
10444 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10445 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10446 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10447 		return;
10448 	/*
10449 	 * Revert the link count to that of the first unwritten journal entry.
10450 	 */
10451 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10452 	if (inoref)
10453 		dp->di_nlink = inoref->if_nlink;
10454 
10455 	/*
10456 	 * Set the ext data dependencies to busy.
10457 	 */
10458 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10459 	     adp = TAILQ_NEXT(adp, ad_next)) {
10460 #ifdef INVARIANTS
10461 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10462 			panic("initiate_write_inodeblock_ufs2: lbn order");
10463 		prevlbn = adp->ad_offset;
10464 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10465 			panic("initiate_write_inodeblock_ufs2: "
10466 			    "ext pointer #%jd mismatch %jd != %jd",
10467 			    (intmax_t)adp->ad_offset,
10468 			    (intmax_t)dp->di_extb[adp->ad_offset],
10469 			    (intmax_t)adp->ad_newblkno);
10470 		deplist |= 1 << adp->ad_offset;
10471 		if ((adp->ad_state & ATTACHED) == 0)
10472 			panic("initiate_write_inodeblock_ufs2: Unknown "
10473 			    "state 0x%x", adp->ad_state);
10474 #endif /* INVARIANTS */
10475 		adp->ad_state &= ~ATTACHED;
10476 		adp->ad_state |= UNDONE;
10477 	}
10478 	/*
10479 	 * The on-disk inode cannot claim to be any larger than the last
10480 	 * fragment that has been written. Otherwise, the on-disk inode
10481 	 * might have fragments that were not the last block in the ext
10482 	 * data which would corrupt the filesystem.
10483 	 */
10484 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10485 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10486 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10487 		/* keep going until hitting a rollback to a frag */
10488 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10489 			continue;
10490 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10491 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10492 #ifdef INVARIANTS
10493 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10494 				panic("initiate_write_inodeblock_ufs2: "
10495 				    "lost dep1");
10496 #endif /* INVARIANTS */
10497 			dp->di_extb[i] = 0;
10498 		}
10499 		lastadp = NULL;
10500 		break;
10501 	}
10502 	/*
10503 	 * If we have zero'ed out the last allocated block of the ext
10504 	 * data, roll back the size to the last currently allocated block.
10505 	 * We know that this last allocated block is a full-sized as
10506 	 * we already checked for fragments in the loop above.
10507 	 */
10508 	if (lastadp != NULL &&
10509 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10510 		for (i = lastadp->ad_offset; i >= 0; i--)
10511 			if (dp->di_extb[i] != 0)
10512 				break;
10513 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10514 	}
10515 	/*
10516 	 * Set the file data dependencies to busy.
10517 	 */
10518 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10519 	     adp = TAILQ_NEXT(adp, ad_next)) {
10520 #ifdef INVARIANTS
10521 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10522 			panic("softdep_write_inodeblock: lbn order");
10523 		if ((adp->ad_state & ATTACHED) == 0)
10524 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10525 		prevlbn = adp->ad_offset;
10526 		if (adp->ad_offset < UFS_NDADDR &&
10527 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10528 			panic("initiate_write_inodeblock_ufs2: "
10529 			    "direct pointer #%jd mismatch %jd != %jd",
10530 			    (intmax_t)adp->ad_offset,
10531 			    (intmax_t)dp->di_db[adp->ad_offset],
10532 			    (intmax_t)adp->ad_newblkno);
10533 		if (adp->ad_offset >= UFS_NDADDR &&
10534 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10535 			panic("initiate_write_inodeblock_ufs2: "
10536 			    "indirect pointer #%jd mismatch %jd != %jd",
10537 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10538 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10539 			    (intmax_t)adp->ad_newblkno);
10540 		deplist |= 1 << adp->ad_offset;
10541 		if ((adp->ad_state & ATTACHED) == 0)
10542 			panic("initiate_write_inodeblock_ufs2: Unknown "
10543 			     "state 0x%x", adp->ad_state);
10544 #endif /* INVARIANTS */
10545 		adp->ad_state &= ~ATTACHED;
10546 		adp->ad_state |= UNDONE;
10547 	}
10548 	/*
10549 	 * The on-disk inode cannot claim to be any larger than the last
10550 	 * fragment that has been written. Otherwise, the on-disk inode
10551 	 * might have fragments that were not the last block in the file
10552 	 * which would corrupt the filesystem.
10553 	 */
10554 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10555 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10556 		if (adp->ad_offset >= UFS_NDADDR)
10557 			break;
10558 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10559 		/* keep going until hitting a rollback to a frag */
10560 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10561 			continue;
10562 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10563 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10564 #ifdef INVARIANTS
10565 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10566 				panic("initiate_write_inodeblock_ufs2: "
10567 				    "lost dep2");
10568 #endif /* INVARIANTS */
10569 			dp->di_db[i] = 0;
10570 		}
10571 		for (i = 0; i < UFS_NIADDR; i++) {
10572 #ifdef INVARIANTS
10573 			if (dp->di_ib[i] != 0 &&
10574 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10575 				panic("initiate_write_inodeblock_ufs2: "
10576 				    "lost dep3");
10577 #endif /* INVARIANTS */
10578 			dp->di_ib[i] = 0;
10579 		}
10580 		ffs_update_dinode_ckhash(fs, dp);
10581 		return;
10582 	}
10583 	/*
10584 	 * If we have zero'ed out the last allocated block of the file,
10585 	 * roll back the size to the last currently allocated block.
10586 	 * We know that this last allocated block is a full-sized as
10587 	 * we already checked for fragments in the loop above.
10588 	 */
10589 	if (lastadp != NULL &&
10590 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10591 		for (i = lastadp->ad_offset; i >= 0; i--)
10592 			if (dp->di_db[i] != 0)
10593 				break;
10594 		dp->di_size = (i + 1) * fs->fs_bsize;
10595 	}
10596 	/*
10597 	 * The only dependencies are for indirect blocks.
10598 	 *
10599 	 * The file size for indirect block additions is not guaranteed.
10600 	 * Such a guarantee would be non-trivial to achieve. The conventional
10601 	 * synchronous write implementation also does not make this guarantee.
10602 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10603 	 * can be over-estimated without destroying integrity when the file
10604 	 * moves into the indirect blocks (i.e., is large). If we want to
10605 	 * postpone fsck, we are stuck with this argument.
10606 	 */
10607 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10608 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10609 	ffs_update_dinode_ckhash(fs, dp);
10610 }
10611 
10612 /*
10613  * Cancel an indirdep as a result of truncation.  Release all of the
10614  * children allocindirs and place their journal work on the appropriate
10615  * list.
10616  */
10617 static void
10618 cancel_indirdep(indirdep, bp, freeblks)
10619 	struct indirdep *indirdep;
10620 	struct buf *bp;
10621 	struct freeblks *freeblks;
10622 {
10623 	struct allocindir *aip;
10624 
10625 	/*
10626 	 * None of the indirect pointers will ever be visible,
10627 	 * so they can simply be tossed. GOINGAWAY ensures
10628 	 * that allocated pointers will be saved in the buffer
10629 	 * cache until they are freed. Note that they will
10630 	 * only be able to be found by their physical address
10631 	 * since the inode mapping the logical address will
10632 	 * be gone. The save buffer used for the safe copy
10633 	 * was allocated in setup_allocindir_phase2 using
10634 	 * the physical address so it could be used for this
10635 	 * purpose. Hence we swap the safe copy with the real
10636 	 * copy, allowing the safe copy to be freed and holding
10637 	 * on to the real copy for later use in indir_trunc.
10638 	 */
10639 	if (indirdep->ir_state & GOINGAWAY)
10640 		panic("cancel_indirdep: already gone");
10641 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10642 		indirdep->ir_state |= DEPCOMPLETE;
10643 		LIST_REMOVE(indirdep, ir_next);
10644 	}
10645 	indirdep->ir_state |= GOINGAWAY;
10646 	/*
10647 	 * Pass in bp for blocks still have journal writes
10648 	 * pending so we can cancel them on their own.
10649 	 */
10650 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10651 		cancel_allocindir(aip, bp, freeblks, 0);
10652 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10653 		cancel_allocindir(aip, NULL, freeblks, 0);
10654 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10655 		cancel_allocindir(aip, NULL, freeblks, 0);
10656 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10657 		cancel_allocindir(aip, NULL, freeblks, 0);
10658 	/*
10659 	 * If there are pending partial truncations we need to keep the
10660 	 * old block copy around until they complete.  This is because
10661 	 * the current b_data is not a perfect superset of the available
10662 	 * blocks.
10663 	 */
10664 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10665 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10666 	else
10667 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10668 	WORKLIST_REMOVE(&indirdep->ir_list);
10669 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10670 	indirdep->ir_bp = NULL;
10671 	indirdep->ir_freeblks = freeblks;
10672 }
10673 
10674 /*
10675  * Free an indirdep once it no longer has new pointers to track.
10676  */
10677 static void
10678 free_indirdep(indirdep)
10679 	struct indirdep *indirdep;
10680 {
10681 
10682 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10683 	    ("free_indirdep: Indir trunc list not empty."));
10684 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10685 	    ("free_indirdep: Complete head not empty."));
10686 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10687 	    ("free_indirdep: write head not empty."));
10688 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10689 	    ("free_indirdep: done head not empty."));
10690 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10691 	    ("free_indirdep: deplist head not empty."));
10692 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10693 	    ("free_indirdep: %p still on newblk list.", indirdep));
10694 	KASSERT(indirdep->ir_saveddata == NULL,
10695 	    ("free_indirdep: %p still has saved data.", indirdep));
10696 	if (indirdep->ir_state & ONWORKLIST)
10697 		WORKLIST_REMOVE(&indirdep->ir_list);
10698 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10699 }
10700 
10701 /*
10702  * Called before a write to an indirdep.  This routine is responsible for
10703  * rolling back pointers to a safe state which includes only those
10704  * allocindirs which have been completed.
10705  */
10706 static void
10707 initiate_write_indirdep(indirdep, bp)
10708 	struct indirdep *indirdep;
10709 	struct buf *bp;
10710 {
10711 	struct ufsmount *ump;
10712 
10713 	indirdep->ir_state |= IOSTARTED;
10714 	if (indirdep->ir_state & GOINGAWAY)
10715 		panic("disk_io_initiation: indirdep gone");
10716 	/*
10717 	 * If there are no remaining dependencies, this will be writing
10718 	 * the real pointers.
10719 	 */
10720 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10721 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10722 		return;
10723 	/*
10724 	 * Replace up-to-date version with safe version.
10725 	 */
10726 	if (indirdep->ir_saveddata == NULL) {
10727 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10728 		LOCK_OWNED(ump);
10729 		FREE_LOCK(ump);
10730 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10731 		    M_SOFTDEP_FLAGS);
10732 		ACQUIRE_LOCK(ump);
10733 	}
10734 	indirdep->ir_state &= ~ATTACHED;
10735 	indirdep->ir_state |= UNDONE;
10736 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10737 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10738 	    bp->b_bcount);
10739 }
10740 
10741 /*
10742  * Called when an inode has been cleared in a cg bitmap.  This finally
10743  * eliminates any canceled jaddrefs
10744  */
10745 void
10746 softdep_setup_inofree(mp, bp, ino, wkhd)
10747 	struct mount *mp;
10748 	struct buf *bp;
10749 	ino_t ino;
10750 	struct workhead *wkhd;
10751 {
10752 	struct worklist *wk, *wkn;
10753 	struct inodedep *inodedep;
10754 	struct ufsmount *ump;
10755 	uint8_t *inosused;
10756 	struct cg *cgp;
10757 	struct fs *fs;
10758 
10759 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10760 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10761 	ump = VFSTOUFS(mp);
10762 	ACQUIRE_LOCK(ump);
10763 	fs = ump->um_fs;
10764 	cgp = (struct cg *)bp->b_data;
10765 	inosused = cg_inosused(cgp);
10766 	if (isset(inosused, ino % fs->fs_ipg))
10767 		panic("softdep_setup_inofree: inode %ju not freed.",
10768 		    (uintmax_t)ino);
10769 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10770 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10771 		    (uintmax_t)ino, inodedep);
10772 	if (wkhd) {
10773 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10774 			if (wk->wk_type != D_JADDREF)
10775 				continue;
10776 			WORKLIST_REMOVE(wk);
10777 			/*
10778 			 * We can free immediately even if the jaddref
10779 			 * isn't attached in a background write as now
10780 			 * the bitmaps are reconciled.
10781 			 */
10782 			wk->wk_state |= COMPLETE | ATTACHED;
10783 			free_jaddref(WK_JADDREF(wk));
10784 		}
10785 		jwork_move(&bp->b_dep, wkhd);
10786 	}
10787 	FREE_LOCK(ump);
10788 }
10789 
10790 
10791 /*
10792  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10793  * map.  Any dependencies waiting for the write to clear are added to the
10794  * buf's list and any jnewblks that are being canceled are discarded
10795  * immediately.
10796  */
10797 void
10798 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10799 	struct mount *mp;
10800 	struct buf *bp;
10801 	ufs2_daddr_t blkno;
10802 	int frags;
10803 	struct workhead *wkhd;
10804 {
10805 	struct bmsafemap *bmsafemap;
10806 	struct jnewblk *jnewblk;
10807 	struct ufsmount *ump;
10808 	struct worklist *wk;
10809 	struct fs *fs;
10810 #ifdef INVARIANTS
10811 	uint8_t *blksfree;
10812 	struct cg *cgp;
10813 	ufs2_daddr_t jstart;
10814 	ufs2_daddr_t jend;
10815 	ufs2_daddr_t end;
10816 	long bno;
10817 	int i;
10818 #endif
10819 
10820 	CTR3(KTR_SUJ,
10821 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10822 	    blkno, frags, wkhd);
10823 
10824 	ump = VFSTOUFS(mp);
10825 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10826 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10827 	ACQUIRE_LOCK(ump);
10828 	/* Lookup the bmsafemap so we track when it is dirty. */
10829 	fs = ump->um_fs;
10830 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10831 	/*
10832 	 * Detach any jnewblks which have been canceled.  They must linger
10833 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10834 	 * an unjournaled allocation from hitting the disk.
10835 	 */
10836 	if (wkhd) {
10837 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10838 			CTR2(KTR_SUJ,
10839 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10840 			    blkno, wk->wk_type);
10841 			WORKLIST_REMOVE(wk);
10842 			if (wk->wk_type != D_JNEWBLK) {
10843 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10844 				continue;
10845 			}
10846 			jnewblk = WK_JNEWBLK(wk);
10847 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10848 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10849 #ifdef INVARIANTS
10850 			/*
10851 			 * Assert that this block is free in the bitmap
10852 			 * before we discard the jnewblk.
10853 			 */
10854 			cgp = (struct cg *)bp->b_data;
10855 			blksfree = cg_blksfree(cgp);
10856 			bno = dtogd(fs, jnewblk->jn_blkno);
10857 			for (i = jnewblk->jn_oldfrags;
10858 			    i < jnewblk->jn_frags; i++) {
10859 				if (isset(blksfree, bno + i))
10860 					continue;
10861 				panic("softdep_setup_blkfree: not free");
10862 			}
10863 #endif
10864 			/*
10865 			 * Even if it's not attached we can free immediately
10866 			 * as the new bitmap is correct.
10867 			 */
10868 			wk->wk_state |= COMPLETE | ATTACHED;
10869 			free_jnewblk(jnewblk);
10870 		}
10871 	}
10872 
10873 #ifdef INVARIANTS
10874 	/*
10875 	 * Assert that we are not freeing a block which has an outstanding
10876 	 * allocation dependency.
10877 	 */
10878 	fs = VFSTOUFS(mp)->um_fs;
10879 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10880 	end = blkno + frags;
10881 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10882 		/*
10883 		 * Don't match against blocks that will be freed when the
10884 		 * background write is done.
10885 		 */
10886 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10887 		    (COMPLETE | DEPCOMPLETE))
10888 			continue;
10889 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10890 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10891 		if ((blkno >= jstart && blkno < jend) ||
10892 		    (end > jstart && end <= jend)) {
10893 			printf("state 0x%X %jd - %d %d dep %p\n",
10894 			    jnewblk->jn_state, jnewblk->jn_blkno,
10895 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10896 			    jnewblk->jn_dep);
10897 			panic("softdep_setup_blkfree: "
10898 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10899 			    blkno, end, frags, jstart, jend);
10900 		}
10901 	}
10902 #endif
10903 	FREE_LOCK(ump);
10904 }
10905 
10906 /*
10907  * Revert a block allocation when the journal record that describes it
10908  * is not yet written.
10909  */
10910 static int
10911 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10912 	struct jnewblk *jnewblk;
10913 	struct fs *fs;
10914 	struct cg *cgp;
10915 	uint8_t *blksfree;
10916 {
10917 	ufs1_daddr_t fragno;
10918 	long cgbno, bbase;
10919 	int frags, blk;
10920 	int i;
10921 
10922 	frags = 0;
10923 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10924 	/*
10925 	 * We have to test which frags need to be rolled back.  We may
10926 	 * be operating on a stale copy when doing background writes.
10927 	 */
10928 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10929 		if (isclr(blksfree, cgbno + i))
10930 			frags++;
10931 	if (frags == 0)
10932 		return (0);
10933 	/*
10934 	 * This is mostly ffs_blkfree() sans some validation and
10935 	 * superblock updates.
10936 	 */
10937 	if (frags == fs->fs_frag) {
10938 		fragno = fragstoblks(fs, cgbno);
10939 		ffs_setblock(fs, blksfree, fragno);
10940 		ffs_clusteracct(fs, cgp, fragno, 1);
10941 		cgp->cg_cs.cs_nbfree++;
10942 	} else {
10943 		cgbno += jnewblk->jn_oldfrags;
10944 		bbase = cgbno - fragnum(fs, cgbno);
10945 		/* Decrement the old frags.  */
10946 		blk = blkmap(fs, blksfree, bbase);
10947 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10948 		/* Deallocate the fragment */
10949 		for (i = 0; i < frags; i++)
10950 			setbit(blksfree, cgbno + i);
10951 		cgp->cg_cs.cs_nffree += frags;
10952 		/* Add back in counts associated with the new frags */
10953 		blk = blkmap(fs, blksfree, bbase);
10954 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10955 		/* If a complete block has been reassembled, account for it. */
10956 		fragno = fragstoblks(fs, bbase);
10957 		if (ffs_isblock(fs, blksfree, fragno)) {
10958 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10959 			ffs_clusteracct(fs, cgp, fragno, 1);
10960 			cgp->cg_cs.cs_nbfree++;
10961 		}
10962 	}
10963 	stat_jnewblk++;
10964 	jnewblk->jn_state &= ~ATTACHED;
10965 	jnewblk->jn_state |= UNDONE;
10966 
10967 	return (frags);
10968 }
10969 
10970 static void
10971 initiate_write_bmsafemap(bmsafemap, bp)
10972 	struct bmsafemap *bmsafemap;
10973 	struct buf *bp;			/* The cg block. */
10974 {
10975 	struct jaddref *jaddref;
10976 	struct jnewblk *jnewblk;
10977 	uint8_t *inosused;
10978 	uint8_t *blksfree;
10979 	struct cg *cgp;
10980 	struct fs *fs;
10981 	ino_t ino;
10982 
10983 	/*
10984 	 * If this is a background write, we did this at the time that
10985 	 * the copy was made, so do not need to do it again.
10986 	 */
10987 	if (bmsafemap->sm_state & IOSTARTED)
10988 		return;
10989 	bmsafemap->sm_state |= IOSTARTED;
10990 	/*
10991 	 * Clear any inode allocations which are pending journal writes.
10992 	 */
10993 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10994 		cgp = (struct cg *)bp->b_data;
10995 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10996 		inosused = cg_inosused(cgp);
10997 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10998 			ino = jaddref->ja_ino % fs->fs_ipg;
10999 			if (isset(inosused, ino)) {
11000 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11001 					cgp->cg_cs.cs_ndir--;
11002 				cgp->cg_cs.cs_nifree++;
11003 				clrbit(inosused, ino);
11004 				jaddref->ja_state &= ~ATTACHED;
11005 				jaddref->ja_state |= UNDONE;
11006 				stat_jaddref++;
11007 			} else
11008 				panic("initiate_write_bmsafemap: inode %ju "
11009 				    "marked free", (uintmax_t)jaddref->ja_ino);
11010 		}
11011 	}
11012 	/*
11013 	 * Clear any block allocations which are pending journal writes.
11014 	 */
11015 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11016 		cgp = (struct cg *)bp->b_data;
11017 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11018 		blksfree = cg_blksfree(cgp);
11019 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11020 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11021 				continue;
11022 			panic("initiate_write_bmsafemap: block %jd "
11023 			    "marked free", jnewblk->jn_blkno);
11024 		}
11025 	}
11026 	/*
11027 	 * Move allocation lists to the written lists so they can be
11028 	 * cleared once the block write is complete.
11029 	 */
11030 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11031 	    inodedep, id_deps);
11032 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11033 	    newblk, nb_deps);
11034 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11035 	    wk_list);
11036 }
11037 
11038 /*
11039  * This routine is called during the completion interrupt
11040  * service routine for a disk write (from the procedure called
11041  * by the device driver to inform the filesystem caches of
11042  * a request completion).  It should be called early in this
11043  * procedure, before the block is made available to other
11044  * processes or other routines are called.
11045  *
11046  */
11047 static void
11048 softdep_disk_write_complete(bp)
11049 	struct buf *bp;		/* describes the completed disk write */
11050 {
11051 	struct worklist *wk;
11052 	struct worklist *owk;
11053 	struct ufsmount *ump;
11054 	struct workhead reattach;
11055 	struct freeblks *freeblks;
11056 	struct buf *sbp;
11057 
11058 	ump = softdep_bp_to_mp(bp);
11059 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11060 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11061 	     "with outstanding dependencies for buffer %p", bp));
11062 	if (ump == NULL)
11063 		return;
11064 	/*
11065 	 * If an error occurred while doing the write, then the data
11066 	 * has not hit the disk and the dependencies cannot be processed.
11067 	 * But we do have to go through and roll forward any dependencies
11068 	 * that were rolled back before the disk write.
11069 	 */
11070 	sbp = NULL;
11071 	ACQUIRE_LOCK(ump);
11072 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11073 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11074 			switch (wk->wk_type) {
11075 
11076 			case D_PAGEDEP:
11077 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11078 				continue;
11079 
11080 			case D_INODEDEP:
11081 				handle_written_inodeblock(WK_INODEDEP(wk),
11082 				    bp, 0);
11083 				continue;
11084 
11085 			case D_BMSAFEMAP:
11086 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11087 				    bp, 0);
11088 				continue;
11089 
11090 			case D_INDIRDEP:
11091 				handle_written_indirdep(WK_INDIRDEP(wk),
11092 				    bp, &sbp, 0);
11093 				continue;
11094 			default:
11095 				/* nothing to roll forward */
11096 				continue;
11097 			}
11098 		}
11099 		FREE_LOCK(ump);
11100 		if (sbp)
11101 			brelse(sbp);
11102 		return;
11103 	}
11104 	LIST_INIT(&reattach);
11105 
11106 	/*
11107 	 * Ump SU lock must not be released anywhere in this code segment.
11108 	 */
11109 	owk = NULL;
11110 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11111 		WORKLIST_REMOVE(wk);
11112 		atomic_add_long(&dep_write[wk->wk_type], 1);
11113 		if (wk == owk)
11114 			panic("duplicate worklist: %p\n", wk);
11115 		owk = wk;
11116 		switch (wk->wk_type) {
11117 
11118 		case D_PAGEDEP:
11119 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11120 			    WRITESUCCEEDED))
11121 				WORKLIST_INSERT(&reattach, wk);
11122 			continue;
11123 
11124 		case D_INODEDEP:
11125 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11126 			    WRITESUCCEEDED))
11127 				WORKLIST_INSERT(&reattach, wk);
11128 			continue;
11129 
11130 		case D_BMSAFEMAP:
11131 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11132 			    WRITESUCCEEDED))
11133 				WORKLIST_INSERT(&reattach, wk);
11134 			continue;
11135 
11136 		case D_MKDIR:
11137 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11138 			continue;
11139 
11140 		case D_ALLOCDIRECT:
11141 			wk->wk_state |= COMPLETE;
11142 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11143 			continue;
11144 
11145 		case D_ALLOCINDIR:
11146 			wk->wk_state |= COMPLETE;
11147 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11148 			continue;
11149 
11150 		case D_INDIRDEP:
11151 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11152 			    WRITESUCCEEDED))
11153 				WORKLIST_INSERT(&reattach, wk);
11154 			continue;
11155 
11156 		case D_FREEBLKS:
11157 			wk->wk_state |= COMPLETE;
11158 			freeblks = WK_FREEBLKS(wk);
11159 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11160 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11161 				add_to_worklist(wk, WK_NODELAY);
11162 			continue;
11163 
11164 		case D_FREEWORK:
11165 			handle_written_freework(WK_FREEWORK(wk));
11166 			break;
11167 
11168 		case D_JSEGDEP:
11169 			free_jsegdep(WK_JSEGDEP(wk));
11170 			continue;
11171 
11172 		case D_JSEG:
11173 			handle_written_jseg(WK_JSEG(wk), bp);
11174 			continue;
11175 
11176 		case D_SBDEP:
11177 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11178 				WORKLIST_INSERT(&reattach, wk);
11179 			continue;
11180 
11181 		case D_FREEDEP:
11182 			free_freedep(WK_FREEDEP(wk));
11183 			continue;
11184 
11185 		default:
11186 			panic("handle_disk_write_complete: Unknown type %s",
11187 			    TYPENAME(wk->wk_type));
11188 			/* NOTREACHED */
11189 		}
11190 	}
11191 	/*
11192 	 * Reattach any requests that must be redone.
11193 	 */
11194 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11195 		WORKLIST_REMOVE(wk);
11196 		WORKLIST_INSERT(&bp->b_dep, wk);
11197 	}
11198 	FREE_LOCK(ump);
11199 	if (sbp)
11200 		brelse(sbp);
11201 }
11202 
11203 /*
11204  * Called from within softdep_disk_write_complete above.
11205  */
11206 static void
11207 handle_allocdirect_partdone(adp, wkhd)
11208 	struct allocdirect *adp;	/* the completed allocdirect */
11209 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11210 {
11211 	struct allocdirectlst *listhead;
11212 	struct allocdirect *listadp;
11213 	struct inodedep *inodedep;
11214 	long bsize;
11215 
11216 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11217 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11218 		return;
11219 	/*
11220 	 * The on-disk inode cannot claim to be any larger than the last
11221 	 * fragment that has been written. Otherwise, the on-disk inode
11222 	 * might have fragments that were not the last block in the file
11223 	 * which would corrupt the filesystem. Thus, we cannot free any
11224 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11225 	 * these blocks must be rolled back to zero before writing the inode.
11226 	 * We check the currently active set of allocdirects in id_inoupdt
11227 	 * or id_extupdt as appropriate.
11228 	 */
11229 	inodedep = adp->ad_inodedep;
11230 	bsize = inodedep->id_fs->fs_bsize;
11231 	if (adp->ad_state & EXTDATA)
11232 		listhead = &inodedep->id_extupdt;
11233 	else
11234 		listhead = &inodedep->id_inoupdt;
11235 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11236 		/* found our block */
11237 		if (listadp == adp)
11238 			break;
11239 		/* continue if ad_oldlbn is not a fragment */
11240 		if (listadp->ad_oldsize == 0 ||
11241 		    listadp->ad_oldsize == bsize)
11242 			continue;
11243 		/* hit a fragment */
11244 		return;
11245 	}
11246 	/*
11247 	 * If we have reached the end of the current list without
11248 	 * finding the just finished dependency, then it must be
11249 	 * on the future dependency list. Future dependencies cannot
11250 	 * be freed until they are moved to the current list.
11251 	 */
11252 	if (listadp == NULL) {
11253 #ifdef INVARIANTS
11254 		if (adp->ad_state & EXTDATA)
11255 			listhead = &inodedep->id_newextupdt;
11256 		else
11257 			listhead = &inodedep->id_newinoupdt;
11258 		TAILQ_FOREACH(listadp, listhead, ad_next)
11259 			/* found our block */
11260 			if (listadp == adp)
11261 				break;
11262 		if (listadp == NULL)
11263 			panic("handle_allocdirect_partdone: lost dep");
11264 #endif /* INVARIANTS */
11265 		return;
11266 	}
11267 	/*
11268 	 * If we have found the just finished dependency, then queue
11269 	 * it along with anything that follows it that is complete.
11270 	 * Since the pointer has not yet been written in the inode
11271 	 * as the dependency prevents it, place the allocdirect on the
11272 	 * bufwait list where it will be freed once the pointer is
11273 	 * valid.
11274 	 */
11275 	if (wkhd == NULL)
11276 		wkhd = &inodedep->id_bufwait;
11277 	for (; adp; adp = listadp) {
11278 		listadp = TAILQ_NEXT(adp, ad_next);
11279 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11280 			return;
11281 		TAILQ_REMOVE(listhead, adp, ad_next);
11282 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11283 	}
11284 }
11285 
11286 /*
11287  * Called from within softdep_disk_write_complete above.  This routine
11288  * completes successfully written allocindirs.
11289  */
11290 static void
11291 handle_allocindir_partdone(aip)
11292 	struct allocindir *aip;		/* the completed allocindir */
11293 {
11294 	struct indirdep *indirdep;
11295 
11296 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11297 		return;
11298 	indirdep = aip->ai_indirdep;
11299 	LIST_REMOVE(aip, ai_next);
11300 	/*
11301 	 * Don't set a pointer while the buffer is undergoing IO or while
11302 	 * we have active truncations.
11303 	 */
11304 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11305 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11306 		return;
11307 	}
11308 	if (indirdep->ir_state & UFS1FMT)
11309 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11310 		    aip->ai_newblkno;
11311 	else
11312 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11313 		    aip->ai_newblkno;
11314 	/*
11315 	 * Await the pointer write before freeing the allocindir.
11316 	 */
11317 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11318 }
11319 
11320 /*
11321  * Release segments held on a jwork list.
11322  */
11323 static void
11324 handle_jwork(wkhd)
11325 	struct workhead *wkhd;
11326 {
11327 	struct worklist *wk;
11328 
11329 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11330 		WORKLIST_REMOVE(wk);
11331 		switch (wk->wk_type) {
11332 		case D_JSEGDEP:
11333 			free_jsegdep(WK_JSEGDEP(wk));
11334 			continue;
11335 		case D_FREEDEP:
11336 			free_freedep(WK_FREEDEP(wk));
11337 			continue;
11338 		case D_FREEFRAG:
11339 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11340 			WORKITEM_FREE(wk, D_FREEFRAG);
11341 			continue;
11342 		case D_FREEWORK:
11343 			handle_written_freework(WK_FREEWORK(wk));
11344 			continue;
11345 		default:
11346 			panic("handle_jwork: Unknown type %s\n",
11347 			    TYPENAME(wk->wk_type));
11348 		}
11349 	}
11350 }
11351 
11352 /*
11353  * Handle the bufwait list on an inode when it is safe to release items
11354  * held there.  This normally happens after an inode block is written but
11355  * may be delayed and handled later if there are pending journal items that
11356  * are not yet safe to be released.
11357  */
11358 static struct freefile *
11359 handle_bufwait(inodedep, refhd)
11360 	struct inodedep *inodedep;
11361 	struct workhead *refhd;
11362 {
11363 	struct jaddref *jaddref;
11364 	struct freefile *freefile;
11365 	struct worklist *wk;
11366 
11367 	freefile = NULL;
11368 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11369 		WORKLIST_REMOVE(wk);
11370 		switch (wk->wk_type) {
11371 		case D_FREEFILE:
11372 			/*
11373 			 * We defer adding freefile to the worklist
11374 			 * until all other additions have been made to
11375 			 * ensure that it will be done after all the
11376 			 * old blocks have been freed.
11377 			 */
11378 			if (freefile != NULL)
11379 				panic("handle_bufwait: freefile");
11380 			freefile = WK_FREEFILE(wk);
11381 			continue;
11382 
11383 		case D_MKDIR:
11384 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11385 			continue;
11386 
11387 		case D_DIRADD:
11388 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11389 			continue;
11390 
11391 		case D_FREEFRAG:
11392 			wk->wk_state |= COMPLETE;
11393 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11394 				add_to_worklist(wk, 0);
11395 			continue;
11396 
11397 		case D_DIRREM:
11398 			wk->wk_state |= COMPLETE;
11399 			add_to_worklist(wk, 0);
11400 			continue;
11401 
11402 		case D_ALLOCDIRECT:
11403 		case D_ALLOCINDIR:
11404 			free_newblk(WK_NEWBLK(wk));
11405 			continue;
11406 
11407 		case D_JNEWBLK:
11408 			wk->wk_state |= COMPLETE;
11409 			free_jnewblk(WK_JNEWBLK(wk));
11410 			continue;
11411 
11412 		/*
11413 		 * Save freed journal segments and add references on
11414 		 * the supplied list which will delay their release
11415 		 * until the cg bitmap is cleared on disk.
11416 		 */
11417 		case D_JSEGDEP:
11418 			if (refhd == NULL)
11419 				free_jsegdep(WK_JSEGDEP(wk));
11420 			else
11421 				WORKLIST_INSERT(refhd, wk);
11422 			continue;
11423 
11424 		case D_JADDREF:
11425 			jaddref = WK_JADDREF(wk);
11426 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11427 			    if_deps);
11428 			/*
11429 			 * Transfer any jaddrefs to the list to be freed with
11430 			 * the bitmap if we're handling a removed file.
11431 			 */
11432 			if (refhd == NULL) {
11433 				wk->wk_state |= COMPLETE;
11434 				free_jaddref(jaddref);
11435 			} else
11436 				WORKLIST_INSERT(refhd, wk);
11437 			continue;
11438 
11439 		default:
11440 			panic("handle_bufwait: Unknown type %p(%s)",
11441 			    wk, TYPENAME(wk->wk_type));
11442 			/* NOTREACHED */
11443 		}
11444 	}
11445 	return (freefile);
11446 }
11447 /*
11448  * Called from within softdep_disk_write_complete above to restore
11449  * in-memory inode block contents to their most up-to-date state. Note
11450  * that this routine is always called from interrupt level with further
11451  * interrupts from this device blocked.
11452  *
11453  * If the write did not succeed, we will do all the roll-forward
11454  * operations, but we will not take the actions that will allow its
11455  * dependencies to be processed.
11456  */
11457 static int
11458 handle_written_inodeblock(inodedep, bp, flags)
11459 	struct inodedep *inodedep;
11460 	struct buf *bp;		/* buffer containing the inode block */
11461 	int flags;
11462 {
11463 	struct freefile *freefile;
11464 	struct allocdirect *adp, *nextadp;
11465 	struct ufs1_dinode *dp1 = NULL;
11466 	struct ufs2_dinode *dp2 = NULL;
11467 	struct workhead wkhd;
11468 	int hadchanges, fstype;
11469 	ino_t freelink;
11470 
11471 	LIST_INIT(&wkhd);
11472 	hadchanges = 0;
11473 	freefile = NULL;
11474 	if ((inodedep->id_state & IOSTARTED) == 0)
11475 		panic("handle_written_inodeblock: not started");
11476 	inodedep->id_state &= ~IOSTARTED;
11477 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11478 		fstype = UFS1;
11479 		dp1 = (struct ufs1_dinode *)bp->b_data +
11480 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11481 		freelink = dp1->di_freelink;
11482 	} else {
11483 		fstype = UFS2;
11484 		dp2 = (struct ufs2_dinode *)bp->b_data +
11485 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11486 		freelink = dp2->di_freelink;
11487 	}
11488 	/*
11489 	 * Leave this inodeblock dirty until it's in the list.
11490 	 */
11491 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11492 	    (flags & WRITESUCCEEDED)) {
11493 		struct inodedep *inon;
11494 
11495 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11496 		if ((inon == NULL && freelink == 0) ||
11497 		    (inon && inon->id_ino == freelink)) {
11498 			if (inon)
11499 				inon->id_state |= UNLINKPREV;
11500 			inodedep->id_state |= UNLINKNEXT;
11501 		}
11502 		hadchanges = 1;
11503 	}
11504 	/*
11505 	 * If we had to rollback the inode allocation because of
11506 	 * bitmaps being incomplete, then simply restore it.
11507 	 * Keep the block dirty so that it will not be reclaimed until
11508 	 * all associated dependencies have been cleared and the
11509 	 * corresponding updates written to disk.
11510 	 */
11511 	if (inodedep->id_savedino1 != NULL) {
11512 		hadchanges = 1;
11513 		if (fstype == UFS1)
11514 			*dp1 = *inodedep->id_savedino1;
11515 		else
11516 			*dp2 = *inodedep->id_savedino2;
11517 		free(inodedep->id_savedino1, M_SAVEDINO);
11518 		inodedep->id_savedino1 = NULL;
11519 		if ((bp->b_flags & B_DELWRI) == 0)
11520 			stat_inode_bitmap++;
11521 		bdirty(bp);
11522 		/*
11523 		 * If the inode is clear here and GOINGAWAY it will never
11524 		 * be written.  Process the bufwait and clear any pending
11525 		 * work which may include the freefile.
11526 		 */
11527 		if (inodedep->id_state & GOINGAWAY)
11528 			goto bufwait;
11529 		return (1);
11530 	}
11531 	if (flags & WRITESUCCEEDED)
11532 		inodedep->id_state |= COMPLETE;
11533 	/*
11534 	 * Roll forward anything that had to be rolled back before
11535 	 * the inode could be updated.
11536 	 */
11537 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11538 		nextadp = TAILQ_NEXT(adp, ad_next);
11539 		if (adp->ad_state & ATTACHED)
11540 			panic("handle_written_inodeblock: new entry");
11541 		if (fstype == UFS1) {
11542 			if (adp->ad_offset < UFS_NDADDR) {
11543 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11544 					panic("%s %s #%jd mismatch %d != %jd",
11545 					    "handle_written_inodeblock:",
11546 					    "direct pointer",
11547 					    (intmax_t)adp->ad_offset,
11548 					    dp1->di_db[adp->ad_offset],
11549 					    (intmax_t)adp->ad_oldblkno);
11550 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11551 			} else {
11552 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11553 				    0)
11554 					panic("%s: %s #%jd allocated as %d",
11555 					    "handle_written_inodeblock",
11556 					    "indirect pointer",
11557 					    (intmax_t)adp->ad_offset -
11558 					    UFS_NDADDR,
11559 					    dp1->di_ib[adp->ad_offset -
11560 					    UFS_NDADDR]);
11561 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11562 				    adp->ad_newblkno;
11563 			}
11564 		} else {
11565 			if (adp->ad_offset < UFS_NDADDR) {
11566 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11567 					panic("%s: %s #%jd %s %jd != %jd",
11568 					    "handle_written_inodeblock",
11569 					    "direct pointer",
11570 					    (intmax_t)adp->ad_offset, "mismatch",
11571 					    (intmax_t)dp2->di_db[adp->ad_offset],
11572 					    (intmax_t)adp->ad_oldblkno);
11573 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11574 			} else {
11575 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11576 				    0)
11577 					panic("%s: %s #%jd allocated as %jd",
11578 					    "handle_written_inodeblock",
11579 					    "indirect pointer",
11580 					    (intmax_t)adp->ad_offset -
11581 					    UFS_NDADDR,
11582 					    (intmax_t)
11583 					    dp2->di_ib[adp->ad_offset -
11584 					    UFS_NDADDR]);
11585 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11586 				    adp->ad_newblkno;
11587 			}
11588 		}
11589 		adp->ad_state &= ~UNDONE;
11590 		adp->ad_state |= ATTACHED;
11591 		hadchanges = 1;
11592 	}
11593 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11594 		nextadp = TAILQ_NEXT(adp, ad_next);
11595 		if (adp->ad_state & ATTACHED)
11596 			panic("handle_written_inodeblock: new entry");
11597 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11598 			panic("%s: direct pointers #%jd %s %jd != %jd",
11599 			    "handle_written_inodeblock",
11600 			    (intmax_t)adp->ad_offset, "mismatch",
11601 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11602 			    (intmax_t)adp->ad_oldblkno);
11603 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11604 		adp->ad_state &= ~UNDONE;
11605 		adp->ad_state |= ATTACHED;
11606 		hadchanges = 1;
11607 	}
11608 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11609 		stat_direct_blk_ptrs++;
11610 	/*
11611 	 * Reset the file size to its most up-to-date value.
11612 	 */
11613 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11614 		panic("handle_written_inodeblock: bad size");
11615 	if (inodedep->id_savednlink > UFS_LINK_MAX)
11616 		panic("handle_written_inodeblock: Invalid link count "
11617 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11618 		    inodedep);
11619 	if (fstype == UFS1) {
11620 		if (dp1->di_nlink != inodedep->id_savednlink) {
11621 			dp1->di_nlink = inodedep->id_savednlink;
11622 			hadchanges = 1;
11623 		}
11624 		if (dp1->di_size != inodedep->id_savedsize) {
11625 			dp1->di_size = inodedep->id_savedsize;
11626 			hadchanges = 1;
11627 		}
11628 	} else {
11629 		if (dp2->di_nlink != inodedep->id_savednlink) {
11630 			dp2->di_nlink = inodedep->id_savednlink;
11631 			hadchanges = 1;
11632 		}
11633 		if (dp2->di_size != inodedep->id_savedsize) {
11634 			dp2->di_size = inodedep->id_savedsize;
11635 			hadchanges = 1;
11636 		}
11637 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11638 			dp2->di_extsize = inodedep->id_savedextsize;
11639 			hadchanges = 1;
11640 		}
11641 	}
11642 	inodedep->id_savedsize = -1;
11643 	inodedep->id_savedextsize = -1;
11644 	inodedep->id_savednlink = -1;
11645 	/*
11646 	 * If there were any rollbacks in the inode block, then it must be
11647 	 * marked dirty so that its will eventually get written back in
11648 	 * its correct form.
11649 	 */
11650 	if (hadchanges) {
11651 		if (fstype == UFS2)
11652 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11653 		bdirty(bp);
11654 	}
11655 bufwait:
11656 	/*
11657 	 * If the write did not succeed, we have done all the roll-forward
11658 	 * operations, but we cannot take the actions that will allow its
11659 	 * dependencies to be processed.
11660 	 */
11661 	if ((flags & WRITESUCCEEDED) == 0)
11662 		return (hadchanges);
11663 	/*
11664 	 * Process any allocdirects that completed during the update.
11665 	 */
11666 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11667 		handle_allocdirect_partdone(adp, &wkhd);
11668 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11669 		handle_allocdirect_partdone(adp, &wkhd);
11670 	/*
11671 	 * Process deallocations that were held pending until the
11672 	 * inode had been written to disk. Freeing of the inode
11673 	 * is delayed until after all blocks have been freed to
11674 	 * avoid creation of new <vfsid, inum, lbn> triples
11675 	 * before the old ones have been deleted.  Completely
11676 	 * unlinked inodes are not processed until the unlinked
11677 	 * inode list is written or the last reference is removed.
11678 	 */
11679 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11680 		freefile = handle_bufwait(inodedep, NULL);
11681 		if (freefile && !LIST_EMPTY(&wkhd)) {
11682 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11683 			freefile = NULL;
11684 		}
11685 	}
11686 	/*
11687 	 * Move rolled forward dependency completions to the bufwait list
11688 	 * now that those that were already written have been processed.
11689 	 */
11690 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11691 		panic("handle_written_inodeblock: bufwait but no changes");
11692 	jwork_move(&inodedep->id_bufwait, &wkhd);
11693 
11694 	if (freefile != NULL) {
11695 		/*
11696 		 * If the inode is goingaway it was never written.  Fake up
11697 		 * the state here so free_inodedep() can succeed.
11698 		 */
11699 		if (inodedep->id_state & GOINGAWAY)
11700 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11701 		if (free_inodedep(inodedep) == 0)
11702 			panic("handle_written_inodeblock: live inodedep %p",
11703 			    inodedep);
11704 		add_to_worklist(&freefile->fx_list, 0);
11705 		return (0);
11706 	}
11707 
11708 	/*
11709 	 * If no outstanding dependencies, free it.
11710 	 */
11711 	if (free_inodedep(inodedep) ||
11712 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11713 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11714 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11715 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11716 		return (0);
11717 	return (hadchanges);
11718 }
11719 
11720 /*
11721  * Perform needed roll-forwards and kick off any dependencies that
11722  * can now be processed.
11723  *
11724  * If the write did not succeed, we will do all the roll-forward
11725  * operations, but we will not take the actions that will allow its
11726  * dependencies to be processed.
11727  */
11728 static int
11729 handle_written_indirdep(indirdep, bp, bpp, flags)
11730 	struct indirdep *indirdep;
11731 	struct buf *bp;
11732 	struct buf **bpp;
11733 	int flags;
11734 {
11735 	struct allocindir *aip;
11736 	struct buf *sbp;
11737 	int chgs;
11738 
11739 	if (indirdep->ir_state & GOINGAWAY)
11740 		panic("handle_written_indirdep: indirdep gone");
11741 	if ((indirdep->ir_state & IOSTARTED) == 0)
11742 		panic("handle_written_indirdep: IO not started");
11743 	chgs = 0;
11744 	/*
11745 	 * If there were rollbacks revert them here.
11746 	 */
11747 	if (indirdep->ir_saveddata) {
11748 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11749 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11750 			free(indirdep->ir_saveddata, M_INDIRDEP);
11751 			indirdep->ir_saveddata = NULL;
11752 		}
11753 		chgs = 1;
11754 	}
11755 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11756 	indirdep->ir_state |= ATTACHED;
11757 	/*
11758 	 * If the write did not succeed, we have done all the roll-forward
11759 	 * operations, but we cannot take the actions that will allow its
11760 	 * dependencies to be processed.
11761 	 */
11762 	if ((flags & WRITESUCCEEDED) == 0) {
11763 		stat_indir_blk_ptrs++;
11764 		bdirty(bp);
11765 		return (1);
11766 	}
11767 	/*
11768 	 * Move allocindirs with written pointers to the completehd if
11769 	 * the indirdep's pointer is not yet written.  Otherwise
11770 	 * free them here.
11771 	 */
11772 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11773 		LIST_REMOVE(aip, ai_next);
11774 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11775 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11776 			    ai_next);
11777 			newblk_freefrag(&aip->ai_block);
11778 			continue;
11779 		}
11780 		free_newblk(&aip->ai_block);
11781 	}
11782 	/*
11783 	 * Move allocindirs that have finished dependency processing from
11784 	 * the done list to the write list after updating the pointers.
11785 	 */
11786 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11787 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11788 			handle_allocindir_partdone(aip);
11789 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11790 				panic("disk_write_complete: not gone");
11791 			chgs = 1;
11792 		}
11793 	}
11794 	/*
11795 	 * Preserve the indirdep if there were any changes or if it is not
11796 	 * yet valid on disk.
11797 	 */
11798 	if (chgs) {
11799 		stat_indir_blk_ptrs++;
11800 		bdirty(bp);
11801 		return (1);
11802 	}
11803 	/*
11804 	 * If there were no changes we can discard the savedbp and detach
11805 	 * ourselves from the buf.  We are only carrying completed pointers
11806 	 * in this case.
11807 	 */
11808 	sbp = indirdep->ir_savebp;
11809 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11810 	indirdep->ir_savebp = NULL;
11811 	indirdep->ir_bp = NULL;
11812 	if (*bpp != NULL)
11813 		panic("handle_written_indirdep: bp already exists.");
11814 	*bpp = sbp;
11815 	/*
11816 	 * The indirdep may not be freed until its parent points at it.
11817 	 */
11818 	if (indirdep->ir_state & DEPCOMPLETE)
11819 		free_indirdep(indirdep);
11820 
11821 	return (0);
11822 }
11823 
11824 /*
11825  * Process a diradd entry after its dependent inode has been written.
11826  */
11827 static void
11828 diradd_inode_written(dap, inodedep)
11829 	struct diradd *dap;
11830 	struct inodedep *inodedep;
11831 {
11832 
11833 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
11834 	dap->da_state |= COMPLETE;
11835 	complete_diradd(dap);
11836 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11837 }
11838 
11839 /*
11840  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11841  * be called with the per-filesystem lock and the buf lock on the cg held.
11842  */
11843 static int
11844 bmsafemap_backgroundwrite(bmsafemap, bp)
11845 	struct bmsafemap *bmsafemap;
11846 	struct buf *bp;
11847 {
11848 	int dirty;
11849 
11850 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11851 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11852 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11853 	/*
11854 	 * If we're initiating a background write we need to process the
11855 	 * rollbacks as they exist now, not as they exist when IO starts.
11856 	 * No other consumers will look at the contents of the shadowed
11857 	 * buf so this is safe to do here.
11858 	 */
11859 	if (bp->b_xflags & BX_BKGRDMARKER)
11860 		initiate_write_bmsafemap(bmsafemap, bp);
11861 
11862 	return (dirty);
11863 }
11864 
11865 /*
11866  * Re-apply an allocation when a cg write is complete.
11867  */
11868 static int
11869 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11870 	struct jnewblk *jnewblk;
11871 	struct fs *fs;
11872 	struct cg *cgp;
11873 	uint8_t *blksfree;
11874 {
11875 	ufs1_daddr_t fragno;
11876 	ufs2_daddr_t blkno;
11877 	long cgbno, bbase;
11878 	int frags, blk;
11879 	int i;
11880 
11881 	frags = 0;
11882 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11883 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11884 		if (isclr(blksfree, cgbno + i))
11885 			panic("jnewblk_rollforward: re-allocated fragment");
11886 		frags++;
11887 	}
11888 	if (frags == fs->fs_frag) {
11889 		blkno = fragstoblks(fs, cgbno);
11890 		ffs_clrblock(fs, blksfree, (long)blkno);
11891 		ffs_clusteracct(fs, cgp, blkno, -1);
11892 		cgp->cg_cs.cs_nbfree--;
11893 	} else {
11894 		bbase = cgbno - fragnum(fs, cgbno);
11895 		cgbno += jnewblk->jn_oldfrags;
11896                 /* If a complete block had been reassembled, account for it. */
11897 		fragno = fragstoblks(fs, bbase);
11898 		if (ffs_isblock(fs, blksfree, fragno)) {
11899 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11900 			ffs_clusteracct(fs, cgp, fragno, -1);
11901 			cgp->cg_cs.cs_nbfree--;
11902 		}
11903 		/* Decrement the old frags.  */
11904 		blk = blkmap(fs, blksfree, bbase);
11905 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11906 		/* Allocate the fragment */
11907 		for (i = 0; i < frags; i++)
11908 			clrbit(blksfree, cgbno + i);
11909 		cgp->cg_cs.cs_nffree -= frags;
11910 		/* Add back in counts associated with the new frags */
11911 		blk = blkmap(fs, blksfree, bbase);
11912 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11913 	}
11914 	return (frags);
11915 }
11916 
11917 /*
11918  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11919  * changes if it's not a background write.  Set all written dependencies
11920  * to DEPCOMPLETE and free the structure if possible.
11921  *
11922  * If the write did not succeed, we will do all the roll-forward
11923  * operations, but we will not take the actions that will allow its
11924  * dependencies to be processed.
11925  */
11926 static int
11927 handle_written_bmsafemap(bmsafemap, bp, flags)
11928 	struct bmsafemap *bmsafemap;
11929 	struct buf *bp;
11930 	int flags;
11931 {
11932 	struct newblk *newblk;
11933 	struct inodedep *inodedep;
11934 	struct jaddref *jaddref, *jatmp;
11935 	struct jnewblk *jnewblk, *jntmp;
11936 	struct ufsmount *ump;
11937 	uint8_t *inosused;
11938 	uint8_t *blksfree;
11939 	struct cg *cgp;
11940 	struct fs *fs;
11941 	ino_t ino;
11942 	int foreground;
11943 	int chgs;
11944 
11945 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11946 		panic("handle_written_bmsafemap: Not started\n");
11947 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11948 	chgs = 0;
11949 	bmsafemap->sm_state &= ~IOSTARTED;
11950 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11951 	/*
11952 	 * If write was successful, release journal work that was waiting
11953 	 * on the write. Otherwise move the work back.
11954 	 */
11955 	if (flags & WRITESUCCEEDED)
11956 		handle_jwork(&bmsafemap->sm_freewr);
11957 	else
11958 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11959 		    worklist, wk_list);
11960 
11961 	/*
11962 	 * Restore unwritten inode allocation pending jaddref writes.
11963 	 */
11964 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11965 		cgp = (struct cg *)bp->b_data;
11966 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11967 		inosused = cg_inosused(cgp);
11968 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11969 		    ja_bmdeps, jatmp) {
11970 			if ((jaddref->ja_state & UNDONE) == 0)
11971 				continue;
11972 			ino = jaddref->ja_ino % fs->fs_ipg;
11973 			if (isset(inosused, ino))
11974 				panic("handle_written_bmsafemap: "
11975 				    "re-allocated inode");
11976 			/* Do the roll-forward only if it's a real copy. */
11977 			if (foreground) {
11978 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11979 					cgp->cg_cs.cs_ndir++;
11980 				cgp->cg_cs.cs_nifree--;
11981 				setbit(inosused, ino);
11982 				chgs = 1;
11983 			}
11984 			jaddref->ja_state &= ~UNDONE;
11985 			jaddref->ja_state |= ATTACHED;
11986 			free_jaddref(jaddref);
11987 		}
11988 	}
11989 	/*
11990 	 * Restore any block allocations which are pending journal writes.
11991 	 */
11992 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11993 		cgp = (struct cg *)bp->b_data;
11994 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11995 		blksfree = cg_blksfree(cgp);
11996 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11997 		    jntmp) {
11998 			if ((jnewblk->jn_state & UNDONE) == 0)
11999 				continue;
12000 			/* Do the roll-forward only if it's a real copy. */
12001 			if (foreground &&
12002 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12003 				chgs = 1;
12004 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12005 			jnewblk->jn_state |= ATTACHED;
12006 			free_jnewblk(jnewblk);
12007 		}
12008 	}
12009 	/*
12010 	 * If the write did not succeed, we have done all the roll-forward
12011 	 * operations, but we cannot take the actions that will allow its
12012 	 * dependencies to be processed.
12013 	 */
12014 	if ((flags & WRITESUCCEEDED) == 0) {
12015 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12016 		    newblk, nb_deps);
12017 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12018 		    worklist, wk_list);
12019 		if (foreground)
12020 			bdirty(bp);
12021 		return (1);
12022 	}
12023 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12024 		newblk->nb_state |= DEPCOMPLETE;
12025 		newblk->nb_state &= ~ONDEPLIST;
12026 		newblk->nb_bmsafemap = NULL;
12027 		LIST_REMOVE(newblk, nb_deps);
12028 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12029 			handle_allocdirect_partdone(
12030 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12031 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12032 			handle_allocindir_partdone(
12033 			    WK_ALLOCINDIR(&newblk->nb_list));
12034 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12035 			panic("handle_written_bmsafemap: Unexpected type: %s",
12036 			    TYPENAME(newblk->nb_list.wk_type));
12037 	}
12038 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12039 		inodedep->id_state |= DEPCOMPLETE;
12040 		inodedep->id_state &= ~ONDEPLIST;
12041 		LIST_REMOVE(inodedep, id_deps);
12042 		inodedep->id_bmsafemap = NULL;
12043 	}
12044 	LIST_REMOVE(bmsafemap, sm_next);
12045 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12046 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12047 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12048 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12049 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12050 		LIST_REMOVE(bmsafemap, sm_hash);
12051 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12052 		return (0);
12053 	}
12054 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12055 	if (foreground)
12056 		bdirty(bp);
12057 	return (1);
12058 }
12059 
12060 /*
12061  * Try to free a mkdir dependency.
12062  */
12063 static void
12064 complete_mkdir(mkdir)
12065 	struct mkdir *mkdir;
12066 {
12067 	struct diradd *dap;
12068 
12069 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12070 		return;
12071 	LIST_REMOVE(mkdir, md_mkdirs);
12072 	dap = mkdir->md_diradd;
12073 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12074 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12075 		dap->da_state |= DEPCOMPLETE;
12076 		complete_diradd(dap);
12077 	}
12078 	WORKITEM_FREE(mkdir, D_MKDIR);
12079 }
12080 
12081 /*
12082  * Handle the completion of a mkdir dependency.
12083  */
12084 static void
12085 handle_written_mkdir(mkdir, type)
12086 	struct mkdir *mkdir;
12087 	int type;
12088 {
12089 
12090 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12091 		panic("handle_written_mkdir: bad type");
12092 	mkdir->md_state |= COMPLETE;
12093 	complete_mkdir(mkdir);
12094 }
12095 
12096 static int
12097 free_pagedep(pagedep)
12098 	struct pagedep *pagedep;
12099 {
12100 	int i;
12101 
12102 	if (pagedep->pd_state & NEWBLOCK)
12103 		return (0);
12104 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12105 		return (0);
12106 	for (i = 0; i < DAHASHSZ; i++)
12107 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12108 			return (0);
12109 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12110 		return (0);
12111 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12112 		return (0);
12113 	if (pagedep->pd_state & ONWORKLIST)
12114 		WORKLIST_REMOVE(&pagedep->pd_list);
12115 	LIST_REMOVE(pagedep, pd_hash);
12116 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12117 
12118 	return (1);
12119 }
12120 
12121 /*
12122  * Called from within softdep_disk_write_complete above.
12123  * A write operation was just completed. Removed inodes can
12124  * now be freed and associated block pointers may be committed.
12125  * Note that this routine is always called from interrupt level
12126  * with further interrupts from this device blocked.
12127  *
12128  * If the write did not succeed, we will do all the roll-forward
12129  * operations, but we will not take the actions that will allow its
12130  * dependencies to be processed.
12131  */
12132 static int
12133 handle_written_filepage(pagedep, bp, flags)
12134 	struct pagedep *pagedep;
12135 	struct buf *bp;		/* buffer containing the written page */
12136 	int flags;
12137 {
12138 	struct dirrem *dirrem;
12139 	struct diradd *dap, *nextdap;
12140 	struct direct *ep;
12141 	int i, chgs;
12142 
12143 	if ((pagedep->pd_state & IOSTARTED) == 0)
12144 		panic("handle_written_filepage: not started");
12145 	pagedep->pd_state &= ~IOSTARTED;
12146 	if ((flags & WRITESUCCEEDED) == 0)
12147 		goto rollforward;
12148 	/*
12149 	 * Process any directory removals that have been committed.
12150 	 */
12151 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12152 		LIST_REMOVE(dirrem, dm_next);
12153 		dirrem->dm_state |= COMPLETE;
12154 		dirrem->dm_dirinum = pagedep->pd_ino;
12155 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12156 		    ("handle_written_filepage: Journal entries not written."));
12157 		add_to_worklist(&dirrem->dm_list, 0);
12158 	}
12159 	/*
12160 	 * Free any directory additions that have been committed.
12161 	 * If it is a newly allocated block, we have to wait until
12162 	 * the on-disk directory inode claims the new block.
12163 	 */
12164 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12165 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12166 			free_diradd(dap, NULL);
12167 rollforward:
12168 	/*
12169 	 * Uncommitted directory entries must be restored.
12170 	 */
12171 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12172 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12173 		     dap = nextdap) {
12174 			nextdap = LIST_NEXT(dap, da_pdlist);
12175 			if (dap->da_state & ATTACHED)
12176 				panic("handle_written_filepage: attached");
12177 			ep = (struct direct *)
12178 			    ((char *)bp->b_data + dap->da_offset);
12179 			ep->d_ino = dap->da_newinum;
12180 			dap->da_state &= ~UNDONE;
12181 			dap->da_state |= ATTACHED;
12182 			chgs = 1;
12183 			/*
12184 			 * If the inode referenced by the directory has
12185 			 * been written out, then the dependency can be
12186 			 * moved to the pending list.
12187 			 */
12188 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12189 				LIST_REMOVE(dap, da_pdlist);
12190 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12191 				    da_pdlist);
12192 			}
12193 		}
12194 	}
12195 	/*
12196 	 * If there were any rollbacks in the directory, then it must be
12197 	 * marked dirty so that its will eventually get written back in
12198 	 * its correct form.
12199 	 */
12200 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12201 		if ((bp->b_flags & B_DELWRI) == 0)
12202 			stat_dir_entry++;
12203 		bdirty(bp);
12204 		return (1);
12205 	}
12206 	/*
12207 	 * If we are not waiting for a new directory block to be
12208 	 * claimed by its inode, then the pagedep will be freed.
12209 	 * Otherwise it will remain to track any new entries on
12210 	 * the page in case they are fsync'ed.
12211 	 */
12212 	free_pagedep(pagedep);
12213 	return (0);
12214 }
12215 
12216 /*
12217  * Writing back in-core inode structures.
12218  *
12219  * The filesystem only accesses an inode's contents when it occupies an
12220  * "in-core" inode structure.  These "in-core" structures are separate from
12221  * the page frames used to cache inode blocks.  Only the latter are
12222  * transferred to/from the disk.  So, when the updated contents of the
12223  * "in-core" inode structure are copied to the corresponding in-memory inode
12224  * block, the dependencies are also transferred.  The following procedure is
12225  * called when copying a dirty "in-core" inode to a cached inode block.
12226  */
12227 
12228 /*
12229  * Called when an inode is loaded from disk. If the effective link count
12230  * differed from the actual link count when it was last flushed, then we
12231  * need to ensure that the correct effective link count is put back.
12232  */
12233 void
12234 softdep_load_inodeblock(ip)
12235 	struct inode *ip;	/* the "in_core" copy of the inode */
12236 {
12237 	struct inodedep *inodedep;
12238 	struct ufsmount *ump;
12239 
12240 	ump = ITOUMP(ip);
12241 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12242 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12243 	/*
12244 	 * Check for alternate nlink count.
12245 	 */
12246 	ip->i_effnlink = ip->i_nlink;
12247 	ACQUIRE_LOCK(ump);
12248 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12249 		FREE_LOCK(ump);
12250 		return;
12251 	}
12252 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12253 	FREE_LOCK(ump);
12254 }
12255 
12256 /*
12257  * This routine is called just before the "in-core" inode
12258  * information is to be copied to the in-memory inode block.
12259  * Recall that an inode block contains several inodes. If
12260  * the force flag is set, then the dependencies will be
12261  * cleared so that the update can always be made. Note that
12262  * the buffer is locked when this routine is called, so we
12263  * will never be in the middle of writing the inode block
12264  * to disk.
12265  */
12266 void
12267 softdep_update_inodeblock(ip, bp, waitfor)
12268 	struct inode *ip;	/* the "in_core" copy of the inode */
12269 	struct buf *bp;		/* the buffer containing the inode block */
12270 	int waitfor;		/* nonzero => update must be allowed */
12271 {
12272 	struct inodedep *inodedep;
12273 	struct inoref *inoref;
12274 	struct ufsmount *ump;
12275 	struct worklist *wk;
12276 	struct mount *mp;
12277 	struct buf *ibp;
12278 	struct fs *fs;
12279 	int error;
12280 
12281 	ump = ITOUMP(ip);
12282 	mp = UFSTOVFS(ump);
12283 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12284 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12285 	fs = ump->um_fs;
12286 	/*
12287 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12288 	 * does not have access to the in-core ip so must write directly into
12289 	 * the inode block buffer when setting freelink.
12290 	 */
12291 	if (fs->fs_magic == FS_UFS1_MAGIC)
12292 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12293 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12294 	else
12295 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12296 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12297 	/*
12298 	 * If the effective link count is not equal to the actual link
12299 	 * count, then we must track the difference in an inodedep while
12300 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12301 	 * if there is no existing inodedep, then there are no dependencies
12302 	 * to track.
12303 	 */
12304 	ACQUIRE_LOCK(ump);
12305 again:
12306 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12307 		FREE_LOCK(ump);
12308 		if (ip->i_effnlink != ip->i_nlink)
12309 			panic("softdep_update_inodeblock: bad link count");
12310 		return;
12311 	}
12312 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12313 		panic("softdep_update_inodeblock: bad delta");
12314 	/*
12315 	 * If we're flushing all dependencies we must also move any waiting
12316 	 * for journal writes onto the bufwait list prior to I/O.
12317 	 */
12318 	if (waitfor) {
12319 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12320 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12321 			    == DEPCOMPLETE) {
12322 				jwait(&inoref->if_list, MNT_WAIT);
12323 				goto again;
12324 			}
12325 		}
12326 	}
12327 	/*
12328 	 * Changes have been initiated. Anything depending on these
12329 	 * changes cannot occur until this inode has been written.
12330 	 */
12331 	inodedep->id_state &= ~COMPLETE;
12332 	if ((inodedep->id_state & ONWORKLIST) == 0)
12333 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12334 	/*
12335 	 * Any new dependencies associated with the incore inode must
12336 	 * now be moved to the list associated with the buffer holding
12337 	 * the in-memory copy of the inode. Once merged process any
12338 	 * allocdirects that are completed by the merger.
12339 	 */
12340 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12341 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12342 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12343 		    NULL);
12344 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12345 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12346 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12347 		    NULL);
12348 	/*
12349 	 * Now that the inode has been pushed into the buffer, the
12350 	 * operations dependent on the inode being written to disk
12351 	 * can be moved to the id_bufwait so that they will be
12352 	 * processed when the buffer I/O completes.
12353 	 */
12354 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12355 		WORKLIST_REMOVE(wk);
12356 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12357 	}
12358 	/*
12359 	 * Newly allocated inodes cannot be written until the bitmap
12360 	 * that allocates them have been written (indicated by
12361 	 * DEPCOMPLETE being set in id_state). If we are doing a
12362 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12363 	 * to be written so that the update can be done.
12364 	 */
12365 	if (waitfor == 0) {
12366 		FREE_LOCK(ump);
12367 		return;
12368 	}
12369 retry:
12370 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12371 		FREE_LOCK(ump);
12372 		return;
12373 	}
12374 	ibp = inodedep->id_bmsafemap->sm_buf;
12375 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12376 	if (ibp == NULL) {
12377 		/*
12378 		 * If ibp came back as NULL, the dependency could have been
12379 		 * freed while we slept.  Look it up again, and check to see
12380 		 * that it has completed.
12381 		 */
12382 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12383 			goto retry;
12384 		FREE_LOCK(ump);
12385 		return;
12386 	}
12387 	FREE_LOCK(ump);
12388 	if ((error = bwrite(ibp)) != 0)
12389 		softdep_error("softdep_update_inodeblock: bwrite", error);
12390 }
12391 
12392 /*
12393  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12394  * old inode dependency list (such as id_inoupdt).
12395  */
12396 static void
12397 merge_inode_lists(newlisthead, oldlisthead)
12398 	struct allocdirectlst *newlisthead;
12399 	struct allocdirectlst *oldlisthead;
12400 {
12401 	struct allocdirect *listadp, *newadp;
12402 
12403 	newadp = TAILQ_FIRST(newlisthead);
12404 	if (newadp != NULL)
12405 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12406 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12407 		if (listadp->ad_offset < newadp->ad_offset) {
12408 			listadp = TAILQ_NEXT(listadp, ad_next);
12409 			continue;
12410 		}
12411 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12412 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12413 		if (listadp->ad_offset == newadp->ad_offset) {
12414 			allocdirect_merge(oldlisthead, newadp,
12415 			    listadp);
12416 			listadp = newadp;
12417 		}
12418 		newadp = TAILQ_FIRST(newlisthead);
12419 	}
12420 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12421 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12422 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12423 	}
12424 }
12425 
12426 /*
12427  * If we are doing an fsync, then we must ensure that any directory
12428  * entries for the inode have been written after the inode gets to disk.
12429  */
12430 int
12431 softdep_fsync(vp)
12432 	struct vnode *vp;	/* the "in_core" copy of the inode */
12433 {
12434 	struct inodedep *inodedep;
12435 	struct pagedep *pagedep;
12436 	struct inoref *inoref;
12437 	struct ufsmount *ump;
12438 	struct worklist *wk;
12439 	struct diradd *dap;
12440 	struct mount *mp;
12441 	struct vnode *pvp;
12442 	struct inode *ip;
12443 	struct buf *bp;
12444 	struct fs *fs;
12445 	struct thread *td = curthread;
12446 	int error, flushparent, pagedep_new_block;
12447 	ino_t parentino;
12448 	ufs_lbn_t lbn;
12449 
12450 	ip = VTOI(vp);
12451 	mp = vp->v_mount;
12452 	ump = VFSTOUFS(mp);
12453 	fs = ump->um_fs;
12454 	if (MOUNTEDSOFTDEP(mp) == 0)
12455 		return (0);
12456 	ACQUIRE_LOCK(ump);
12457 restart:
12458 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12459 		FREE_LOCK(ump);
12460 		return (0);
12461 	}
12462 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12463 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12464 		    == DEPCOMPLETE) {
12465 			jwait(&inoref->if_list, MNT_WAIT);
12466 			goto restart;
12467 		}
12468 	}
12469 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12470 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12471 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12472 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12473 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12474 		panic("softdep_fsync: pending ops %p", inodedep);
12475 	for (error = 0, flushparent = 0; ; ) {
12476 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12477 			break;
12478 		if (wk->wk_type != D_DIRADD)
12479 			panic("softdep_fsync: Unexpected type %s",
12480 			    TYPENAME(wk->wk_type));
12481 		dap = WK_DIRADD(wk);
12482 		/*
12483 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12484 		 * dependency or is contained in a newly allocated block.
12485 		 */
12486 		if (dap->da_state & DIRCHG)
12487 			pagedep = dap->da_previous->dm_pagedep;
12488 		else
12489 			pagedep = dap->da_pagedep;
12490 		parentino = pagedep->pd_ino;
12491 		lbn = pagedep->pd_lbn;
12492 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12493 			panic("softdep_fsync: dirty");
12494 		if ((dap->da_state & MKDIR_PARENT) ||
12495 		    (pagedep->pd_state & NEWBLOCK))
12496 			flushparent = 1;
12497 		else
12498 			flushparent = 0;
12499 		/*
12500 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12501 		 * then we will not be able to release and recover the
12502 		 * vnode below, so we just have to give up on writing its
12503 		 * directory entry out. It will eventually be written, just
12504 		 * not now, but then the user was not asking to have it
12505 		 * written, so we are not breaking any promises.
12506 		 */
12507 		if (vp->v_iflag & VI_DOOMED)
12508 			break;
12509 		/*
12510 		 * We prevent deadlock by always fetching inodes from the
12511 		 * root, moving down the directory tree. Thus, when fetching
12512 		 * our parent directory, we first try to get the lock. If
12513 		 * that fails, we must unlock ourselves before requesting
12514 		 * the lock on our parent. See the comment in ufs_lookup
12515 		 * for details on possible races.
12516 		 */
12517 		FREE_LOCK(ump);
12518 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12519 		    FFSV_FORCEINSMQ)) {
12520 			/*
12521 			 * Unmount cannot proceed after unlock because
12522 			 * caller must have called vn_start_write().
12523 			 */
12524 			VOP_UNLOCK(vp, 0);
12525 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12526 			    &pvp, FFSV_FORCEINSMQ);
12527 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12528 			if (vp->v_iflag & VI_DOOMED) {
12529 				if (error == 0)
12530 					vput(pvp);
12531 				error = ENOENT;
12532 			}
12533 			if (error != 0)
12534 				return (error);
12535 		}
12536 		/*
12537 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12538 		 * that are contained in direct blocks will be resolved by
12539 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12540 		 * may require a complete sync'ing of the directory. So, we
12541 		 * try the cheap and fast ffs_update first, and if that fails,
12542 		 * then we do the slower ffs_syncvnode of the directory.
12543 		 */
12544 		if (flushparent) {
12545 			int locked;
12546 
12547 			if ((error = ffs_update(pvp, 1)) != 0) {
12548 				vput(pvp);
12549 				return (error);
12550 			}
12551 			ACQUIRE_LOCK(ump);
12552 			locked = 1;
12553 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12554 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12555 					if (wk->wk_type != D_DIRADD)
12556 						panic("softdep_fsync: Unexpected type %s",
12557 						      TYPENAME(wk->wk_type));
12558 					dap = WK_DIRADD(wk);
12559 					if (dap->da_state & DIRCHG)
12560 						pagedep = dap->da_previous->dm_pagedep;
12561 					else
12562 						pagedep = dap->da_pagedep;
12563 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12564 					FREE_LOCK(ump);
12565 					locked = 0;
12566 					if (pagedep_new_block && (error =
12567 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12568 						vput(pvp);
12569 						return (error);
12570 					}
12571 				}
12572 			}
12573 			if (locked)
12574 				FREE_LOCK(ump);
12575 		}
12576 		/*
12577 		 * Flush directory page containing the inode's name.
12578 		 */
12579 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12580 		    &bp);
12581 		if (error == 0)
12582 			error = bwrite(bp);
12583 		else
12584 			brelse(bp);
12585 		vput(pvp);
12586 		if (error != 0)
12587 			return (error);
12588 		ACQUIRE_LOCK(ump);
12589 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12590 			break;
12591 	}
12592 	FREE_LOCK(ump);
12593 	return (0);
12594 }
12595 
12596 /*
12597  * Flush all the dirty bitmaps associated with the block device
12598  * before flushing the rest of the dirty blocks so as to reduce
12599  * the number of dependencies that will have to be rolled back.
12600  *
12601  * XXX Unused?
12602  */
12603 void
12604 softdep_fsync_mountdev(vp)
12605 	struct vnode *vp;
12606 {
12607 	struct buf *bp, *nbp;
12608 	struct worklist *wk;
12609 	struct bufobj *bo;
12610 
12611 	if (!vn_isdisk(vp, NULL))
12612 		panic("softdep_fsync_mountdev: vnode not a disk");
12613 	bo = &vp->v_bufobj;
12614 restart:
12615 	BO_LOCK(bo);
12616 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12617 		/*
12618 		 * If it is already scheduled, skip to the next buffer.
12619 		 */
12620 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12621 			continue;
12622 
12623 		if ((bp->b_flags & B_DELWRI) == 0)
12624 			panic("softdep_fsync_mountdev: not dirty");
12625 		/*
12626 		 * We are only interested in bitmaps with outstanding
12627 		 * dependencies.
12628 		 */
12629 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12630 		    wk->wk_type != D_BMSAFEMAP ||
12631 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12632 			BUF_UNLOCK(bp);
12633 			continue;
12634 		}
12635 		BO_UNLOCK(bo);
12636 		bremfree(bp);
12637 		(void) bawrite(bp);
12638 		goto restart;
12639 	}
12640 	drain_output(vp);
12641 	BO_UNLOCK(bo);
12642 }
12643 
12644 /*
12645  * Sync all cylinder groups that were dirty at the time this function is
12646  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12647  * is used to flush freedep activity that may be holding up writes to a
12648  * indirect block.
12649  */
12650 static int
12651 sync_cgs(mp, waitfor)
12652 	struct mount *mp;
12653 	int waitfor;
12654 {
12655 	struct bmsafemap *bmsafemap;
12656 	struct bmsafemap *sentinel;
12657 	struct ufsmount *ump;
12658 	struct buf *bp;
12659 	int error;
12660 
12661 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12662 	sentinel->sm_cg = -1;
12663 	ump = VFSTOUFS(mp);
12664 	error = 0;
12665 	ACQUIRE_LOCK(ump);
12666 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12667 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12668 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12669 		/* Skip sentinels and cgs with no work to release. */
12670 		if (bmsafemap->sm_cg == -1 ||
12671 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12672 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12673 			LIST_REMOVE(sentinel, sm_next);
12674 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12675 			continue;
12676 		}
12677 		/*
12678 		 * If we don't get the lock and we're waiting try again, if
12679 		 * not move on to the next buf and try to sync it.
12680 		 */
12681 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12682 		if (bp == NULL && waitfor == MNT_WAIT)
12683 			continue;
12684 		LIST_REMOVE(sentinel, sm_next);
12685 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12686 		if (bp == NULL)
12687 			continue;
12688 		FREE_LOCK(ump);
12689 		if (waitfor == MNT_NOWAIT)
12690 			bawrite(bp);
12691 		else
12692 			error = bwrite(bp);
12693 		ACQUIRE_LOCK(ump);
12694 		if (error)
12695 			break;
12696 	}
12697 	LIST_REMOVE(sentinel, sm_next);
12698 	FREE_LOCK(ump);
12699 	free(sentinel, M_BMSAFEMAP);
12700 	return (error);
12701 }
12702 
12703 /*
12704  * This routine is called when we are trying to synchronously flush a
12705  * file. This routine must eliminate any filesystem metadata dependencies
12706  * so that the syncing routine can succeed.
12707  */
12708 int
12709 softdep_sync_metadata(struct vnode *vp)
12710 {
12711 	struct inode *ip;
12712 	int error;
12713 
12714 	ip = VTOI(vp);
12715 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12716 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12717 	/*
12718 	 * Ensure that any direct block dependencies have been cleared,
12719 	 * truncations are started, and inode references are journaled.
12720 	 */
12721 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12722 	/*
12723 	 * Write all journal records to prevent rollbacks on devvp.
12724 	 */
12725 	if (vp->v_type == VCHR)
12726 		softdep_flushjournal(vp->v_mount);
12727 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12728 	/*
12729 	 * Ensure that all truncates are written so we won't find deps on
12730 	 * indirect blocks.
12731 	 */
12732 	process_truncates(vp);
12733 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12734 
12735 	return (error);
12736 }
12737 
12738 /*
12739  * This routine is called when we are attempting to sync a buf with
12740  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12741  * other IO it can but returns EBUSY if the buffer is not yet able to
12742  * be written.  Dependencies which will not cause rollbacks will always
12743  * return 0.
12744  */
12745 int
12746 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12747 {
12748 	struct indirdep *indirdep;
12749 	struct pagedep *pagedep;
12750 	struct allocindir *aip;
12751 	struct newblk *newblk;
12752 	struct ufsmount *ump;
12753 	struct buf *nbp;
12754 	struct worklist *wk;
12755 	int i, error;
12756 
12757 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12758 	    ("softdep_sync_buf called on non-softdep filesystem"));
12759 	/*
12760 	 * For VCHR we just don't want to force flush any dependencies that
12761 	 * will cause rollbacks.
12762 	 */
12763 	if (vp->v_type == VCHR) {
12764 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12765 			return (EBUSY);
12766 		return (0);
12767 	}
12768 	ump = VFSTOUFS(vp->v_mount);
12769 	ACQUIRE_LOCK(ump);
12770 	/*
12771 	 * As we hold the buffer locked, none of its dependencies
12772 	 * will disappear.
12773 	 */
12774 	error = 0;
12775 top:
12776 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12777 		switch (wk->wk_type) {
12778 
12779 		case D_ALLOCDIRECT:
12780 		case D_ALLOCINDIR:
12781 			newblk = WK_NEWBLK(wk);
12782 			if (newblk->nb_jnewblk != NULL) {
12783 				if (waitfor == MNT_NOWAIT) {
12784 					error = EBUSY;
12785 					goto out_unlock;
12786 				}
12787 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12788 				goto top;
12789 			}
12790 			if (newblk->nb_state & DEPCOMPLETE ||
12791 			    waitfor == MNT_NOWAIT)
12792 				continue;
12793 			nbp = newblk->nb_bmsafemap->sm_buf;
12794 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12795 			if (nbp == NULL)
12796 				goto top;
12797 			FREE_LOCK(ump);
12798 			if ((error = bwrite(nbp)) != 0)
12799 				goto out;
12800 			ACQUIRE_LOCK(ump);
12801 			continue;
12802 
12803 		case D_INDIRDEP:
12804 			indirdep = WK_INDIRDEP(wk);
12805 			if (waitfor == MNT_NOWAIT) {
12806 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12807 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12808 					error = EBUSY;
12809 					goto out_unlock;
12810 				}
12811 			}
12812 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12813 				panic("softdep_sync_buf: truncation pending.");
12814 		restart:
12815 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12816 				newblk = (struct newblk *)aip;
12817 				if (newblk->nb_jnewblk != NULL) {
12818 					jwait(&newblk->nb_jnewblk->jn_list,
12819 					    waitfor);
12820 					goto restart;
12821 				}
12822 				if (newblk->nb_state & DEPCOMPLETE)
12823 					continue;
12824 				nbp = newblk->nb_bmsafemap->sm_buf;
12825 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12826 				if (nbp == NULL)
12827 					goto restart;
12828 				FREE_LOCK(ump);
12829 				if ((error = bwrite(nbp)) != 0)
12830 					goto out;
12831 				ACQUIRE_LOCK(ump);
12832 				goto restart;
12833 			}
12834 			continue;
12835 
12836 		case D_PAGEDEP:
12837 			/*
12838 			 * Only flush directory entries in synchronous passes.
12839 			 */
12840 			if (waitfor != MNT_WAIT) {
12841 				error = EBUSY;
12842 				goto out_unlock;
12843 			}
12844 			/*
12845 			 * While syncing snapshots, we must allow recursive
12846 			 * lookups.
12847 			 */
12848 			BUF_AREC(bp);
12849 			/*
12850 			 * We are trying to sync a directory that may
12851 			 * have dependencies on both its own metadata
12852 			 * and/or dependencies on the inodes of any
12853 			 * recently allocated files. We walk its diradd
12854 			 * lists pushing out the associated inode.
12855 			 */
12856 			pagedep = WK_PAGEDEP(wk);
12857 			for (i = 0; i < DAHASHSZ; i++) {
12858 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12859 					continue;
12860 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12861 				    &pagedep->pd_diraddhd[i]))) {
12862 					BUF_NOREC(bp);
12863 					goto out_unlock;
12864 				}
12865 			}
12866 			BUF_NOREC(bp);
12867 			continue;
12868 
12869 		case D_FREEWORK:
12870 		case D_FREEDEP:
12871 		case D_JSEGDEP:
12872 		case D_JNEWBLK:
12873 			continue;
12874 
12875 		default:
12876 			panic("softdep_sync_buf: Unknown type %s",
12877 			    TYPENAME(wk->wk_type));
12878 			/* NOTREACHED */
12879 		}
12880 	}
12881 out_unlock:
12882 	FREE_LOCK(ump);
12883 out:
12884 	return (error);
12885 }
12886 
12887 /*
12888  * Flush the dependencies associated with an inodedep.
12889  */
12890 static int
12891 flush_inodedep_deps(vp, mp, ino)
12892 	struct vnode *vp;
12893 	struct mount *mp;
12894 	ino_t ino;
12895 {
12896 	struct inodedep *inodedep;
12897 	struct inoref *inoref;
12898 	struct ufsmount *ump;
12899 	int error, waitfor;
12900 
12901 	/*
12902 	 * This work is done in two passes. The first pass grabs most
12903 	 * of the buffers and begins asynchronously writing them. The
12904 	 * only way to wait for these asynchronous writes is to sleep
12905 	 * on the filesystem vnode which may stay busy for a long time
12906 	 * if the filesystem is active. So, instead, we make a second
12907 	 * pass over the dependencies blocking on each write. In the
12908 	 * usual case we will be blocking against a write that we
12909 	 * initiated, so when it is done the dependency will have been
12910 	 * resolved. Thus the second pass is expected to end quickly.
12911 	 * We give a brief window at the top of the loop to allow
12912 	 * any pending I/O to complete.
12913 	 */
12914 	ump = VFSTOUFS(mp);
12915 	LOCK_OWNED(ump);
12916 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12917 		if (error)
12918 			return (error);
12919 		FREE_LOCK(ump);
12920 		ACQUIRE_LOCK(ump);
12921 restart:
12922 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12923 			return (0);
12924 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12925 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12926 			    == DEPCOMPLETE) {
12927 				jwait(&inoref->if_list, MNT_WAIT);
12928 				goto restart;
12929 			}
12930 		}
12931 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12932 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12933 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12934 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12935 			continue;
12936 		/*
12937 		 * If pass2, we are done, otherwise do pass 2.
12938 		 */
12939 		if (waitfor == MNT_WAIT)
12940 			break;
12941 		waitfor = MNT_WAIT;
12942 	}
12943 	/*
12944 	 * Try freeing inodedep in case all dependencies have been removed.
12945 	 */
12946 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12947 		(void) free_inodedep(inodedep);
12948 	return (0);
12949 }
12950 
12951 /*
12952  * Flush an inode dependency list.
12953  */
12954 static int
12955 flush_deplist(listhead, waitfor, errorp)
12956 	struct allocdirectlst *listhead;
12957 	int waitfor;
12958 	int *errorp;
12959 {
12960 	struct allocdirect *adp;
12961 	struct newblk *newblk;
12962 	struct ufsmount *ump;
12963 	struct buf *bp;
12964 
12965 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
12966 		return (0);
12967 	ump = VFSTOUFS(adp->ad_list.wk_mp);
12968 	LOCK_OWNED(ump);
12969 	TAILQ_FOREACH(adp, listhead, ad_next) {
12970 		newblk = (struct newblk *)adp;
12971 		if (newblk->nb_jnewblk != NULL) {
12972 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12973 			return (1);
12974 		}
12975 		if (newblk->nb_state & DEPCOMPLETE)
12976 			continue;
12977 		bp = newblk->nb_bmsafemap->sm_buf;
12978 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12979 		if (bp == NULL) {
12980 			if (waitfor == MNT_NOWAIT)
12981 				continue;
12982 			return (1);
12983 		}
12984 		FREE_LOCK(ump);
12985 		if (waitfor == MNT_NOWAIT)
12986 			bawrite(bp);
12987 		else
12988 			*errorp = bwrite(bp);
12989 		ACQUIRE_LOCK(ump);
12990 		return (1);
12991 	}
12992 	return (0);
12993 }
12994 
12995 /*
12996  * Flush dependencies associated with an allocdirect block.
12997  */
12998 static int
12999 flush_newblk_dep(vp, mp, lbn)
13000 	struct vnode *vp;
13001 	struct mount *mp;
13002 	ufs_lbn_t lbn;
13003 {
13004 	struct newblk *newblk;
13005 	struct ufsmount *ump;
13006 	struct bufobj *bo;
13007 	struct inode *ip;
13008 	struct buf *bp;
13009 	ufs2_daddr_t blkno;
13010 	int error;
13011 
13012 	error = 0;
13013 	bo = &vp->v_bufobj;
13014 	ip = VTOI(vp);
13015 	blkno = DIP(ip, i_db[lbn]);
13016 	if (blkno == 0)
13017 		panic("flush_newblk_dep: Missing block");
13018 	ump = VFSTOUFS(mp);
13019 	ACQUIRE_LOCK(ump);
13020 	/*
13021 	 * Loop until all dependencies related to this block are satisfied.
13022 	 * We must be careful to restart after each sleep in case a write
13023 	 * completes some part of this process for us.
13024 	 */
13025 	for (;;) {
13026 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13027 			FREE_LOCK(ump);
13028 			break;
13029 		}
13030 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13031 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13032 		/*
13033 		 * Flush the journal.
13034 		 */
13035 		if (newblk->nb_jnewblk != NULL) {
13036 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13037 			continue;
13038 		}
13039 		/*
13040 		 * Write the bitmap dependency.
13041 		 */
13042 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13043 			bp = newblk->nb_bmsafemap->sm_buf;
13044 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13045 			if (bp == NULL)
13046 				continue;
13047 			FREE_LOCK(ump);
13048 			error = bwrite(bp);
13049 			if (error)
13050 				break;
13051 			ACQUIRE_LOCK(ump);
13052 			continue;
13053 		}
13054 		/*
13055 		 * Write the buffer.
13056 		 */
13057 		FREE_LOCK(ump);
13058 		BO_LOCK(bo);
13059 		bp = gbincore(bo, lbn);
13060 		if (bp != NULL) {
13061 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13062 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13063 			if (error == ENOLCK) {
13064 				ACQUIRE_LOCK(ump);
13065 				error = 0;
13066 				continue; /* Slept, retry */
13067 			}
13068 			if (error != 0)
13069 				break;	/* Failed */
13070 			if (bp->b_flags & B_DELWRI) {
13071 				bremfree(bp);
13072 				error = bwrite(bp);
13073 				if (error)
13074 					break;
13075 			} else
13076 				BUF_UNLOCK(bp);
13077 		} else
13078 			BO_UNLOCK(bo);
13079 		/*
13080 		 * We have to wait for the direct pointers to
13081 		 * point at the newdirblk before the dependency
13082 		 * will go away.
13083 		 */
13084 		error = ffs_update(vp, 1);
13085 		if (error)
13086 			break;
13087 		ACQUIRE_LOCK(ump);
13088 	}
13089 	return (error);
13090 }
13091 
13092 /*
13093  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13094  */
13095 static int
13096 flush_pagedep_deps(pvp, mp, diraddhdp)
13097 	struct vnode *pvp;
13098 	struct mount *mp;
13099 	struct diraddhd *diraddhdp;
13100 {
13101 	struct inodedep *inodedep;
13102 	struct inoref *inoref;
13103 	struct ufsmount *ump;
13104 	struct diradd *dap;
13105 	struct vnode *vp;
13106 	int error = 0;
13107 	struct buf *bp;
13108 	ino_t inum;
13109 	struct diraddhd unfinished;
13110 
13111 	LIST_INIT(&unfinished);
13112 	ump = VFSTOUFS(mp);
13113 	LOCK_OWNED(ump);
13114 restart:
13115 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13116 		/*
13117 		 * Flush ourselves if this directory entry
13118 		 * has a MKDIR_PARENT dependency.
13119 		 */
13120 		if (dap->da_state & MKDIR_PARENT) {
13121 			FREE_LOCK(ump);
13122 			if ((error = ffs_update(pvp, 1)) != 0)
13123 				break;
13124 			ACQUIRE_LOCK(ump);
13125 			/*
13126 			 * If that cleared dependencies, go on to next.
13127 			 */
13128 			if (dap != LIST_FIRST(diraddhdp))
13129 				continue;
13130 			/*
13131 			 * All MKDIR_PARENT dependencies and all the
13132 			 * NEWBLOCK pagedeps that are contained in direct
13133 			 * blocks were resolved by doing above ffs_update.
13134 			 * Pagedeps contained in indirect blocks may
13135 			 * require a complete sync'ing of the directory.
13136 			 * We are in the midst of doing a complete sync,
13137 			 * so if they are not resolved in this pass we
13138 			 * defer them for now as they will be sync'ed by
13139 			 * our caller shortly.
13140 			 */
13141 			LIST_REMOVE(dap, da_pdlist);
13142 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13143 			continue;
13144 		}
13145 		/*
13146 		 * A newly allocated directory must have its "." and
13147 		 * ".." entries written out before its name can be
13148 		 * committed in its parent.
13149 		 */
13150 		inum = dap->da_newinum;
13151 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13152 			panic("flush_pagedep_deps: lost inode1");
13153 		/*
13154 		 * Wait for any pending journal adds to complete so we don't
13155 		 * cause rollbacks while syncing.
13156 		 */
13157 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13158 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13159 			    == DEPCOMPLETE) {
13160 				jwait(&inoref->if_list, MNT_WAIT);
13161 				goto restart;
13162 			}
13163 		}
13164 		if (dap->da_state & MKDIR_BODY) {
13165 			FREE_LOCK(ump);
13166 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13167 			    FFSV_FORCEINSMQ)))
13168 				break;
13169 			error = flush_newblk_dep(vp, mp, 0);
13170 			/*
13171 			 * If we still have the dependency we might need to
13172 			 * update the vnode to sync the new link count to
13173 			 * disk.
13174 			 */
13175 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13176 				error = ffs_update(vp, 1);
13177 			vput(vp);
13178 			if (error != 0)
13179 				break;
13180 			ACQUIRE_LOCK(ump);
13181 			/*
13182 			 * If that cleared dependencies, go on to next.
13183 			 */
13184 			if (dap != LIST_FIRST(diraddhdp))
13185 				continue;
13186 			if (dap->da_state & MKDIR_BODY) {
13187 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13188 				    &inodedep);
13189 				panic("flush_pagedep_deps: MKDIR_BODY "
13190 				    "inodedep %p dap %p vp %p",
13191 				    inodedep, dap, vp);
13192 			}
13193 		}
13194 		/*
13195 		 * Flush the inode on which the directory entry depends.
13196 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13197 		 * the only remaining dependency is that the updated inode
13198 		 * count must get pushed to disk. The inode has already
13199 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13200 		 * the time of the reference count change. So we need only
13201 		 * locate that buffer, ensure that there will be no rollback
13202 		 * caused by a bitmap dependency, then write the inode buffer.
13203 		 */
13204 retry:
13205 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13206 			panic("flush_pagedep_deps: lost inode");
13207 		/*
13208 		 * If the inode still has bitmap dependencies,
13209 		 * push them to disk.
13210 		 */
13211 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13212 			bp = inodedep->id_bmsafemap->sm_buf;
13213 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13214 			if (bp == NULL)
13215 				goto retry;
13216 			FREE_LOCK(ump);
13217 			if ((error = bwrite(bp)) != 0)
13218 				break;
13219 			ACQUIRE_LOCK(ump);
13220 			if (dap != LIST_FIRST(diraddhdp))
13221 				continue;
13222 		}
13223 		/*
13224 		 * If the inode is still sitting in a buffer waiting
13225 		 * to be written or waiting for the link count to be
13226 		 * adjusted update it here to flush it to disk.
13227 		 */
13228 		if (dap == LIST_FIRST(diraddhdp)) {
13229 			FREE_LOCK(ump);
13230 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13231 			    FFSV_FORCEINSMQ)))
13232 				break;
13233 			error = ffs_update(vp, 1);
13234 			vput(vp);
13235 			if (error)
13236 				break;
13237 			ACQUIRE_LOCK(ump);
13238 		}
13239 		/*
13240 		 * If we have failed to get rid of all the dependencies
13241 		 * then something is seriously wrong.
13242 		 */
13243 		if (dap == LIST_FIRST(diraddhdp)) {
13244 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13245 			panic("flush_pagedep_deps: failed to flush "
13246 			    "inodedep %p ino %ju dap %p",
13247 			    inodedep, (uintmax_t)inum, dap);
13248 		}
13249 	}
13250 	if (error)
13251 		ACQUIRE_LOCK(ump);
13252 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13253 		LIST_REMOVE(dap, da_pdlist);
13254 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13255 	}
13256 	return (error);
13257 }
13258 
13259 /*
13260  * A large burst of file addition or deletion activity can drive the
13261  * memory load excessively high. First attempt to slow things down
13262  * using the techniques below. If that fails, this routine requests
13263  * the offending operations to fall back to running synchronously
13264  * until the memory load returns to a reasonable level.
13265  */
13266 int
13267 softdep_slowdown(vp)
13268 	struct vnode *vp;
13269 {
13270 	struct ufsmount *ump;
13271 	int jlow;
13272 	int max_softdeps_hard;
13273 
13274 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13275 	    ("softdep_slowdown called on non-softdep filesystem"));
13276 	ump = VFSTOUFS(vp->v_mount);
13277 	ACQUIRE_LOCK(ump);
13278 	jlow = 0;
13279 	/*
13280 	 * Check for journal space if needed.
13281 	 */
13282 	if (DOINGSUJ(vp)) {
13283 		if (journal_space(ump, 0) == 0)
13284 			jlow = 1;
13285 	}
13286 	/*
13287 	 * If the system is under its limits and our filesystem is
13288 	 * not responsible for more than our share of the usage and
13289 	 * we are not low on journal space, then no need to slow down.
13290 	 */
13291 	max_softdeps_hard = max_softdeps * 11 / 10;
13292 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13293 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13294 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13295 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13296 	    ump->softdep_curdeps[D_DIRREM] <
13297 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13298 	    ump->softdep_curdeps[D_INODEDEP] <
13299 	    max_softdeps_hard / stat_flush_threads &&
13300 	    ump->softdep_curdeps[D_INDIRDEP] <
13301 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13302 	    ump->softdep_curdeps[D_FREEBLKS] <
13303 	    max_softdeps_hard / stat_flush_threads) {
13304 		FREE_LOCK(ump);
13305   		return (0);
13306 	}
13307 	/*
13308 	 * If the journal is low or our filesystem is over its limit
13309 	 * then speedup the cleanup.
13310 	 */
13311 	if (ump->softdep_curdeps[D_INDIRDEP] <
13312 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13313 		softdep_speedup(ump);
13314 	stat_sync_limit_hit += 1;
13315 	FREE_LOCK(ump);
13316 	/*
13317 	 * We only slow down the rate at which new dependencies are
13318 	 * generated if we are not using journaling. With journaling,
13319 	 * the cleanup should always be sufficient to keep things
13320 	 * under control.
13321 	 */
13322 	if (DOINGSUJ(vp))
13323 		return (0);
13324 	return (1);
13325 }
13326 
13327 /*
13328  * Called by the allocation routines when they are about to fail
13329  * in the hope that we can free up the requested resource (inodes
13330  * or disk space).
13331  *
13332  * First check to see if the work list has anything on it. If it has,
13333  * clean up entries until we successfully free the requested resource.
13334  * Because this process holds inodes locked, we cannot handle any remove
13335  * requests that might block on a locked inode as that could lead to
13336  * deadlock. If the worklist yields none of the requested resource,
13337  * start syncing out vnodes to free up the needed space.
13338  */
13339 int
13340 softdep_request_cleanup(fs, vp, cred, resource)
13341 	struct fs *fs;
13342 	struct vnode *vp;
13343 	struct ucred *cred;
13344 	int resource;
13345 {
13346 	struct ufsmount *ump;
13347 	struct mount *mp;
13348 	long starttime;
13349 	ufs2_daddr_t needed;
13350 	int error, failed_vnode;
13351 
13352 	/*
13353 	 * If we are being called because of a process doing a
13354 	 * copy-on-write, then it is not safe to process any
13355 	 * worklist items as we will recurse into the copyonwrite
13356 	 * routine.  This will result in an incoherent snapshot.
13357 	 * If the vnode that we hold is a snapshot, we must avoid
13358 	 * handling other resources that could cause deadlock.
13359 	 */
13360 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13361 		return (0);
13362 
13363 	if (resource == FLUSH_BLOCKS_WAIT)
13364 		stat_cleanup_blkrequests += 1;
13365 	else
13366 		stat_cleanup_inorequests += 1;
13367 
13368 	mp = vp->v_mount;
13369 	ump = VFSTOUFS(mp);
13370 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13371 	UFS_UNLOCK(ump);
13372 	error = ffs_update(vp, 1);
13373 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13374 		UFS_LOCK(ump);
13375 		return (0);
13376 	}
13377 	/*
13378 	 * If we are in need of resources, start by cleaning up
13379 	 * any block removals associated with our inode.
13380 	 */
13381 	ACQUIRE_LOCK(ump);
13382 	process_removes(vp);
13383 	process_truncates(vp);
13384 	FREE_LOCK(ump);
13385 	/*
13386 	 * Now clean up at least as many resources as we will need.
13387 	 *
13388 	 * When requested to clean up inodes, the number that are needed
13389 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13390 	 * plus a bit of slop (2) in case some more writers show up while
13391 	 * we are cleaning.
13392 	 *
13393 	 * When requested to free up space, the amount of space that
13394 	 * we need is enough blocks to allocate a full-sized segment
13395 	 * (fs_contigsumsize). The number of such segments that will
13396 	 * be needed is set by the number of simultaneous writers
13397 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13398 	 * writers show up while we are cleaning.
13399 	 *
13400 	 * Additionally, if we are unpriviledged and allocating space,
13401 	 * we need to ensure that we clean up enough blocks to get the
13402 	 * needed number of blocks over the threshold of the minimum
13403 	 * number of blocks required to be kept free by the filesystem
13404 	 * (fs_minfree).
13405 	 */
13406 	if (resource == FLUSH_INODES_WAIT) {
13407 		needed = vfs_mount_fetch_counter(vp->v_mount,
13408 		    MNT_COUNT_WRITEOPCOUNT) + 2;
13409 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13410 		needed = (vfs_mount_fetch_counter(vp->v_mount,
13411 		    MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13412 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13413 			needed += fragstoblks(fs,
13414 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13415 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13416 	} else {
13417 		UFS_LOCK(ump);
13418 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13419 		    resource);
13420 		return (0);
13421 	}
13422 	starttime = time_second;
13423 retry:
13424 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13425 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13426 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13427 	    fs->fs_cstotal.cs_nifree <= needed)) {
13428 		ACQUIRE_LOCK(ump);
13429 		if (ump->softdep_on_worklist > 0 &&
13430 		    process_worklist_item(UFSTOVFS(ump),
13431 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13432 			stat_worklist_push += 1;
13433 		FREE_LOCK(ump);
13434 	}
13435 	/*
13436 	 * If we still need resources and there are no more worklist
13437 	 * entries to process to obtain them, we have to start flushing
13438 	 * the dirty vnodes to force the release of additional requests
13439 	 * to the worklist that we can then process to reap addition
13440 	 * resources. We walk the vnodes associated with the mount point
13441 	 * until we get the needed worklist requests that we can reap.
13442 	 *
13443 	 * If there are several threads all needing to clean the same
13444 	 * mount point, only one is allowed to walk the mount list.
13445 	 * When several threads all try to walk the same mount list,
13446 	 * they end up competing with each other and often end up in
13447 	 * livelock. This approach ensures that forward progress is
13448 	 * made at the cost of occational ENOSPC errors being returned
13449 	 * that might otherwise have been avoided.
13450 	 */
13451 	error = 1;
13452 	if ((resource == FLUSH_BLOCKS_WAIT &&
13453 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13454 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13455 	     fs->fs_cstotal.cs_nifree <= needed)) {
13456 		ACQUIRE_LOCK(ump);
13457 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13458 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13459 			FREE_LOCK(ump);
13460 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13461 			ACQUIRE_LOCK(ump);
13462 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13463 			FREE_LOCK(ump);
13464 			if (ump->softdep_on_worklist > 0) {
13465 				stat_cleanup_retries += 1;
13466 				if (!failed_vnode)
13467 					goto retry;
13468 			}
13469 		} else {
13470 			FREE_LOCK(ump);
13471 			error = 0;
13472 		}
13473 		stat_cleanup_failures += 1;
13474 	}
13475 	if (time_second - starttime > stat_cleanup_high_delay)
13476 		stat_cleanup_high_delay = time_second - starttime;
13477 	UFS_LOCK(ump);
13478 	return (error);
13479 }
13480 
13481 /*
13482  * Scan the vnodes for the specified mount point flushing out any
13483  * vnodes that can be locked without waiting. Finally, try to flush
13484  * the device associated with the mount point if it can be locked
13485  * without waiting.
13486  *
13487  * We return 0 if we were able to lock every vnode in our scan.
13488  * If we had to skip one or more vnodes, we return 1.
13489  */
13490 static int
13491 softdep_request_cleanup_flush(mp, ump)
13492 	struct mount *mp;
13493 	struct ufsmount *ump;
13494 {
13495 	struct thread *td;
13496 	struct vnode *lvp, *mvp;
13497 	int failed_vnode;
13498 
13499 	failed_vnode = 0;
13500 	td = curthread;
13501 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13502 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13503 			VI_UNLOCK(lvp);
13504 			continue;
13505 		}
13506 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13507 		    td) != 0) {
13508 			failed_vnode = 1;
13509 			continue;
13510 		}
13511 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13512 			vput(lvp);
13513 			continue;
13514 		}
13515 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13516 		vput(lvp);
13517 	}
13518 	lvp = ump->um_devvp;
13519 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13520 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13521 		VOP_UNLOCK(lvp, 0);
13522 	}
13523 	return (failed_vnode);
13524 }
13525 
13526 static bool
13527 softdep_excess_items(struct ufsmount *ump, int item)
13528 {
13529 
13530 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13531 	return (dep_current[item] > max_softdeps &&
13532 	    ump->softdep_curdeps[item] > max_softdeps /
13533 	    stat_flush_threads);
13534 }
13535 
13536 static void
13537 schedule_cleanup(struct mount *mp)
13538 {
13539 	struct ufsmount *ump;
13540 	struct thread *td;
13541 
13542 	ump = VFSTOUFS(mp);
13543 	LOCK_OWNED(ump);
13544 	FREE_LOCK(ump);
13545 	td = curthread;
13546 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13547 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13548 		/*
13549 		 * No ast is delivered to kernel threads, so nobody
13550 		 * would deref the mp.  Some kernel threads
13551 		 * explicitely check for AST, e.g. NFS daemon does
13552 		 * this in the serving loop.
13553 		 */
13554 		return;
13555 	}
13556 	if (td->td_su != NULL)
13557 		vfs_rel(td->td_su);
13558 	vfs_ref(mp);
13559 	td->td_su = mp;
13560 	thread_lock(td);
13561 	td->td_flags |= TDF_ASTPENDING;
13562 	thread_unlock(td);
13563 }
13564 
13565 static void
13566 softdep_ast_cleanup_proc(struct thread *td)
13567 {
13568 	struct mount *mp;
13569 	struct ufsmount *ump;
13570 	int error;
13571 	bool req;
13572 
13573 	while ((mp = td->td_su) != NULL) {
13574 		td->td_su = NULL;
13575 		error = vfs_busy(mp, MBF_NOWAIT);
13576 		vfs_rel(mp);
13577 		if (error != 0)
13578 			return;
13579 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13580 			ump = VFSTOUFS(mp);
13581 			for (;;) {
13582 				req = false;
13583 				ACQUIRE_LOCK(ump);
13584 				if (softdep_excess_items(ump, D_INODEDEP)) {
13585 					req = true;
13586 					request_cleanup(mp, FLUSH_INODES);
13587 				}
13588 				if (softdep_excess_items(ump, D_DIRREM)) {
13589 					req = true;
13590 					request_cleanup(mp, FLUSH_BLOCKS);
13591 				}
13592 				FREE_LOCK(ump);
13593 				if (softdep_excess_items(ump, D_NEWBLK) ||
13594 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13595 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13596 					error = vn_start_write(NULL, &mp,
13597 					    V_WAIT);
13598 					if (error == 0) {
13599 						req = true;
13600 						VFS_SYNC(mp, MNT_WAIT);
13601 						vn_finished_write(mp);
13602 					}
13603 				}
13604 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13605 					break;
13606 			}
13607 		}
13608 		vfs_unbusy(mp);
13609 	}
13610 	if ((mp = td->td_su) != NULL) {
13611 		td->td_su = NULL;
13612 		vfs_rel(mp);
13613 	}
13614 }
13615 
13616 /*
13617  * If memory utilization has gotten too high, deliberately slow things
13618  * down and speed up the I/O processing.
13619  */
13620 static int
13621 request_cleanup(mp, resource)
13622 	struct mount *mp;
13623 	int resource;
13624 {
13625 	struct thread *td = curthread;
13626 	struct ufsmount *ump;
13627 
13628 	ump = VFSTOUFS(mp);
13629 	LOCK_OWNED(ump);
13630 	/*
13631 	 * We never hold up the filesystem syncer or buf daemon.
13632 	 */
13633 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13634 		return (0);
13635 	/*
13636 	 * First check to see if the work list has gotten backlogged.
13637 	 * If it has, co-opt this process to help clean up two entries.
13638 	 * Because this process may hold inodes locked, we cannot
13639 	 * handle any remove requests that might block on a locked
13640 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13641 	 * to avoid recursively processing the worklist.
13642 	 */
13643 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13644 		td->td_pflags |= TDP_SOFTDEP;
13645 		process_worklist_item(mp, 2, LK_NOWAIT);
13646 		td->td_pflags &= ~TDP_SOFTDEP;
13647 		stat_worklist_push += 2;
13648 		return(1);
13649 	}
13650 	/*
13651 	 * Next, we attempt to speed up the syncer process. If that
13652 	 * is successful, then we allow the process to continue.
13653 	 */
13654 	if (softdep_speedup(ump) &&
13655 	    resource != FLUSH_BLOCKS_WAIT &&
13656 	    resource != FLUSH_INODES_WAIT)
13657 		return(0);
13658 	/*
13659 	 * If we are resource constrained on inode dependencies, try
13660 	 * flushing some dirty inodes. Otherwise, we are constrained
13661 	 * by file deletions, so try accelerating flushes of directories
13662 	 * with removal dependencies. We would like to do the cleanup
13663 	 * here, but we probably hold an inode locked at this point and
13664 	 * that might deadlock against one that we try to clean. So,
13665 	 * the best that we can do is request the syncer daemon to do
13666 	 * the cleanup for us.
13667 	 */
13668 	switch (resource) {
13669 
13670 	case FLUSH_INODES:
13671 	case FLUSH_INODES_WAIT:
13672 		ACQUIRE_GBLLOCK(&lk);
13673 		stat_ino_limit_push += 1;
13674 		req_clear_inodedeps += 1;
13675 		FREE_GBLLOCK(&lk);
13676 		stat_countp = &stat_ino_limit_hit;
13677 		break;
13678 
13679 	case FLUSH_BLOCKS:
13680 	case FLUSH_BLOCKS_WAIT:
13681 		ACQUIRE_GBLLOCK(&lk);
13682 		stat_blk_limit_push += 1;
13683 		req_clear_remove += 1;
13684 		FREE_GBLLOCK(&lk);
13685 		stat_countp = &stat_blk_limit_hit;
13686 		break;
13687 
13688 	default:
13689 		panic("request_cleanup: unknown type");
13690 	}
13691 	/*
13692 	 * Hopefully the syncer daemon will catch up and awaken us.
13693 	 * We wait at most tickdelay before proceeding in any case.
13694 	 */
13695 	ACQUIRE_GBLLOCK(&lk);
13696 	FREE_LOCK(ump);
13697 	proc_waiting += 1;
13698 	if (callout_pending(&softdep_callout) == FALSE)
13699 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13700 		    pause_timer, 0);
13701 
13702 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13703 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13704 	proc_waiting -= 1;
13705 	FREE_GBLLOCK(&lk);
13706 	ACQUIRE_LOCK(ump);
13707 	return (1);
13708 }
13709 
13710 /*
13711  * Awaken processes pausing in request_cleanup and clear proc_waiting
13712  * to indicate that there is no longer a timer running. Pause_timer
13713  * will be called with the global softdep mutex (&lk) locked.
13714  */
13715 static void
13716 pause_timer(arg)
13717 	void *arg;
13718 {
13719 
13720 	GBLLOCK_OWNED(&lk);
13721 	/*
13722 	 * The callout_ API has acquired mtx and will hold it around this
13723 	 * function call.
13724 	 */
13725 	*stat_countp += proc_waiting;
13726 	wakeup(&proc_waiting);
13727 }
13728 
13729 /*
13730  * If requested, try removing inode or removal dependencies.
13731  */
13732 static void
13733 check_clear_deps(mp)
13734 	struct mount *mp;
13735 {
13736 
13737 	/*
13738 	 * If we are suspended, it may be because of our using
13739 	 * too many inodedeps, so help clear them out.
13740 	 */
13741 	if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13742 		clear_inodedeps(mp);
13743 	/*
13744 	 * General requests for cleanup of backed up dependencies
13745 	 */
13746 	ACQUIRE_GBLLOCK(&lk);
13747 	if (req_clear_inodedeps) {
13748 		req_clear_inodedeps -= 1;
13749 		FREE_GBLLOCK(&lk);
13750 		clear_inodedeps(mp);
13751 		ACQUIRE_GBLLOCK(&lk);
13752 		wakeup(&proc_waiting);
13753 	}
13754 	if (req_clear_remove) {
13755 		req_clear_remove -= 1;
13756 		FREE_GBLLOCK(&lk);
13757 		clear_remove(mp);
13758 		ACQUIRE_GBLLOCK(&lk);
13759 		wakeup(&proc_waiting);
13760 	}
13761 	FREE_GBLLOCK(&lk);
13762 }
13763 
13764 /*
13765  * Flush out a directory with at least one removal dependency in an effort to
13766  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13767  */
13768 static void
13769 clear_remove(mp)
13770 	struct mount *mp;
13771 {
13772 	struct pagedep_hashhead *pagedephd;
13773 	struct pagedep *pagedep;
13774 	struct ufsmount *ump;
13775 	struct vnode *vp;
13776 	struct bufobj *bo;
13777 	int error, cnt;
13778 	ino_t ino;
13779 
13780 	ump = VFSTOUFS(mp);
13781 	LOCK_OWNED(ump);
13782 
13783 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13784 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13785 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13786 			ump->pagedep_nextclean = 0;
13787 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13788 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13789 				continue;
13790 			ino = pagedep->pd_ino;
13791 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13792 				continue;
13793 			FREE_LOCK(ump);
13794 
13795 			/*
13796 			 * Let unmount clear deps
13797 			 */
13798 			error = vfs_busy(mp, MBF_NOWAIT);
13799 			if (error != 0)
13800 				goto finish_write;
13801 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13802 			     FFSV_FORCEINSMQ);
13803 			vfs_unbusy(mp);
13804 			if (error != 0) {
13805 				softdep_error("clear_remove: vget", error);
13806 				goto finish_write;
13807 			}
13808 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13809 				softdep_error("clear_remove: fsync", error);
13810 			bo = &vp->v_bufobj;
13811 			BO_LOCK(bo);
13812 			drain_output(vp);
13813 			BO_UNLOCK(bo);
13814 			vput(vp);
13815 		finish_write:
13816 			vn_finished_write(mp);
13817 			ACQUIRE_LOCK(ump);
13818 			return;
13819 		}
13820 	}
13821 }
13822 
13823 /*
13824  * Clear out a block of dirty inodes in an effort to reduce
13825  * the number of inodedep dependency structures.
13826  */
13827 static void
13828 clear_inodedeps(mp)
13829 	struct mount *mp;
13830 {
13831 	struct inodedep_hashhead *inodedephd;
13832 	struct inodedep *inodedep;
13833 	struct ufsmount *ump;
13834 	struct vnode *vp;
13835 	struct fs *fs;
13836 	int error, cnt;
13837 	ino_t firstino, lastino, ino;
13838 
13839 	ump = VFSTOUFS(mp);
13840 	fs = ump->um_fs;
13841 	LOCK_OWNED(ump);
13842 	/*
13843 	 * Pick a random inode dependency to be cleared.
13844 	 * We will then gather up all the inodes in its block
13845 	 * that have dependencies and flush them out.
13846 	 */
13847 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13848 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13849 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13850 			ump->inodedep_nextclean = 0;
13851 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13852 			break;
13853 	}
13854 	if (inodedep == NULL)
13855 		return;
13856 	/*
13857 	 * Find the last inode in the block with dependencies.
13858 	 */
13859 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13860 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13861 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13862 			break;
13863 	/*
13864 	 * Asynchronously push all but the last inode with dependencies.
13865 	 * Synchronously push the last inode with dependencies to ensure
13866 	 * that the inode block gets written to free up the inodedeps.
13867 	 */
13868 	for (ino = firstino; ino <= lastino; ino++) {
13869 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13870 			continue;
13871 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13872 			continue;
13873 		FREE_LOCK(ump);
13874 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13875 		if (error != 0) {
13876 			vn_finished_write(mp);
13877 			ACQUIRE_LOCK(ump);
13878 			return;
13879 		}
13880 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13881 		    FFSV_FORCEINSMQ)) != 0) {
13882 			softdep_error("clear_inodedeps: vget", error);
13883 			vfs_unbusy(mp);
13884 			vn_finished_write(mp);
13885 			ACQUIRE_LOCK(ump);
13886 			return;
13887 		}
13888 		vfs_unbusy(mp);
13889 		if (ino == lastino) {
13890 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13891 				softdep_error("clear_inodedeps: fsync1", error);
13892 		} else {
13893 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13894 				softdep_error("clear_inodedeps: fsync2", error);
13895 			BO_LOCK(&vp->v_bufobj);
13896 			drain_output(vp);
13897 			BO_UNLOCK(&vp->v_bufobj);
13898 		}
13899 		vput(vp);
13900 		vn_finished_write(mp);
13901 		ACQUIRE_LOCK(ump);
13902 	}
13903 }
13904 
13905 void
13906 softdep_buf_append(bp, wkhd)
13907 	struct buf *bp;
13908 	struct workhead *wkhd;
13909 {
13910 	struct worklist *wk;
13911 	struct ufsmount *ump;
13912 
13913 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13914 		return;
13915 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13916 	    ("softdep_buf_append called on non-softdep filesystem"));
13917 	ump = VFSTOUFS(wk->wk_mp);
13918 	ACQUIRE_LOCK(ump);
13919 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13920 		WORKLIST_REMOVE(wk);
13921 		WORKLIST_INSERT(&bp->b_dep, wk);
13922 	}
13923 	FREE_LOCK(ump);
13924 
13925 }
13926 
13927 void
13928 softdep_inode_append(ip, cred, wkhd)
13929 	struct inode *ip;
13930 	struct ucred *cred;
13931 	struct workhead *wkhd;
13932 {
13933 	struct buf *bp;
13934 	struct fs *fs;
13935 	struct ufsmount *ump;
13936 	int error;
13937 
13938 	ump = ITOUMP(ip);
13939 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13940 	    ("softdep_inode_append called on non-softdep filesystem"));
13941 	fs = ump->um_fs;
13942 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13943 	    (int)fs->fs_bsize, cred, &bp);
13944 	if (error) {
13945 		bqrelse(bp);
13946 		softdep_freework(wkhd);
13947 		return;
13948 	}
13949 	softdep_buf_append(bp, wkhd);
13950 	bqrelse(bp);
13951 }
13952 
13953 void
13954 softdep_freework(wkhd)
13955 	struct workhead *wkhd;
13956 {
13957 	struct worklist *wk;
13958 	struct ufsmount *ump;
13959 
13960 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13961 		return;
13962 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13963 	    ("softdep_freework called on non-softdep filesystem"));
13964 	ump = VFSTOUFS(wk->wk_mp);
13965 	ACQUIRE_LOCK(ump);
13966 	handle_jwork(wkhd);
13967 	FREE_LOCK(ump);
13968 }
13969 
13970 static struct ufsmount *
13971 softdep_bp_to_mp(bp)
13972 	struct buf *bp;
13973 {
13974 	struct mount *mp;
13975 	struct vnode *vp;
13976 
13977 	if (LIST_EMPTY(&bp->b_dep))
13978 		return (NULL);
13979 	vp = bp->b_vp;
13980 	KASSERT(vp != NULL,
13981 	    ("%s, buffer with dependencies lacks vnode", __func__));
13982 
13983 	/*
13984 	 * The ump mount point is stable after we get a correct
13985 	 * pointer, since bp is locked and this prevents unmount from
13986 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
13987 	 * head wk_mp, because we do not yet own SU ump lock and
13988 	 * workitem might be freed while dereferenced.
13989 	 */
13990 retry:
13991 	switch (vp->v_type) {
13992 	case VCHR:
13993 		VI_LOCK(vp);
13994 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
13995 		VI_UNLOCK(vp);
13996 		if (mp == NULL)
13997 			goto retry;
13998 		break;
13999 	case VREG:
14000 	case VDIR:
14001 	case VLNK:
14002 	case VFIFO:
14003 	case VSOCK:
14004 		mp = vp->v_mount;
14005 		break;
14006 	case VBLK:
14007 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14008 		/* FALLTHROUGH */
14009 	case VNON:
14010 	case VBAD:
14011 	case VMARKER:
14012 		mp = NULL;
14013 		break;
14014 	default:
14015 		vn_printf(vp, "unknown vnode type");
14016 		mp = NULL;
14017 		break;
14018 	}
14019 	return (VFSTOUFS(mp));
14020 }
14021 
14022 /*
14023  * Function to determine if the buffer has outstanding dependencies
14024  * that will cause a roll-back if the buffer is written. If wantcount
14025  * is set, return number of dependencies, otherwise just yes or no.
14026  */
14027 static int
14028 softdep_count_dependencies(bp, wantcount)
14029 	struct buf *bp;
14030 	int wantcount;
14031 {
14032 	struct worklist *wk;
14033 	struct ufsmount *ump;
14034 	struct bmsafemap *bmsafemap;
14035 	struct freework *freework;
14036 	struct inodedep *inodedep;
14037 	struct indirdep *indirdep;
14038 	struct freeblks *freeblks;
14039 	struct allocindir *aip;
14040 	struct pagedep *pagedep;
14041 	struct dirrem *dirrem;
14042 	struct newblk *newblk;
14043 	struct mkdir *mkdir;
14044 	struct diradd *dap;
14045 	int i, retval;
14046 
14047 	ump = softdep_bp_to_mp(bp);
14048 	if (ump == NULL)
14049 		return (0);
14050 	retval = 0;
14051 	ACQUIRE_LOCK(ump);
14052 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14053 		switch (wk->wk_type) {
14054 
14055 		case D_INODEDEP:
14056 			inodedep = WK_INODEDEP(wk);
14057 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14058 				/* bitmap allocation dependency */
14059 				retval += 1;
14060 				if (!wantcount)
14061 					goto out;
14062 			}
14063 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14064 				/* direct block pointer dependency */
14065 				retval += 1;
14066 				if (!wantcount)
14067 					goto out;
14068 			}
14069 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14070 				/* direct block pointer dependency */
14071 				retval += 1;
14072 				if (!wantcount)
14073 					goto out;
14074 			}
14075 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14076 				/* Add reference dependency. */
14077 				retval += 1;
14078 				if (!wantcount)
14079 					goto out;
14080 			}
14081 			continue;
14082 
14083 		case D_INDIRDEP:
14084 			indirdep = WK_INDIRDEP(wk);
14085 
14086 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14087 				/* indirect truncation dependency */
14088 				retval += 1;
14089 				if (!wantcount)
14090 					goto out;
14091 			}
14092 
14093 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14094 				/* indirect block pointer dependency */
14095 				retval += 1;
14096 				if (!wantcount)
14097 					goto out;
14098 			}
14099 			continue;
14100 
14101 		case D_PAGEDEP:
14102 			pagedep = WK_PAGEDEP(wk);
14103 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14104 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14105 					/* Journal remove ref dependency. */
14106 					retval += 1;
14107 					if (!wantcount)
14108 						goto out;
14109 				}
14110 			}
14111 			for (i = 0; i < DAHASHSZ; i++) {
14112 
14113 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14114 					/* directory entry dependency */
14115 					retval += 1;
14116 					if (!wantcount)
14117 						goto out;
14118 				}
14119 			}
14120 			continue;
14121 
14122 		case D_BMSAFEMAP:
14123 			bmsafemap = WK_BMSAFEMAP(wk);
14124 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14125 				/* Add reference dependency. */
14126 				retval += 1;
14127 				if (!wantcount)
14128 					goto out;
14129 			}
14130 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14131 				/* Allocate block dependency. */
14132 				retval += 1;
14133 				if (!wantcount)
14134 					goto out;
14135 			}
14136 			continue;
14137 
14138 		case D_FREEBLKS:
14139 			freeblks = WK_FREEBLKS(wk);
14140 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14141 				/* Freeblk journal dependency. */
14142 				retval += 1;
14143 				if (!wantcount)
14144 					goto out;
14145 			}
14146 			continue;
14147 
14148 		case D_ALLOCDIRECT:
14149 		case D_ALLOCINDIR:
14150 			newblk = WK_NEWBLK(wk);
14151 			if (newblk->nb_jnewblk) {
14152 				/* Journal allocate dependency. */
14153 				retval += 1;
14154 				if (!wantcount)
14155 					goto out;
14156 			}
14157 			continue;
14158 
14159 		case D_MKDIR:
14160 			mkdir = WK_MKDIR(wk);
14161 			if (mkdir->md_jaddref) {
14162 				/* Journal reference dependency. */
14163 				retval += 1;
14164 				if (!wantcount)
14165 					goto out;
14166 			}
14167 			continue;
14168 
14169 		case D_FREEWORK:
14170 		case D_FREEDEP:
14171 		case D_JSEGDEP:
14172 		case D_JSEG:
14173 		case D_SBDEP:
14174 			/* never a dependency on these blocks */
14175 			continue;
14176 
14177 		default:
14178 			panic("softdep_count_dependencies: Unexpected type %s",
14179 			    TYPENAME(wk->wk_type));
14180 			/* NOTREACHED */
14181 		}
14182 	}
14183 out:
14184 	FREE_LOCK(ump);
14185 	return (retval);
14186 }
14187 
14188 /*
14189  * Acquire exclusive access to a buffer.
14190  * Must be called with a locked mtx parameter.
14191  * Return acquired buffer or NULL on failure.
14192  */
14193 static struct buf *
14194 getdirtybuf(bp, lock, waitfor)
14195 	struct buf *bp;
14196 	struct rwlock *lock;
14197 	int waitfor;
14198 {
14199 	int error;
14200 
14201 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14202 		if (waitfor != MNT_WAIT)
14203 			return (NULL);
14204 		error = BUF_LOCK(bp,
14205 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14206 		/*
14207 		 * Even if we successfully acquire bp here, we have dropped
14208 		 * lock, which may violates our guarantee.
14209 		 */
14210 		if (error == 0)
14211 			BUF_UNLOCK(bp);
14212 		else if (error != ENOLCK)
14213 			panic("getdirtybuf: inconsistent lock: %d", error);
14214 		rw_wlock(lock);
14215 		return (NULL);
14216 	}
14217 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14218 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14219 			rw_wunlock(lock);
14220 			BO_LOCK(bp->b_bufobj);
14221 			BUF_UNLOCK(bp);
14222 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14223 				bp->b_vflags |= BV_BKGRDWAIT;
14224 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14225 				       PRIBIO | PDROP, "getbuf", 0);
14226 			} else
14227 				BO_UNLOCK(bp->b_bufobj);
14228 			rw_wlock(lock);
14229 			return (NULL);
14230 		}
14231 		BUF_UNLOCK(bp);
14232 		if (waitfor != MNT_WAIT)
14233 			return (NULL);
14234 #ifdef DEBUG_VFS_LOCKS
14235 		if (bp->b_vp->v_type != VCHR)
14236 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14237 #endif
14238 		bp->b_vflags |= BV_BKGRDWAIT;
14239 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14240 		return (NULL);
14241 	}
14242 	if ((bp->b_flags & B_DELWRI) == 0) {
14243 		BUF_UNLOCK(bp);
14244 		return (NULL);
14245 	}
14246 	bremfree(bp);
14247 	return (bp);
14248 }
14249 
14250 
14251 /*
14252  * Check if it is safe to suspend the file system now.  On entry,
14253  * the vnode interlock for devvp should be held.  Return 0 with
14254  * the mount interlock held if the file system can be suspended now,
14255  * otherwise return EAGAIN with the mount interlock held.
14256  */
14257 int
14258 softdep_check_suspend(struct mount *mp,
14259 		      struct vnode *devvp,
14260 		      int softdep_depcnt,
14261 		      int softdep_accdepcnt,
14262 		      int secondary_writes,
14263 		      int secondary_accwrites)
14264 {
14265 	struct bufobj *bo;
14266 	struct ufsmount *ump;
14267 	struct inodedep *inodedep;
14268 	int error, unlinked;
14269 
14270 	bo = &devvp->v_bufobj;
14271 	ASSERT_BO_WLOCKED(bo);
14272 
14273 	/*
14274 	 * If we are not running with soft updates, then we need only
14275 	 * deal with secondary writes as we try to suspend.
14276 	 */
14277 	if (MOUNTEDSOFTDEP(mp) == 0) {
14278 		MNT_ILOCK(mp);
14279 		while (mp->mnt_secondary_writes != 0) {
14280 			BO_UNLOCK(bo);
14281 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14282 			    (PUSER - 1) | PDROP, "secwr", 0);
14283 			BO_LOCK(bo);
14284 			MNT_ILOCK(mp);
14285 		}
14286 
14287 		/*
14288 		 * Reasons for needing more work before suspend:
14289 		 * - Dirty buffers on devvp.
14290 		 * - Secondary writes occurred after start of vnode sync loop
14291 		 */
14292 		error = 0;
14293 		if (bo->bo_numoutput > 0 ||
14294 		    bo->bo_dirty.bv_cnt > 0 ||
14295 		    secondary_writes != 0 ||
14296 		    mp->mnt_secondary_writes != 0 ||
14297 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14298 			error = EAGAIN;
14299 		BO_UNLOCK(bo);
14300 		return (error);
14301 	}
14302 
14303 	/*
14304 	 * If we are running with soft updates, then we need to coordinate
14305 	 * with them as we try to suspend.
14306 	 */
14307 	ump = VFSTOUFS(mp);
14308 	for (;;) {
14309 		if (!TRY_ACQUIRE_LOCK(ump)) {
14310 			BO_UNLOCK(bo);
14311 			ACQUIRE_LOCK(ump);
14312 			FREE_LOCK(ump);
14313 			BO_LOCK(bo);
14314 			continue;
14315 		}
14316 		MNT_ILOCK(mp);
14317 		if (mp->mnt_secondary_writes != 0) {
14318 			FREE_LOCK(ump);
14319 			BO_UNLOCK(bo);
14320 			msleep(&mp->mnt_secondary_writes,
14321 			       MNT_MTX(mp),
14322 			       (PUSER - 1) | PDROP, "secwr", 0);
14323 			BO_LOCK(bo);
14324 			continue;
14325 		}
14326 		break;
14327 	}
14328 
14329 	unlinked = 0;
14330 	if (MOUNTEDSUJ(mp)) {
14331 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14332 		    inodedep != NULL;
14333 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14334 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14335 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14336 			    UNLINKONLIST) ||
14337 			    !check_inodedep_free(inodedep))
14338 				continue;
14339 			unlinked++;
14340 		}
14341 	}
14342 
14343 	/*
14344 	 * Reasons for needing more work before suspend:
14345 	 * - Dirty buffers on devvp.
14346 	 * - Softdep activity occurred after start of vnode sync loop
14347 	 * - Secondary writes occurred after start of vnode sync loop
14348 	 */
14349 	error = 0;
14350 	if (bo->bo_numoutput > 0 ||
14351 	    bo->bo_dirty.bv_cnt > 0 ||
14352 	    softdep_depcnt != unlinked ||
14353 	    ump->softdep_deps != unlinked ||
14354 	    softdep_accdepcnt != ump->softdep_accdeps ||
14355 	    secondary_writes != 0 ||
14356 	    mp->mnt_secondary_writes != 0 ||
14357 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14358 		error = EAGAIN;
14359 	FREE_LOCK(ump);
14360 	BO_UNLOCK(bo);
14361 	return (error);
14362 }
14363 
14364 
14365 /*
14366  * Get the number of dependency structures for the file system, both
14367  * the current number and the total number allocated.  These will
14368  * later be used to detect that softdep processing has occurred.
14369  */
14370 void
14371 softdep_get_depcounts(struct mount *mp,
14372 		      int *softdep_depsp,
14373 		      int *softdep_accdepsp)
14374 {
14375 	struct ufsmount *ump;
14376 
14377 	if (MOUNTEDSOFTDEP(mp) == 0) {
14378 		*softdep_depsp = 0;
14379 		*softdep_accdepsp = 0;
14380 		return;
14381 	}
14382 	ump = VFSTOUFS(mp);
14383 	ACQUIRE_LOCK(ump);
14384 	*softdep_depsp = ump->softdep_deps;
14385 	*softdep_accdepsp = ump->softdep_accdeps;
14386 	FREE_LOCK(ump);
14387 }
14388 
14389 /*
14390  * Wait for pending output on a vnode to complete.
14391  */
14392 static void
14393 drain_output(vp)
14394 	struct vnode *vp;
14395 {
14396 
14397 	ASSERT_VOP_LOCKED(vp, "drain_output");
14398 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14399 }
14400 
14401 /*
14402  * Called whenever a buffer that is being invalidated or reallocated
14403  * contains dependencies. This should only happen if an I/O error has
14404  * occurred. The routine is called with the buffer locked.
14405  */
14406 static void
14407 softdep_deallocate_dependencies(bp)
14408 	struct buf *bp;
14409 {
14410 
14411 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14412 		panic("softdep_deallocate_dependencies: dangling deps");
14413 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14414 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14415 	else
14416 		printf("softdep_deallocate_dependencies: "
14417 		    "got error %d while accessing filesystem\n", bp->b_error);
14418 	if (bp->b_error != ENXIO)
14419 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14420 }
14421 
14422 /*
14423  * Function to handle asynchronous write errors in the filesystem.
14424  */
14425 static void
14426 softdep_error(func, error)
14427 	char *func;
14428 	int error;
14429 {
14430 
14431 	/* XXX should do something better! */
14432 	printf("%s: got error %d while accessing filesystem\n", func, error);
14433 }
14434 
14435 #ifdef DDB
14436 
14437 /* exported to ffs_vfsops.c */
14438 extern void db_print_ffs(struct ufsmount *ump);
14439 void
14440 db_print_ffs(struct ufsmount *ump)
14441 {
14442 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14443 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14444 	db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14445 	    ump->um_fs, ump->softdep_on_worklist,
14446 	    ump->softdep_deps, ump->softdep_req);
14447 }
14448 
14449 static void
14450 worklist_print(struct worklist *wk, int verbose)
14451 {
14452 
14453 	if (!verbose) {
14454 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14455 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14456 		return;
14457 	}
14458 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14459 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14460 	    LIST_NEXT(wk, wk_list));
14461 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14462 }
14463 
14464 static void
14465 inodedep_print(struct inodedep *inodedep, int verbose)
14466 {
14467 
14468 	worklist_print(&inodedep->id_list, 0);
14469 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14470 	    inodedep->id_fs,
14471 	    (intmax_t)inodedep->id_ino,
14472 	    (intmax_t)fsbtodb(inodedep->id_fs,
14473 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14474 	    (intmax_t)inodedep->id_nlinkdelta,
14475 	    (intmax_t)inodedep->id_savednlink);
14476 
14477 	if (verbose == 0)
14478 		return;
14479 
14480 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14481 	    inodedep->id_bmsafemap,
14482 	    inodedep->id_mkdiradd,
14483 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14484 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14485 	    LIST_FIRST(&inodedep->id_dirremhd),
14486 	    LIST_FIRST(&inodedep->id_pendinghd),
14487 	    LIST_FIRST(&inodedep->id_bufwait));
14488 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14489 	    LIST_FIRST(&inodedep->id_inowait),
14490 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14491 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14492 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14493 	    TAILQ_FIRST(&inodedep->id_extupdt),
14494 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14495 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14496 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14497 	    inodedep->id_savedino1,
14498 	    (intmax_t)inodedep->id_savedsize,
14499 	    (intmax_t)inodedep->id_savedextsize);
14500 }
14501 
14502 static void
14503 newblk_print(struct newblk *nbp)
14504 {
14505 
14506 	worklist_print(&nbp->nb_list, 0);
14507 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14508 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14509 	    &nbp->nb_jnewblk,
14510 	    &nbp->nb_bmsafemap,
14511 	    &nbp->nb_freefrag);
14512 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14513 	    LIST_FIRST(&nbp->nb_indirdeps),
14514 	    LIST_FIRST(&nbp->nb_newdirblk),
14515 	    LIST_FIRST(&nbp->nb_jwork));
14516 }
14517 
14518 static void
14519 allocdirect_print(struct allocdirect *adp)
14520 {
14521 
14522 	newblk_print(&adp->ad_block);
14523 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14524 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14525 	db_printf("    offset %d, inodedep %p\n",
14526 	    adp->ad_offset, adp->ad_inodedep);
14527 }
14528 
14529 static void
14530 allocindir_print(struct allocindir *aip)
14531 {
14532 
14533 	newblk_print(&aip->ai_block);
14534 	db_printf("    oldblkno %jd, lbn %jd\n",
14535 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14536 	db_printf("    offset %d, indirdep %p\n",
14537 	    aip->ai_offset, aip->ai_indirdep);
14538 }
14539 
14540 static void
14541 mkdir_print(struct mkdir *mkdir)
14542 {
14543 
14544 	worklist_print(&mkdir->md_list, 0);
14545 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14546 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14547 }
14548 
14549 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14550 {
14551 
14552 	if (have_addr == 0) {
14553 		db_printf("inodedep address required\n");
14554 		return;
14555 	}
14556 	inodedep_print((struct inodedep*)addr, 1);
14557 }
14558 
14559 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14560 {
14561 	struct inodedep_hashhead *inodedephd;
14562 	struct inodedep *inodedep;
14563 	struct ufsmount *ump;
14564 	int cnt;
14565 
14566 	if (have_addr == 0) {
14567 		db_printf("ufsmount address required\n");
14568 		return;
14569 	}
14570 	ump = (struct ufsmount *)addr;
14571 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14572 		inodedephd = &ump->inodedep_hashtbl[cnt];
14573 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14574 			inodedep_print(inodedep, 0);
14575 		}
14576 	}
14577 }
14578 
14579 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14580 {
14581 
14582 	if (have_addr == 0) {
14583 		db_printf("worklist address required\n");
14584 		return;
14585 	}
14586 	worklist_print((struct worklist *)addr, 1);
14587 }
14588 
14589 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14590 {
14591 	struct worklist *wk;
14592 	struct workhead *wkhd;
14593 
14594 	if (have_addr == 0) {
14595 		db_printf("worklist address required "
14596 		    "(for example value in bp->b_dep)\n");
14597 		return;
14598 	}
14599 	/*
14600 	 * We often do not have the address of the worklist head but
14601 	 * instead a pointer to its first entry (e.g., we have the
14602 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
14603 	 * pointer of bp->b_dep will point at the head of the list, so
14604 	 * we cheat and use that instead. If we are in the middle of
14605 	 * a list we will still get the same result, so nothing
14606 	 * unexpected will result.
14607 	 */
14608 	wk = (struct worklist *)addr;
14609 	if (wk == NULL)
14610 		return;
14611 	wkhd = (struct workhead *)wk->wk_list.le_prev;
14612 	LIST_FOREACH(wk, wkhd, wk_list) {
14613 		switch(wk->wk_type) {
14614 		case D_INODEDEP:
14615 			inodedep_print(WK_INODEDEP(wk), 0);
14616 			continue;
14617 		case D_ALLOCDIRECT:
14618 			allocdirect_print(WK_ALLOCDIRECT(wk));
14619 			continue;
14620 		case D_ALLOCINDIR:
14621 			allocindir_print(WK_ALLOCINDIR(wk));
14622 			continue;
14623 		case D_MKDIR:
14624 			mkdir_print(WK_MKDIR(wk));
14625 			continue;
14626 		default:
14627 			worklist_print(wk, 0);
14628 			continue;
14629 		}
14630 	}
14631 }
14632 
14633 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14634 {
14635 	if (have_addr == 0) {
14636 		db_printf("mkdir address required\n");
14637 		return;
14638 	}
14639 	mkdir_print((struct mkdir *)addr);
14640 }
14641 
14642 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14643 {
14644 	struct mkdirlist *mkdirlisthd;
14645 	struct mkdir *mkdir;
14646 
14647 	if (have_addr == 0) {
14648 		db_printf("mkdir listhead address required\n");
14649 		return;
14650 	}
14651 	mkdirlisthd = (struct mkdirlist *)addr;
14652 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14653 		mkdir_print(mkdir);
14654 		if (mkdir->md_diradd != NULL) {
14655 			db_printf("    ");
14656 			worklist_print(&mkdir->md_diradd->da_list, 0);
14657 		}
14658 		if (mkdir->md_jaddref != NULL) {
14659 			db_printf("    ");
14660 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
14661 		}
14662 	}
14663 }
14664 
14665 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
14666 {
14667 	if (have_addr == 0) {
14668 		db_printf("allocdirect address required\n");
14669 		return;
14670 	}
14671 	allocdirect_print((struct allocdirect *)addr);
14672 }
14673 
14674 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
14675 {
14676 	if (have_addr == 0) {
14677 		db_printf("allocindir address required\n");
14678 		return;
14679 	}
14680 	allocindir_print((struct allocindir *)addr);
14681 }
14682 
14683 #endif /* DDB */
14684 
14685 #endif /* SOFTUPDATES */
14686