xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 2c3f47a727372086b41ef9ce06eb1f1eb83a67d3)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1998, 2000 Marshall Kirk McKusick.
5  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
6  * All rights reserved.
7  *
8  * The soft updates code is derived from the appendix of a University
9  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
10  * "Soft Updates: A Solution to the Metadata Update Problem in File
11  * Systems", CSE-TR-254-95, August 1995).
12  *
13  * Further information about soft updates can be obtained from:
14  *
15  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
16  *	1614 Oxford Street		mckusick@mckusick.com
17  *	Berkeley, CA 94709-1608		+1-510-843-9542
18  *	USA
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
35  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
36  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
42  */
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include "opt_ffs.h"
48 #include "opt_quota.h"
49 #include "opt_ddb.h"
50 
51 #include <sys/param.h>
52 #include <sys/kernel.h>
53 #include <sys/systm.h>
54 #include <sys/bio.h>
55 #include <sys/buf.h>
56 #include <sys/kdb.h>
57 #include <sys/kthread.h>
58 #include <sys/ktr.h>
59 #include <sys/limits.h>
60 #include <sys/lock.h>
61 #include <sys/malloc.h>
62 #include <sys/mount.h>
63 #include <sys/mutex.h>
64 #include <sys/namei.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/racct.h>
68 #include <sys/rwlock.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/syslog.h>
72 #include <sys/vnode.h>
73 #include <sys/conf.h>
74 
75 #include <ufs/ufs/dir.h>
76 #include <ufs/ufs/extattr.h>
77 #include <ufs/ufs/quota.h>
78 #include <ufs/ufs/inode.h>
79 #include <ufs/ufs/ufsmount.h>
80 #include <ufs/ffs/fs.h>
81 #include <ufs/ffs/softdep.h>
82 #include <ufs/ffs/ffs_extern.h>
83 #include <ufs/ufs/ufs_extern.h>
84 
85 #include <vm/vm.h>
86 #include <vm/vm_extern.h>
87 #include <vm/vm_object.h>
88 
89 #include <geom/geom.h>
90 
91 #include <ddb/ddb.h>
92 
93 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
94 
95 #ifndef SOFTUPDATES
96 
97 int
98 softdep_flushfiles(oldmnt, flags, td)
99 	struct mount *oldmnt;
100 	int flags;
101 	struct thread *td;
102 {
103 
104 	panic("softdep_flushfiles called");
105 }
106 
107 int
108 softdep_mount(devvp, mp, fs, cred)
109 	struct vnode *devvp;
110 	struct mount *mp;
111 	struct fs *fs;
112 	struct ucred *cred;
113 {
114 
115 	return (0);
116 }
117 
118 void
119 softdep_initialize()
120 {
121 
122 	return;
123 }
124 
125 void
126 softdep_uninitialize()
127 {
128 
129 	return;
130 }
131 
132 void
133 softdep_unmount(mp)
134 	struct mount *mp;
135 {
136 
137 	panic("softdep_unmount called");
138 }
139 
140 void
141 softdep_setup_sbupdate(ump, fs, bp)
142 	struct ufsmount *ump;
143 	struct fs *fs;
144 	struct buf *bp;
145 {
146 
147 	panic("softdep_setup_sbupdate called");
148 }
149 
150 void
151 softdep_setup_inomapdep(bp, ip, newinum, mode)
152 	struct buf *bp;
153 	struct inode *ip;
154 	ino_t newinum;
155 	int mode;
156 {
157 
158 	panic("softdep_setup_inomapdep called");
159 }
160 
161 void
162 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
163 	struct buf *bp;
164 	struct mount *mp;
165 	ufs2_daddr_t newblkno;
166 	int frags;
167 	int oldfrags;
168 {
169 
170 	panic("softdep_setup_blkmapdep called");
171 }
172 
173 void
174 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
175 	struct inode *ip;
176 	ufs_lbn_t lbn;
177 	ufs2_daddr_t newblkno;
178 	ufs2_daddr_t oldblkno;
179 	long newsize;
180 	long oldsize;
181 	struct buf *bp;
182 {
183 
184 	panic("softdep_setup_allocdirect called");
185 }
186 
187 void
188 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
189 	struct inode *ip;
190 	ufs_lbn_t lbn;
191 	ufs2_daddr_t newblkno;
192 	ufs2_daddr_t oldblkno;
193 	long newsize;
194 	long oldsize;
195 	struct buf *bp;
196 {
197 
198 	panic("softdep_setup_allocext called");
199 }
200 
201 void
202 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
203 	struct inode *ip;
204 	ufs_lbn_t lbn;
205 	struct buf *bp;
206 	int ptrno;
207 	ufs2_daddr_t newblkno;
208 	ufs2_daddr_t oldblkno;
209 	struct buf *nbp;
210 {
211 
212 	panic("softdep_setup_allocindir_page called");
213 }
214 
215 void
216 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
217 	struct buf *nbp;
218 	struct inode *ip;
219 	struct buf *bp;
220 	int ptrno;
221 	ufs2_daddr_t newblkno;
222 {
223 
224 	panic("softdep_setup_allocindir_meta called");
225 }
226 
227 void
228 softdep_journal_freeblocks(ip, cred, length, flags)
229 	struct inode *ip;
230 	struct ucred *cred;
231 	off_t length;
232 	int flags;
233 {
234 
235 	panic("softdep_journal_freeblocks called");
236 }
237 
238 void
239 softdep_journal_fsync(ip)
240 	struct inode *ip;
241 {
242 
243 	panic("softdep_journal_fsync called");
244 }
245 
246 void
247 softdep_setup_freeblocks(ip, length, flags)
248 	struct inode *ip;
249 	off_t length;
250 	int flags;
251 {
252 
253 	panic("softdep_setup_freeblocks called");
254 }
255 
256 void
257 softdep_freefile(pvp, ino, mode)
258 		struct vnode *pvp;
259 		ino_t ino;
260 		int mode;
261 {
262 
263 	panic("softdep_freefile called");
264 }
265 
266 int
267 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
268 	struct buf *bp;
269 	struct inode *dp;
270 	off_t diroffset;
271 	ino_t newinum;
272 	struct buf *newdirbp;
273 	int isnewblk;
274 {
275 
276 	panic("softdep_setup_directory_add called");
277 }
278 
279 void
280 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
281 	struct buf *bp;
282 	struct inode *dp;
283 	caddr_t base;
284 	caddr_t oldloc;
285 	caddr_t newloc;
286 	int entrysize;
287 {
288 
289 	panic("softdep_change_directoryentry_offset called");
290 }
291 
292 void
293 softdep_setup_remove(bp, dp, ip, isrmdir)
294 	struct buf *bp;
295 	struct inode *dp;
296 	struct inode *ip;
297 	int isrmdir;
298 {
299 
300 	panic("softdep_setup_remove called");
301 }
302 
303 void
304 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
305 	struct buf *bp;
306 	struct inode *dp;
307 	struct inode *ip;
308 	ino_t newinum;
309 	int isrmdir;
310 {
311 
312 	panic("softdep_setup_directory_change called");
313 }
314 
315 void
316 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
317 	struct mount *mp;
318 	struct buf *bp;
319 	ufs2_daddr_t blkno;
320 	int frags;
321 	struct workhead *wkhd;
322 {
323 
324 	panic("%s called", __FUNCTION__);
325 }
326 
327 void
328 softdep_setup_inofree(mp, bp, ino, wkhd)
329 	struct mount *mp;
330 	struct buf *bp;
331 	ino_t ino;
332 	struct workhead *wkhd;
333 {
334 
335 	panic("%s called", __FUNCTION__);
336 }
337 
338 void
339 softdep_setup_unlink(dp, ip)
340 	struct inode *dp;
341 	struct inode *ip;
342 {
343 
344 	panic("%s called", __FUNCTION__);
345 }
346 
347 void
348 softdep_setup_link(dp, ip)
349 	struct inode *dp;
350 	struct inode *ip;
351 {
352 
353 	panic("%s called", __FUNCTION__);
354 }
355 
356 void
357 softdep_revert_link(dp, ip)
358 	struct inode *dp;
359 	struct inode *ip;
360 {
361 
362 	panic("%s called", __FUNCTION__);
363 }
364 
365 void
366 softdep_setup_rmdir(dp, ip)
367 	struct inode *dp;
368 	struct inode *ip;
369 {
370 
371 	panic("%s called", __FUNCTION__);
372 }
373 
374 void
375 softdep_revert_rmdir(dp, ip)
376 	struct inode *dp;
377 	struct inode *ip;
378 {
379 
380 	panic("%s called", __FUNCTION__);
381 }
382 
383 void
384 softdep_setup_create(dp, ip)
385 	struct inode *dp;
386 	struct inode *ip;
387 {
388 
389 	panic("%s called", __FUNCTION__);
390 }
391 
392 void
393 softdep_revert_create(dp, ip)
394 	struct inode *dp;
395 	struct inode *ip;
396 {
397 
398 	panic("%s called", __FUNCTION__);
399 }
400 
401 void
402 softdep_setup_mkdir(dp, ip)
403 	struct inode *dp;
404 	struct inode *ip;
405 {
406 
407 	panic("%s called", __FUNCTION__);
408 }
409 
410 void
411 softdep_revert_mkdir(dp, ip)
412 	struct inode *dp;
413 	struct inode *ip;
414 {
415 
416 	panic("%s called", __FUNCTION__);
417 }
418 
419 void
420 softdep_setup_dotdot_link(dp, ip)
421 	struct inode *dp;
422 	struct inode *ip;
423 {
424 
425 	panic("%s called", __FUNCTION__);
426 }
427 
428 int
429 softdep_prealloc(vp, waitok)
430 	struct vnode *vp;
431 	int waitok;
432 {
433 
434 	panic("%s called", __FUNCTION__);
435 }
436 
437 int
438 softdep_journal_lookup(mp, vpp)
439 	struct mount *mp;
440 	struct vnode **vpp;
441 {
442 
443 	return (ENOENT);
444 }
445 
446 void
447 softdep_change_linkcnt(ip)
448 	struct inode *ip;
449 {
450 
451 	panic("softdep_change_linkcnt called");
452 }
453 
454 void
455 softdep_load_inodeblock(ip)
456 	struct inode *ip;
457 {
458 
459 	panic("softdep_load_inodeblock called");
460 }
461 
462 void
463 softdep_update_inodeblock(ip, bp, waitfor)
464 	struct inode *ip;
465 	struct buf *bp;
466 	int waitfor;
467 {
468 
469 	panic("softdep_update_inodeblock called");
470 }
471 
472 int
473 softdep_fsync(vp)
474 	struct vnode *vp;	/* the "in_core" copy of the inode */
475 {
476 
477 	return (0);
478 }
479 
480 void
481 softdep_fsync_mountdev(vp)
482 	struct vnode *vp;
483 {
484 
485 	return;
486 }
487 
488 int
489 softdep_flushworklist(oldmnt, countp, td)
490 	struct mount *oldmnt;
491 	int *countp;
492 	struct thread *td;
493 {
494 
495 	*countp = 0;
496 	return (0);
497 }
498 
499 int
500 softdep_sync_metadata(struct vnode *vp)
501 {
502 
503 	panic("softdep_sync_metadata called");
504 }
505 
506 int
507 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
508 {
509 
510 	panic("softdep_sync_buf called");
511 }
512 
513 int
514 softdep_slowdown(vp)
515 	struct vnode *vp;
516 {
517 
518 	panic("softdep_slowdown called");
519 }
520 
521 int
522 softdep_request_cleanup(fs, vp, cred, resource)
523 	struct fs *fs;
524 	struct vnode *vp;
525 	struct ucred *cred;
526 	int resource;
527 {
528 
529 	return (0);
530 }
531 
532 int
533 softdep_check_suspend(struct mount *mp,
534 		      struct vnode *devvp,
535 		      int softdep_depcnt,
536 		      int softdep_accdepcnt,
537 		      int secondary_writes,
538 		      int secondary_accwrites)
539 {
540 	struct bufobj *bo;
541 	int error;
542 
543 	(void) softdep_depcnt,
544 	(void) softdep_accdepcnt;
545 
546 	bo = &devvp->v_bufobj;
547 	ASSERT_BO_WLOCKED(bo);
548 
549 	MNT_ILOCK(mp);
550 	while (mp->mnt_secondary_writes != 0) {
551 		BO_UNLOCK(bo);
552 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
553 		    (PUSER - 1) | PDROP, "secwr", 0);
554 		BO_LOCK(bo);
555 		MNT_ILOCK(mp);
556 	}
557 
558 	/*
559 	 * Reasons for needing more work before suspend:
560 	 * - Dirty buffers on devvp.
561 	 * - Secondary writes occurred after start of vnode sync loop
562 	 */
563 	error = 0;
564 	if (bo->bo_numoutput > 0 ||
565 	    bo->bo_dirty.bv_cnt > 0 ||
566 	    secondary_writes != 0 ||
567 	    mp->mnt_secondary_writes != 0 ||
568 	    secondary_accwrites != mp->mnt_secondary_accwrites)
569 		error = EAGAIN;
570 	BO_UNLOCK(bo);
571 	return (error);
572 }
573 
574 void
575 softdep_get_depcounts(struct mount *mp,
576 		      int *softdepactivep,
577 		      int *softdepactiveaccp)
578 {
579 	(void) mp;
580 	*softdepactivep = 0;
581 	*softdepactiveaccp = 0;
582 }
583 
584 void
585 softdep_buf_append(bp, wkhd)
586 	struct buf *bp;
587 	struct workhead *wkhd;
588 {
589 
590 	panic("softdep_buf_appendwork called");
591 }
592 
593 void
594 softdep_inode_append(ip, cred, wkhd)
595 	struct inode *ip;
596 	struct ucred *cred;
597 	struct workhead *wkhd;
598 {
599 
600 	panic("softdep_inode_appendwork called");
601 }
602 
603 void
604 softdep_freework(wkhd)
605 	struct workhead *wkhd;
606 {
607 
608 	panic("softdep_freework called");
609 }
610 
611 #else
612 
613 FEATURE(softupdates, "FFS soft-updates support");
614 
615 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
616     "soft updates stats");
617 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
618     "total dependencies allocated");
619 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
620     "high use dependencies allocated");
621 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
622     "current dependencies allocated");
623 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
624     "current dependencies written");
625 
626 unsigned long dep_current[D_LAST + 1];
627 unsigned long dep_highuse[D_LAST + 1];
628 unsigned long dep_total[D_LAST + 1];
629 unsigned long dep_write[D_LAST + 1];
630 
631 #define	SOFTDEP_TYPE(type, str, long)					\
632     static MALLOC_DEFINE(M_ ## type, #str, long);			\
633     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
634 	&dep_total[D_ ## type], 0, "");					\
635     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
636 	&dep_current[D_ ## type], 0, "");				\
637     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
638 	&dep_highuse[D_ ## type], 0, "");				\
639     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
640 	&dep_write[D_ ## type], 0, "");
641 
642 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
643 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
644 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
645     "Block or frag allocated from cyl group map");
646 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
647 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
648 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
649 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
650 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
651 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
652 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
653 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
654 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
655 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
656 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
657 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
658 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
659 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
660 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
661 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
662 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
663 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
664 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
665 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
666 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
667 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
668 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
669 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
670 
671 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
672 
673 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
674 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
675 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
676 
677 #define M_SOFTDEP_FLAGS	(M_WAITOK)
678 
679 /*
680  * translate from workitem type to memory type
681  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
682  */
683 static struct malloc_type *memtype[] = {
684 	NULL,
685 	M_PAGEDEP,
686 	M_INODEDEP,
687 	M_BMSAFEMAP,
688 	M_NEWBLK,
689 	M_ALLOCDIRECT,
690 	M_INDIRDEP,
691 	M_ALLOCINDIR,
692 	M_FREEFRAG,
693 	M_FREEBLKS,
694 	M_FREEFILE,
695 	M_DIRADD,
696 	M_MKDIR,
697 	M_DIRREM,
698 	M_NEWDIRBLK,
699 	M_FREEWORK,
700 	M_FREEDEP,
701 	M_JADDREF,
702 	M_JREMREF,
703 	M_JMVREF,
704 	M_JNEWBLK,
705 	M_JFREEBLK,
706 	M_JFREEFRAG,
707 	M_JSEG,
708 	M_JSEGDEP,
709 	M_SBDEP,
710 	M_JTRUNC,
711 	M_JFSYNC,
712 	M_SENTINEL
713 };
714 
715 #define DtoM(type) (memtype[type])
716 
717 /*
718  * Names of malloc types.
719  */
720 #define TYPENAME(type)  \
721 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
722 	memtype[type]->ks_shortdesc : "???")
723 /*
724  * End system adaptation definitions.
725  */
726 
727 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
728 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
729 
730 /*
731  * Internal function prototypes.
732  */
733 static	void check_clear_deps(struct mount *);
734 static	void softdep_error(char *, int);
735 static	int softdep_process_worklist(struct mount *, int);
736 static	int softdep_waitidle(struct mount *, int);
737 static	void drain_output(struct vnode *);
738 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
739 static	int check_inodedep_free(struct inodedep *);
740 static	void clear_remove(struct mount *);
741 static	void clear_inodedeps(struct mount *);
742 static	void unlinked_inodedep(struct mount *, struct inodedep *);
743 static	void clear_unlinked_inodedep(struct inodedep *);
744 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
745 static	int flush_pagedep_deps(struct vnode *, struct mount *,
746 	    struct diraddhd *);
747 static	int free_pagedep(struct pagedep *);
748 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
749 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
750 static	int flush_deplist(struct allocdirectlst *, int, int *);
751 static	int sync_cgs(struct mount *, int);
752 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
753 static	int handle_written_sbdep(struct sbdep *, struct buf *);
754 static	void initiate_write_sbdep(struct sbdep *);
755 static	void diradd_inode_written(struct diradd *, struct inodedep *);
756 static	int handle_written_indirdep(struct indirdep *, struct buf *,
757 	    struct buf**, int);
758 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
759 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
760 	    uint8_t *);
761 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
762 static	void handle_written_jaddref(struct jaddref *);
763 static	void handle_written_jremref(struct jremref *);
764 static	void handle_written_jseg(struct jseg *, struct buf *);
765 static	void handle_written_jnewblk(struct jnewblk *);
766 static	void handle_written_jblkdep(struct jblkdep *);
767 static	void handle_written_jfreefrag(struct jfreefrag *);
768 static	void complete_jseg(struct jseg *);
769 static	void complete_jsegs(struct jseg *);
770 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
771 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
772 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
773 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
774 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
775 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
776 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
777 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
778 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
779 static	inline void inoref_write(struct inoref *, struct jseg *,
780 	    struct jrefrec *);
781 static	void handle_allocdirect_partdone(struct allocdirect *,
782 	    struct workhead *);
783 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
784 	    struct workhead *);
785 static	void indirdep_complete(struct indirdep *);
786 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
787 static	void indirblk_insert(struct freework *);
788 static	void indirblk_remove(struct freework *);
789 static	void handle_allocindir_partdone(struct allocindir *);
790 static	void initiate_write_filepage(struct pagedep *, struct buf *);
791 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
792 static	void handle_written_mkdir(struct mkdir *, int);
793 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
794 	    uint8_t *);
795 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
796 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
797 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
798 static	void handle_workitem_freefile(struct freefile *);
799 static	int handle_workitem_remove(struct dirrem *, int);
800 static	struct dirrem *newdirrem(struct buf *, struct inode *,
801 	    struct inode *, int, struct dirrem **);
802 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
803 	    struct buf *);
804 static	void cancel_indirdep(struct indirdep *, struct buf *,
805 	    struct freeblks *);
806 static	void free_indirdep(struct indirdep *);
807 static	void free_diradd(struct diradd *, struct workhead *);
808 static	void merge_diradd(struct inodedep *, struct diradd *);
809 static	void complete_diradd(struct diradd *);
810 static	struct diradd *diradd_lookup(struct pagedep *, int);
811 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
812 	    struct jremref *);
813 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
814 	    struct jremref *);
815 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
816 	    struct jremref *, struct jremref *);
817 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
818 	    struct jremref *);
819 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
820 	    struct freeblks *, int);
821 static	int setup_trunc_indir(struct freeblks *, struct inode *,
822 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
823 static	void complete_trunc_indir(struct freework *);
824 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
825 	    int);
826 static	void complete_mkdir(struct mkdir *);
827 static	void free_newdirblk(struct newdirblk *);
828 static	void free_jremref(struct jremref *);
829 static	void free_jaddref(struct jaddref *);
830 static	void free_jsegdep(struct jsegdep *);
831 static	void free_jsegs(struct jblocks *);
832 static	void rele_jseg(struct jseg *);
833 static	void free_jseg(struct jseg *, struct jblocks *);
834 static	void free_jnewblk(struct jnewblk *);
835 static	void free_jblkdep(struct jblkdep *);
836 static	void free_jfreefrag(struct jfreefrag *);
837 static	void free_freedep(struct freedep *);
838 static	void journal_jremref(struct dirrem *, struct jremref *,
839 	    struct inodedep *);
840 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
841 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
842 	    struct workhead *);
843 static	void cancel_jfreefrag(struct jfreefrag *);
844 static	inline void setup_freedirect(struct freeblks *, struct inode *,
845 	    int, int);
846 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
847 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
848 	    ufs_lbn_t, int);
849 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
850 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
851 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
852 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
853 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
854 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
855 	    int, int);
856 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
857 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
858 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
859 static	void newblk_freefrag(struct newblk*);
860 static	void free_newblk(struct newblk *);
861 static	void cancel_allocdirect(struct allocdirectlst *,
862 	    struct allocdirect *, struct freeblks *);
863 static	int check_inode_unwritten(struct inodedep *);
864 static	int free_inodedep(struct inodedep *);
865 static	void freework_freeblock(struct freework *, u_long);
866 static	void freework_enqueue(struct freework *);
867 static	int handle_workitem_freeblocks(struct freeblks *, int);
868 static	int handle_complete_freeblocks(struct freeblks *, int);
869 static	void handle_workitem_indirblk(struct freework *);
870 static	void handle_written_freework(struct freework *);
871 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
872 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
873 	    struct workhead *);
874 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
875 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
876 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
877 	    ufs2_daddr_t, ufs_lbn_t);
878 static	void handle_workitem_freefrag(struct freefrag *);
879 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
880 	    ufs_lbn_t, u_long);
881 static	void allocdirect_merge(struct allocdirectlst *,
882 	    struct allocdirect *, struct allocdirect *);
883 static	struct freefrag *allocindir_merge(struct allocindir *,
884 	    struct allocindir *);
885 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
886 	    struct bmsafemap **);
887 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
888 	    int cg, struct bmsafemap *);
889 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
890 	    struct newblk **);
891 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
892 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
893 	    struct inodedep **);
894 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
895 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
896 	    int, struct pagedep **);
897 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
898 	    struct pagedep **);
899 static	void pause_timer(void *);
900 static	int request_cleanup(struct mount *, int);
901 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
902 static	void schedule_cleanup(struct mount *);
903 static void softdep_ast_cleanup_proc(struct thread *);
904 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
905 static	int process_worklist_item(struct mount *, int, int);
906 static	void process_removes(struct vnode *);
907 static	void process_truncates(struct vnode *);
908 static	void jwork_move(struct workhead *, struct workhead *);
909 static	void jwork_insert(struct workhead *, struct jsegdep *);
910 static	void add_to_worklist(struct worklist *, int);
911 static	void wake_worklist(struct worklist *);
912 static	void wait_worklist(struct worklist *, char *);
913 static	void remove_from_worklist(struct worklist *);
914 static	void softdep_flush(void *);
915 static	void softdep_flushjournal(struct mount *);
916 static	int softdep_speedup(struct ufsmount *);
917 static	void worklist_speedup(struct mount *);
918 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
919 static	void journal_unmount(struct ufsmount *);
920 static	int journal_space(struct ufsmount *, int);
921 static	void journal_suspend(struct ufsmount *);
922 static	int journal_unsuspend(struct ufsmount *ump);
923 static	void softdep_prelink(struct vnode *, struct vnode *);
924 static	void add_to_journal(struct worklist *);
925 static	void remove_from_journal(struct worklist *);
926 static	bool softdep_excess_items(struct ufsmount *, int);
927 static	void softdep_process_journal(struct mount *, struct worklist *, int);
928 static	struct jremref *newjremref(struct dirrem *, struct inode *,
929 	    struct inode *ip, off_t, nlink_t);
930 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
931 	    uint16_t);
932 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
933 	    uint16_t);
934 static	inline struct jsegdep *inoref_jseg(struct inoref *);
935 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
936 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
937 	    ufs2_daddr_t, int);
938 static	void adjust_newfreework(struct freeblks *, int);
939 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
940 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
941 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
942 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
943 	    ufs2_daddr_t, long, ufs_lbn_t);
944 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
945 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
946 static	int jwait(struct worklist *, int);
947 static	struct inodedep *inodedep_lookup_ip(struct inode *);
948 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
949 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
950 static	void handle_jwork(struct workhead *);
951 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
952 	    struct mkdir **);
953 static	struct jblocks *jblocks_create(void);
954 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
955 static	void jblocks_free(struct jblocks *, struct mount *, int);
956 static	void jblocks_destroy(struct jblocks *);
957 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
958 
959 /*
960  * Exported softdep operations.
961  */
962 static	void softdep_disk_io_initiation(struct buf *);
963 static	void softdep_disk_write_complete(struct buf *);
964 static	void softdep_deallocate_dependencies(struct buf *);
965 static	int softdep_count_dependencies(struct buf *bp, int);
966 
967 /*
968  * Global lock over all of soft updates.
969  */
970 static struct mtx lk;
971 MTX_SYSINIT(softdep_lock, &lk, "Global Softdep Lock", MTX_DEF);
972 
973 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
974 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
975 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
976 
977 /*
978  * Per-filesystem soft-updates locking.
979  */
980 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
981 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
982 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
983 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
984 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
985 				    RA_WLOCKED)
986 
987 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
988 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
989 
990 /*
991  * Worklist queue management.
992  * These routines require that the lock be held.
993  */
994 #ifndef /* NOT */ INVARIANTS
995 #define WORKLIST_INSERT(head, item) do {	\
996 	(item)->wk_state |= ONWORKLIST;		\
997 	LIST_INSERT_HEAD(head, item, wk_list);	\
998 } while (0)
999 #define WORKLIST_REMOVE(item) do {		\
1000 	(item)->wk_state &= ~ONWORKLIST;	\
1001 	LIST_REMOVE(item, wk_list);		\
1002 } while (0)
1003 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1004 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1005 
1006 #else /* INVARIANTS */
1007 static	void worklist_insert(struct workhead *, struct worklist *, int,
1008 	const char *, int);
1009 static	void worklist_remove(struct worklist *, int, const char *, int);
1010 
1011 #define WORKLIST_INSERT(head, item) \
1012 	worklist_insert(head, item, 1, __func__, __LINE__)
1013 #define WORKLIST_INSERT_UNLOCKED(head, item)\
1014 	worklist_insert(head, item, 0, __func__, __LINE__)
1015 #define WORKLIST_REMOVE(item)\
1016 	worklist_remove(item, 1, __func__, __LINE__)
1017 #define WORKLIST_REMOVE_UNLOCKED(item)\
1018 	worklist_remove(item, 0, __func__, __LINE__)
1019 
1020 static void
1021 worklist_insert(head, item, locked, func, line)
1022 	struct workhead *head;
1023 	struct worklist *item;
1024 	int locked;
1025 	const char *func;
1026 	int line;
1027 {
1028 
1029 	if (locked)
1030 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1031 	if (item->wk_state & ONWORKLIST)
1032 		panic("worklist_insert: %p %s(0x%X) already on list, "
1033 		    "added in function %s at line %d",
1034 		    item, TYPENAME(item->wk_type), item->wk_state,
1035 		    item->wk_func, item->wk_line);
1036 	item->wk_state |= ONWORKLIST;
1037 	item->wk_func = func;
1038 	item->wk_line = line;
1039 	LIST_INSERT_HEAD(head, item, wk_list);
1040 }
1041 
1042 static void
1043 worklist_remove(item, locked, func, line)
1044 	struct worklist *item;
1045 	int locked;
1046 	const char *func;
1047 	int line;
1048 {
1049 
1050 	if (locked)
1051 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1052 	if ((item->wk_state & ONWORKLIST) == 0)
1053 		panic("worklist_remove: %p %s(0x%X) not on list, "
1054 		    "removed in function %s at line %d",
1055 		    item, TYPENAME(item->wk_type), item->wk_state,
1056 		    item->wk_func, item->wk_line);
1057 	item->wk_state &= ~ONWORKLIST;
1058 	item->wk_func = func;
1059 	item->wk_line = line;
1060 	LIST_REMOVE(item, wk_list);
1061 }
1062 #endif /* INVARIANTS */
1063 
1064 /*
1065  * Merge two jsegdeps keeping only the oldest one as newer references
1066  * can't be discarded until after older references.
1067  */
1068 static inline struct jsegdep *
1069 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1070 {
1071 	struct jsegdep *swp;
1072 
1073 	if (two == NULL)
1074 		return (one);
1075 
1076 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1077 		swp = one;
1078 		one = two;
1079 		two = swp;
1080 	}
1081 	WORKLIST_REMOVE(&two->jd_list);
1082 	free_jsegdep(two);
1083 
1084 	return (one);
1085 }
1086 
1087 /*
1088  * If two freedeps are compatible free one to reduce list size.
1089  */
1090 static inline struct freedep *
1091 freedep_merge(struct freedep *one, struct freedep *two)
1092 {
1093 	if (two == NULL)
1094 		return (one);
1095 
1096 	if (one->fd_freework == two->fd_freework) {
1097 		WORKLIST_REMOVE(&two->fd_list);
1098 		free_freedep(two);
1099 	}
1100 	return (one);
1101 }
1102 
1103 /*
1104  * Move journal work from one list to another.  Duplicate freedeps and
1105  * jsegdeps are coalesced to keep the lists as small as possible.
1106  */
1107 static void
1108 jwork_move(dst, src)
1109 	struct workhead *dst;
1110 	struct workhead *src;
1111 {
1112 	struct freedep *freedep;
1113 	struct jsegdep *jsegdep;
1114 	struct worklist *wkn;
1115 	struct worklist *wk;
1116 
1117 	KASSERT(dst != src,
1118 	    ("jwork_move: dst == src"));
1119 	freedep = NULL;
1120 	jsegdep = NULL;
1121 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1122 		if (wk->wk_type == D_JSEGDEP)
1123 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1124 		else if (wk->wk_type == D_FREEDEP)
1125 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1126 	}
1127 
1128 	while ((wk = LIST_FIRST(src)) != NULL) {
1129 		WORKLIST_REMOVE(wk);
1130 		WORKLIST_INSERT(dst, wk);
1131 		if (wk->wk_type == D_JSEGDEP) {
1132 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1133 			continue;
1134 		}
1135 		if (wk->wk_type == D_FREEDEP)
1136 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1137 	}
1138 }
1139 
1140 static void
1141 jwork_insert(dst, jsegdep)
1142 	struct workhead *dst;
1143 	struct jsegdep *jsegdep;
1144 {
1145 	struct jsegdep *jsegdepn;
1146 	struct worklist *wk;
1147 
1148 	LIST_FOREACH(wk, dst, wk_list)
1149 		if (wk->wk_type == D_JSEGDEP)
1150 			break;
1151 	if (wk == NULL) {
1152 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1153 		return;
1154 	}
1155 	jsegdepn = WK_JSEGDEP(wk);
1156 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1157 		WORKLIST_REMOVE(wk);
1158 		free_jsegdep(jsegdepn);
1159 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1160 	} else
1161 		free_jsegdep(jsegdep);
1162 }
1163 
1164 /*
1165  * Routines for tracking and managing workitems.
1166  */
1167 static	void workitem_free(struct worklist *, int);
1168 static	void workitem_alloc(struct worklist *, int, struct mount *);
1169 static	void workitem_reassign(struct worklist *, int);
1170 
1171 #define	WORKITEM_FREE(item, type) \
1172 	workitem_free((struct worklist *)(item), (type))
1173 #define	WORKITEM_REASSIGN(item, type) \
1174 	workitem_reassign((struct worklist *)(item), (type))
1175 
1176 static void
1177 workitem_free(item, type)
1178 	struct worklist *item;
1179 	int type;
1180 {
1181 	struct ufsmount *ump;
1182 
1183 #ifdef INVARIANTS
1184 	if (item->wk_state & ONWORKLIST)
1185 		panic("workitem_free: %s(0x%X) still on list, "
1186 		    "added in function %s at line %d",
1187 		    TYPENAME(item->wk_type), item->wk_state,
1188 		    item->wk_func, item->wk_line);
1189 	if (item->wk_type != type && type != D_NEWBLK)
1190 		panic("workitem_free: type mismatch %s != %s",
1191 		    TYPENAME(item->wk_type), TYPENAME(type));
1192 #endif
1193 	if (item->wk_state & IOWAITING)
1194 		wakeup(item);
1195 	ump = VFSTOUFS(item->wk_mp);
1196 	LOCK_OWNED(ump);
1197 	KASSERT(ump->softdep_deps > 0,
1198 	    ("workitem_free: %s: softdep_deps going negative",
1199 	    ump->um_fs->fs_fsmnt));
1200 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1201 		wakeup(&ump->softdep_deps);
1202 	KASSERT(dep_current[item->wk_type] > 0,
1203 	    ("workitem_free: %s: dep_current[%s] going negative",
1204 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1205 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1206 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1207 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1208 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1209 	ump->softdep_curdeps[item->wk_type] -= 1;
1210 	free(item, DtoM(type));
1211 }
1212 
1213 static void
1214 workitem_alloc(item, type, mp)
1215 	struct worklist *item;
1216 	int type;
1217 	struct mount *mp;
1218 {
1219 	struct ufsmount *ump;
1220 
1221 	item->wk_type = type;
1222 	item->wk_mp = mp;
1223 	item->wk_state = 0;
1224 
1225 	ump = VFSTOUFS(mp);
1226 	ACQUIRE_GBLLOCK(&lk);
1227 	dep_current[type]++;
1228 	if (dep_current[type] > dep_highuse[type])
1229 		dep_highuse[type] = dep_current[type];
1230 	dep_total[type]++;
1231 	FREE_GBLLOCK(&lk);
1232 	ACQUIRE_LOCK(ump);
1233 	ump->softdep_curdeps[type] += 1;
1234 	ump->softdep_deps++;
1235 	ump->softdep_accdeps++;
1236 	FREE_LOCK(ump);
1237 }
1238 
1239 static void
1240 workitem_reassign(item, newtype)
1241 	struct worklist *item;
1242 	int newtype;
1243 {
1244 	struct ufsmount *ump;
1245 
1246 	ump = VFSTOUFS(item->wk_mp);
1247 	LOCK_OWNED(ump);
1248 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1249 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1250 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1251 	ump->softdep_curdeps[item->wk_type] -= 1;
1252 	ump->softdep_curdeps[newtype] += 1;
1253 	KASSERT(dep_current[item->wk_type] > 0,
1254 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1255 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1256 	ACQUIRE_GBLLOCK(&lk);
1257 	dep_current[newtype]++;
1258 	dep_current[item->wk_type]--;
1259 	if (dep_current[newtype] > dep_highuse[newtype])
1260 		dep_highuse[newtype] = dep_current[newtype];
1261 	dep_total[newtype]++;
1262 	FREE_GBLLOCK(&lk);
1263 	item->wk_type = newtype;
1264 }
1265 
1266 /*
1267  * Workitem queue management
1268  */
1269 static int max_softdeps;	/* maximum number of structs before slowdown */
1270 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1271 static int proc_waiting;	/* tracks whether we have a timeout posted */
1272 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1273 static struct callout softdep_callout;
1274 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1275 static int req_clear_remove;	/* syncer process flush some freeblks */
1276 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1277 
1278 /*
1279  * runtime statistics
1280  */
1281 static int stat_flush_threads;	/* number of softdep flushing threads */
1282 static int stat_worklist_push;	/* number of worklist cleanups */
1283 static int stat_blk_limit_push;	/* number of times block limit neared */
1284 static int stat_ino_limit_push;	/* number of times inode limit neared */
1285 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1286 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1287 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1288 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1289 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1290 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1291 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1292 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1293 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1294 static int stat_journal_min;	/* Times hit journal min threshold */
1295 static int stat_journal_low;	/* Times hit journal low threshold */
1296 static int stat_journal_wait;	/* Times blocked in jwait(). */
1297 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1298 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1299 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1300 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1301 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1302 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1303 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1304 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1305 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1306 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1307 
1308 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1309     &max_softdeps, 0, "");
1310 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1311     &tickdelay, 0, "");
1312 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1313     &stat_flush_threads, 0, "");
1314 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1315     &stat_worklist_push, 0,"");
1316 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1317     &stat_blk_limit_push, 0,"");
1318 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1319     &stat_ino_limit_push, 0,"");
1320 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1321     &stat_blk_limit_hit, 0, "");
1322 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1323     &stat_ino_limit_hit, 0, "");
1324 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1325     &stat_sync_limit_hit, 0, "");
1326 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1327     &stat_indir_blk_ptrs, 0, "");
1328 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1329     &stat_inode_bitmap, 0, "");
1330 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1331     &stat_direct_blk_ptrs, 0, "");
1332 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1333     &stat_dir_entry, 0, "");
1334 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1335     &stat_jaddref, 0, "");
1336 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1337     &stat_jnewblk, 0, "");
1338 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1339     &stat_journal_low, 0, "");
1340 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1341     &stat_journal_min, 0, "");
1342 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1343     &stat_journal_wait, 0, "");
1344 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1345     &stat_jwait_filepage, 0, "");
1346 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1347     &stat_jwait_freeblks, 0, "");
1348 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1349     &stat_jwait_inode, 0, "");
1350 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1351     &stat_jwait_newblk, 0, "");
1352 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1353     &stat_cleanup_blkrequests, 0, "");
1354 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1355     &stat_cleanup_inorequests, 0, "");
1356 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1357     &stat_cleanup_high_delay, 0, "");
1358 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1359     &stat_cleanup_retries, 0, "");
1360 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1361     &stat_cleanup_failures, 0, "");
1362 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1363     &softdep_flushcache, 0, "");
1364 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1365     &stat_emptyjblocks, 0, "");
1366 
1367 SYSCTL_DECL(_vfs_ffs);
1368 
1369 /* Whether to recompute the summary at mount time */
1370 static int compute_summary_at_mount = 0;
1371 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1372 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1373 static int print_threads = 0;
1374 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1375     &print_threads, 0, "Notify flusher thread start/stop");
1376 
1377 /* List of all filesystems mounted with soft updates */
1378 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1379 
1380 /*
1381  * This function cleans the worklist for a filesystem.
1382  * Each filesystem running with soft dependencies gets its own
1383  * thread to run in this function. The thread is started up in
1384  * softdep_mount and shutdown in softdep_unmount. They show up
1385  * as part of the kernel "bufdaemon" process whose process
1386  * entry is available in bufdaemonproc.
1387  */
1388 static int searchfailed;
1389 extern struct proc *bufdaemonproc;
1390 static void
1391 softdep_flush(addr)
1392 	void *addr;
1393 {
1394 	struct mount *mp;
1395 	struct thread *td;
1396 	struct ufsmount *ump;
1397 
1398 	td = curthread;
1399 	td->td_pflags |= TDP_NORUNNINGBUF;
1400 	mp = (struct mount *)addr;
1401 	ump = VFSTOUFS(mp);
1402 	atomic_add_int(&stat_flush_threads, 1);
1403 	ACQUIRE_LOCK(ump);
1404 	ump->softdep_flags &= ~FLUSH_STARTING;
1405 	wakeup(&ump->softdep_flushtd);
1406 	FREE_LOCK(ump);
1407 	if (print_threads) {
1408 		if (stat_flush_threads == 1)
1409 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1410 			    bufdaemonproc->p_pid);
1411 		printf("Start thread %s\n", td->td_name);
1412 	}
1413 	for (;;) {
1414 		while (softdep_process_worklist(mp, 0) > 0 ||
1415 		    (MOUNTEDSUJ(mp) &&
1416 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1417 			kthread_suspend_check();
1418 		ACQUIRE_LOCK(ump);
1419 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1420 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1421 			    "sdflush", hz / 2);
1422 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1423 		/*
1424 		 * Check to see if we are done and need to exit.
1425 		 */
1426 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1427 			FREE_LOCK(ump);
1428 			continue;
1429 		}
1430 		ump->softdep_flags &= ~FLUSH_EXIT;
1431 		FREE_LOCK(ump);
1432 		wakeup(&ump->softdep_flags);
1433 		if (print_threads)
1434 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1435 		atomic_subtract_int(&stat_flush_threads, 1);
1436 		kthread_exit();
1437 		panic("kthread_exit failed\n");
1438 	}
1439 }
1440 
1441 static void
1442 worklist_speedup(mp)
1443 	struct mount *mp;
1444 {
1445 	struct ufsmount *ump;
1446 
1447 	ump = VFSTOUFS(mp);
1448 	LOCK_OWNED(ump);
1449 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1450 		ump->softdep_flags |= FLUSH_CLEANUP;
1451 	wakeup(&ump->softdep_flushtd);
1452 }
1453 
1454 static int
1455 softdep_speedup(ump)
1456 	struct ufsmount *ump;
1457 {
1458 	struct ufsmount *altump;
1459 	struct mount_softdeps *sdp;
1460 
1461 	LOCK_OWNED(ump);
1462 	worklist_speedup(ump->um_mountp);
1463 	bd_speedup();
1464 	/*
1465 	 * If we have global shortages, then we need other
1466 	 * filesystems to help with the cleanup. Here we wakeup a
1467 	 * flusher thread for a filesystem that is over its fair
1468 	 * share of resources.
1469 	 */
1470 	if (req_clear_inodedeps || req_clear_remove) {
1471 		ACQUIRE_GBLLOCK(&lk);
1472 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1473 			if ((altump = sdp->sd_ump) == ump)
1474 				continue;
1475 			if (((req_clear_inodedeps &&
1476 			    altump->softdep_curdeps[D_INODEDEP] >
1477 			    max_softdeps / stat_flush_threads) ||
1478 			    (req_clear_remove &&
1479 			    altump->softdep_curdeps[D_DIRREM] >
1480 			    (max_softdeps / 2) / stat_flush_threads)) &&
1481 			    TRY_ACQUIRE_LOCK(altump))
1482 				break;
1483 		}
1484 		if (sdp == NULL) {
1485 			searchfailed++;
1486 			FREE_GBLLOCK(&lk);
1487 		} else {
1488 			/*
1489 			 * Move to the end of the list so we pick a
1490 			 * different one on out next try.
1491 			 */
1492 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1493 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1494 			FREE_GBLLOCK(&lk);
1495 			if ((altump->softdep_flags &
1496 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1497 				altump->softdep_flags |= FLUSH_CLEANUP;
1498 			altump->um_softdep->sd_cleanups++;
1499 			wakeup(&altump->softdep_flushtd);
1500 			FREE_LOCK(altump);
1501 		}
1502 	}
1503 	return (speedup_syncer());
1504 }
1505 
1506 /*
1507  * Add an item to the end of the work queue.
1508  * This routine requires that the lock be held.
1509  * This is the only routine that adds items to the list.
1510  * The following routine is the only one that removes items
1511  * and does so in order from first to last.
1512  */
1513 
1514 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1515 #define	WK_NODELAY	0x0002	/* Process immediately. */
1516 
1517 static void
1518 add_to_worklist(wk, flags)
1519 	struct worklist *wk;
1520 	int flags;
1521 {
1522 	struct ufsmount *ump;
1523 
1524 	ump = VFSTOUFS(wk->wk_mp);
1525 	LOCK_OWNED(ump);
1526 	if (wk->wk_state & ONWORKLIST)
1527 		panic("add_to_worklist: %s(0x%X) already on list",
1528 		    TYPENAME(wk->wk_type), wk->wk_state);
1529 	wk->wk_state |= ONWORKLIST;
1530 	if (ump->softdep_on_worklist == 0) {
1531 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1532 		ump->softdep_worklist_tail = wk;
1533 	} else if (flags & WK_HEAD) {
1534 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1535 	} else {
1536 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1537 		ump->softdep_worklist_tail = wk;
1538 	}
1539 	ump->softdep_on_worklist += 1;
1540 	if (flags & WK_NODELAY)
1541 		worklist_speedup(wk->wk_mp);
1542 }
1543 
1544 /*
1545  * Remove the item to be processed. If we are removing the last
1546  * item on the list, we need to recalculate the tail pointer.
1547  */
1548 static void
1549 remove_from_worklist(wk)
1550 	struct worklist *wk;
1551 {
1552 	struct ufsmount *ump;
1553 
1554 	ump = VFSTOUFS(wk->wk_mp);
1555 	if (ump->softdep_worklist_tail == wk)
1556 		ump->softdep_worklist_tail =
1557 		    (struct worklist *)wk->wk_list.le_prev;
1558 	WORKLIST_REMOVE(wk);
1559 	ump->softdep_on_worklist -= 1;
1560 }
1561 
1562 static void
1563 wake_worklist(wk)
1564 	struct worklist *wk;
1565 {
1566 	if (wk->wk_state & IOWAITING) {
1567 		wk->wk_state &= ~IOWAITING;
1568 		wakeup(wk);
1569 	}
1570 }
1571 
1572 static void
1573 wait_worklist(wk, wmesg)
1574 	struct worklist *wk;
1575 	char *wmesg;
1576 {
1577 	struct ufsmount *ump;
1578 
1579 	ump = VFSTOUFS(wk->wk_mp);
1580 	wk->wk_state |= IOWAITING;
1581 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1582 }
1583 
1584 /*
1585  * Process that runs once per second to handle items in the background queue.
1586  *
1587  * Note that we ensure that everything is done in the order in which they
1588  * appear in the queue. The code below depends on this property to ensure
1589  * that blocks of a file are freed before the inode itself is freed. This
1590  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1591  * until all the old ones have been purged from the dependency lists.
1592  */
1593 static int
1594 softdep_process_worklist(mp, full)
1595 	struct mount *mp;
1596 	int full;
1597 {
1598 	int cnt, matchcnt;
1599 	struct ufsmount *ump;
1600 	long starttime;
1601 
1602 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1603 	if (MOUNTEDSOFTDEP(mp) == 0)
1604 		return (0);
1605 	matchcnt = 0;
1606 	ump = VFSTOUFS(mp);
1607 	ACQUIRE_LOCK(ump);
1608 	starttime = time_second;
1609 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1610 	check_clear_deps(mp);
1611 	while (ump->softdep_on_worklist > 0) {
1612 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1613 			break;
1614 		else
1615 			matchcnt += cnt;
1616 		check_clear_deps(mp);
1617 		/*
1618 		 * We do not generally want to stop for buffer space, but if
1619 		 * we are really being a buffer hog, we will stop and wait.
1620 		 */
1621 		if (should_yield()) {
1622 			FREE_LOCK(ump);
1623 			kern_yield(PRI_USER);
1624 			bwillwrite();
1625 			ACQUIRE_LOCK(ump);
1626 		}
1627 		/*
1628 		 * Never allow processing to run for more than one
1629 		 * second. This gives the syncer thread the opportunity
1630 		 * to pause if appropriate.
1631 		 */
1632 		if (!full && starttime != time_second)
1633 			break;
1634 	}
1635 	if (full == 0)
1636 		journal_unsuspend(ump);
1637 	FREE_LOCK(ump);
1638 	return (matchcnt);
1639 }
1640 
1641 /*
1642  * Process all removes associated with a vnode if we are running out of
1643  * journal space.  Any other process which attempts to flush these will
1644  * be unable as we have the vnodes locked.
1645  */
1646 static void
1647 process_removes(vp)
1648 	struct vnode *vp;
1649 {
1650 	struct inodedep *inodedep;
1651 	struct dirrem *dirrem;
1652 	struct ufsmount *ump;
1653 	struct mount *mp;
1654 	ino_t inum;
1655 
1656 	mp = vp->v_mount;
1657 	ump = VFSTOUFS(mp);
1658 	LOCK_OWNED(ump);
1659 	inum = VTOI(vp)->i_number;
1660 	for (;;) {
1661 top:
1662 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1663 			return;
1664 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1665 			/*
1666 			 * If another thread is trying to lock this vnode
1667 			 * it will fail but we must wait for it to do so
1668 			 * before we can proceed.
1669 			 */
1670 			if (dirrem->dm_state & INPROGRESS) {
1671 				wait_worklist(&dirrem->dm_list, "pwrwait");
1672 				goto top;
1673 			}
1674 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1675 			    (COMPLETE | ONWORKLIST))
1676 				break;
1677 		}
1678 		if (dirrem == NULL)
1679 			return;
1680 		remove_from_worklist(&dirrem->dm_list);
1681 		FREE_LOCK(ump);
1682 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1683 			panic("process_removes: suspended filesystem");
1684 		handle_workitem_remove(dirrem, 0);
1685 		vn_finished_secondary_write(mp);
1686 		ACQUIRE_LOCK(ump);
1687 	}
1688 }
1689 
1690 /*
1691  * Process all truncations associated with a vnode if we are running out
1692  * of journal space.  This is called when the vnode lock is already held
1693  * and no other process can clear the truncation.  This function returns
1694  * a value greater than zero if it did any work.
1695  */
1696 static void
1697 process_truncates(vp)
1698 	struct vnode *vp;
1699 {
1700 	struct inodedep *inodedep;
1701 	struct freeblks *freeblks;
1702 	struct ufsmount *ump;
1703 	struct mount *mp;
1704 	ino_t inum;
1705 	int cgwait;
1706 
1707 	mp = vp->v_mount;
1708 	ump = VFSTOUFS(mp);
1709 	LOCK_OWNED(ump);
1710 	inum = VTOI(vp)->i_number;
1711 	for (;;) {
1712 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1713 			return;
1714 		cgwait = 0;
1715 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1716 			/* Journal entries not yet written.  */
1717 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1718 				jwait(&LIST_FIRST(
1719 				    &freeblks->fb_jblkdephd)->jb_list,
1720 				    MNT_WAIT);
1721 				break;
1722 			}
1723 			/* Another thread is executing this item. */
1724 			if (freeblks->fb_state & INPROGRESS) {
1725 				wait_worklist(&freeblks->fb_list, "ptrwait");
1726 				break;
1727 			}
1728 			/* Freeblks is waiting on a inode write. */
1729 			if ((freeblks->fb_state & COMPLETE) == 0) {
1730 				FREE_LOCK(ump);
1731 				ffs_update(vp, 1);
1732 				ACQUIRE_LOCK(ump);
1733 				break;
1734 			}
1735 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1736 			    (ALLCOMPLETE | ONWORKLIST)) {
1737 				remove_from_worklist(&freeblks->fb_list);
1738 				freeblks->fb_state |= INPROGRESS;
1739 				FREE_LOCK(ump);
1740 				if (vn_start_secondary_write(NULL, &mp,
1741 				    V_NOWAIT))
1742 					panic("process_truncates: "
1743 					    "suspended filesystem");
1744 				handle_workitem_freeblocks(freeblks, 0);
1745 				vn_finished_secondary_write(mp);
1746 				ACQUIRE_LOCK(ump);
1747 				break;
1748 			}
1749 			if (freeblks->fb_cgwait)
1750 				cgwait++;
1751 		}
1752 		if (cgwait) {
1753 			FREE_LOCK(ump);
1754 			sync_cgs(mp, MNT_WAIT);
1755 			ffs_sync_snap(mp, MNT_WAIT);
1756 			ACQUIRE_LOCK(ump);
1757 			continue;
1758 		}
1759 		if (freeblks == NULL)
1760 			break;
1761 	}
1762 	return;
1763 }
1764 
1765 /*
1766  * Process one item on the worklist.
1767  */
1768 static int
1769 process_worklist_item(mp, target, flags)
1770 	struct mount *mp;
1771 	int target;
1772 	int flags;
1773 {
1774 	struct worklist sentinel;
1775 	struct worklist *wk;
1776 	struct ufsmount *ump;
1777 	int matchcnt;
1778 	int error;
1779 
1780 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1781 	/*
1782 	 * If we are being called because of a process doing a
1783 	 * copy-on-write, then it is not safe to write as we may
1784 	 * recurse into the copy-on-write routine.
1785 	 */
1786 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1787 		return (-1);
1788 	PHOLD(curproc);	/* Don't let the stack go away. */
1789 	ump = VFSTOUFS(mp);
1790 	LOCK_OWNED(ump);
1791 	matchcnt = 0;
1792 	sentinel.wk_mp = NULL;
1793 	sentinel.wk_type = D_SENTINEL;
1794 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1795 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1796 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1797 		if (wk->wk_type == D_SENTINEL) {
1798 			LIST_REMOVE(&sentinel, wk_list);
1799 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1800 			continue;
1801 		}
1802 		if (wk->wk_state & INPROGRESS)
1803 			panic("process_worklist_item: %p already in progress.",
1804 			    wk);
1805 		wk->wk_state |= INPROGRESS;
1806 		remove_from_worklist(wk);
1807 		FREE_LOCK(ump);
1808 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1809 			panic("process_worklist_item: suspended filesystem");
1810 		switch (wk->wk_type) {
1811 		case D_DIRREM:
1812 			/* removal of a directory entry */
1813 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1814 			break;
1815 
1816 		case D_FREEBLKS:
1817 			/* releasing blocks and/or fragments from a file */
1818 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1819 			    flags);
1820 			break;
1821 
1822 		case D_FREEFRAG:
1823 			/* releasing a fragment when replaced as a file grows */
1824 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1825 			error = 0;
1826 			break;
1827 
1828 		case D_FREEFILE:
1829 			/* releasing an inode when its link count drops to 0 */
1830 			handle_workitem_freefile(WK_FREEFILE(wk));
1831 			error = 0;
1832 			break;
1833 
1834 		default:
1835 			panic("%s_process_worklist: Unknown type %s",
1836 			    "softdep", TYPENAME(wk->wk_type));
1837 			/* NOTREACHED */
1838 		}
1839 		vn_finished_secondary_write(mp);
1840 		ACQUIRE_LOCK(ump);
1841 		if (error == 0) {
1842 			if (++matchcnt == target)
1843 				break;
1844 			continue;
1845 		}
1846 		/*
1847 		 * We have to retry the worklist item later.  Wake up any
1848 		 * waiters who may be able to complete it immediately and
1849 		 * add the item back to the head so we don't try to execute
1850 		 * it again.
1851 		 */
1852 		wk->wk_state &= ~INPROGRESS;
1853 		wake_worklist(wk);
1854 		add_to_worklist(wk, WK_HEAD);
1855 	}
1856 	/* Sentinal could've become the tail from remove_from_worklist. */
1857 	if (ump->softdep_worklist_tail == &sentinel)
1858 		ump->softdep_worklist_tail =
1859 		    (struct worklist *)sentinel.wk_list.le_prev;
1860 	LIST_REMOVE(&sentinel, wk_list);
1861 	PRELE(curproc);
1862 	return (matchcnt);
1863 }
1864 
1865 /*
1866  * Move dependencies from one buffer to another.
1867  */
1868 int
1869 softdep_move_dependencies(oldbp, newbp)
1870 	struct buf *oldbp;
1871 	struct buf *newbp;
1872 {
1873 	struct worklist *wk, *wktail;
1874 	struct ufsmount *ump;
1875 	int dirty;
1876 
1877 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1878 		return (0);
1879 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1880 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1881 	dirty = 0;
1882 	wktail = NULL;
1883 	ump = VFSTOUFS(wk->wk_mp);
1884 	ACQUIRE_LOCK(ump);
1885 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1886 		LIST_REMOVE(wk, wk_list);
1887 		if (wk->wk_type == D_BMSAFEMAP &&
1888 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1889 			dirty = 1;
1890 		if (wktail == NULL)
1891 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1892 		else
1893 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1894 		wktail = wk;
1895 	}
1896 	FREE_LOCK(ump);
1897 
1898 	return (dirty);
1899 }
1900 
1901 /*
1902  * Purge the work list of all items associated with a particular mount point.
1903  */
1904 int
1905 softdep_flushworklist(oldmnt, countp, td)
1906 	struct mount *oldmnt;
1907 	int *countp;
1908 	struct thread *td;
1909 {
1910 	struct vnode *devvp;
1911 	struct ufsmount *ump;
1912 	int count, error;
1913 
1914 	/*
1915 	 * Alternately flush the block device associated with the mount
1916 	 * point and process any dependencies that the flushing
1917 	 * creates. We continue until no more worklist dependencies
1918 	 * are found.
1919 	 */
1920 	*countp = 0;
1921 	error = 0;
1922 	ump = VFSTOUFS(oldmnt);
1923 	devvp = ump->um_devvp;
1924 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1925 		*countp += count;
1926 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1927 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1928 		VOP_UNLOCK(devvp, 0);
1929 		if (error != 0)
1930 			break;
1931 	}
1932 	return (error);
1933 }
1934 
1935 #define	SU_WAITIDLE_RETRIES	20
1936 static int
1937 softdep_waitidle(struct mount *mp, int flags __unused)
1938 {
1939 	struct ufsmount *ump;
1940 	struct vnode *devvp;
1941 	struct thread *td;
1942 	int error, i;
1943 
1944 	ump = VFSTOUFS(mp);
1945 	devvp = ump->um_devvp;
1946 	td = curthread;
1947 	error = 0;
1948 	ACQUIRE_LOCK(ump);
1949 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1950 		ump->softdep_req = 1;
1951 		KASSERT((flags & FORCECLOSE) == 0 ||
1952 		    ump->softdep_on_worklist == 0,
1953 		    ("softdep_waitidle: work added after flush"));
1954 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1955 		    "softdeps", 10 * hz);
1956 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1957 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1958 		VOP_UNLOCK(devvp, 0);
1959 		ACQUIRE_LOCK(ump);
1960 		if (error != 0)
1961 			break;
1962 	}
1963 	ump->softdep_req = 0;
1964 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1965 		error = EBUSY;
1966 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1967 		    mp);
1968 	}
1969 	FREE_LOCK(ump);
1970 	return (error);
1971 }
1972 
1973 /*
1974  * Flush all vnodes and worklist items associated with a specified mount point.
1975  */
1976 int
1977 softdep_flushfiles(oldmnt, flags, td)
1978 	struct mount *oldmnt;
1979 	int flags;
1980 	struct thread *td;
1981 {
1982 #ifdef QUOTA
1983 	struct ufsmount *ump;
1984 	int i;
1985 #endif
1986 	int error, early, depcount, loopcnt, retry_flush_count, retry;
1987 	int morework;
1988 
1989 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1990 	    ("softdep_flushfiles called on non-softdep filesystem"));
1991 	loopcnt = 10;
1992 	retry_flush_count = 3;
1993 retry_flush:
1994 	error = 0;
1995 
1996 	/*
1997 	 * Alternately flush the vnodes associated with the mount
1998 	 * point and process any dependencies that the flushing
1999 	 * creates. In theory, this loop can happen at most twice,
2000 	 * but we give it a few extra just to be sure.
2001 	 */
2002 	for (; loopcnt > 0; loopcnt--) {
2003 		/*
2004 		 * Do another flush in case any vnodes were brought in
2005 		 * as part of the cleanup operations.
2006 		 */
2007 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2008 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2009 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2010 			break;
2011 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2012 		    depcount == 0)
2013 			break;
2014 	}
2015 	/*
2016 	 * If we are unmounting then it is an error to fail. If we
2017 	 * are simply trying to downgrade to read-only, then filesystem
2018 	 * activity can keep us busy forever, so we just fail with EBUSY.
2019 	 */
2020 	if (loopcnt == 0) {
2021 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2022 			panic("softdep_flushfiles: looping");
2023 		error = EBUSY;
2024 	}
2025 	if (!error)
2026 		error = softdep_waitidle(oldmnt, flags);
2027 	if (!error) {
2028 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2029 			retry = 0;
2030 			MNT_ILOCK(oldmnt);
2031 			morework = oldmnt->mnt_nvnodelistsize > 0;
2032 #ifdef QUOTA
2033 			ump = VFSTOUFS(oldmnt);
2034 			UFS_LOCK(ump);
2035 			for (i = 0; i < MAXQUOTAS; i++) {
2036 				if (ump->um_quotas[i] != NULLVP)
2037 					morework = 1;
2038 			}
2039 			UFS_UNLOCK(ump);
2040 #endif
2041 			if (morework) {
2042 				if (--retry_flush_count > 0) {
2043 					retry = 1;
2044 					loopcnt = 3;
2045 				} else
2046 					error = EBUSY;
2047 			}
2048 			MNT_IUNLOCK(oldmnt);
2049 			if (retry)
2050 				goto retry_flush;
2051 		}
2052 	}
2053 	return (error);
2054 }
2055 
2056 /*
2057  * Structure hashing.
2058  *
2059  * There are four types of structures that can be looked up:
2060  *	1) pagedep structures identified by mount point, inode number,
2061  *	   and logical block.
2062  *	2) inodedep structures identified by mount point and inode number.
2063  *	3) newblk structures identified by mount point and
2064  *	   physical block number.
2065  *	4) bmsafemap structures identified by mount point and
2066  *	   cylinder group number.
2067  *
2068  * The "pagedep" and "inodedep" dependency structures are hashed
2069  * separately from the file blocks and inodes to which they correspond.
2070  * This separation helps when the in-memory copy of an inode or
2071  * file block must be replaced. It also obviates the need to access
2072  * an inode or file page when simply updating (or de-allocating)
2073  * dependency structures. Lookup of newblk structures is needed to
2074  * find newly allocated blocks when trying to associate them with
2075  * their allocdirect or allocindir structure.
2076  *
2077  * The lookup routines optionally create and hash a new instance when
2078  * an existing entry is not found. The bmsafemap lookup routine always
2079  * allocates a new structure if an existing one is not found.
2080  */
2081 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2082 
2083 /*
2084  * Structures and routines associated with pagedep caching.
2085  */
2086 #define	PAGEDEP_HASH(ump, inum, lbn) \
2087 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2088 
2089 static int
2090 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2091 	struct pagedep_hashhead *pagedephd;
2092 	ino_t ino;
2093 	ufs_lbn_t lbn;
2094 	struct pagedep **pagedeppp;
2095 {
2096 	struct pagedep *pagedep;
2097 
2098 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2099 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2100 			*pagedeppp = pagedep;
2101 			return (1);
2102 		}
2103 	}
2104 	*pagedeppp = NULL;
2105 	return (0);
2106 }
2107 /*
2108  * Look up a pagedep. Return 1 if found, 0 otherwise.
2109  * If not found, allocate if DEPALLOC flag is passed.
2110  * Found or allocated entry is returned in pagedeppp.
2111  */
2112 static int
2113 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2114 	struct mount *mp;
2115 	struct buf *bp;
2116 	ino_t ino;
2117 	ufs_lbn_t lbn;
2118 	int flags;
2119 	struct pagedep **pagedeppp;
2120 {
2121 	struct pagedep *pagedep;
2122 	struct pagedep_hashhead *pagedephd;
2123 	struct worklist *wk;
2124 	struct ufsmount *ump;
2125 	int ret;
2126 	int i;
2127 
2128 	ump = VFSTOUFS(mp);
2129 	LOCK_OWNED(ump);
2130 	if (bp) {
2131 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2132 			if (wk->wk_type == D_PAGEDEP) {
2133 				*pagedeppp = WK_PAGEDEP(wk);
2134 				return (1);
2135 			}
2136 		}
2137 	}
2138 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2139 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2140 	if (ret) {
2141 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2142 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2143 		return (1);
2144 	}
2145 	if ((flags & DEPALLOC) == 0)
2146 		return (0);
2147 	FREE_LOCK(ump);
2148 	pagedep = malloc(sizeof(struct pagedep),
2149 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2150 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2151 	ACQUIRE_LOCK(ump);
2152 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2153 	if (*pagedeppp) {
2154 		/*
2155 		 * This should never happen since we only create pagedeps
2156 		 * with the vnode lock held.  Could be an assert.
2157 		 */
2158 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2159 		return (ret);
2160 	}
2161 	pagedep->pd_ino = ino;
2162 	pagedep->pd_lbn = lbn;
2163 	LIST_INIT(&pagedep->pd_dirremhd);
2164 	LIST_INIT(&pagedep->pd_pendinghd);
2165 	for (i = 0; i < DAHASHSZ; i++)
2166 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2167 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2168 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2169 	*pagedeppp = pagedep;
2170 	return (0);
2171 }
2172 
2173 /*
2174  * Structures and routines associated with inodedep caching.
2175  */
2176 #define	INODEDEP_HASH(ump, inum) \
2177       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2178 
2179 static int
2180 inodedep_find(inodedephd, inum, inodedeppp)
2181 	struct inodedep_hashhead *inodedephd;
2182 	ino_t inum;
2183 	struct inodedep **inodedeppp;
2184 {
2185 	struct inodedep *inodedep;
2186 
2187 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2188 		if (inum == inodedep->id_ino)
2189 			break;
2190 	if (inodedep) {
2191 		*inodedeppp = inodedep;
2192 		return (1);
2193 	}
2194 	*inodedeppp = NULL;
2195 
2196 	return (0);
2197 }
2198 /*
2199  * Look up an inodedep. Return 1 if found, 0 if not found.
2200  * If not found, allocate if DEPALLOC flag is passed.
2201  * Found or allocated entry is returned in inodedeppp.
2202  */
2203 static int
2204 inodedep_lookup(mp, inum, flags, inodedeppp)
2205 	struct mount *mp;
2206 	ino_t inum;
2207 	int flags;
2208 	struct inodedep **inodedeppp;
2209 {
2210 	struct inodedep *inodedep;
2211 	struct inodedep_hashhead *inodedephd;
2212 	struct ufsmount *ump;
2213 	struct fs *fs;
2214 
2215 	ump = VFSTOUFS(mp);
2216 	LOCK_OWNED(ump);
2217 	fs = ump->um_fs;
2218 	inodedephd = INODEDEP_HASH(ump, inum);
2219 
2220 	if (inodedep_find(inodedephd, inum, inodedeppp))
2221 		return (1);
2222 	if ((flags & DEPALLOC) == 0)
2223 		return (0);
2224 	/*
2225 	 * If the system is over its limit and our filesystem is
2226 	 * responsible for more than our share of that usage and
2227 	 * we are not in a rush, request some inodedep cleanup.
2228 	 */
2229 	if (softdep_excess_items(ump, D_INODEDEP))
2230 		schedule_cleanup(mp);
2231 	else
2232 		FREE_LOCK(ump);
2233 	inodedep = malloc(sizeof(struct inodedep),
2234 		M_INODEDEP, M_SOFTDEP_FLAGS);
2235 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2236 	ACQUIRE_LOCK(ump);
2237 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2238 		WORKITEM_FREE(inodedep, D_INODEDEP);
2239 		return (1);
2240 	}
2241 	inodedep->id_fs = fs;
2242 	inodedep->id_ino = inum;
2243 	inodedep->id_state = ALLCOMPLETE;
2244 	inodedep->id_nlinkdelta = 0;
2245 	inodedep->id_savedino1 = NULL;
2246 	inodedep->id_savedsize = -1;
2247 	inodedep->id_savedextsize = -1;
2248 	inodedep->id_savednlink = -1;
2249 	inodedep->id_bmsafemap = NULL;
2250 	inodedep->id_mkdiradd = NULL;
2251 	LIST_INIT(&inodedep->id_dirremhd);
2252 	LIST_INIT(&inodedep->id_pendinghd);
2253 	LIST_INIT(&inodedep->id_inowait);
2254 	LIST_INIT(&inodedep->id_bufwait);
2255 	TAILQ_INIT(&inodedep->id_inoreflst);
2256 	TAILQ_INIT(&inodedep->id_inoupdt);
2257 	TAILQ_INIT(&inodedep->id_newinoupdt);
2258 	TAILQ_INIT(&inodedep->id_extupdt);
2259 	TAILQ_INIT(&inodedep->id_newextupdt);
2260 	TAILQ_INIT(&inodedep->id_freeblklst);
2261 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2262 	*inodedeppp = inodedep;
2263 	return (0);
2264 }
2265 
2266 /*
2267  * Structures and routines associated with newblk caching.
2268  */
2269 #define	NEWBLK_HASH(ump, inum) \
2270 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2271 
2272 static int
2273 newblk_find(newblkhd, newblkno, flags, newblkpp)
2274 	struct newblk_hashhead *newblkhd;
2275 	ufs2_daddr_t newblkno;
2276 	int flags;
2277 	struct newblk **newblkpp;
2278 {
2279 	struct newblk *newblk;
2280 
2281 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2282 		if (newblkno != newblk->nb_newblkno)
2283 			continue;
2284 		/*
2285 		 * If we're creating a new dependency don't match those that
2286 		 * have already been converted to allocdirects.  This is for
2287 		 * a frag extend.
2288 		 */
2289 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2290 			continue;
2291 		break;
2292 	}
2293 	if (newblk) {
2294 		*newblkpp = newblk;
2295 		return (1);
2296 	}
2297 	*newblkpp = NULL;
2298 	return (0);
2299 }
2300 
2301 /*
2302  * Look up a newblk. Return 1 if found, 0 if not found.
2303  * If not found, allocate if DEPALLOC flag is passed.
2304  * Found or allocated entry is returned in newblkpp.
2305  */
2306 static int
2307 newblk_lookup(mp, newblkno, flags, newblkpp)
2308 	struct mount *mp;
2309 	ufs2_daddr_t newblkno;
2310 	int flags;
2311 	struct newblk **newblkpp;
2312 {
2313 	struct newblk *newblk;
2314 	struct newblk_hashhead *newblkhd;
2315 	struct ufsmount *ump;
2316 
2317 	ump = VFSTOUFS(mp);
2318 	LOCK_OWNED(ump);
2319 	newblkhd = NEWBLK_HASH(ump, newblkno);
2320 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2321 		return (1);
2322 	if ((flags & DEPALLOC) == 0)
2323 		return (0);
2324 	if (softdep_excess_items(ump, D_NEWBLK) ||
2325 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2326 	    softdep_excess_items(ump, D_ALLOCINDIR))
2327 		schedule_cleanup(mp);
2328 	else
2329 		FREE_LOCK(ump);
2330 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2331 	    M_SOFTDEP_FLAGS | M_ZERO);
2332 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2333 	ACQUIRE_LOCK(ump);
2334 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2335 		WORKITEM_FREE(newblk, D_NEWBLK);
2336 		return (1);
2337 	}
2338 	newblk->nb_freefrag = NULL;
2339 	LIST_INIT(&newblk->nb_indirdeps);
2340 	LIST_INIT(&newblk->nb_newdirblk);
2341 	LIST_INIT(&newblk->nb_jwork);
2342 	newblk->nb_state = ATTACHED;
2343 	newblk->nb_newblkno = newblkno;
2344 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2345 	*newblkpp = newblk;
2346 	return (0);
2347 }
2348 
2349 /*
2350  * Structures and routines associated with freed indirect block caching.
2351  */
2352 #define	INDIR_HASH(ump, blkno) \
2353 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2354 
2355 /*
2356  * Lookup an indirect block in the indir hash table.  The freework is
2357  * removed and potentially freed.  The caller must do a blocking journal
2358  * write before writing to the blkno.
2359  */
2360 static int
2361 indirblk_lookup(mp, blkno)
2362 	struct mount *mp;
2363 	ufs2_daddr_t blkno;
2364 {
2365 	struct freework *freework;
2366 	struct indir_hashhead *wkhd;
2367 	struct ufsmount *ump;
2368 
2369 	ump = VFSTOUFS(mp);
2370 	wkhd = INDIR_HASH(ump, blkno);
2371 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2372 		if (freework->fw_blkno != blkno)
2373 			continue;
2374 		indirblk_remove(freework);
2375 		return (1);
2376 	}
2377 	return (0);
2378 }
2379 
2380 /*
2381  * Insert an indirect block represented by freework into the indirblk
2382  * hash table so that it may prevent the block from being re-used prior
2383  * to the journal being written.
2384  */
2385 static void
2386 indirblk_insert(freework)
2387 	struct freework *freework;
2388 {
2389 	struct jblocks *jblocks;
2390 	struct jseg *jseg;
2391 	struct ufsmount *ump;
2392 
2393 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2394 	jblocks = ump->softdep_jblocks;
2395 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2396 	if (jseg == NULL)
2397 		return;
2398 
2399 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2400 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2401 	    fw_next);
2402 	freework->fw_state &= ~DEPCOMPLETE;
2403 }
2404 
2405 static void
2406 indirblk_remove(freework)
2407 	struct freework *freework;
2408 {
2409 	struct ufsmount *ump;
2410 
2411 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2412 	LIST_REMOVE(freework, fw_segs);
2413 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2414 	freework->fw_state |= DEPCOMPLETE;
2415 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2416 		WORKITEM_FREE(freework, D_FREEWORK);
2417 }
2418 
2419 /*
2420  * Executed during filesystem system initialization before
2421  * mounting any filesystems.
2422  */
2423 void
2424 softdep_initialize()
2425 {
2426 
2427 	TAILQ_INIT(&softdepmounts);
2428 #ifdef __LP64__
2429 	max_softdeps = desiredvnodes * 4;
2430 #else
2431 	max_softdeps = desiredvnodes * 2;
2432 #endif
2433 
2434 	/* initialise bioops hack */
2435 	bioops.io_start = softdep_disk_io_initiation;
2436 	bioops.io_complete = softdep_disk_write_complete;
2437 	bioops.io_deallocate = softdep_deallocate_dependencies;
2438 	bioops.io_countdeps = softdep_count_dependencies;
2439 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2440 
2441 	/* Initialize the callout with an mtx. */
2442 	callout_init_mtx(&softdep_callout, &lk, 0);
2443 }
2444 
2445 /*
2446  * Executed after all filesystems have been unmounted during
2447  * filesystem module unload.
2448  */
2449 void
2450 softdep_uninitialize()
2451 {
2452 
2453 	/* clear bioops hack */
2454 	bioops.io_start = NULL;
2455 	bioops.io_complete = NULL;
2456 	bioops.io_deallocate = NULL;
2457 	bioops.io_countdeps = NULL;
2458 	softdep_ast_cleanup = NULL;
2459 
2460 	callout_drain(&softdep_callout);
2461 }
2462 
2463 /*
2464  * Called at mount time to notify the dependency code that a
2465  * filesystem wishes to use it.
2466  */
2467 int
2468 softdep_mount(devvp, mp, fs, cred)
2469 	struct vnode *devvp;
2470 	struct mount *mp;
2471 	struct fs *fs;
2472 	struct ucred *cred;
2473 {
2474 	struct csum_total cstotal;
2475 	struct mount_softdeps *sdp;
2476 	struct ufsmount *ump;
2477 	struct cg *cgp;
2478 	struct buf *bp;
2479 	u_int cyl, i;
2480 	int error;
2481 
2482 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2483 	    M_WAITOK | M_ZERO);
2484 	MNT_ILOCK(mp);
2485 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2486 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2487 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2488 			MNTK_SOFTDEP | MNTK_NOASYNC;
2489 	}
2490 	ump = VFSTOUFS(mp);
2491 	ump->um_softdep = sdp;
2492 	MNT_IUNLOCK(mp);
2493 	rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2494 	sdp->sd_ump = ump;
2495 	LIST_INIT(&ump->softdep_workitem_pending);
2496 	LIST_INIT(&ump->softdep_journal_pending);
2497 	TAILQ_INIT(&ump->softdep_unlinked);
2498 	LIST_INIT(&ump->softdep_dirtycg);
2499 	ump->softdep_worklist_tail = NULL;
2500 	ump->softdep_on_worklist = 0;
2501 	ump->softdep_deps = 0;
2502 	LIST_INIT(&ump->softdep_mkdirlisthd);
2503 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2504 	    &ump->pagedep_hash_size);
2505 	ump->pagedep_nextclean = 0;
2506 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2507 	    &ump->inodedep_hash_size);
2508 	ump->inodedep_nextclean = 0;
2509 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2510 	    &ump->newblk_hash_size);
2511 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2512 	    &ump->bmsafemap_hash_size);
2513 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2514 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2515 	    M_FREEWORK, M_WAITOK);
2516 	ump->indir_hash_size = i - 1;
2517 	for (i = 0; i <= ump->indir_hash_size; i++)
2518 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2519 	ACQUIRE_GBLLOCK(&lk);
2520 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2521 	FREE_GBLLOCK(&lk);
2522 	if ((fs->fs_flags & FS_SUJ) &&
2523 	    (error = journal_mount(mp, fs, cred)) != 0) {
2524 		printf("Failed to start journal: %d\n", error);
2525 		softdep_unmount(mp);
2526 		return (error);
2527 	}
2528 	/*
2529 	 * Start our flushing thread in the bufdaemon process.
2530 	 */
2531 	ACQUIRE_LOCK(ump);
2532 	ump->softdep_flags |= FLUSH_STARTING;
2533 	FREE_LOCK(ump);
2534 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2535 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2536 	    mp->mnt_stat.f_mntonname);
2537 	ACQUIRE_LOCK(ump);
2538 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2539 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2540 		    hz / 2);
2541 	}
2542 	FREE_LOCK(ump);
2543 	/*
2544 	 * When doing soft updates, the counters in the
2545 	 * superblock may have gotten out of sync. Recomputation
2546 	 * can take a long time and can be deferred for background
2547 	 * fsck.  However, the old behavior of scanning the cylinder
2548 	 * groups and recalculating them at mount time is available
2549 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2550 	 */
2551 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2552 		return (0);
2553 	bzero(&cstotal, sizeof cstotal);
2554 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2555 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2556 		    fs->fs_cgsize, cred, &bp)) != 0) {
2557 			brelse(bp);
2558 			softdep_unmount(mp);
2559 			return (error);
2560 		}
2561 		cgp = (struct cg *)bp->b_data;
2562 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2563 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2564 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2565 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2566 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2567 		brelse(bp);
2568 	}
2569 #ifdef INVARIANTS
2570 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2571 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2572 #endif
2573 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2574 	return (0);
2575 }
2576 
2577 void
2578 softdep_unmount(mp)
2579 	struct mount *mp;
2580 {
2581 	struct ufsmount *ump;
2582 #ifdef INVARIANTS
2583 	int i;
2584 #endif
2585 
2586 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2587 	    ("softdep_unmount called on non-softdep filesystem"));
2588 	ump = VFSTOUFS(mp);
2589 	MNT_ILOCK(mp);
2590 	mp->mnt_flag &= ~MNT_SOFTDEP;
2591 	if (MOUNTEDSUJ(mp) == 0) {
2592 		MNT_IUNLOCK(mp);
2593 	} else {
2594 		mp->mnt_flag &= ~MNT_SUJ;
2595 		MNT_IUNLOCK(mp);
2596 		journal_unmount(ump);
2597 	}
2598 	/*
2599 	 * Shut down our flushing thread. Check for NULL is if
2600 	 * softdep_mount errors out before the thread has been created.
2601 	 */
2602 	if (ump->softdep_flushtd != NULL) {
2603 		ACQUIRE_LOCK(ump);
2604 		ump->softdep_flags |= FLUSH_EXIT;
2605 		wakeup(&ump->softdep_flushtd);
2606 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2607 		    "sdwait", 0);
2608 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2609 		    ("Thread shutdown failed"));
2610 	}
2611 	/*
2612 	 * Free up our resources.
2613 	 */
2614 	ACQUIRE_GBLLOCK(&lk);
2615 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2616 	FREE_GBLLOCK(&lk);
2617 	rw_destroy(LOCK_PTR(ump));
2618 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2619 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2620 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2621 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2622 	    ump->bmsafemap_hash_size);
2623 	free(ump->indir_hashtbl, M_FREEWORK);
2624 #ifdef INVARIANTS
2625 	for (i = 0; i <= D_LAST; i++)
2626 		KASSERT(ump->softdep_curdeps[i] == 0,
2627 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2628 		    TYPENAME(i), ump->softdep_curdeps[i]));
2629 #endif
2630 	free(ump->um_softdep, M_MOUNTDATA);
2631 }
2632 
2633 static struct jblocks *
2634 jblocks_create(void)
2635 {
2636 	struct jblocks *jblocks;
2637 
2638 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2639 	TAILQ_INIT(&jblocks->jb_segs);
2640 	jblocks->jb_avail = 10;
2641 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2642 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2643 
2644 	return (jblocks);
2645 }
2646 
2647 static ufs2_daddr_t
2648 jblocks_alloc(jblocks, bytes, actual)
2649 	struct jblocks *jblocks;
2650 	int bytes;
2651 	int *actual;
2652 {
2653 	ufs2_daddr_t daddr;
2654 	struct jextent *jext;
2655 	int freecnt;
2656 	int blocks;
2657 
2658 	blocks = bytes / DEV_BSIZE;
2659 	jext = &jblocks->jb_extent[jblocks->jb_head];
2660 	freecnt = jext->je_blocks - jblocks->jb_off;
2661 	if (freecnt == 0) {
2662 		jblocks->jb_off = 0;
2663 		if (++jblocks->jb_head > jblocks->jb_used)
2664 			jblocks->jb_head = 0;
2665 		jext = &jblocks->jb_extent[jblocks->jb_head];
2666 		freecnt = jext->je_blocks;
2667 	}
2668 	if (freecnt > blocks)
2669 		freecnt = blocks;
2670 	*actual = freecnt * DEV_BSIZE;
2671 	daddr = jext->je_daddr + jblocks->jb_off;
2672 	jblocks->jb_off += freecnt;
2673 	jblocks->jb_free -= freecnt;
2674 
2675 	return (daddr);
2676 }
2677 
2678 static void
2679 jblocks_free(jblocks, mp, bytes)
2680 	struct jblocks *jblocks;
2681 	struct mount *mp;
2682 	int bytes;
2683 {
2684 
2685 	LOCK_OWNED(VFSTOUFS(mp));
2686 	jblocks->jb_free += bytes / DEV_BSIZE;
2687 	if (jblocks->jb_suspended)
2688 		worklist_speedup(mp);
2689 	wakeup(jblocks);
2690 }
2691 
2692 static void
2693 jblocks_destroy(jblocks)
2694 	struct jblocks *jblocks;
2695 {
2696 
2697 	if (jblocks->jb_extent)
2698 		free(jblocks->jb_extent, M_JBLOCKS);
2699 	free(jblocks, M_JBLOCKS);
2700 }
2701 
2702 static void
2703 jblocks_add(jblocks, daddr, blocks)
2704 	struct jblocks *jblocks;
2705 	ufs2_daddr_t daddr;
2706 	int blocks;
2707 {
2708 	struct jextent *jext;
2709 
2710 	jblocks->jb_blocks += blocks;
2711 	jblocks->jb_free += blocks;
2712 	jext = &jblocks->jb_extent[jblocks->jb_used];
2713 	/* Adding the first block. */
2714 	if (jext->je_daddr == 0) {
2715 		jext->je_daddr = daddr;
2716 		jext->je_blocks = blocks;
2717 		return;
2718 	}
2719 	/* Extending the last extent. */
2720 	if (jext->je_daddr + jext->je_blocks == daddr) {
2721 		jext->je_blocks += blocks;
2722 		return;
2723 	}
2724 	/* Adding a new extent. */
2725 	if (++jblocks->jb_used == jblocks->jb_avail) {
2726 		jblocks->jb_avail *= 2;
2727 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2728 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2729 		memcpy(jext, jblocks->jb_extent,
2730 		    sizeof(struct jextent) * jblocks->jb_used);
2731 		free(jblocks->jb_extent, M_JBLOCKS);
2732 		jblocks->jb_extent = jext;
2733 	}
2734 	jext = &jblocks->jb_extent[jblocks->jb_used];
2735 	jext->je_daddr = daddr;
2736 	jext->je_blocks = blocks;
2737 	return;
2738 }
2739 
2740 int
2741 softdep_journal_lookup(mp, vpp)
2742 	struct mount *mp;
2743 	struct vnode **vpp;
2744 {
2745 	struct componentname cnp;
2746 	struct vnode *dvp;
2747 	ino_t sujournal;
2748 	int error;
2749 
2750 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2751 	if (error)
2752 		return (error);
2753 	bzero(&cnp, sizeof(cnp));
2754 	cnp.cn_nameiop = LOOKUP;
2755 	cnp.cn_flags = ISLASTCN;
2756 	cnp.cn_thread = curthread;
2757 	cnp.cn_cred = curthread->td_ucred;
2758 	cnp.cn_pnbuf = SUJ_FILE;
2759 	cnp.cn_nameptr = SUJ_FILE;
2760 	cnp.cn_namelen = strlen(SUJ_FILE);
2761 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2762 	vput(dvp);
2763 	if (error != 0)
2764 		return (error);
2765 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2766 	return (error);
2767 }
2768 
2769 /*
2770  * Open and verify the journal file.
2771  */
2772 static int
2773 journal_mount(mp, fs, cred)
2774 	struct mount *mp;
2775 	struct fs *fs;
2776 	struct ucred *cred;
2777 {
2778 	struct jblocks *jblocks;
2779 	struct ufsmount *ump;
2780 	struct vnode *vp;
2781 	struct inode *ip;
2782 	ufs2_daddr_t blkno;
2783 	int bcount;
2784 	int error;
2785 	int i;
2786 
2787 	ump = VFSTOUFS(mp);
2788 	ump->softdep_journal_tail = NULL;
2789 	ump->softdep_on_journal = 0;
2790 	ump->softdep_accdeps = 0;
2791 	ump->softdep_req = 0;
2792 	ump->softdep_jblocks = NULL;
2793 	error = softdep_journal_lookup(mp, &vp);
2794 	if (error != 0) {
2795 		printf("Failed to find journal.  Use tunefs to create one\n");
2796 		return (error);
2797 	}
2798 	ip = VTOI(vp);
2799 	if (ip->i_size < SUJ_MIN) {
2800 		error = ENOSPC;
2801 		goto out;
2802 	}
2803 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2804 	jblocks = jblocks_create();
2805 	for (i = 0; i < bcount; i++) {
2806 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2807 		if (error)
2808 			break;
2809 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2810 	}
2811 	if (error) {
2812 		jblocks_destroy(jblocks);
2813 		goto out;
2814 	}
2815 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2816 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2817 	ump->softdep_jblocks = jblocks;
2818 out:
2819 	if (error == 0) {
2820 		MNT_ILOCK(mp);
2821 		mp->mnt_flag |= MNT_SUJ;
2822 		mp->mnt_flag &= ~MNT_SOFTDEP;
2823 		MNT_IUNLOCK(mp);
2824 		/*
2825 		 * Only validate the journal contents if the
2826 		 * filesystem is clean, otherwise we write the logs
2827 		 * but they'll never be used.  If the filesystem was
2828 		 * still dirty when we mounted it the journal is
2829 		 * invalid and a new journal can only be valid if it
2830 		 * starts from a clean mount.
2831 		 */
2832 		if (fs->fs_clean) {
2833 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2834 			ip->i_flags |= IN_MODIFIED;
2835 			ffs_update(vp, 1);
2836 		}
2837 	}
2838 	vput(vp);
2839 	return (error);
2840 }
2841 
2842 static void
2843 journal_unmount(ump)
2844 	struct ufsmount *ump;
2845 {
2846 
2847 	if (ump->softdep_jblocks)
2848 		jblocks_destroy(ump->softdep_jblocks);
2849 	ump->softdep_jblocks = NULL;
2850 }
2851 
2852 /*
2853  * Called when a journal record is ready to be written.  Space is allocated
2854  * and the journal entry is created when the journal is flushed to stable
2855  * store.
2856  */
2857 static void
2858 add_to_journal(wk)
2859 	struct worklist *wk;
2860 {
2861 	struct ufsmount *ump;
2862 
2863 	ump = VFSTOUFS(wk->wk_mp);
2864 	LOCK_OWNED(ump);
2865 	if (wk->wk_state & ONWORKLIST)
2866 		panic("add_to_journal: %s(0x%X) already on list",
2867 		    TYPENAME(wk->wk_type), wk->wk_state);
2868 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2869 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2870 		ump->softdep_jblocks->jb_age = ticks;
2871 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2872 	} else
2873 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2874 	ump->softdep_journal_tail = wk;
2875 	ump->softdep_on_journal += 1;
2876 }
2877 
2878 /*
2879  * Remove an arbitrary item for the journal worklist maintain the tail
2880  * pointer.  This happens when a new operation obviates the need to
2881  * journal an old operation.
2882  */
2883 static void
2884 remove_from_journal(wk)
2885 	struct worklist *wk;
2886 {
2887 	struct ufsmount *ump;
2888 
2889 	ump = VFSTOUFS(wk->wk_mp);
2890 	LOCK_OWNED(ump);
2891 #ifdef INVARIANTS
2892 	{
2893 		struct worklist *wkn;
2894 
2895 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2896 			if (wkn == wk)
2897 				break;
2898 		if (wkn == NULL)
2899 			panic("remove_from_journal: %p is not in journal", wk);
2900 	}
2901 #endif
2902 	/*
2903 	 * We emulate a TAILQ to save space in most structures which do not
2904 	 * require TAILQ semantics.  Here we must update the tail position
2905 	 * when removing the tail which is not the final entry. This works
2906 	 * only if the worklist linkage are at the beginning of the structure.
2907 	 */
2908 	if (ump->softdep_journal_tail == wk)
2909 		ump->softdep_journal_tail =
2910 		    (struct worklist *)wk->wk_list.le_prev;
2911 	WORKLIST_REMOVE(wk);
2912 	ump->softdep_on_journal -= 1;
2913 }
2914 
2915 /*
2916  * Check for journal space as well as dependency limits so the prelink
2917  * code can throttle both journaled and non-journaled filesystems.
2918  * Threshold is 0 for low and 1 for min.
2919  */
2920 static int
2921 journal_space(ump, thresh)
2922 	struct ufsmount *ump;
2923 	int thresh;
2924 {
2925 	struct jblocks *jblocks;
2926 	int limit, avail;
2927 
2928 	jblocks = ump->softdep_jblocks;
2929 	if (jblocks == NULL)
2930 		return (1);
2931 	/*
2932 	 * We use a tighter restriction here to prevent request_cleanup()
2933 	 * running in threads from running into locks we currently hold.
2934 	 * We have to be over the limit and our filesystem has to be
2935 	 * responsible for more than our share of that usage.
2936 	 */
2937 	limit = (max_softdeps / 10) * 9;
2938 	if (dep_current[D_INODEDEP] > limit &&
2939 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2940 		return (0);
2941 	if (thresh)
2942 		thresh = jblocks->jb_min;
2943 	else
2944 		thresh = jblocks->jb_low;
2945 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2946 	avail = jblocks->jb_free - avail;
2947 
2948 	return (avail > thresh);
2949 }
2950 
2951 static void
2952 journal_suspend(ump)
2953 	struct ufsmount *ump;
2954 {
2955 	struct jblocks *jblocks;
2956 	struct mount *mp;
2957 
2958 	mp = UFSTOVFS(ump);
2959 	jblocks = ump->softdep_jblocks;
2960 	MNT_ILOCK(mp);
2961 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2962 		stat_journal_min++;
2963 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2964 		mp->mnt_susp_owner = ump->softdep_flushtd;
2965 	}
2966 	jblocks->jb_suspended = 1;
2967 	MNT_IUNLOCK(mp);
2968 }
2969 
2970 static int
2971 journal_unsuspend(struct ufsmount *ump)
2972 {
2973 	struct jblocks *jblocks;
2974 	struct mount *mp;
2975 
2976 	mp = UFSTOVFS(ump);
2977 	jblocks = ump->softdep_jblocks;
2978 
2979 	if (jblocks != NULL && jblocks->jb_suspended &&
2980 	    journal_space(ump, jblocks->jb_min)) {
2981 		jblocks->jb_suspended = 0;
2982 		FREE_LOCK(ump);
2983 		mp->mnt_susp_owner = curthread;
2984 		vfs_write_resume(mp, 0);
2985 		ACQUIRE_LOCK(ump);
2986 		return (1);
2987 	}
2988 	return (0);
2989 }
2990 
2991 /*
2992  * Called before any allocation function to be certain that there is
2993  * sufficient space in the journal prior to creating any new records.
2994  * Since in the case of block allocation we may have multiple locked
2995  * buffers at the time of the actual allocation we can not block
2996  * when the journal records are created.  Doing so would create a deadlock
2997  * if any of these buffers needed to be flushed to reclaim space.  Instead
2998  * we require a sufficiently large amount of available space such that
2999  * each thread in the system could have passed this allocation check and
3000  * still have sufficient free space.  With 20% of a minimum journal size
3001  * of 1MB we have 6553 records available.
3002  */
3003 int
3004 softdep_prealloc(vp, waitok)
3005 	struct vnode *vp;
3006 	int waitok;
3007 {
3008 	struct ufsmount *ump;
3009 
3010 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3011 	    ("softdep_prealloc called on non-softdep filesystem"));
3012 	/*
3013 	 * Nothing to do if we are not running journaled soft updates.
3014 	 * If we currently hold the snapshot lock, we must avoid
3015 	 * handling other resources that could cause deadlock.  Do not
3016 	 * touch quotas vnode since it is typically recursed with
3017 	 * other vnode locks held.
3018 	 */
3019 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3020 	    (vp->v_vflag & VV_SYSTEM) != 0)
3021 		return (0);
3022 	ump = VFSTOUFS(vp->v_mount);
3023 	ACQUIRE_LOCK(ump);
3024 	if (journal_space(ump, 0)) {
3025 		FREE_LOCK(ump);
3026 		return (0);
3027 	}
3028 	stat_journal_low++;
3029 	FREE_LOCK(ump);
3030 	if (waitok == MNT_NOWAIT)
3031 		return (ENOSPC);
3032 	/*
3033 	 * Attempt to sync this vnode once to flush any journal
3034 	 * work attached to it.
3035 	 */
3036 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3037 		ffs_syncvnode(vp, waitok, 0);
3038 	ACQUIRE_LOCK(ump);
3039 	process_removes(vp);
3040 	process_truncates(vp);
3041 	if (journal_space(ump, 0) == 0) {
3042 		softdep_speedup(ump);
3043 		if (journal_space(ump, 1) == 0)
3044 			journal_suspend(ump);
3045 	}
3046 	FREE_LOCK(ump);
3047 
3048 	return (0);
3049 }
3050 
3051 /*
3052  * Before adjusting a link count on a vnode verify that we have sufficient
3053  * journal space.  If not, process operations that depend on the currently
3054  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3055  * and softdep flush threads can not acquire these locks to reclaim space.
3056  */
3057 static void
3058 softdep_prelink(dvp, vp)
3059 	struct vnode *dvp;
3060 	struct vnode *vp;
3061 {
3062 	struct ufsmount *ump;
3063 
3064 	ump = VFSTOUFS(dvp->v_mount);
3065 	LOCK_OWNED(ump);
3066 	/*
3067 	 * Nothing to do if we have sufficient journal space.
3068 	 * If we currently hold the snapshot lock, we must avoid
3069 	 * handling other resources that could cause deadlock.
3070 	 */
3071 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3072 		return;
3073 	stat_journal_low++;
3074 	FREE_LOCK(ump);
3075 	if (vp)
3076 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3077 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3078 	ACQUIRE_LOCK(ump);
3079 	/* Process vp before dvp as it may create .. removes. */
3080 	if (vp) {
3081 		process_removes(vp);
3082 		process_truncates(vp);
3083 	}
3084 	process_removes(dvp);
3085 	process_truncates(dvp);
3086 	softdep_speedup(ump);
3087 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3088 	if (journal_space(ump, 0) == 0) {
3089 		softdep_speedup(ump);
3090 		if (journal_space(ump, 1) == 0)
3091 			journal_suspend(ump);
3092 	}
3093 }
3094 
3095 static void
3096 jseg_write(ump, jseg, data)
3097 	struct ufsmount *ump;
3098 	struct jseg *jseg;
3099 	uint8_t *data;
3100 {
3101 	struct jsegrec *rec;
3102 
3103 	rec = (struct jsegrec *)data;
3104 	rec->jsr_seq = jseg->js_seq;
3105 	rec->jsr_oldest = jseg->js_oldseq;
3106 	rec->jsr_cnt = jseg->js_cnt;
3107 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3108 	rec->jsr_crc = 0;
3109 	rec->jsr_time = ump->um_fs->fs_mtime;
3110 }
3111 
3112 static inline void
3113 inoref_write(inoref, jseg, rec)
3114 	struct inoref *inoref;
3115 	struct jseg *jseg;
3116 	struct jrefrec *rec;
3117 {
3118 
3119 	inoref->if_jsegdep->jd_seg = jseg;
3120 	rec->jr_ino = inoref->if_ino;
3121 	rec->jr_parent = inoref->if_parent;
3122 	rec->jr_nlink = inoref->if_nlink;
3123 	rec->jr_mode = inoref->if_mode;
3124 	rec->jr_diroff = inoref->if_diroff;
3125 }
3126 
3127 static void
3128 jaddref_write(jaddref, jseg, data)
3129 	struct jaddref *jaddref;
3130 	struct jseg *jseg;
3131 	uint8_t *data;
3132 {
3133 	struct jrefrec *rec;
3134 
3135 	rec = (struct jrefrec *)data;
3136 	rec->jr_op = JOP_ADDREF;
3137 	inoref_write(&jaddref->ja_ref, jseg, rec);
3138 }
3139 
3140 static void
3141 jremref_write(jremref, jseg, data)
3142 	struct jremref *jremref;
3143 	struct jseg *jseg;
3144 	uint8_t *data;
3145 {
3146 	struct jrefrec *rec;
3147 
3148 	rec = (struct jrefrec *)data;
3149 	rec->jr_op = JOP_REMREF;
3150 	inoref_write(&jremref->jr_ref, jseg, rec);
3151 }
3152 
3153 static void
3154 jmvref_write(jmvref, jseg, data)
3155 	struct jmvref *jmvref;
3156 	struct jseg *jseg;
3157 	uint8_t *data;
3158 {
3159 	struct jmvrec *rec;
3160 
3161 	rec = (struct jmvrec *)data;
3162 	rec->jm_op = JOP_MVREF;
3163 	rec->jm_ino = jmvref->jm_ino;
3164 	rec->jm_parent = jmvref->jm_parent;
3165 	rec->jm_oldoff = jmvref->jm_oldoff;
3166 	rec->jm_newoff = jmvref->jm_newoff;
3167 }
3168 
3169 static void
3170 jnewblk_write(jnewblk, jseg, data)
3171 	struct jnewblk *jnewblk;
3172 	struct jseg *jseg;
3173 	uint8_t *data;
3174 {
3175 	struct jblkrec *rec;
3176 
3177 	jnewblk->jn_jsegdep->jd_seg = jseg;
3178 	rec = (struct jblkrec *)data;
3179 	rec->jb_op = JOP_NEWBLK;
3180 	rec->jb_ino = jnewblk->jn_ino;
3181 	rec->jb_blkno = jnewblk->jn_blkno;
3182 	rec->jb_lbn = jnewblk->jn_lbn;
3183 	rec->jb_frags = jnewblk->jn_frags;
3184 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3185 }
3186 
3187 static void
3188 jfreeblk_write(jfreeblk, jseg, data)
3189 	struct jfreeblk *jfreeblk;
3190 	struct jseg *jseg;
3191 	uint8_t *data;
3192 {
3193 	struct jblkrec *rec;
3194 
3195 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3196 	rec = (struct jblkrec *)data;
3197 	rec->jb_op = JOP_FREEBLK;
3198 	rec->jb_ino = jfreeblk->jf_ino;
3199 	rec->jb_blkno = jfreeblk->jf_blkno;
3200 	rec->jb_lbn = jfreeblk->jf_lbn;
3201 	rec->jb_frags = jfreeblk->jf_frags;
3202 	rec->jb_oldfrags = 0;
3203 }
3204 
3205 static void
3206 jfreefrag_write(jfreefrag, jseg, data)
3207 	struct jfreefrag *jfreefrag;
3208 	struct jseg *jseg;
3209 	uint8_t *data;
3210 {
3211 	struct jblkrec *rec;
3212 
3213 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3214 	rec = (struct jblkrec *)data;
3215 	rec->jb_op = JOP_FREEBLK;
3216 	rec->jb_ino = jfreefrag->fr_ino;
3217 	rec->jb_blkno = jfreefrag->fr_blkno;
3218 	rec->jb_lbn = jfreefrag->fr_lbn;
3219 	rec->jb_frags = jfreefrag->fr_frags;
3220 	rec->jb_oldfrags = 0;
3221 }
3222 
3223 static void
3224 jtrunc_write(jtrunc, jseg, data)
3225 	struct jtrunc *jtrunc;
3226 	struct jseg *jseg;
3227 	uint8_t *data;
3228 {
3229 	struct jtrncrec *rec;
3230 
3231 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3232 	rec = (struct jtrncrec *)data;
3233 	rec->jt_op = JOP_TRUNC;
3234 	rec->jt_ino = jtrunc->jt_ino;
3235 	rec->jt_size = jtrunc->jt_size;
3236 	rec->jt_extsize = jtrunc->jt_extsize;
3237 }
3238 
3239 static void
3240 jfsync_write(jfsync, jseg, data)
3241 	struct jfsync *jfsync;
3242 	struct jseg *jseg;
3243 	uint8_t *data;
3244 {
3245 	struct jtrncrec *rec;
3246 
3247 	rec = (struct jtrncrec *)data;
3248 	rec->jt_op = JOP_SYNC;
3249 	rec->jt_ino = jfsync->jfs_ino;
3250 	rec->jt_size = jfsync->jfs_size;
3251 	rec->jt_extsize = jfsync->jfs_extsize;
3252 }
3253 
3254 static void
3255 softdep_flushjournal(mp)
3256 	struct mount *mp;
3257 {
3258 	struct jblocks *jblocks;
3259 	struct ufsmount *ump;
3260 
3261 	if (MOUNTEDSUJ(mp) == 0)
3262 		return;
3263 	ump = VFSTOUFS(mp);
3264 	jblocks = ump->softdep_jblocks;
3265 	ACQUIRE_LOCK(ump);
3266 	while (ump->softdep_on_journal) {
3267 		jblocks->jb_needseg = 1;
3268 		softdep_process_journal(mp, NULL, MNT_WAIT);
3269 	}
3270 	FREE_LOCK(ump);
3271 }
3272 
3273 static void softdep_synchronize_completed(struct bio *);
3274 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3275 
3276 static void
3277 softdep_synchronize_completed(bp)
3278         struct bio *bp;
3279 {
3280 	struct jseg *oldest;
3281 	struct jseg *jseg;
3282 	struct ufsmount *ump;
3283 
3284 	/*
3285 	 * caller1 marks the last segment written before we issued the
3286 	 * synchronize cache.
3287 	 */
3288 	jseg = bp->bio_caller1;
3289 	if (jseg == NULL) {
3290 		g_destroy_bio(bp);
3291 		return;
3292 	}
3293 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3294 	ACQUIRE_LOCK(ump);
3295 	oldest = NULL;
3296 	/*
3297 	 * Mark all the journal entries waiting on the synchronize cache
3298 	 * as completed so they may continue on.
3299 	 */
3300 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3301 		jseg->js_state |= COMPLETE;
3302 		oldest = jseg;
3303 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3304 	}
3305 	/*
3306 	 * Restart deferred journal entry processing from the oldest
3307 	 * completed jseg.
3308 	 */
3309 	if (oldest)
3310 		complete_jsegs(oldest);
3311 
3312 	FREE_LOCK(ump);
3313 	g_destroy_bio(bp);
3314 }
3315 
3316 /*
3317  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3318  * barriers.  The journal must be written prior to any blocks that depend
3319  * on it and the journal can not be released until the blocks have be
3320  * written.  This code handles both barriers simultaneously.
3321  */
3322 static void
3323 softdep_synchronize(bp, ump, caller1)
3324 	struct bio *bp;
3325 	struct ufsmount *ump;
3326 	void *caller1;
3327 {
3328 
3329 	bp->bio_cmd = BIO_FLUSH;
3330 	bp->bio_flags |= BIO_ORDERED;
3331 	bp->bio_data = NULL;
3332 	bp->bio_offset = ump->um_cp->provider->mediasize;
3333 	bp->bio_length = 0;
3334 	bp->bio_done = softdep_synchronize_completed;
3335 	bp->bio_caller1 = caller1;
3336 	g_io_request(bp,
3337 	    (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3338 }
3339 
3340 /*
3341  * Flush some journal records to disk.
3342  */
3343 static void
3344 softdep_process_journal(mp, needwk, flags)
3345 	struct mount *mp;
3346 	struct worklist *needwk;
3347 	int flags;
3348 {
3349 	struct jblocks *jblocks;
3350 	struct ufsmount *ump;
3351 	struct worklist *wk;
3352 	struct jseg *jseg;
3353 	struct buf *bp;
3354 	struct bio *bio;
3355 	uint8_t *data;
3356 	struct fs *fs;
3357 	int shouldflush;
3358 	int segwritten;
3359 	int jrecmin;	/* Minimum records per block. */
3360 	int jrecmax;	/* Maximum records per block. */
3361 	int size;
3362 	int cnt;
3363 	int off;
3364 	int devbsize;
3365 
3366 	if (MOUNTEDSUJ(mp) == 0)
3367 		return;
3368 	shouldflush = softdep_flushcache;
3369 	bio = NULL;
3370 	jseg = NULL;
3371 	ump = VFSTOUFS(mp);
3372 	LOCK_OWNED(ump);
3373 	fs = ump->um_fs;
3374 	jblocks = ump->softdep_jblocks;
3375 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3376 	/*
3377 	 * We write anywhere between a disk block and fs block.  The upper
3378 	 * bound is picked to prevent buffer cache fragmentation and limit
3379 	 * processing time per I/O.
3380 	 */
3381 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3382 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3383 	segwritten = 0;
3384 	for (;;) {
3385 		cnt = ump->softdep_on_journal;
3386 		/*
3387 		 * Criteria for writing a segment:
3388 		 * 1) We have a full block.
3389 		 * 2) We're called from jwait() and haven't found the
3390 		 *    journal item yet.
3391 		 * 3) Always write if needseg is set.
3392 		 * 4) If we are called from process_worklist and have
3393 		 *    not yet written anything we write a partial block
3394 		 *    to enforce a 1 second maximum latency on journal
3395 		 *    entries.
3396 		 */
3397 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3398 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3399 			break;
3400 		cnt++;
3401 		/*
3402 		 * Verify some free journal space.  softdep_prealloc() should
3403 		 * guarantee that we don't run out so this is indicative of
3404 		 * a problem with the flow control.  Try to recover
3405 		 * gracefully in any event.
3406 		 */
3407 		while (jblocks->jb_free == 0) {
3408 			if (flags != MNT_WAIT)
3409 				break;
3410 			printf("softdep: Out of journal space!\n");
3411 			softdep_speedup(ump);
3412 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3413 		}
3414 		FREE_LOCK(ump);
3415 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3416 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3417 		LIST_INIT(&jseg->js_entries);
3418 		LIST_INIT(&jseg->js_indirs);
3419 		jseg->js_state = ATTACHED;
3420 		if (shouldflush == 0)
3421 			jseg->js_state |= COMPLETE;
3422 		else if (bio == NULL)
3423 			bio = g_alloc_bio();
3424 		jseg->js_jblocks = jblocks;
3425 		bp = geteblk(fs->fs_bsize, 0);
3426 		ACQUIRE_LOCK(ump);
3427 		/*
3428 		 * If there was a race while we were allocating the block
3429 		 * and jseg the entry we care about was likely written.
3430 		 * We bail out in both the WAIT and NOWAIT case and assume
3431 		 * the caller will loop if the entry it cares about is
3432 		 * not written.
3433 		 */
3434 		cnt = ump->softdep_on_journal;
3435 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3436 			bp->b_flags |= B_INVAL | B_NOCACHE;
3437 			WORKITEM_FREE(jseg, D_JSEG);
3438 			FREE_LOCK(ump);
3439 			brelse(bp);
3440 			ACQUIRE_LOCK(ump);
3441 			break;
3442 		}
3443 		/*
3444 		 * Calculate the disk block size required for the available
3445 		 * records rounded to the min size.
3446 		 */
3447 		if (cnt == 0)
3448 			size = devbsize;
3449 		else if (cnt < jrecmax)
3450 			size = howmany(cnt, jrecmin) * devbsize;
3451 		else
3452 			size = fs->fs_bsize;
3453 		/*
3454 		 * Allocate a disk block for this journal data and account
3455 		 * for truncation of the requested size if enough contiguous
3456 		 * space was not available.
3457 		 */
3458 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3459 		bp->b_lblkno = bp->b_blkno;
3460 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3461 		bp->b_bcount = size;
3462 		bp->b_flags &= ~B_INVAL;
3463 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3464 		/*
3465 		 * Initialize our jseg with cnt records.  Assign the next
3466 		 * sequence number to it and link it in-order.
3467 		 */
3468 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3469 		jseg->js_buf = bp;
3470 		jseg->js_cnt = cnt;
3471 		jseg->js_refs = cnt + 1;	/* Self ref. */
3472 		jseg->js_size = size;
3473 		jseg->js_seq = jblocks->jb_nextseq++;
3474 		if (jblocks->jb_oldestseg == NULL)
3475 			jblocks->jb_oldestseg = jseg;
3476 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3477 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3478 		if (jblocks->jb_writeseg == NULL)
3479 			jblocks->jb_writeseg = jseg;
3480 		/*
3481 		 * Start filling in records from the pending list.
3482 		 */
3483 		data = bp->b_data;
3484 		off = 0;
3485 
3486 		/*
3487 		 * Always put a header on the first block.
3488 		 * XXX As with below, there might not be a chance to get
3489 		 * into the loop.  Ensure that something valid is written.
3490 		 */
3491 		jseg_write(ump, jseg, data);
3492 		off += JREC_SIZE;
3493 		data = bp->b_data + off;
3494 
3495 		/*
3496 		 * XXX Something is wrong here.  There's no work to do,
3497 		 * but we need to perform and I/O and allow it to complete
3498 		 * anyways.
3499 		 */
3500 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3501 			stat_emptyjblocks++;
3502 
3503 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3504 		    != NULL) {
3505 			if (cnt == 0)
3506 				break;
3507 			/* Place a segment header on every device block. */
3508 			if ((off % devbsize) == 0) {
3509 				jseg_write(ump, jseg, data);
3510 				off += JREC_SIZE;
3511 				data = bp->b_data + off;
3512 			}
3513 			if (wk == needwk)
3514 				needwk = NULL;
3515 			remove_from_journal(wk);
3516 			wk->wk_state |= INPROGRESS;
3517 			WORKLIST_INSERT(&jseg->js_entries, wk);
3518 			switch (wk->wk_type) {
3519 			case D_JADDREF:
3520 				jaddref_write(WK_JADDREF(wk), jseg, data);
3521 				break;
3522 			case D_JREMREF:
3523 				jremref_write(WK_JREMREF(wk), jseg, data);
3524 				break;
3525 			case D_JMVREF:
3526 				jmvref_write(WK_JMVREF(wk), jseg, data);
3527 				break;
3528 			case D_JNEWBLK:
3529 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3530 				break;
3531 			case D_JFREEBLK:
3532 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3533 				break;
3534 			case D_JFREEFRAG:
3535 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3536 				break;
3537 			case D_JTRUNC:
3538 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3539 				break;
3540 			case D_JFSYNC:
3541 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3542 				break;
3543 			default:
3544 				panic("process_journal: Unknown type %s",
3545 				    TYPENAME(wk->wk_type));
3546 				/* NOTREACHED */
3547 			}
3548 			off += JREC_SIZE;
3549 			data = bp->b_data + off;
3550 			cnt--;
3551 		}
3552 
3553 		/* Clear any remaining space so we don't leak kernel data */
3554 		if (size > off)
3555 			bzero(data, size - off);
3556 
3557 		/*
3558 		 * Write this one buffer and continue.
3559 		 */
3560 		segwritten = 1;
3561 		jblocks->jb_needseg = 0;
3562 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3563 		FREE_LOCK(ump);
3564 		pbgetvp(ump->um_devvp, bp);
3565 		/*
3566 		 * We only do the blocking wait once we find the journal
3567 		 * entry we're looking for.
3568 		 */
3569 		if (needwk == NULL && flags == MNT_WAIT)
3570 			bwrite(bp);
3571 		else
3572 			bawrite(bp);
3573 		ACQUIRE_LOCK(ump);
3574 	}
3575 	/*
3576 	 * If we wrote a segment issue a synchronize cache so the journal
3577 	 * is reflected on disk before the data is written.  Since reclaiming
3578 	 * journal space also requires writing a journal record this
3579 	 * process also enforces a barrier before reclamation.
3580 	 */
3581 	if (segwritten && shouldflush) {
3582 		softdep_synchronize(bio, ump,
3583 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3584 	} else if (bio)
3585 		g_destroy_bio(bio);
3586 	/*
3587 	 * If we've suspended the filesystem because we ran out of journal
3588 	 * space either try to sync it here to make some progress or
3589 	 * unsuspend it if we already have.
3590 	 */
3591 	if (flags == 0 && jblocks->jb_suspended) {
3592 		if (journal_unsuspend(ump))
3593 			return;
3594 		FREE_LOCK(ump);
3595 		VFS_SYNC(mp, MNT_NOWAIT);
3596 		ffs_sbupdate(ump, MNT_WAIT, 0);
3597 		ACQUIRE_LOCK(ump);
3598 	}
3599 }
3600 
3601 /*
3602  * Complete a jseg, allowing all dependencies awaiting journal writes
3603  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3604  * structures so that the journal segment can be freed to reclaim space.
3605  */
3606 static void
3607 complete_jseg(jseg)
3608 	struct jseg *jseg;
3609 {
3610 	struct worklist *wk;
3611 	struct jmvref *jmvref;
3612 #ifdef INVARIANTS
3613 	int i = 0;
3614 #endif
3615 
3616 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3617 		WORKLIST_REMOVE(wk);
3618 		wk->wk_state &= ~INPROGRESS;
3619 		wk->wk_state |= COMPLETE;
3620 		KASSERT(i++ < jseg->js_cnt,
3621 		    ("handle_written_jseg: overflow %d >= %d",
3622 		    i - 1, jseg->js_cnt));
3623 		switch (wk->wk_type) {
3624 		case D_JADDREF:
3625 			handle_written_jaddref(WK_JADDREF(wk));
3626 			break;
3627 		case D_JREMREF:
3628 			handle_written_jremref(WK_JREMREF(wk));
3629 			break;
3630 		case D_JMVREF:
3631 			rele_jseg(jseg);	/* No jsegdep. */
3632 			jmvref = WK_JMVREF(wk);
3633 			LIST_REMOVE(jmvref, jm_deps);
3634 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3635 				free_pagedep(jmvref->jm_pagedep);
3636 			WORKITEM_FREE(jmvref, D_JMVREF);
3637 			break;
3638 		case D_JNEWBLK:
3639 			handle_written_jnewblk(WK_JNEWBLK(wk));
3640 			break;
3641 		case D_JFREEBLK:
3642 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3643 			break;
3644 		case D_JTRUNC:
3645 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3646 			break;
3647 		case D_JFSYNC:
3648 			rele_jseg(jseg);	/* No jsegdep. */
3649 			WORKITEM_FREE(wk, D_JFSYNC);
3650 			break;
3651 		case D_JFREEFRAG:
3652 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3653 			break;
3654 		default:
3655 			panic("handle_written_jseg: Unknown type %s",
3656 			    TYPENAME(wk->wk_type));
3657 			/* NOTREACHED */
3658 		}
3659 	}
3660 	/* Release the self reference so the structure may be freed. */
3661 	rele_jseg(jseg);
3662 }
3663 
3664 /*
3665  * Determine which jsegs are ready for completion processing.  Waits for
3666  * synchronize cache to complete as well as forcing in-order completion
3667  * of journal entries.
3668  */
3669 static void
3670 complete_jsegs(jseg)
3671 	struct jseg *jseg;
3672 {
3673 	struct jblocks *jblocks;
3674 	struct jseg *jsegn;
3675 
3676 	jblocks = jseg->js_jblocks;
3677 	/*
3678 	 * Don't allow out of order completions.  If this isn't the first
3679 	 * block wait for it to write before we're done.
3680 	 */
3681 	if (jseg != jblocks->jb_writeseg)
3682 		return;
3683 	/* Iterate through available jsegs processing their entries. */
3684 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3685 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3686 		jsegn = TAILQ_NEXT(jseg, js_next);
3687 		complete_jseg(jseg);
3688 		jseg = jsegn;
3689 	}
3690 	jblocks->jb_writeseg = jseg;
3691 	/*
3692 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3693 	 */
3694 	free_jsegs(jblocks);
3695 }
3696 
3697 /*
3698  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3699  * the final completions.
3700  */
3701 static void
3702 handle_written_jseg(jseg, bp)
3703 	struct jseg *jseg;
3704 	struct buf *bp;
3705 {
3706 
3707 	if (jseg->js_refs == 0)
3708 		panic("handle_written_jseg: No self-reference on %p", jseg);
3709 	jseg->js_state |= DEPCOMPLETE;
3710 	/*
3711 	 * We'll never need this buffer again, set flags so it will be
3712 	 * discarded.
3713 	 */
3714 	bp->b_flags |= B_INVAL | B_NOCACHE;
3715 	pbrelvp(bp);
3716 	complete_jsegs(jseg);
3717 }
3718 
3719 static inline struct jsegdep *
3720 inoref_jseg(inoref)
3721 	struct inoref *inoref;
3722 {
3723 	struct jsegdep *jsegdep;
3724 
3725 	jsegdep = inoref->if_jsegdep;
3726 	inoref->if_jsegdep = NULL;
3727 
3728 	return (jsegdep);
3729 }
3730 
3731 /*
3732  * Called once a jremref has made it to stable store.  The jremref is marked
3733  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3734  * for the jremref to complete will be awoken by free_jremref.
3735  */
3736 static void
3737 handle_written_jremref(jremref)
3738 	struct jremref *jremref;
3739 {
3740 	struct inodedep *inodedep;
3741 	struct jsegdep *jsegdep;
3742 	struct dirrem *dirrem;
3743 
3744 	/* Grab the jsegdep. */
3745 	jsegdep = inoref_jseg(&jremref->jr_ref);
3746 	/*
3747 	 * Remove us from the inoref list.
3748 	 */
3749 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3750 	    0, &inodedep) == 0)
3751 		panic("handle_written_jremref: Lost inodedep");
3752 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3753 	/*
3754 	 * Complete the dirrem.
3755 	 */
3756 	dirrem = jremref->jr_dirrem;
3757 	jremref->jr_dirrem = NULL;
3758 	LIST_REMOVE(jremref, jr_deps);
3759 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3760 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3761 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3762 	    (dirrem->dm_state & COMPLETE) != 0)
3763 		add_to_worklist(&dirrem->dm_list, 0);
3764 	free_jremref(jremref);
3765 }
3766 
3767 /*
3768  * Called once a jaddref has made it to stable store.  The dependency is
3769  * marked complete and any dependent structures are added to the inode
3770  * bufwait list to be completed as soon as it is written.  If a bitmap write
3771  * depends on this entry we move the inode into the inodedephd of the
3772  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3773  */
3774 static void
3775 handle_written_jaddref(jaddref)
3776 	struct jaddref *jaddref;
3777 {
3778 	struct jsegdep *jsegdep;
3779 	struct inodedep *inodedep;
3780 	struct diradd *diradd;
3781 	struct mkdir *mkdir;
3782 
3783 	/* Grab the jsegdep. */
3784 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3785 	mkdir = NULL;
3786 	diradd = NULL;
3787 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3788 	    0, &inodedep) == 0)
3789 		panic("handle_written_jaddref: Lost inodedep.");
3790 	if (jaddref->ja_diradd == NULL)
3791 		panic("handle_written_jaddref: No dependency");
3792 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3793 		diradd = jaddref->ja_diradd;
3794 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3795 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3796 		mkdir = jaddref->ja_mkdir;
3797 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3798 	} else if (jaddref->ja_state & MKDIR_BODY)
3799 		mkdir = jaddref->ja_mkdir;
3800 	else
3801 		panic("handle_written_jaddref: Unknown dependency %p",
3802 		    jaddref->ja_diradd);
3803 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3804 	/*
3805 	 * Remove us from the inode list.
3806 	 */
3807 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3808 	/*
3809 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3810 	 */
3811 	if (mkdir) {
3812 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3813 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3814 		    TYPENAME(mkdir->md_list.wk_type)));
3815 		mkdir->md_jaddref = NULL;
3816 		diradd = mkdir->md_diradd;
3817 		mkdir->md_state |= DEPCOMPLETE;
3818 		complete_mkdir(mkdir);
3819 	}
3820 	jwork_insert(&diradd->da_jwork, jsegdep);
3821 	if (jaddref->ja_state & NEWBLOCK) {
3822 		inodedep->id_state |= ONDEPLIST;
3823 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3824 		    inodedep, id_deps);
3825 	}
3826 	free_jaddref(jaddref);
3827 }
3828 
3829 /*
3830  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3831  * is placed in the bmsafemap to await notification of a written bitmap.  If
3832  * the operation was canceled we add the segdep to the appropriate
3833  * dependency to free the journal space once the canceling operation
3834  * completes.
3835  */
3836 static void
3837 handle_written_jnewblk(jnewblk)
3838 	struct jnewblk *jnewblk;
3839 {
3840 	struct bmsafemap *bmsafemap;
3841 	struct freefrag *freefrag;
3842 	struct freework *freework;
3843 	struct jsegdep *jsegdep;
3844 	struct newblk *newblk;
3845 
3846 	/* Grab the jsegdep. */
3847 	jsegdep = jnewblk->jn_jsegdep;
3848 	jnewblk->jn_jsegdep = NULL;
3849 	if (jnewblk->jn_dep == NULL)
3850 		panic("handle_written_jnewblk: No dependency for the segdep.");
3851 	switch (jnewblk->jn_dep->wk_type) {
3852 	case D_NEWBLK:
3853 	case D_ALLOCDIRECT:
3854 	case D_ALLOCINDIR:
3855 		/*
3856 		 * Add the written block to the bmsafemap so it can
3857 		 * be notified when the bitmap is on disk.
3858 		 */
3859 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3860 		newblk->nb_jnewblk = NULL;
3861 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3862 			bmsafemap = newblk->nb_bmsafemap;
3863 			newblk->nb_state |= ONDEPLIST;
3864 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3865 			    nb_deps);
3866 		}
3867 		jwork_insert(&newblk->nb_jwork, jsegdep);
3868 		break;
3869 	case D_FREEFRAG:
3870 		/*
3871 		 * A newblock being removed by a freefrag when replaced by
3872 		 * frag extension.
3873 		 */
3874 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3875 		freefrag->ff_jdep = NULL;
3876 		jwork_insert(&freefrag->ff_jwork, jsegdep);
3877 		break;
3878 	case D_FREEWORK:
3879 		/*
3880 		 * A direct block was removed by truncate.
3881 		 */
3882 		freework = WK_FREEWORK(jnewblk->jn_dep);
3883 		freework->fw_jnewblk = NULL;
3884 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3885 		break;
3886 	default:
3887 		panic("handle_written_jnewblk: Unknown type %d.",
3888 		    jnewblk->jn_dep->wk_type);
3889 	}
3890 	jnewblk->jn_dep = NULL;
3891 	free_jnewblk(jnewblk);
3892 }
3893 
3894 /*
3895  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3896  * an in-flight allocation that has not yet been committed.  Divorce us
3897  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3898  * to the worklist.
3899  */
3900 static void
3901 cancel_jfreefrag(jfreefrag)
3902 	struct jfreefrag *jfreefrag;
3903 {
3904 	struct freefrag *freefrag;
3905 
3906 	if (jfreefrag->fr_jsegdep) {
3907 		free_jsegdep(jfreefrag->fr_jsegdep);
3908 		jfreefrag->fr_jsegdep = NULL;
3909 	}
3910 	freefrag = jfreefrag->fr_freefrag;
3911 	jfreefrag->fr_freefrag = NULL;
3912 	free_jfreefrag(jfreefrag);
3913 	freefrag->ff_state |= DEPCOMPLETE;
3914 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3915 }
3916 
3917 /*
3918  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3919  */
3920 static void
3921 free_jfreefrag(jfreefrag)
3922 	struct jfreefrag *jfreefrag;
3923 {
3924 
3925 	if (jfreefrag->fr_state & INPROGRESS)
3926 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3927 	else if (jfreefrag->fr_state & ONWORKLIST)
3928 		remove_from_journal(&jfreefrag->fr_list);
3929 	if (jfreefrag->fr_freefrag != NULL)
3930 		panic("free_jfreefrag:  Still attached to a freefrag.");
3931 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3932 }
3933 
3934 /*
3935  * Called when the journal write for a jfreefrag completes.  The parent
3936  * freefrag is added to the worklist if this completes its dependencies.
3937  */
3938 static void
3939 handle_written_jfreefrag(jfreefrag)
3940 	struct jfreefrag *jfreefrag;
3941 {
3942 	struct jsegdep *jsegdep;
3943 	struct freefrag *freefrag;
3944 
3945 	/* Grab the jsegdep. */
3946 	jsegdep = jfreefrag->fr_jsegdep;
3947 	jfreefrag->fr_jsegdep = NULL;
3948 	freefrag = jfreefrag->fr_freefrag;
3949 	if (freefrag == NULL)
3950 		panic("handle_written_jfreefrag: No freefrag.");
3951 	freefrag->ff_state |= DEPCOMPLETE;
3952 	freefrag->ff_jdep = NULL;
3953 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3954 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3955 		add_to_worklist(&freefrag->ff_list, 0);
3956 	jfreefrag->fr_freefrag = NULL;
3957 	free_jfreefrag(jfreefrag);
3958 }
3959 
3960 /*
3961  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3962  * is removed from the freeblks list of pending journal writes and the
3963  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3964  * have been reclaimed.
3965  */
3966 static void
3967 handle_written_jblkdep(jblkdep)
3968 	struct jblkdep *jblkdep;
3969 {
3970 	struct freeblks *freeblks;
3971 	struct jsegdep *jsegdep;
3972 
3973 	/* Grab the jsegdep. */
3974 	jsegdep = jblkdep->jb_jsegdep;
3975 	jblkdep->jb_jsegdep = NULL;
3976 	freeblks = jblkdep->jb_freeblks;
3977 	LIST_REMOVE(jblkdep, jb_deps);
3978 	jwork_insert(&freeblks->fb_jwork, jsegdep);
3979 	/*
3980 	 * If the freeblks is all journaled, we can add it to the worklist.
3981 	 */
3982 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3983 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3984 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3985 
3986 	free_jblkdep(jblkdep);
3987 }
3988 
3989 static struct jsegdep *
3990 newjsegdep(struct worklist *wk)
3991 {
3992 	struct jsegdep *jsegdep;
3993 
3994 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3995 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3996 	jsegdep->jd_seg = NULL;
3997 
3998 	return (jsegdep);
3999 }
4000 
4001 static struct jmvref *
4002 newjmvref(dp, ino, oldoff, newoff)
4003 	struct inode *dp;
4004 	ino_t ino;
4005 	off_t oldoff;
4006 	off_t newoff;
4007 {
4008 	struct jmvref *jmvref;
4009 
4010 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4011 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4012 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4013 	jmvref->jm_parent = dp->i_number;
4014 	jmvref->jm_ino = ino;
4015 	jmvref->jm_oldoff = oldoff;
4016 	jmvref->jm_newoff = newoff;
4017 
4018 	return (jmvref);
4019 }
4020 
4021 /*
4022  * Allocate a new jremref that tracks the removal of ip from dp with the
4023  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4024  * DEPCOMPLETE as we have all the information required for the journal write
4025  * and the directory has already been removed from the buffer.  The caller
4026  * is responsible for linking the jremref into the pagedep and adding it
4027  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4028  * a DOTDOT addition so handle_workitem_remove() can properly assign
4029  * the jsegdep when we're done.
4030  */
4031 static struct jremref *
4032 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4033     off_t diroff, nlink_t nlink)
4034 {
4035 	struct jremref *jremref;
4036 
4037 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4038 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4039 	jremref->jr_state = ATTACHED;
4040 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4041 	   nlink, ip->i_mode);
4042 	jremref->jr_dirrem = dirrem;
4043 
4044 	return (jremref);
4045 }
4046 
4047 static inline void
4048 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4049     nlink_t nlink, uint16_t mode)
4050 {
4051 
4052 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4053 	inoref->if_diroff = diroff;
4054 	inoref->if_ino = ino;
4055 	inoref->if_parent = parent;
4056 	inoref->if_nlink = nlink;
4057 	inoref->if_mode = mode;
4058 }
4059 
4060 /*
4061  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4062  * directory offset may not be known until later.  The caller is responsible
4063  * adding the entry to the journal when this information is available.  nlink
4064  * should be the link count prior to the addition and mode is only required
4065  * to have the correct FMT.
4066  */
4067 static struct jaddref *
4068 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4069     uint16_t mode)
4070 {
4071 	struct jaddref *jaddref;
4072 
4073 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4074 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4075 	jaddref->ja_state = ATTACHED;
4076 	jaddref->ja_mkdir = NULL;
4077 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4078 
4079 	return (jaddref);
4080 }
4081 
4082 /*
4083  * Create a new free dependency for a freework.  The caller is responsible
4084  * for adjusting the reference count when it has the lock held.  The freedep
4085  * will track an outstanding bitmap write that will ultimately clear the
4086  * freework to continue.
4087  */
4088 static struct freedep *
4089 newfreedep(struct freework *freework)
4090 {
4091 	struct freedep *freedep;
4092 
4093 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4094 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4095 	freedep->fd_freework = freework;
4096 
4097 	return (freedep);
4098 }
4099 
4100 /*
4101  * Free a freedep structure once the buffer it is linked to is written.  If
4102  * this is the last reference to the freework schedule it for completion.
4103  */
4104 static void
4105 free_freedep(freedep)
4106 	struct freedep *freedep;
4107 {
4108 	struct freework *freework;
4109 
4110 	freework = freedep->fd_freework;
4111 	freework->fw_freeblks->fb_cgwait--;
4112 	if (--freework->fw_ref == 0)
4113 		freework_enqueue(freework);
4114 	WORKITEM_FREE(freedep, D_FREEDEP);
4115 }
4116 
4117 /*
4118  * Allocate a new freework structure that may be a level in an indirect
4119  * when parent is not NULL or a top level block when it is.  The top level
4120  * freework structures are allocated without the per-filesystem lock held
4121  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4122  */
4123 static struct freework *
4124 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4125 	struct ufsmount *ump;
4126 	struct freeblks *freeblks;
4127 	struct freework *parent;
4128 	ufs_lbn_t lbn;
4129 	ufs2_daddr_t nb;
4130 	int frags;
4131 	int off;
4132 	int journal;
4133 {
4134 	struct freework *freework;
4135 
4136 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4137 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4138 	freework->fw_state = ATTACHED;
4139 	freework->fw_jnewblk = NULL;
4140 	freework->fw_freeblks = freeblks;
4141 	freework->fw_parent = parent;
4142 	freework->fw_lbn = lbn;
4143 	freework->fw_blkno = nb;
4144 	freework->fw_frags = frags;
4145 	freework->fw_indir = NULL;
4146 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4147 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4148 	freework->fw_start = freework->fw_off = off;
4149 	if (journal)
4150 		newjfreeblk(freeblks, lbn, nb, frags);
4151 	if (parent == NULL) {
4152 		ACQUIRE_LOCK(ump);
4153 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4154 		freeblks->fb_ref++;
4155 		FREE_LOCK(ump);
4156 	}
4157 
4158 	return (freework);
4159 }
4160 
4161 /*
4162  * Eliminate a jfreeblk for a block that does not need journaling.
4163  */
4164 static void
4165 cancel_jfreeblk(freeblks, blkno)
4166 	struct freeblks *freeblks;
4167 	ufs2_daddr_t blkno;
4168 {
4169 	struct jfreeblk *jfreeblk;
4170 	struct jblkdep *jblkdep;
4171 
4172 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4173 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4174 			continue;
4175 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4176 		if (jfreeblk->jf_blkno == blkno)
4177 			break;
4178 	}
4179 	if (jblkdep == NULL)
4180 		return;
4181 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4182 	free_jsegdep(jblkdep->jb_jsegdep);
4183 	LIST_REMOVE(jblkdep, jb_deps);
4184 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4185 }
4186 
4187 /*
4188  * Allocate a new jfreeblk to journal top level block pointer when truncating
4189  * a file.  The caller must add this to the worklist when the per-filesystem
4190  * lock is held.
4191  */
4192 static struct jfreeblk *
4193 newjfreeblk(freeblks, lbn, blkno, frags)
4194 	struct freeblks *freeblks;
4195 	ufs_lbn_t lbn;
4196 	ufs2_daddr_t blkno;
4197 	int frags;
4198 {
4199 	struct jfreeblk *jfreeblk;
4200 
4201 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4202 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4203 	    freeblks->fb_list.wk_mp);
4204 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4205 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4206 	jfreeblk->jf_ino = freeblks->fb_inum;
4207 	jfreeblk->jf_lbn = lbn;
4208 	jfreeblk->jf_blkno = blkno;
4209 	jfreeblk->jf_frags = frags;
4210 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4211 
4212 	return (jfreeblk);
4213 }
4214 
4215 /*
4216  * The journal is only prepared to handle full-size block numbers, so we
4217  * have to adjust the record to reflect the change to a full-size block.
4218  * For example, suppose we have a block made up of fragments 8-15 and
4219  * want to free its last two fragments. We are given a request that says:
4220  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4221  * where frags are the number of fragments to free and oldfrags are the
4222  * number of fragments to keep. To block align it, we have to change it to
4223  * have a valid full-size blkno, so it becomes:
4224  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4225  */
4226 static void
4227 adjust_newfreework(freeblks, frag_offset)
4228 	struct freeblks *freeblks;
4229 	int frag_offset;
4230 {
4231 	struct jfreeblk *jfreeblk;
4232 
4233 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4234 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4235 	    ("adjust_newfreework: Missing freeblks dependency"));
4236 
4237 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4238 	jfreeblk->jf_blkno -= frag_offset;
4239 	jfreeblk->jf_frags += frag_offset;
4240 }
4241 
4242 /*
4243  * Allocate a new jtrunc to track a partial truncation.
4244  */
4245 static struct jtrunc *
4246 newjtrunc(freeblks, size, extsize)
4247 	struct freeblks *freeblks;
4248 	off_t size;
4249 	int extsize;
4250 {
4251 	struct jtrunc *jtrunc;
4252 
4253 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4254 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4255 	    freeblks->fb_list.wk_mp);
4256 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4257 	jtrunc->jt_dep.jb_freeblks = freeblks;
4258 	jtrunc->jt_ino = freeblks->fb_inum;
4259 	jtrunc->jt_size = size;
4260 	jtrunc->jt_extsize = extsize;
4261 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4262 
4263 	return (jtrunc);
4264 }
4265 
4266 /*
4267  * If we're canceling a new bitmap we have to search for another ref
4268  * to move into the bmsafemap dep.  This might be better expressed
4269  * with another structure.
4270  */
4271 static void
4272 move_newblock_dep(jaddref, inodedep)
4273 	struct jaddref *jaddref;
4274 	struct inodedep *inodedep;
4275 {
4276 	struct inoref *inoref;
4277 	struct jaddref *jaddrefn;
4278 
4279 	jaddrefn = NULL;
4280 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4281 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4282 		if ((jaddref->ja_state & NEWBLOCK) &&
4283 		    inoref->if_list.wk_type == D_JADDREF) {
4284 			jaddrefn = (struct jaddref *)inoref;
4285 			break;
4286 		}
4287 	}
4288 	if (jaddrefn == NULL)
4289 		return;
4290 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4291 	jaddrefn->ja_state |= jaddref->ja_state &
4292 	    (ATTACHED | UNDONE | NEWBLOCK);
4293 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4294 	jaddref->ja_state |= ATTACHED;
4295 	LIST_REMOVE(jaddref, ja_bmdeps);
4296 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4297 	    ja_bmdeps);
4298 }
4299 
4300 /*
4301  * Cancel a jaddref either before it has been written or while it is being
4302  * written.  This happens when a link is removed before the add reaches
4303  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4304  * and inode to prevent the link count or bitmap from reaching the disk
4305  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4306  * required.
4307  *
4308  * Returns 1 if the canceled addref requires journaling of the remove and
4309  * 0 otherwise.
4310  */
4311 static int
4312 cancel_jaddref(jaddref, inodedep, wkhd)
4313 	struct jaddref *jaddref;
4314 	struct inodedep *inodedep;
4315 	struct workhead *wkhd;
4316 {
4317 	struct inoref *inoref;
4318 	struct jsegdep *jsegdep;
4319 	int needsj;
4320 
4321 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4322 	    ("cancel_jaddref: Canceling complete jaddref"));
4323 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4324 		needsj = 1;
4325 	else
4326 		needsj = 0;
4327 	if (inodedep == NULL)
4328 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4329 		    0, &inodedep) == 0)
4330 			panic("cancel_jaddref: Lost inodedep");
4331 	/*
4332 	 * We must adjust the nlink of any reference operation that follows
4333 	 * us so that it is consistent with the in-memory reference.  This
4334 	 * ensures that inode nlink rollbacks always have the correct link.
4335 	 */
4336 	if (needsj == 0) {
4337 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4338 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4339 			if (inoref->if_state & GOINGAWAY)
4340 				break;
4341 			inoref->if_nlink--;
4342 		}
4343 	}
4344 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4345 	if (jaddref->ja_state & NEWBLOCK)
4346 		move_newblock_dep(jaddref, inodedep);
4347 	wake_worklist(&jaddref->ja_list);
4348 	jaddref->ja_mkdir = NULL;
4349 	if (jaddref->ja_state & INPROGRESS) {
4350 		jaddref->ja_state &= ~INPROGRESS;
4351 		WORKLIST_REMOVE(&jaddref->ja_list);
4352 		jwork_insert(wkhd, jsegdep);
4353 	} else {
4354 		free_jsegdep(jsegdep);
4355 		if (jaddref->ja_state & DEPCOMPLETE)
4356 			remove_from_journal(&jaddref->ja_list);
4357 	}
4358 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4359 	/*
4360 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4361 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4362 	 * no longer need this addref attached to the inoreflst and it
4363 	 * will incorrectly adjust nlink if we leave it.
4364 	 */
4365 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4366 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4367 		    if_deps);
4368 		jaddref->ja_state |= COMPLETE;
4369 		free_jaddref(jaddref);
4370 		return (needsj);
4371 	}
4372 	/*
4373 	 * Leave the head of the list for jsegdeps for fast merging.
4374 	 */
4375 	if (LIST_FIRST(wkhd) != NULL) {
4376 		jaddref->ja_state |= ONWORKLIST;
4377 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4378 	} else
4379 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4380 
4381 	return (needsj);
4382 }
4383 
4384 /*
4385  * Attempt to free a jaddref structure when some work completes.  This
4386  * should only succeed once the entry is written and all dependencies have
4387  * been notified.
4388  */
4389 static void
4390 free_jaddref(jaddref)
4391 	struct jaddref *jaddref;
4392 {
4393 
4394 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4395 		return;
4396 	if (jaddref->ja_ref.if_jsegdep)
4397 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4398 		    jaddref, jaddref->ja_state);
4399 	if (jaddref->ja_state & NEWBLOCK)
4400 		LIST_REMOVE(jaddref, ja_bmdeps);
4401 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4402 		panic("free_jaddref: Bad state %p(0x%X)",
4403 		    jaddref, jaddref->ja_state);
4404 	if (jaddref->ja_mkdir != NULL)
4405 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4406 	WORKITEM_FREE(jaddref, D_JADDREF);
4407 }
4408 
4409 /*
4410  * Free a jremref structure once it has been written or discarded.
4411  */
4412 static void
4413 free_jremref(jremref)
4414 	struct jremref *jremref;
4415 {
4416 
4417 	if (jremref->jr_ref.if_jsegdep)
4418 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4419 	if (jremref->jr_state & INPROGRESS)
4420 		panic("free_jremref: IO still pending");
4421 	WORKITEM_FREE(jremref, D_JREMREF);
4422 }
4423 
4424 /*
4425  * Free a jnewblk structure.
4426  */
4427 static void
4428 free_jnewblk(jnewblk)
4429 	struct jnewblk *jnewblk;
4430 {
4431 
4432 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4433 		return;
4434 	LIST_REMOVE(jnewblk, jn_deps);
4435 	if (jnewblk->jn_dep != NULL)
4436 		panic("free_jnewblk: Dependency still attached.");
4437 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4438 }
4439 
4440 /*
4441  * Cancel a jnewblk which has been been made redundant by frag extension.
4442  */
4443 static void
4444 cancel_jnewblk(jnewblk, wkhd)
4445 	struct jnewblk *jnewblk;
4446 	struct workhead *wkhd;
4447 {
4448 	struct jsegdep *jsegdep;
4449 
4450 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4451 	jsegdep = jnewblk->jn_jsegdep;
4452 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4453 		panic("cancel_jnewblk: Invalid state");
4454 	jnewblk->jn_jsegdep  = NULL;
4455 	jnewblk->jn_dep = NULL;
4456 	jnewblk->jn_state |= GOINGAWAY;
4457 	if (jnewblk->jn_state & INPROGRESS) {
4458 		jnewblk->jn_state &= ~INPROGRESS;
4459 		WORKLIST_REMOVE(&jnewblk->jn_list);
4460 		jwork_insert(wkhd, jsegdep);
4461 	} else {
4462 		free_jsegdep(jsegdep);
4463 		remove_from_journal(&jnewblk->jn_list);
4464 	}
4465 	wake_worklist(&jnewblk->jn_list);
4466 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4467 }
4468 
4469 static void
4470 free_jblkdep(jblkdep)
4471 	struct jblkdep *jblkdep;
4472 {
4473 
4474 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4475 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4476 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4477 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4478 	else
4479 		panic("free_jblkdep: Unexpected type %s",
4480 		    TYPENAME(jblkdep->jb_list.wk_type));
4481 }
4482 
4483 /*
4484  * Free a single jseg once it is no longer referenced in memory or on
4485  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4486  * to disappear.
4487  */
4488 static void
4489 free_jseg(jseg, jblocks)
4490 	struct jseg *jseg;
4491 	struct jblocks *jblocks;
4492 {
4493 	struct freework *freework;
4494 
4495 	/*
4496 	 * Free freework structures that were lingering to indicate freed
4497 	 * indirect blocks that forced journal write ordering on reallocate.
4498 	 */
4499 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4500 		indirblk_remove(freework);
4501 	if (jblocks->jb_oldestseg == jseg)
4502 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4503 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4504 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4505 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4506 	    ("free_jseg: Freed jseg has valid entries."));
4507 	WORKITEM_FREE(jseg, D_JSEG);
4508 }
4509 
4510 /*
4511  * Free all jsegs that meet the criteria for being reclaimed and update
4512  * oldestseg.
4513  */
4514 static void
4515 free_jsegs(jblocks)
4516 	struct jblocks *jblocks;
4517 {
4518 	struct jseg *jseg;
4519 
4520 	/*
4521 	 * Free only those jsegs which have none allocated before them to
4522 	 * preserve the journal space ordering.
4523 	 */
4524 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4525 		/*
4526 		 * Only reclaim space when nothing depends on this journal
4527 		 * set and another set has written that it is no longer
4528 		 * valid.
4529 		 */
4530 		if (jseg->js_refs != 0) {
4531 			jblocks->jb_oldestseg = jseg;
4532 			return;
4533 		}
4534 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4535 			break;
4536 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4537 			break;
4538 		/*
4539 		 * We can free jsegs that didn't write entries when
4540 		 * oldestwrseq == js_seq.
4541 		 */
4542 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4543 		    jseg->js_cnt != 0)
4544 			break;
4545 		free_jseg(jseg, jblocks);
4546 	}
4547 	/*
4548 	 * If we exited the loop above we still must discover the
4549 	 * oldest valid segment.
4550 	 */
4551 	if (jseg)
4552 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4553 		     jseg = TAILQ_NEXT(jseg, js_next))
4554 			if (jseg->js_refs != 0)
4555 				break;
4556 	jblocks->jb_oldestseg = jseg;
4557 	/*
4558 	 * The journal has no valid records but some jsegs may still be
4559 	 * waiting on oldestwrseq to advance.  We force a small record
4560 	 * out to permit these lingering records to be reclaimed.
4561 	 */
4562 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4563 		jblocks->jb_needseg = 1;
4564 }
4565 
4566 /*
4567  * Release one reference to a jseg and free it if the count reaches 0.  This
4568  * should eventually reclaim journal space as well.
4569  */
4570 static void
4571 rele_jseg(jseg)
4572 	struct jseg *jseg;
4573 {
4574 
4575 	KASSERT(jseg->js_refs > 0,
4576 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4577 	if (--jseg->js_refs != 0)
4578 		return;
4579 	free_jsegs(jseg->js_jblocks);
4580 }
4581 
4582 /*
4583  * Release a jsegdep and decrement the jseg count.
4584  */
4585 static void
4586 free_jsegdep(jsegdep)
4587 	struct jsegdep *jsegdep;
4588 {
4589 
4590 	if (jsegdep->jd_seg)
4591 		rele_jseg(jsegdep->jd_seg);
4592 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4593 }
4594 
4595 /*
4596  * Wait for a journal item to make it to disk.  Initiate journal processing
4597  * if required.
4598  */
4599 static int
4600 jwait(wk, waitfor)
4601 	struct worklist *wk;
4602 	int waitfor;
4603 {
4604 
4605 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4606 	/*
4607 	 * Blocking journal waits cause slow synchronous behavior.  Record
4608 	 * stats on the frequency of these blocking operations.
4609 	 */
4610 	if (waitfor == MNT_WAIT) {
4611 		stat_journal_wait++;
4612 		switch (wk->wk_type) {
4613 		case D_JREMREF:
4614 		case D_JMVREF:
4615 			stat_jwait_filepage++;
4616 			break;
4617 		case D_JTRUNC:
4618 		case D_JFREEBLK:
4619 			stat_jwait_freeblks++;
4620 			break;
4621 		case D_JNEWBLK:
4622 			stat_jwait_newblk++;
4623 			break;
4624 		case D_JADDREF:
4625 			stat_jwait_inode++;
4626 			break;
4627 		default:
4628 			break;
4629 		}
4630 	}
4631 	/*
4632 	 * If IO has not started we process the journal.  We can't mark the
4633 	 * worklist item as IOWAITING because we drop the lock while
4634 	 * processing the journal and the worklist entry may be freed after
4635 	 * this point.  The caller may call back in and re-issue the request.
4636 	 */
4637 	if ((wk->wk_state & INPROGRESS) == 0) {
4638 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4639 		if (waitfor != MNT_WAIT)
4640 			return (EBUSY);
4641 		return (0);
4642 	}
4643 	if (waitfor != MNT_WAIT)
4644 		return (EBUSY);
4645 	wait_worklist(wk, "jwait");
4646 	return (0);
4647 }
4648 
4649 /*
4650  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4651  * appropriate.  This is a convenience function to reduce duplicate code
4652  * for the setup and revert functions below.
4653  */
4654 static struct inodedep *
4655 inodedep_lookup_ip(ip)
4656 	struct inode *ip;
4657 {
4658 	struct inodedep *inodedep;
4659 
4660 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4661 	    ("inodedep_lookup_ip: bad delta"));
4662 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4663 	    &inodedep);
4664 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4665 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4666 
4667 	return (inodedep);
4668 }
4669 
4670 /*
4671  * Called prior to creating a new inode and linking it to a directory.  The
4672  * jaddref structure must already be allocated by softdep_setup_inomapdep
4673  * and it is discovered here so we can initialize the mode and update
4674  * nlinkdelta.
4675  */
4676 void
4677 softdep_setup_create(dp, ip)
4678 	struct inode *dp;
4679 	struct inode *ip;
4680 {
4681 	struct inodedep *inodedep;
4682 	struct jaddref *jaddref;
4683 	struct vnode *dvp;
4684 
4685 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4686 	    ("softdep_setup_create called on non-softdep filesystem"));
4687 	KASSERT(ip->i_nlink == 1,
4688 	    ("softdep_setup_create: Invalid link count."));
4689 	dvp = ITOV(dp);
4690 	ACQUIRE_LOCK(ITOUMP(dp));
4691 	inodedep = inodedep_lookup_ip(ip);
4692 	if (DOINGSUJ(dvp)) {
4693 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4694 		    inoreflst);
4695 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4696 		    ("softdep_setup_create: No addref structure present."));
4697 	}
4698 	softdep_prelink(dvp, NULL);
4699 	FREE_LOCK(ITOUMP(dp));
4700 }
4701 
4702 /*
4703  * Create a jaddref structure to track the addition of a DOTDOT link when
4704  * we are reparenting an inode as part of a rename.  This jaddref will be
4705  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4706  * non-journaling softdep.
4707  */
4708 void
4709 softdep_setup_dotdot_link(dp, ip)
4710 	struct inode *dp;
4711 	struct inode *ip;
4712 {
4713 	struct inodedep *inodedep;
4714 	struct jaddref *jaddref;
4715 	struct vnode *dvp;
4716 
4717 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4718 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4719 	dvp = ITOV(dp);
4720 	jaddref = NULL;
4721 	/*
4722 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4723 	 * is used as a normal link would be.
4724 	 */
4725 	if (DOINGSUJ(dvp))
4726 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4727 		    dp->i_effnlink - 1, dp->i_mode);
4728 	ACQUIRE_LOCK(ITOUMP(dp));
4729 	inodedep = inodedep_lookup_ip(dp);
4730 	if (jaddref)
4731 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4732 		    if_deps);
4733 	softdep_prelink(dvp, ITOV(ip));
4734 	FREE_LOCK(ITOUMP(dp));
4735 }
4736 
4737 /*
4738  * Create a jaddref structure to track a new link to an inode.  The directory
4739  * offset is not known until softdep_setup_directory_add or
4740  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4741  * softdep.
4742  */
4743 void
4744 softdep_setup_link(dp, ip)
4745 	struct inode *dp;
4746 	struct inode *ip;
4747 {
4748 	struct inodedep *inodedep;
4749 	struct jaddref *jaddref;
4750 	struct vnode *dvp;
4751 
4752 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4753 	    ("softdep_setup_link called on non-softdep filesystem"));
4754 	dvp = ITOV(dp);
4755 	jaddref = NULL;
4756 	if (DOINGSUJ(dvp))
4757 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4758 		    ip->i_mode);
4759 	ACQUIRE_LOCK(ITOUMP(dp));
4760 	inodedep = inodedep_lookup_ip(ip);
4761 	if (jaddref)
4762 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4763 		    if_deps);
4764 	softdep_prelink(dvp, ITOV(ip));
4765 	FREE_LOCK(ITOUMP(dp));
4766 }
4767 
4768 /*
4769  * Called to create the jaddref structures to track . and .. references as
4770  * well as lookup and further initialize the incomplete jaddref created
4771  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4772  * nlinkdelta for non-journaling softdep.
4773  */
4774 void
4775 softdep_setup_mkdir(dp, ip)
4776 	struct inode *dp;
4777 	struct inode *ip;
4778 {
4779 	struct inodedep *inodedep;
4780 	struct jaddref *dotdotaddref;
4781 	struct jaddref *dotaddref;
4782 	struct jaddref *jaddref;
4783 	struct vnode *dvp;
4784 
4785 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4786 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
4787 	dvp = ITOV(dp);
4788 	dotaddref = dotdotaddref = NULL;
4789 	if (DOINGSUJ(dvp)) {
4790 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4791 		    ip->i_mode);
4792 		dotaddref->ja_state |= MKDIR_BODY;
4793 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4794 		    dp->i_effnlink - 1, dp->i_mode);
4795 		dotdotaddref->ja_state |= MKDIR_PARENT;
4796 	}
4797 	ACQUIRE_LOCK(ITOUMP(dp));
4798 	inodedep = inodedep_lookup_ip(ip);
4799 	if (DOINGSUJ(dvp)) {
4800 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4801 		    inoreflst);
4802 		KASSERT(jaddref != NULL,
4803 		    ("softdep_setup_mkdir: No addref structure present."));
4804 		KASSERT(jaddref->ja_parent == dp->i_number,
4805 		    ("softdep_setup_mkdir: bad parent %ju",
4806 		    (uintmax_t)jaddref->ja_parent));
4807 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4808 		    if_deps);
4809 	}
4810 	inodedep = inodedep_lookup_ip(dp);
4811 	if (DOINGSUJ(dvp))
4812 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4813 		    &dotdotaddref->ja_ref, if_deps);
4814 	softdep_prelink(ITOV(dp), NULL);
4815 	FREE_LOCK(ITOUMP(dp));
4816 }
4817 
4818 /*
4819  * Called to track nlinkdelta of the inode and parent directories prior to
4820  * unlinking a directory.
4821  */
4822 void
4823 softdep_setup_rmdir(dp, ip)
4824 	struct inode *dp;
4825 	struct inode *ip;
4826 {
4827 	struct vnode *dvp;
4828 
4829 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4830 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4831 	dvp = ITOV(dp);
4832 	ACQUIRE_LOCK(ITOUMP(dp));
4833 	(void) inodedep_lookup_ip(ip);
4834 	(void) inodedep_lookup_ip(dp);
4835 	softdep_prelink(dvp, ITOV(ip));
4836 	FREE_LOCK(ITOUMP(dp));
4837 }
4838 
4839 /*
4840  * Called to track nlinkdelta of the inode and parent directories prior to
4841  * unlink.
4842  */
4843 void
4844 softdep_setup_unlink(dp, ip)
4845 	struct inode *dp;
4846 	struct inode *ip;
4847 {
4848 	struct vnode *dvp;
4849 
4850 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4851 	    ("softdep_setup_unlink called on non-softdep filesystem"));
4852 	dvp = ITOV(dp);
4853 	ACQUIRE_LOCK(ITOUMP(dp));
4854 	(void) inodedep_lookup_ip(ip);
4855 	(void) inodedep_lookup_ip(dp);
4856 	softdep_prelink(dvp, ITOV(ip));
4857 	FREE_LOCK(ITOUMP(dp));
4858 }
4859 
4860 /*
4861  * Called to release the journal structures created by a failed non-directory
4862  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4863  */
4864 void
4865 softdep_revert_create(dp, ip)
4866 	struct inode *dp;
4867 	struct inode *ip;
4868 {
4869 	struct inodedep *inodedep;
4870 	struct jaddref *jaddref;
4871 	struct vnode *dvp;
4872 
4873 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4874 	    ("softdep_revert_create called on non-softdep filesystem"));
4875 	dvp = ITOV(dp);
4876 	ACQUIRE_LOCK(ITOUMP(dp));
4877 	inodedep = inodedep_lookup_ip(ip);
4878 	if (DOINGSUJ(dvp)) {
4879 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4880 		    inoreflst);
4881 		KASSERT(jaddref->ja_parent == dp->i_number,
4882 		    ("softdep_revert_create: addref parent mismatch"));
4883 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4884 	}
4885 	FREE_LOCK(ITOUMP(dp));
4886 }
4887 
4888 /*
4889  * Called to release the journal structures created by a failed link
4890  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4891  */
4892 void
4893 softdep_revert_link(dp, ip)
4894 	struct inode *dp;
4895 	struct inode *ip;
4896 {
4897 	struct inodedep *inodedep;
4898 	struct jaddref *jaddref;
4899 	struct vnode *dvp;
4900 
4901 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4902 	    ("softdep_revert_link called on non-softdep filesystem"));
4903 	dvp = ITOV(dp);
4904 	ACQUIRE_LOCK(ITOUMP(dp));
4905 	inodedep = inodedep_lookup_ip(ip);
4906 	if (DOINGSUJ(dvp)) {
4907 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4908 		    inoreflst);
4909 		KASSERT(jaddref->ja_parent == dp->i_number,
4910 		    ("softdep_revert_link: addref parent mismatch"));
4911 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4912 	}
4913 	FREE_LOCK(ITOUMP(dp));
4914 }
4915 
4916 /*
4917  * Called to release the journal structures created by a failed mkdir
4918  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4919  */
4920 void
4921 softdep_revert_mkdir(dp, ip)
4922 	struct inode *dp;
4923 	struct inode *ip;
4924 {
4925 	struct inodedep *inodedep;
4926 	struct jaddref *jaddref;
4927 	struct jaddref *dotaddref;
4928 	struct vnode *dvp;
4929 
4930 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4931 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4932 	dvp = ITOV(dp);
4933 
4934 	ACQUIRE_LOCK(ITOUMP(dp));
4935 	inodedep = inodedep_lookup_ip(dp);
4936 	if (DOINGSUJ(dvp)) {
4937 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4938 		    inoreflst);
4939 		KASSERT(jaddref->ja_parent == ip->i_number,
4940 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4941 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4942 	}
4943 	inodedep = inodedep_lookup_ip(ip);
4944 	if (DOINGSUJ(dvp)) {
4945 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4946 		    inoreflst);
4947 		KASSERT(jaddref->ja_parent == dp->i_number,
4948 		    ("softdep_revert_mkdir: addref parent mismatch"));
4949 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4950 		    inoreflst, if_deps);
4951 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4952 		KASSERT(dotaddref->ja_parent == ip->i_number,
4953 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4954 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4955 	}
4956 	FREE_LOCK(ITOUMP(dp));
4957 }
4958 
4959 /*
4960  * Called to correct nlinkdelta after a failed rmdir.
4961  */
4962 void
4963 softdep_revert_rmdir(dp, ip)
4964 	struct inode *dp;
4965 	struct inode *ip;
4966 {
4967 
4968 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4969 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
4970 	ACQUIRE_LOCK(ITOUMP(dp));
4971 	(void) inodedep_lookup_ip(ip);
4972 	(void) inodedep_lookup_ip(dp);
4973 	FREE_LOCK(ITOUMP(dp));
4974 }
4975 
4976 /*
4977  * Protecting the freemaps (or bitmaps).
4978  *
4979  * To eliminate the need to execute fsck before mounting a filesystem
4980  * after a power failure, one must (conservatively) guarantee that the
4981  * on-disk copy of the bitmaps never indicate that a live inode or block is
4982  * free.  So, when a block or inode is allocated, the bitmap should be
4983  * updated (on disk) before any new pointers.  When a block or inode is
4984  * freed, the bitmap should not be updated until all pointers have been
4985  * reset.  The latter dependency is handled by the delayed de-allocation
4986  * approach described below for block and inode de-allocation.  The former
4987  * dependency is handled by calling the following procedure when a block or
4988  * inode is allocated. When an inode is allocated an "inodedep" is created
4989  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4990  * Each "inodedep" is also inserted into the hash indexing structure so
4991  * that any additional link additions can be made dependent on the inode
4992  * allocation.
4993  *
4994  * The ufs filesystem maintains a number of free block counts (e.g., per
4995  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4996  * in addition to the bitmaps.  These counts are used to improve efficiency
4997  * during allocation and therefore must be consistent with the bitmaps.
4998  * There is no convenient way to guarantee post-crash consistency of these
4999  * counts with simple update ordering, for two main reasons: (1) The counts
5000  * and bitmaps for a single cylinder group block are not in the same disk
5001  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5002  * be written and the other not.  (2) Some of the counts are located in the
5003  * superblock rather than the cylinder group block. So, we focus our soft
5004  * updates implementation on protecting the bitmaps. When mounting a
5005  * filesystem, we recompute the auxiliary counts from the bitmaps.
5006  */
5007 
5008 /*
5009  * Called just after updating the cylinder group block to allocate an inode.
5010  */
5011 void
5012 softdep_setup_inomapdep(bp, ip, newinum, mode)
5013 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5014 	struct inode *ip;	/* inode related to allocation */
5015 	ino_t newinum;		/* new inode number being allocated */
5016 	int mode;
5017 {
5018 	struct inodedep *inodedep;
5019 	struct bmsafemap *bmsafemap;
5020 	struct jaddref *jaddref;
5021 	struct mount *mp;
5022 	struct fs *fs;
5023 
5024 	mp = ITOVFS(ip);
5025 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5026 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5027 	fs = VFSTOUFS(mp)->um_fs;
5028 	jaddref = NULL;
5029 
5030 	/*
5031 	 * Allocate the journal reference add structure so that the bitmap
5032 	 * can be dependent on it.
5033 	 */
5034 	if (MOUNTEDSUJ(mp)) {
5035 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5036 		jaddref->ja_state |= NEWBLOCK;
5037 	}
5038 
5039 	/*
5040 	 * Create a dependency for the newly allocated inode.
5041 	 * Panic if it already exists as something is seriously wrong.
5042 	 * Otherwise add it to the dependency list for the buffer holding
5043 	 * the cylinder group map from which it was allocated.
5044 	 *
5045 	 * We have to preallocate a bmsafemap entry in case it is needed
5046 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5047 	 * have to finish initializing it before we can FREE_LOCK().
5048 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5049 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5050 	 * creating the inodedep as it can be freed during the time
5051 	 * that we FREE_LOCK() while allocating the inodedep. We must
5052 	 * call workitem_alloc() before entering the locked section as
5053 	 * it also acquires the lock and we must avoid trying doing so
5054 	 * recursively.
5055 	 */
5056 	bmsafemap = malloc(sizeof(struct bmsafemap),
5057 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5058 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5059 	ACQUIRE_LOCK(ITOUMP(ip));
5060 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5061 		panic("softdep_setup_inomapdep: dependency %p for new"
5062 		    "inode already exists", inodedep);
5063 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5064 	if (jaddref) {
5065 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5066 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5067 		    if_deps);
5068 	} else {
5069 		inodedep->id_state |= ONDEPLIST;
5070 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5071 	}
5072 	inodedep->id_bmsafemap = bmsafemap;
5073 	inodedep->id_state &= ~DEPCOMPLETE;
5074 	FREE_LOCK(ITOUMP(ip));
5075 }
5076 
5077 /*
5078  * Called just after updating the cylinder group block to
5079  * allocate block or fragment.
5080  */
5081 void
5082 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5083 	struct buf *bp;		/* buffer for cylgroup block with block map */
5084 	struct mount *mp;	/* filesystem doing allocation */
5085 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5086 	int frags;		/* Number of fragments. */
5087 	int oldfrags;		/* Previous number of fragments for extend. */
5088 {
5089 	struct newblk *newblk;
5090 	struct bmsafemap *bmsafemap;
5091 	struct jnewblk *jnewblk;
5092 	struct ufsmount *ump;
5093 	struct fs *fs;
5094 
5095 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5096 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5097 	ump = VFSTOUFS(mp);
5098 	fs = ump->um_fs;
5099 	jnewblk = NULL;
5100 	/*
5101 	 * Create a dependency for the newly allocated block.
5102 	 * Add it to the dependency list for the buffer holding
5103 	 * the cylinder group map from which it was allocated.
5104 	 */
5105 	if (MOUNTEDSUJ(mp)) {
5106 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5107 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5108 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5109 		jnewblk->jn_state = ATTACHED;
5110 		jnewblk->jn_blkno = newblkno;
5111 		jnewblk->jn_frags = frags;
5112 		jnewblk->jn_oldfrags = oldfrags;
5113 #ifdef INVARIANTS
5114 		{
5115 			struct cg *cgp;
5116 			uint8_t *blksfree;
5117 			long bno;
5118 			int i;
5119 
5120 			cgp = (struct cg *)bp->b_data;
5121 			blksfree = cg_blksfree(cgp);
5122 			bno = dtogd(fs, jnewblk->jn_blkno);
5123 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5124 			    i++) {
5125 				if (isset(blksfree, bno + i))
5126 					panic("softdep_setup_blkmapdep: "
5127 					    "free fragment %d from %d-%d "
5128 					    "state 0x%X dep %p", i,
5129 					    jnewblk->jn_oldfrags,
5130 					    jnewblk->jn_frags,
5131 					    jnewblk->jn_state,
5132 					    jnewblk->jn_dep);
5133 			}
5134 		}
5135 #endif
5136 	}
5137 
5138 	CTR3(KTR_SUJ,
5139 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5140 	    newblkno, frags, oldfrags);
5141 	ACQUIRE_LOCK(ump);
5142 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5143 		panic("softdep_setup_blkmapdep: found block");
5144 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5145 	    dtog(fs, newblkno), NULL);
5146 	if (jnewblk) {
5147 		jnewblk->jn_dep = (struct worklist *)newblk;
5148 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5149 	} else {
5150 		newblk->nb_state |= ONDEPLIST;
5151 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5152 	}
5153 	newblk->nb_bmsafemap = bmsafemap;
5154 	newblk->nb_jnewblk = jnewblk;
5155 	FREE_LOCK(ump);
5156 }
5157 
5158 #define	BMSAFEMAP_HASH(ump, cg) \
5159       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5160 
5161 static int
5162 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5163 	struct bmsafemap_hashhead *bmsafemaphd;
5164 	int cg;
5165 	struct bmsafemap **bmsafemapp;
5166 {
5167 	struct bmsafemap *bmsafemap;
5168 
5169 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5170 		if (bmsafemap->sm_cg == cg)
5171 			break;
5172 	if (bmsafemap) {
5173 		*bmsafemapp = bmsafemap;
5174 		return (1);
5175 	}
5176 	*bmsafemapp = NULL;
5177 
5178 	return (0);
5179 }
5180 
5181 /*
5182  * Find the bmsafemap associated with a cylinder group buffer.
5183  * If none exists, create one. The buffer must be locked when
5184  * this routine is called and this routine must be called with
5185  * the softdep lock held. To avoid giving up the lock while
5186  * allocating a new bmsafemap, a preallocated bmsafemap may be
5187  * provided. If it is provided but not needed, it is freed.
5188  */
5189 static struct bmsafemap *
5190 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5191 	struct mount *mp;
5192 	struct buf *bp;
5193 	int cg;
5194 	struct bmsafemap *newbmsafemap;
5195 {
5196 	struct bmsafemap_hashhead *bmsafemaphd;
5197 	struct bmsafemap *bmsafemap, *collision;
5198 	struct worklist *wk;
5199 	struct ufsmount *ump;
5200 
5201 	ump = VFSTOUFS(mp);
5202 	LOCK_OWNED(ump);
5203 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5204 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5205 		if (wk->wk_type == D_BMSAFEMAP) {
5206 			if (newbmsafemap)
5207 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5208 			return (WK_BMSAFEMAP(wk));
5209 		}
5210 	}
5211 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5212 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5213 		if (newbmsafemap)
5214 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5215 		return (bmsafemap);
5216 	}
5217 	if (newbmsafemap) {
5218 		bmsafemap = newbmsafemap;
5219 	} else {
5220 		FREE_LOCK(ump);
5221 		bmsafemap = malloc(sizeof(struct bmsafemap),
5222 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5223 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5224 		ACQUIRE_LOCK(ump);
5225 	}
5226 	bmsafemap->sm_buf = bp;
5227 	LIST_INIT(&bmsafemap->sm_inodedephd);
5228 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5229 	LIST_INIT(&bmsafemap->sm_newblkhd);
5230 	LIST_INIT(&bmsafemap->sm_newblkwr);
5231 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5232 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5233 	LIST_INIT(&bmsafemap->sm_freehd);
5234 	LIST_INIT(&bmsafemap->sm_freewr);
5235 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5236 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5237 		return (collision);
5238 	}
5239 	bmsafemap->sm_cg = cg;
5240 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5241 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5242 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5243 	return (bmsafemap);
5244 }
5245 
5246 /*
5247  * Direct block allocation dependencies.
5248  *
5249  * When a new block is allocated, the corresponding disk locations must be
5250  * initialized (with zeros or new data) before the on-disk inode points to
5251  * them.  Also, the freemap from which the block was allocated must be
5252  * updated (on disk) before the inode's pointer. These two dependencies are
5253  * independent of each other and are needed for all file blocks and indirect
5254  * blocks that are pointed to directly by the inode.  Just before the
5255  * "in-core" version of the inode is updated with a newly allocated block
5256  * number, a procedure (below) is called to setup allocation dependency
5257  * structures.  These structures are removed when the corresponding
5258  * dependencies are satisfied or when the block allocation becomes obsolete
5259  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5260  * fragment that gets upgraded).  All of these cases are handled in
5261  * procedures described later.
5262  *
5263  * When a file extension causes a fragment to be upgraded, either to a larger
5264  * fragment or to a full block, the on-disk location may change (if the
5265  * previous fragment could not simply be extended). In this case, the old
5266  * fragment must be de-allocated, but not until after the inode's pointer has
5267  * been updated. In most cases, this is handled by later procedures, which
5268  * will construct a "freefrag" structure to be added to the workitem queue
5269  * when the inode update is complete (or obsolete).  The main exception to
5270  * this is when an allocation occurs while a pending allocation dependency
5271  * (for the same block pointer) remains.  This case is handled in the main
5272  * allocation dependency setup procedure by immediately freeing the
5273  * unreferenced fragments.
5274  */
5275 void
5276 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5277 	struct inode *ip;	/* inode to which block is being added */
5278 	ufs_lbn_t off;		/* block pointer within inode */
5279 	ufs2_daddr_t newblkno;	/* disk block number being added */
5280 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5281 	long newsize;		/* size of new block */
5282 	long oldsize;		/* size of new block */
5283 	struct buf *bp;		/* bp for allocated block */
5284 {
5285 	struct allocdirect *adp, *oldadp;
5286 	struct allocdirectlst *adphead;
5287 	struct freefrag *freefrag;
5288 	struct inodedep *inodedep;
5289 	struct pagedep *pagedep;
5290 	struct jnewblk *jnewblk;
5291 	struct newblk *newblk;
5292 	struct mount *mp;
5293 	ufs_lbn_t lbn;
5294 
5295 	lbn = bp->b_lblkno;
5296 	mp = ITOVFS(ip);
5297 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5298 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5299 	if (oldblkno && oldblkno != newblkno)
5300 		/*
5301 		 * The usual case is that a smaller fragment that
5302 		 * was just allocated has been replaced with a bigger
5303 		 * fragment or a full-size block. If it is marked as
5304 		 * B_DELWRI, the current contents have not been written
5305 		 * to disk. It is possible that the block was written
5306 		 * earlier, but very uncommon. If the block has never
5307 		 * been written, there is no need to send a BIO_DELETE
5308 		 * for it when it is freed. The gain from avoiding the
5309 		 * TRIMs for the common case of unwritten blocks far
5310 		 * exceeds the cost of the write amplification for the
5311 		 * uncommon case of failing to send a TRIM for a block
5312 		 * that had been written.
5313 		 */
5314 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5315 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5316 	else
5317 		freefrag = NULL;
5318 
5319 	CTR6(KTR_SUJ,
5320 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5321 	    "off %jd newsize %ld oldsize %d",
5322 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5323 	ACQUIRE_LOCK(ITOUMP(ip));
5324 	if (off >= UFS_NDADDR) {
5325 		if (lbn > 0)
5326 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5327 			    lbn, off);
5328 		/* allocating an indirect block */
5329 		if (oldblkno != 0)
5330 			panic("softdep_setup_allocdirect: non-zero indir");
5331 	} else {
5332 		if (off != lbn)
5333 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5334 			    lbn, off);
5335 		/*
5336 		 * Allocating a direct block.
5337 		 *
5338 		 * If we are allocating a directory block, then we must
5339 		 * allocate an associated pagedep to track additions and
5340 		 * deletions.
5341 		 */
5342 		if ((ip->i_mode & IFMT) == IFDIR)
5343 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5344 			    &pagedep);
5345 	}
5346 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5347 		panic("softdep_setup_allocdirect: lost block");
5348 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5349 	    ("softdep_setup_allocdirect: newblk already initialized"));
5350 	/*
5351 	 * Convert the newblk to an allocdirect.
5352 	 */
5353 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5354 	adp = (struct allocdirect *)newblk;
5355 	newblk->nb_freefrag = freefrag;
5356 	adp->ad_offset = off;
5357 	adp->ad_oldblkno = oldblkno;
5358 	adp->ad_newsize = newsize;
5359 	adp->ad_oldsize = oldsize;
5360 
5361 	/*
5362 	 * Finish initializing the journal.
5363 	 */
5364 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5365 		jnewblk->jn_ino = ip->i_number;
5366 		jnewblk->jn_lbn = lbn;
5367 		add_to_journal(&jnewblk->jn_list);
5368 	}
5369 	if (freefrag && freefrag->ff_jdep != NULL &&
5370 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5371 		add_to_journal(freefrag->ff_jdep);
5372 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5373 	adp->ad_inodedep = inodedep;
5374 
5375 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5376 	/*
5377 	 * The list of allocdirects must be kept in sorted and ascending
5378 	 * order so that the rollback routines can quickly determine the
5379 	 * first uncommitted block (the size of the file stored on disk
5380 	 * ends at the end of the lowest committed fragment, or if there
5381 	 * are no fragments, at the end of the highest committed block).
5382 	 * Since files generally grow, the typical case is that the new
5383 	 * block is to be added at the end of the list. We speed this
5384 	 * special case by checking against the last allocdirect in the
5385 	 * list before laboriously traversing the list looking for the
5386 	 * insertion point.
5387 	 */
5388 	adphead = &inodedep->id_newinoupdt;
5389 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5390 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5391 		/* insert at end of list */
5392 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5393 		if (oldadp != NULL && oldadp->ad_offset == off)
5394 			allocdirect_merge(adphead, adp, oldadp);
5395 		FREE_LOCK(ITOUMP(ip));
5396 		return;
5397 	}
5398 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5399 		if (oldadp->ad_offset >= off)
5400 			break;
5401 	}
5402 	if (oldadp == NULL)
5403 		panic("softdep_setup_allocdirect: lost entry");
5404 	/* insert in middle of list */
5405 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5406 	if (oldadp->ad_offset == off)
5407 		allocdirect_merge(adphead, adp, oldadp);
5408 
5409 	FREE_LOCK(ITOUMP(ip));
5410 }
5411 
5412 /*
5413  * Merge a newer and older journal record to be stored either in a
5414  * newblock or freefrag.  This handles aggregating journal records for
5415  * fragment allocation into a second record as well as replacing a
5416  * journal free with an aborted journal allocation.  A segment for the
5417  * oldest record will be placed on wkhd if it has been written.  If not
5418  * the segment for the newer record will suffice.
5419  */
5420 static struct worklist *
5421 jnewblk_merge(new, old, wkhd)
5422 	struct worklist *new;
5423 	struct worklist *old;
5424 	struct workhead *wkhd;
5425 {
5426 	struct jnewblk *njnewblk;
5427 	struct jnewblk *jnewblk;
5428 
5429 	/* Handle NULLs to simplify callers. */
5430 	if (new == NULL)
5431 		return (old);
5432 	if (old == NULL)
5433 		return (new);
5434 	/* Replace a jfreefrag with a jnewblk. */
5435 	if (new->wk_type == D_JFREEFRAG) {
5436 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5437 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5438 			    old, new);
5439 		cancel_jfreefrag(WK_JFREEFRAG(new));
5440 		return (old);
5441 	}
5442 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5443 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5444 		    old->wk_type, new->wk_type);
5445 	/*
5446 	 * Handle merging of two jnewblk records that describe
5447 	 * different sets of fragments in the same block.
5448 	 */
5449 	jnewblk = WK_JNEWBLK(old);
5450 	njnewblk = WK_JNEWBLK(new);
5451 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5452 		panic("jnewblk_merge: Merging disparate blocks.");
5453 	/*
5454 	 * The record may be rolled back in the cg.
5455 	 */
5456 	if (jnewblk->jn_state & UNDONE) {
5457 		jnewblk->jn_state &= ~UNDONE;
5458 		njnewblk->jn_state |= UNDONE;
5459 		njnewblk->jn_state &= ~ATTACHED;
5460 	}
5461 	/*
5462 	 * We modify the newer addref and free the older so that if neither
5463 	 * has been written the most up-to-date copy will be on disk.  If
5464 	 * both have been written but rolled back we only temporarily need
5465 	 * one of them to fix the bits when the cg write completes.
5466 	 */
5467 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5468 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5469 	cancel_jnewblk(jnewblk, wkhd);
5470 	WORKLIST_REMOVE(&jnewblk->jn_list);
5471 	free_jnewblk(jnewblk);
5472 	return (new);
5473 }
5474 
5475 /*
5476  * Replace an old allocdirect dependency with a newer one.
5477  */
5478 static void
5479 allocdirect_merge(adphead, newadp, oldadp)
5480 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5481 	struct allocdirect *newadp;	/* allocdirect being added */
5482 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5483 {
5484 	struct worklist *wk;
5485 	struct freefrag *freefrag;
5486 
5487 	freefrag = NULL;
5488 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5489 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5490 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5491 	    newadp->ad_offset >= UFS_NDADDR)
5492 		panic("%s %jd != new %jd || old size %ld != new %ld",
5493 		    "allocdirect_merge: old blkno",
5494 		    (intmax_t)newadp->ad_oldblkno,
5495 		    (intmax_t)oldadp->ad_newblkno,
5496 		    newadp->ad_oldsize, oldadp->ad_newsize);
5497 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5498 	newadp->ad_oldsize = oldadp->ad_oldsize;
5499 	/*
5500 	 * If the old dependency had a fragment to free or had never
5501 	 * previously had a block allocated, then the new dependency
5502 	 * can immediately post its freefrag and adopt the old freefrag.
5503 	 * This action is done by swapping the freefrag dependencies.
5504 	 * The new dependency gains the old one's freefrag, and the
5505 	 * old one gets the new one and then immediately puts it on
5506 	 * the worklist when it is freed by free_newblk. It is
5507 	 * not possible to do this swap when the old dependency had a
5508 	 * non-zero size but no previous fragment to free. This condition
5509 	 * arises when the new block is an extension of the old block.
5510 	 * Here, the first part of the fragment allocated to the new
5511 	 * dependency is part of the block currently claimed on disk by
5512 	 * the old dependency, so cannot legitimately be freed until the
5513 	 * conditions for the new dependency are fulfilled.
5514 	 */
5515 	freefrag = newadp->ad_freefrag;
5516 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5517 		newadp->ad_freefrag = oldadp->ad_freefrag;
5518 		oldadp->ad_freefrag = freefrag;
5519 	}
5520 	/*
5521 	 * If we are tracking a new directory-block allocation,
5522 	 * move it from the old allocdirect to the new allocdirect.
5523 	 */
5524 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5525 		WORKLIST_REMOVE(wk);
5526 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5527 			panic("allocdirect_merge: extra newdirblk");
5528 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5529 	}
5530 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5531 	/*
5532 	 * We need to move any journal dependencies over to the freefrag
5533 	 * that releases this block if it exists.  Otherwise we are
5534 	 * extending an existing block and we'll wait until that is
5535 	 * complete to release the journal space and extend the
5536 	 * new journal to cover this old space as well.
5537 	 */
5538 	if (freefrag == NULL) {
5539 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5540 			panic("allocdirect_merge: %jd != %jd",
5541 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5542 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5543 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5544 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5545 		    &newadp->ad_block.nb_jwork);
5546 		oldadp->ad_block.nb_jnewblk = NULL;
5547 		cancel_newblk(&oldadp->ad_block, NULL,
5548 		    &newadp->ad_block.nb_jwork);
5549 	} else {
5550 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5551 		    &freefrag->ff_list, &freefrag->ff_jwork);
5552 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5553 		    &freefrag->ff_jwork);
5554 	}
5555 	free_newblk(&oldadp->ad_block);
5556 }
5557 
5558 /*
5559  * Allocate a jfreefrag structure to journal a single block free.
5560  */
5561 static struct jfreefrag *
5562 newjfreefrag(freefrag, ip, blkno, size, lbn)
5563 	struct freefrag *freefrag;
5564 	struct inode *ip;
5565 	ufs2_daddr_t blkno;
5566 	long size;
5567 	ufs_lbn_t lbn;
5568 {
5569 	struct jfreefrag *jfreefrag;
5570 	struct fs *fs;
5571 
5572 	fs = ITOFS(ip);
5573 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5574 	    M_SOFTDEP_FLAGS);
5575 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5576 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5577 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5578 	jfreefrag->fr_ino = ip->i_number;
5579 	jfreefrag->fr_lbn = lbn;
5580 	jfreefrag->fr_blkno = blkno;
5581 	jfreefrag->fr_frags = numfrags(fs, size);
5582 	jfreefrag->fr_freefrag = freefrag;
5583 
5584 	return (jfreefrag);
5585 }
5586 
5587 /*
5588  * Allocate a new freefrag structure.
5589  */
5590 static struct freefrag *
5591 newfreefrag(ip, blkno, size, lbn, key)
5592 	struct inode *ip;
5593 	ufs2_daddr_t blkno;
5594 	long size;
5595 	ufs_lbn_t lbn;
5596 	u_long key;
5597 {
5598 	struct freefrag *freefrag;
5599 	struct ufsmount *ump;
5600 	struct fs *fs;
5601 
5602 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5603 	    ip->i_number, blkno, size, lbn);
5604 	ump = ITOUMP(ip);
5605 	fs = ump->um_fs;
5606 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5607 		panic("newfreefrag: frag size");
5608 	freefrag = malloc(sizeof(struct freefrag),
5609 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5610 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5611 	freefrag->ff_state = ATTACHED;
5612 	LIST_INIT(&freefrag->ff_jwork);
5613 	freefrag->ff_inum = ip->i_number;
5614 	freefrag->ff_vtype = ITOV(ip)->v_type;
5615 	freefrag->ff_blkno = blkno;
5616 	freefrag->ff_fragsize = size;
5617 	freefrag->ff_key = key;
5618 
5619 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5620 		freefrag->ff_jdep = (struct worklist *)
5621 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5622 	} else {
5623 		freefrag->ff_state |= DEPCOMPLETE;
5624 		freefrag->ff_jdep = NULL;
5625 	}
5626 
5627 	return (freefrag);
5628 }
5629 
5630 /*
5631  * This workitem de-allocates fragments that were replaced during
5632  * file block allocation.
5633  */
5634 static void
5635 handle_workitem_freefrag(freefrag)
5636 	struct freefrag *freefrag;
5637 {
5638 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5639 	struct workhead wkhd;
5640 
5641 	CTR3(KTR_SUJ,
5642 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5643 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5644 	/*
5645 	 * It would be illegal to add new completion items to the
5646 	 * freefrag after it was schedule to be done so it must be
5647 	 * safe to modify the list head here.
5648 	 */
5649 	LIST_INIT(&wkhd);
5650 	ACQUIRE_LOCK(ump);
5651 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5652 	/*
5653 	 * If the journal has not been written we must cancel it here.
5654 	 */
5655 	if (freefrag->ff_jdep) {
5656 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5657 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5658 			    freefrag->ff_jdep->wk_type);
5659 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5660 	}
5661 	FREE_LOCK(ump);
5662 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5663 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5664 	   &wkhd, freefrag->ff_key);
5665 	ACQUIRE_LOCK(ump);
5666 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5667 	FREE_LOCK(ump);
5668 }
5669 
5670 /*
5671  * Set up a dependency structure for an external attributes data block.
5672  * This routine follows much of the structure of softdep_setup_allocdirect.
5673  * See the description of softdep_setup_allocdirect above for details.
5674  */
5675 void
5676 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5677 	struct inode *ip;
5678 	ufs_lbn_t off;
5679 	ufs2_daddr_t newblkno;
5680 	ufs2_daddr_t oldblkno;
5681 	long newsize;
5682 	long oldsize;
5683 	struct buf *bp;
5684 {
5685 	struct allocdirect *adp, *oldadp;
5686 	struct allocdirectlst *adphead;
5687 	struct freefrag *freefrag;
5688 	struct inodedep *inodedep;
5689 	struct jnewblk *jnewblk;
5690 	struct newblk *newblk;
5691 	struct mount *mp;
5692 	struct ufsmount *ump;
5693 	ufs_lbn_t lbn;
5694 
5695 	mp = ITOVFS(ip);
5696 	ump = VFSTOUFS(mp);
5697 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5698 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5699 	KASSERT(off < UFS_NXADDR,
5700 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5701 
5702 	lbn = bp->b_lblkno;
5703 	if (oldblkno && oldblkno != newblkno)
5704 		/*
5705 		 * The usual case is that a smaller fragment that
5706 		 * was just allocated has been replaced with a bigger
5707 		 * fragment or a full-size block. If it is marked as
5708 		 * B_DELWRI, the current contents have not been written
5709 		 * to disk. It is possible that the block was written
5710 		 * earlier, but very uncommon. If the block has never
5711 		 * been written, there is no need to send a BIO_DELETE
5712 		 * for it when it is freed. The gain from avoiding the
5713 		 * TRIMs for the common case of unwritten blocks far
5714 		 * exceeds the cost of the write amplification for the
5715 		 * uncommon case of failing to send a TRIM for a block
5716 		 * that had been written.
5717 		 */
5718 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5719 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5720 	else
5721 		freefrag = NULL;
5722 
5723 	ACQUIRE_LOCK(ump);
5724 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5725 		panic("softdep_setup_allocext: lost block");
5726 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5727 	    ("softdep_setup_allocext: newblk already initialized"));
5728 	/*
5729 	 * Convert the newblk to an allocdirect.
5730 	 */
5731 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5732 	adp = (struct allocdirect *)newblk;
5733 	newblk->nb_freefrag = freefrag;
5734 	adp->ad_offset = off;
5735 	adp->ad_oldblkno = oldblkno;
5736 	adp->ad_newsize = newsize;
5737 	adp->ad_oldsize = oldsize;
5738 	adp->ad_state |=  EXTDATA;
5739 
5740 	/*
5741 	 * Finish initializing the journal.
5742 	 */
5743 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5744 		jnewblk->jn_ino = ip->i_number;
5745 		jnewblk->jn_lbn = lbn;
5746 		add_to_journal(&jnewblk->jn_list);
5747 	}
5748 	if (freefrag && freefrag->ff_jdep != NULL &&
5749 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5750 		add_to_journal(freefrag->ff_jdep);
5751 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5752 	adp->ad_inodedep = inodedep;
5753 
5754 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5755 	/*
5756 	 * The list of allocdirects must be kept in sorted and ascending
5757 	 * order so that the rollback routines can quickly determine the
5758 	 * first uncommitted block (the size of the file stored on disk
5759 	 * ends at the end of the lowest committed fragment, or if there
5760 	 * are no fragments, at the end of the highest committed block).
5761 	 * Since files generally grow, the typical case is that the new
5762 	 * block is to be added at the end of the list. We speed this
5763 	 * special case by checking against the last allocdirect in the
5764 	 * list before laboriously traversing the list looking for the
5765 	 * insertion point.
5766 	 */
5767 	adphead = &inodedep->id_newextupdt;
5768 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5769 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5770 		/* insert at end of list */
5771 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5772 		if (oldadp != NULL && oldadp->ad_offset == off)
5773 			allocdirect_merge(adphead, adp, oldadp);
5774 		FREE_LOCK(ump);
5775 		return;
5776 	}
5777 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5778 		if (oldadp->ad_offset >= off)
5779 			break;
5780 	}
5781 	if (oldadp == NULL)
5782 		panic("softdep_setup_allocext: lost entry");
5783 	/* insert in middle of list */
5784 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5785 	if (oldadp->ad_offset == off)
5786 		allocdirect_merge(adphead, adp, oldadp);
5787 	FREE_LOCK(ump);
5788 }
5789 
5790 /*
5791  * Indirect block allocation dependencies.
5792  *
5793  * The same dependencies that exist for a direct block also exist when
5794  * a new block is allocated and pointed to by an entry in a block of
5795  * indirect pointers. The undo/redo states described above are also
5796  * used here. Because an indirect block contains many pointers that
5797  * may have dependencies, a second copy of the entire in-memory indirect
5798  * block is kept. The buffer cache copy is always completely up-to-date.
5799  * The second copy, which is used only as a source for disk writes,
5800  * contains only the safe pointers (i.e., those that have no remaining
5801  * update dependencies). The second copy is freed when all pointers
5802  * are safe. The cache is not allowed to replace indirect blocks with
5803  * pending update dependencies. If a buffer containing an indirect
5804  * block with dependencies is written, these routines will mark it
5805  * dirty again. It can only be successfully written once all the
5806  * dependencies are removed. The ffs_fsync routine in conjunction with
5807  * softdep_sync_metadata work together to get all the dependencies
5808  * removed so that a file can be successfully written to disk. Three
5809  * procedures are used when setting up indirect block pointer
5810  * dependencies. The division is necessary because of the organization
5811  * of the "balloc" routine and because of the distinction between file
5812  * pages and file metadata blocks.
5813  */
5814 
5815 /*
5816  * Allocate a new allocindir structure.
5817  */
5818 static struct allocindir *
5819 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5820 	struct inode *ip;	/* inode for file being extended */
5821 	int ptrno;		/* offset of pointer in indirect block */
5822 	ufs2_daddr_t newblkno;	/* disk block number being added */
5823 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5824 	ufs_lbn_t lbn;
5825 {
5826 	struct newblk *newblk;
5827 	struct allocindir *aip;
5828 	struct freefrag *freefrag;
5829 	struct jnewblk *jnewblk;
5830 
5831 	if (oldblkno)
5832 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
5833 		    SINGLETON_KEY);
5834 	else
5835 		freefrag = NULL;
5836 	ACQUIRE_LOCK(ITOUMP(ip));
5837 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5838 		panic("new_allocindir: lost block");
5839 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5840 	    ("newallocindir: newblk already initialized"));
5841 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5842 	newblk->nb_freefrag = freefrag;
5843 	aip = (struct allocindir *)newblk;
5844 	aip->ai_offset = ptrno;
5845 	aip->ai_oldblkno = oldblkno;
5846 	aip->ai_lbn = lbn;
5847 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5848 		jnewblk->jn_ino = ip->i_number;
5849 		jnewblk->jn_lbn = lbn;
5850 		add_to_journal(&jnewblk->jn_list);
5851 	}
5852 	if (freefrag && freefrag->ff_jdep != NULL &&
5853 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5854 		add_to_journal(freefrag->ff_jdep);
5855 	return (aip);
5856 }
5857 
5858 /*
5859  * Called just before setting an indirect block pointer
5860  * to a newly allocated file page.
5861  */
5862 void
5863 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5864 	struct inode *ip;	/* inode for file being extended */
5865 	ufs_lbn_t lbn;		/* allocated block number within file */
5866 	struct buf *bp;		/* buffer with indirect blk referencing page */
5867 	int ptrno;		/* offset of pointer in indirect block */
5868 	ufs2_daddr_t newblkno;	/* disk block number being added */
5869 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5870 	struct buf *nbp;	/* buffer holding allocated page */
5871 {
5872 	struct inodedep *inodedep;
5873 	struct freefrag *freefrag;
5874 	struct allocindir *aip;
5875 	struct pagedep *pagedep;
5876 	struct mount *mp;
5877 	struct ufsmount *ump;
5878 
5879 	mp = ITOVFS(ip);
5880 	ump = VFSTOUFS(mp);
5881 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5882 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5883 	KASSERT(lbn == nbp->b_lblkno,
5884 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5885 	    lbn, bp->b_lblkno));
5886 	CTR4(KTR_SUJ,
5887 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5888 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5889 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5890 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5891 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5892 	/*
5893 	 * If we are allocating a directory page, then we must
5894 	 * allocate an associated pagedep to track additions and
5895 	 * deletions.
5896 	 */
5897 	if ((ip->i_mode & IFMT) == IFDIR)
5898 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5899 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5900 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5901 	FREE_LOCK(ump);
5902 	if (freefrag)
5903 		handle_workitem_freefrag(freefrag);
5904 }
5905 
5906 /*
5907  * Called just before setting an indirect block pointer to a
5908  * newly allocated indirect block.
5909  */
5910 void
5911 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5912 	struct buf *nbp;	/* newly allocated indirect block */
5913 	struct inode *ip;	/* inode for file being extended */
5914 	struct buf *bp;		/* indirect block referencing allocated block */
5915 	int ptrno;		/* offset of pointer in indirect block */
5916 	ufs2_daddr_t newblkno;	/* disk block number being added */
5917 {
5918 	struct inodedep *inodedep;
5919 	struct allocindir *aip;
5920 	struct ufsmount *ump;
5921 	ufs_lbn_t lbn;
5922 
5923 	ump = ITOUMP(ip);
5924 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5925 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5926 	CTR3(KTR_SUJ,
5927 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5928 	    ip->i_number, newblkno, ptrno);
5929 	lbn = nbp->b_lblkno;
5930 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5931 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5932 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5933 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5934 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5935 		panic("softdep_setup_allocindir_meta: Block already existed");
5936 	FREE_LOCK(ump);
5937 }
5938 
5939 static void
5940 indirdep_complete(indirdep)
5941 	struct indirdep *indirdep;
5942 {
5943 	struct allocindir *aip;
5944 
5945 	LIST_REMOVE(indirdep, ir_next);
5946 	indirdep->ir_state |= DEPCOMPLETE;
5947 
5948 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5949 		LIST_REMOVE(aip, ai_next);
5950 		free_newblk(&aip->ai_block);
5951 	}
5952 	/*
5953 	 * If this indirdep is not attached to a buf it was simply waiting
5954 	 * on completion to clear completehd.  free_indirdep() asserts
5955 	 * that nothing is dangling.
5956 	 */
5957 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5958 		free_indirdep(indirdep);
5959 }
5960 
5961 static struct indirdep *
5962 indirdep_lookup(mp, ip, bp)
5963 	struct mount *mp;
5964 	struct inode *ip;
5965 	struct buf *bp;
5966 {
5967 	struct indirdep *indirdep, *newindirdep;
5968 	struct newblk *newblk;
5969 	struct ufsmount *ump;
5970 	struct worklist *wk;
5971 	struct fs *fs;
5972 	ufs2_daddr_t blkno;
5973 
5974 	ump = VFSTOUFS(mp);
5975 	LOCK_OWNED(ump);
5976 	indirdep = NULL;
5977 	newindirdep = NULL;
5978 	fs = ump->um_fs;
5979 	for (;;) {
5980 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5981 			if (wk->wk_type != D_INDIRDEP)
5982 				continue;
5983 			indirdep = WK_INDIRDEP(wk);
5984 			break;
5985 		}
5986 		/* Found on the buffer worklist, no new structure to free. */
5987 		if (indirdep != NULL && newindirdep == NULL)
5988 			return (indirdep);
5989 		if (indirdep != NULL && newindirdep != NULL)
5990 			panic("indirdep_lookup: simultaneous create");
5991 		/* None found on the buffer and a new structure is ready. */
5992 		if (indirdep == NULL && newindirdep != NULL)
5993 			break;
5994 		/* None found and no new structure available. */
5995 		FREE_LOCK(ump);
5996 		newindirdep = malloc(sizeof(struct indirdep),
5997 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
5998 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5999 		newindirdep->ir_state = ATTACHED;
6000 		if (I_IS_UFS1(ip))
6001 			newindirdep->ir_state |= UFS1FMT;
6002 		TAILQ_INIT(&newindirdep->ir_trunc);
6003 		newindirdep->ir_saveddata = NULL;
6004 		LIST_INIT(&newindirdep->ir_deplisthd);
6005 		LIST_INIT(&newindirdep->ir_donehd);
6006 		LIST_INIT(&newindirdep->ir_writehd);
6007 		LIST_INIT(&newindirdep->ir_completehd);
6008 		if (bp->b_blkno == bp->b_lblkno) {
6009 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6010 			    NULL, NULL);
6011 			bp->b_blkno = blkno;
6012 		}
6013 		newindirdep->ir_freeblks = NULL;
6014 		newindirdep->ir_savebp =
6015 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6016 		newindirdep->ir_bp = bp;
6017 		BUF_KERNPROC(newindirdep->ir_savebp);
6018 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6019 		ACQUIRE_LOCK(ump);
6020 	}
6021 	indirdep = newindirdep;
6022 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6023 	/*
6024 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6025 	 * that we don't free dependencies until the pointers are valid.
6026 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6027 	 * than using the hash.
6028 	 */
6029 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6030 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6031 	else
6032 		indirdep->ir_state |= DEPCOMPLETE;
6033 	return (indirdep);
6034 }
6035 
6036 /*
6037  * Called to finish the allocation of the "aip" allocated
6038  * by one of the two routines above.
6039  */
6040 static struct freefrag *
6041 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6042 	struct buf *bp;		/* in-memory copy of the indirect block */
6043 	struct inode *ip;	/* inode for file being extended */
6044 	struct inodedep *inodedep; /* Inodedep for ip */
6045 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6046 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6047 {
6048 	struct fs *fs;
6049 	struct indirdep *indirdep;
6050 	struct allocindir *oldaip;
6051 	struct freefrag *freefrag;
6052 	struct mount *mp;
6053 	struct ufsmount *ump;
6054 
6055 	mp = ITOVFS(ip);
6056 	ump = VFSTOUFS(mp);
6057 	LOCK_OWNED(ump);
6058 	fs = ump->um_fs;
6059 	if (bp->b_lblkno >= 0)
6060 		panic("setup_allocindir_phase2: not indir blk");
6061 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6062 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6063 	indirdep = indirdep_lookup(mp, ip, bp);
6064 	KASSERT(indirdep->ir_savebp != NULL,
6065 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6066 	aip->ai_indirdep = indirdep;
6067 	/*
6068 	 * Check for an unwritten dependency for this indirect offset.  If
6069 	 * there is, merge the old dependency into the new one.  This happens
6070 	 * as a result of reallocblk only.
6071 	 */
6072 	freefrag = NULL;
6073 	if (aip->ai_oldblkno != 0) {
6074 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6075 			if (oldaip->ai_offset == aip->ai_offset) {
6076 				freefrag = allocindir_merge(aip, oldaip);
6077 				goto done;
6078 			}
6079 		}
6080 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6081 			if (oldaip->ai_offset == aip->ai_offset) {
6082 				freefrag = allocindir_merge(aip, oldaip);
6083 				goto done;
6084 			}
6085 		}
6086 	}
6087 done:
6088 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6089 	return (freefrag);
6090 }
6091 
6092 /*
6093  * Merge two allocindirs which refer to the same block.  Move newblock
6094  * dependencies and setup the freefrags appropriately.
6095  */
6096 static struct freefrag *
6097 allocindir_merge(aip, oldaip)
6098 	struct allocindir *aip;
6099 	struct allocindir *oldaip;
6100 {
6101 	struct freefrag *freefrag;
6102 	struct worklist *wk;
6103 
6104 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6105 		panic("allocindir_merge: blkno");
6106 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6107 	freefrag = aip->ai_freefrag;
6108 	aip->ai_freefrag = oldaip->ai_freefrag;
6109 	oldaip->ai_freefrag = NULL;
6110 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6111 	/*
6112 	 * If we are tracking a new directory-block allocation,
6113 	 * move it from the old allocindir to the new allocindir.
6114 	 */
6115 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6116 		WORKLIST_REMOVE(wk);
6117 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6118 			panic("allocindir_merge: extra newdirblk");
6119 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6120 	}
6121 	/*
6122 	 * We can skip journaling for this freefrag and just complete
6123 	 * any pending journal work for the allocindir that is being
6124 	 * removed after the freefrag completes.
6125 	 */
6126 	if (freefrag->ff_jdep)
6127 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6128 	LIST_REMOVE(oldaip, ai_next);
6129 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6130 	    &freefrag->ff_list, &freefrag->ff_jwork);
6131 	free_newblk(&oldaip->ai_block);
6132 
6133 	return (freefrag);
6134 }
6135 
6136 static inline void
6137 setup_freedirect(freeblks, ip, i, needj)
6138 	struct freeblks *freeblks;
6139 	struct inode *ip;
6140 	int i;
6141 	int needj;
6142 {
6143 	struct ufsmount *ump;
6144 	ufs2_daddr_t blkno;
6145 	int frags;
6146 
6147 	blkno = DIP(ip, i_db[i]);
6148 	if (blkno == 0)
6149 		return;
6150 	DIP_SET(ip, i_db[i], 0);
6151 	ump = ITOUMP(ip);
6152 	frags = sblksize(ump->um_fs, ip->i_size, i);
6153 	frags = numfrags(ump->um_fs, frags);
6154 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6155 }
6156 
6157 static inline void
6158 setup_freeext(freeblks, ip, i, needj)
6159 	struct freeblks *freeblks;
6160 	struct inode *ip;
6161 	int i;
6162 	int needj;
6163 {
6164 	struct ufsmount *ump;
6165 	ufs2_daddr_t blkno;
6166 	int frags;
6167 
6168 	blkno = ip->i_din2->di_extb[i];
6169 	if (blkno == 0)
6170 		return;
6171 	ip->i_din2->di_extb[i] = 0;
6172 	ump = ITOUMP(ip);
6173 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6174 	frags = numfrags(ump->um_fs, frags);
6175 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6176 }
6177 
6178 static inline void
6179 setup_freeindir(freeblks, ip, i, lbn, needj)
6180 	struct freeblks *freeblks;
6181 	struct inode *ip;
6182 	int i;
6183 	ufs_lbn_t lbn;
6184 	int needj;
6185 {
6186 	struct ufsmount *ump;
6187 	ufs2_daddr_t blkno;
6188 
6189 	blkno = DIP(ip, i_ib[i]);
6190 	if (blkno == 0)
6191 		return;
6192 	DIP_SET(ip, i_ib[i], 0);
6193 	ump = ITOUMP(ip);
6194 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6195 	    0, needj);
6196 }
6197 
6198 static inline struct freeblks *
6199 newfreeblks(mp, ip)
6200 	struct mount *mp;
6201 	struct inode *ip;
6202 {
6203 	struct freeblks *freeblks;
6204 
6205 	freeblks = malloc(sizeof(struct freeblks),
6206 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6207 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6208 	LIST_INIT(&freeblks->fb_jblkdephd);
6209 	LIST_INIT(&freeblks->fb_jwork);
6210 	freeblks->fb_ref = 0;
6211 	freeblks->fb_cgwait = 0;
6212 	freeblks->fb_state = ATTACHED;
6213 	freeblks->fb_uid = ip->i_uid;
6214 	freeblks->fb_inum = ip->i_number;
6215 	freeblks->fb_vtype = ITOV(ip)->v_type;
6216 	freeblks->fb_modrev = DIP(ip, i_modrev);
6217 	freeblks->fb_devvp = ITODEVVP(ip);
6218 	freeblks->fb_chkcnt = 0;
6219 	freeblks->fb_len = 0;
6220 
6221 	return (freeblks);
6222 }
6223 
6224 static void
6225 trunc_indirdep(indirdep, freeblks, bp, off)
6226 	struct indirdep *indirdep;
6227 	struct freeblks *freeblks;
6228 	struct buf *bp;
6229 	int off;
6230 {
6231 	struct allocindir *aip, *aipn;
6232 
6233 	/*
6234 	 * The first set of allocindirs won't be in savedbp.
6235 	 */
6236 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6237 		if (aip->ai_offset > off)
6238 			cancel_allocindir(aip, bp, freeblks, 1);
6239 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6240 		if (aip->ai_offset > off)
6241 			cancel_allocindir(aip, bp, freeblks, 1);
6242 	/*
6243 	 * These will exist in savedbp.
6244 	 */
6245 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6246 		if (aip->ai_offset > off)
6247 			cancel_allocindir(aip, NULL, freeblks, 0);
6248 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6249 		if (aip->ai_offset > off)
6250 			cancel_allocindir(aip, NULL, freeblks, 0);
6251 }
6252 
6253 /*
6254  * Follow the chain of indirects down to lastlbn creating a freework
6255  * structure for each.  This will be used to start indir_trunc() at
6256  * the right offset and create the journal records for the parrtial
6257  * truncation.  A second step will handle the truncated dependencies.
6258  */
6259 static int
6260 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6261 	struct freeblks *freeblks;
6262 	struct inode *ip;
6263 	ufs_lbn_t lbn;
6264 	ufs_lbn_t lastlbn;
6265 	ufs2_daddr_t blkno;
6266 {
6267 	struct indirdep *indirdep;
6268 	struct indirdep *indirn;
6269 	struct freework *freework;
6270 	struct newblk *newblk;
6271 	struct mount *mp;
6272 	struct ufsmount *ump;
6273 	struct buf *bp;
6274 	uint8_t *start;
6275 	uint8_t *end;
6276 	ufs_lbn_t lbnadd;
6277 	int level;
6278 	int error;
6279 	int off;
6280 
6281 
6282 	freework = NULL;
6283 	if (blkno == 0)
6284 		return (0);
6285 	mp = freeblks->fb_list.wk_mp;
6286 	ump = VFSTOUFS(mp);
6287 	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6288 	if ((bp->b_flags & B_CACHE) == 0) {
6289 		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6290 		bp->b_iocmd = BIO_READ;
6291 		bp->b_flags &= ~B_INVAL;
6292 		bp->b_ioflags &= ~BIO_ERROR;
6293 		vfs_busy_pages(bp, 0);
6294 		bp->b_iooffset = dbtob(bp->b_blkno);
6295 		bstrategy(bp);
6296 #ifdef RACCT
6297 		if (racct_enable) {
6298 			PROC_LOCK(curproc);
6299 			racct_add_buf(curproc, bp, 0);
6300 			PROC_UNLOCK(curproc);
6301 		}
6302 #endif /* RACCT */
6303 		curthread->td_ru.ru_inblock++;
6304 		error = bufwait(bp);
6305 		if (error) {
6306 			brelse(bp);
6307 			return (error);
6308 		}
6309 	}
6310 	level = lbn_level(lbn);
6311 	lbnadd = lbn_offset(ump->um_fs, level);
6312 	/*
6313 	 * Compute the offset of the last block we want to keep.  Store
6314 	 * in the freework the first block we want to completely free.
6315 	 */
6316 	off = (lastlbn - -(lbn + level)) / lbnadd;
6317 	if (off + 1 == NINDIR(ump->um_fs))
6318 		goto nowork;
6319 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6320 	/*
6321 	 * Link the freework into the indirdep.  This will prevent any new
6322 	 * allocations from proceeding until we are finished with the
6323 	 * truncate and the block is written.
6324 	 */
6325 	ACQUIRE_LOCK(ump);
6326 	indirdep = indirdep_lookup(mp, ip, bp);
6327 	if (indirdep->ir_freeblks)
6328 		panic("setup_trunc_indir: indirdep already truncated.");
6329 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6330 	freework->fw_indir = indirdep;
6331 	/*
6332 	 * Cancel any allocindirs that will not make it to disk.
6333 	 * We have to do this for all copies of the indirdep that
6334 	 * live on this newblk.
6335 	 */
6336 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6337 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6338 		    &newblk) == 0)
6339 			panic("setup_trunc_indir: lost block");
6340 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6341 			trunc_indirdep(indirn, freeblks, bp, off);
6342 	} else
6343 		trunc_indirdep(indirdep, freeblks, bp, off);
6344 	FREE_LOCK(ump);
6345 	/*
6346 	 * Creation is protected by the buf lock. The saveddata is only
6347 	 * needed if a full truncation follows a partial truncation but it
6348 	 * is difficult to allocate in that case so we fetch it anyway.
6349 	 */
6350 	if (indirdep->ir_saveddata == NULL)
6351 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6352 		    M_SOFTDEP_FLAGS);
6353 nowork:
6354 	/* Fetch the blkno of the child and the zero start offset. */
6355 	if (I_IS_UFS1(ip)) {
6356 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6357 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6358 	} else {
6359 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6360 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6361 	}
6362 	if (freework) {
6363 		/* Zero the truncated pointers. */
6364 		end = bp->b_data + bp->b_bcount;
6365 		bzero(start, end - start);
6366 		bdwrite(bp);
6367 	} else
6368 		bqrelse(bp);
6369 	if (level == 0)
6370 		return (0);
6371 	lbn++; /* adjust level */
6372 	lbn -= (off * lbnadd);
6373 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6374 }
6375 
6376 /*
6377  * Complete the partial truncation of an indirect block setup by
6378  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6379  * copy and writes them to disk before the freeblks is allowed to complete.
6380  */
6381 static void
6382 complete_trunc_indir(freework)
6383 	struct freework *freework;
6384 {
6385 	struct freework *fwn;
6386 	struct indirdep *indirdep;
6387 	struct ufsmount *ump;
6388 	struct buf *bp;
6389 	uintptr_t start;
6390 	int count;
6391 
6392 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6393 	LOCK_OWNED(ump);
6394 	indirdep = freework->fw_indir;
6395 	for (;;) {
6396 		bp = indirdep->ir_bp;
6397 		/* See if the block was discarded. */
6398 		if (bp == NULL)
6399 			break;
6400 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6401 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6402 			break;
6403 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6404 		    LOCK_PTR(ump)) == 0)
6405 			BUF_UNLOCK(bp);
6406 		ACQUIRE_LOCK(ump);
6407 	}
6408 	freework->fw_state |= DEPCOMPLETE;
6409 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6410 	/*
6411 	 * Zero the pointers in the saved copy.
6412 	 */
6413 	if (indirdep->ir_state & UFS1FMT)
6414 		start = sizeof(ufs1_daddr_t);
6415 	else
6416 		start = sizeof(ufs2_daddr_t);
6417 	start *= freework->fw_start;
6418 	count = indirdep->ir_savebp->b_bcount - start;
6419 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6420 	bzero((char *)start, count);
6421 	/*
6422 	 * We need to start the next truncation in the list if it has not
6423 	 * been started yet.
6424 	 */
6425 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6426 	if (fwn != NULL) {
6427 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6428 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6429 		if ((fwn->fw_state & ONWORKLIST) == 0)
6430 			freework_enqueue(fwn);
6431 	}
6432 	/*
6433 	 * If bp is NULL the block was fully truncated, restore
6434 	 * the saved block list otherwise free it if it is no
6435 	 * longer needed.
6436 	 */
6437 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6438 		if (bp == NULL)
6439 			bcopy(indirdep->ir_saveddata,
6440 			    indirdep->ir_savebp->b_data,
6441 			    indirdep->ir_savebp->b_bcount);
6442 		free(indirdep->ir_saveddata, M_INDIRDEP);
6443 		indirdep->ir_saveddata = NULL;
6444 	}
6445 	/*
6446 	 * When bp is NULL there is a full truncation pending.  We
6447 	 * must wait for this full truncation to be journaled before
6448 	 * we can release this freework because the disk pointers will
6449 	 * never be written as zero.
6450 	 */
6451 	if (bp == NULL)  {
6452 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6453 			handle_written_freework(freework);
6454 		else
6455 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6456 			   &freework->fw_list);
6457 	} else {
6458 		/* Complete when the real copy is written. */
6459 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6460 		BUF_UNLOCK(bp);
6461 	}
6462 }
6463 
6464 /*
6465  * Calculate the number of blocks we are going to release where datablocks
6466  * is the current total and length is the new file size.
6467  */
6468 static ufs2_daddr_t
6469 blkcount(fs, datablocks, length)
6470 	struct fs *fs;
6471 	ufs2_daddr_t datablocks;
6472 	off_t length;
6473 {
6474 	off_t totblks, numblks;
6475 
6476 	totblks = 0;
6477 	numblks = howmany(length, fs->fs_bsize);
6478 	if (numblks <= UFS_NDADDR) {
6479 		totblks = howmany(length, fs->fs_fsize);
6480 		goto out;
6481 	}
6482         totblks = blkstofrags(fs, numblks);
6483 	numblks -= UFS_NDADDR;
6484 	/*
6485 	 * Count all single, then double, then triple indirects required.
6486 	 * Subtracting one indirects worth of blocks for each pass
6487 	 * acknowledges one of each pointed to by the inode.
6488 	 */
6489 	for (;;) {
6490 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6491 		numblks -= NINDIR(fs);
6492 		if (numblks <= 0)
6493 			break;
6494 		numblks = howmany(numblks, NINDIR(fs));
6495 	}
6496 out:
6497 	totblks = fsbtodb(fs, totblks);
6498 	/*
6499 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6500 	 * references.  We will correct it later in handle_complete_freeblks()
6501 	 * when we know the real count.
6502 	 */
6503 	if (totblks > datablocks)
6504 		return (0);
6505 	return (datablocks - totblks);
6506 }
6507 
6508 /*
6509  * Handle freeblocks for journaled softupdate filesystems.
6510  *
6511  * Contrary to normal softupdates, we must preserve the block pointers in
6512  * indirects until their subordinates are free.  This is to avoid journaling
6513  * every block that is freed which may consume more space than the journal
6514  * itself.  The recovery program will see the free block journals at the
6515  * base of the truncated area and traverse them to reclaim space.  The
6516  * pointers in the inode may be cleared immediately after the journal
6517  * records are written because each direct and indirect pointer in the
6518  * inode is recorded in a journal.  This permits full truncation to proceed
6519  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6520  *
6521  * The algorithm is as follows:
6522  * 1) Traverse the in-memory state and create journal entries to release
6523  *    the relevant blocks and full indirect trees.
6524  * 2) Traverse the indirect block chain adding partial truncation freework
6525  *    records to indirects in the path to lastlbn.  The freework will
6526  *    prevent new allocation dependencies from being satisfied in this
6527  *    indirect until the truncation completes.
6528  * 3) Read and lock the inode block, performing an update with the new size
6529  *    and pointers.  This prevents truncated data from becoming valid on
6530  *    disk through step 4.
6531  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6532  *    eliminate journal work for those records that do not require it.
6533  * 5) Schedule the journal records to be written followed by the inode block.
6534  * 6) Allocate any necessary frags for the end of file.
6535  * 7) Zero any partially truncated blocks.
6536  *
6537  * From this truncation proceeds asynchronously using the freework and
6538  * indir_trunc machinery.  The file will not be extended again into a
6539  * partially truncated indirect block until all work is completed but
6540  * the normal dependency mechanism ensures that it is rolled back/forward
6541  * as appropriate.  Further truncation may occur without delay and is
6542  * serialized in indir_trunc().
6543  */
6544 void
6545 softdep_journal_freeblocks(ip, cred, length, flags)
6546 	struct inode *ip;	/* The inode whose length is to be reduced */
6547 	struct ucred *cred;
6548 	off_t length;		/* The new length for the file */
6549 	int flags;		/* IO_EXT and/or IO_NORMAL */
6550 {
6551 	struct freeblks *freeblks, *fbn;
6552 	struct worklist *wk, *wkn;
6553 	struct inodedep *inodedep;
6554 	struct jblkdep *jblkdep;
6555 	struct allocdirect *adp, *adpn;
6556 	struct ufsmount *ump;
6557 	struct fs *fs;
6558 	struct buf *bp;
6559 	struct vnode *vp;
6560 	struct mount *mp;
6561 	ufs2_daddr_t extblocks, datablocks;
6562 	ufs_lbn_t tmpval, lbn, lastlbn;
6563 	int frags, lastoff, iboff, allocblock, needj, error, i;
6564 
6565 	ump = ITOUMP(ip);
6566 	mp = UFSTOVFS(ump);
6567 	fs = ump->um_fs;
6568 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6569 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6570 	vp = ITOV(ip);
6571 	needj = 1;
6572 	iboff = -1;
6573 	allocblock = 0;
6574 	extblocks = 0;
6575 	datablocks = 0;
6576 	frags = 0;
6577 	freeblks = newfreeblks(mp, ip);
6578 	ACQUIRE_LOCK(ump);
6579 	/*
6580 	 * If we're truncating a removed file that will never be written
6581 	 * we don't need to journal the block frees.  The canceled journals
6582 	 * for the allocations will suffice.
6583 	 */
6584 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6585 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6586 	    length == 0)
6587 		needj = 0;
6588 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6589 	    ip->i_number, length, needj);
6590 	FREE_LOCK(ump);
6591 	/*
6592 	 * Calculate the lbn that we are truncating to.  This results in -1
6593 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6594 	 * to keep, not the first lbn we want to truncate.
6595 	 */
6596 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6597 	lastoff = blkoff(fs, length);
6598 	/*
6599 	 * Compute frags we are keeping in lastlbn.  0 means all.
6600 	 */
6601 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6602 		frags = fragroundup(fs, lastoff);
6603 		/* adp offset of last valid allocdirect. */
6604 		iboff = lastlbn;
6605 	} else if (lastlbn > 0)
6606 		iboff = UFS_NDADDR;
6607 	if (fs->fs_magic == FS_UFS2_MAGIC)
6608 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6609 	/*
6610 	 * Handle normal data blocks and indirects.  This section saves
6611 	 * values used after the inode update to complete frag and indirect
6612 	 * truncation.
6613 	 */
6614 	if ((flags & IO_NORMAL) != 0) {
6615 		/*
6616 		 * Handle truncation of whole direct and indirect blocks.
6617 		 */
6618 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6619 			setup_freedirect(freeblks, ip, i, needj);
6620 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6621 		    i < UFS_NIADDR;
6622 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6623 			/* Release a whole indirect tree. */
6624 			if (lbn > lastlbn) {
6625 				setup_freeindir(freeblks, ip, i, -lbn -i,
6626 				    needj);
6627 				continue;
6628 			}
6629 			iboff = i + UFS_NDADDR;
6630 			/*
6631 			 * Traverse partially truncated indirect tree.
6632 			 */
6633 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6634 				setup_trunc_indir(freeblks, ip, -lbn - i,
6635 				    lastlbn, DIP(ip, i_ib[i]));
6636 		}
6637 		/*
6638 		 * Handle partial truncation to a frag boundary.
6639 		 */
6640 		if (frags) {
6641 			ufs2_daddr_t blkno;
6642 			long oldfrags;
6643 
6644 			oldfrags = blksize(fs, ip, lastlbn);
6645 			blkno = DIP(ip, i_db[lastlbn]);
6646 			if (blkno && oldfrags != frags) {
6647 				oldfrags -= frags;
6648 				oldfrags = numfrags(fs, oldfrags);
6649 				blkno += numfrags(fs, frags);
6650 				newfreework(ump, freeblks, NULL, lastlbn,
6651 				    blkno, oldfrags, 0, needj);
6652 				if (needj)
6653 					adjust_newfreework(freeblks,
6654 					    numfrags(fs, frags));
6655 			} else if (blkno == 0)
6656 				allocblock = 1;
6657 		}
6658 		/*
6659 		 * Add a journal record for partial truncate if we are
6660 		 * handling indirect blocks.  Non-indirects need no extra
6661 		 * journaling.
6662 		 */
6663 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6664 			ip->i_flag |= IN_TRUNCATED;
6665 			newjtrunc(freeblks, length, 0);
6666 		}
6667 		ip->i_size = length;
6668 		DIP_SET(ip, i_size, ip->i_size);
6669 		datablocks = DIP(ip, i_blocks) - extblocks;
6670 		if (length != 0)
6671 			datablocks = blkcount(fs, datablocks, length);
6672 		freeblks->fb_len = length;
6673 	}
6674 	if ((flags & IO_EXT) != 0) {
6675 		for (i = 0; i < UFS_NXADDR; i++)
6676 			setup_freeext(freeblks, ip, i, needj);
6677 		ip->i_din2->di_extsize = 0;
6678 		datablocks += extblocks;
6679 	}
6680 #ifdef QUOTA
6681 	/* Reference the quotas in case the block count is wrong in the end. */
6682 	quotaref(vp, freeblks->fb_quota);
6683 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6684 #endif
6685 	freeblks->fb_chkcnt = -datablocks;
6686 	UFS_LOCK(ump);
6687 	fs->fs_pendingblocks += datablocks;
6688 	UFS_UNLOCK(ump);
6689 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6690 	/*
6691 	 * Handle truncation of incomplete alloc direct dependencies.  We
6692 	 * hold the inode block locked to prevent incomplete dependencies
6693 	 * from reaching the disk while we are eliminating those that
6694 	 * have been truncated.  This is a partially inlined ffs_update().
6695 	 */
6696 	ufs_itimes(vp);
6697 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6698 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6699 	    (int)fs->fs_bsize, cred, &bp);
6700 	if (error) {
6701 		softdep_error("softdep_journal_freeblocks", error);
6702 		return;
6703 	}
6704 	if (bp->b_bufsize == fs->fs_bsize)
6705 		bp->b_flags |= B_CLUSTEROK;
6706 	softdep_update_inodeblock(ip, bp, 0);
6707 	if (ump->um_fstype == UFS1) {
6708 		*((struct ufs1_dinode *)bp->b_data +
6709 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6710 	} else {
6711 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6712 		*((struct ufs2_dinode *)bp->b_data +
6713 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6714 	}
6715 	ACQUIRE_LOCK(ump);
6716 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6717 	if ((inodedep->id_state & IOSTARTED) != 0)
6718 		panic("softdep_setup_freeblocks: inode busy");
6719 	/*
6720 	 * Add the freeblks structure to the list of operations that
6721 	 * must await the zero'ed inode being written to disk. If we
6722 	 * still have a bitmap dependency (needj), then the inode
6723 	 * has never been written to disk, so we can process the
6724 	 * freeblks below once we have deleted the dependencies.
6725 	 */
6726 	if (needj)
6727 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6728 	else
6729 		freeblks->fb_state |= COMPLETE;
6730 	if ((flags & IO_NORMAL) != 0) {
6731 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6732 			if (adp->ad_offset > iboff)
6733 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6734 				    freeblks);
6735 			/*
6736 			 * Truncate the allocdirect.  We could eliminate
6737 			 * or modify journal records as well.
6738 			 */
6739 			else if (adp->ad_offset == iboff && frags)
6740 				adp->ad_newsize = frags;
6741 		}
6742 	}
6743 	if ((flags & IO_EXT) != 0)
6744 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6745 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6746 			    freeblks);
6747 	/*
6748 	 * Scan the bufwait list for newblock dependencies that will never
6749 	 * make it to disk.
6750 	 */
6751 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6752 		if (wk->wk_type != D_ALLOCDIRECT)
6753 			continue;
6754 		adp = WK_ALLOCDIRECT(wk);
6755 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6756 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6757 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6758 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6759 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6760 		}
6761 	}
6762 	/*
6763 	 * Add journal work.
6764 	 */
6765 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6766 		add_to_journal(&jblkdep->jb_list);
6767 	FREE_LOCK(ump);
6768 	bdwrite(bp);
6769 	/*
6770 	 * Truncate dependency structures beyond length.
6771 	 */
6772 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6773 	/*
6774 	 * This is only set when we need to allocate a fragment because
6775 	 * none existed at the end of a frag-sized file.  It handles only
6776 	 * allocating a new, zero filled block.
6777 	 */
6778 	if (allocblock) {
6779 		ip->i_size = length - lastoff;
6780 		DIP_SET(ip, i_size, ip->i_size);
6781 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6782 		if (error != 0) {
6783 			softdep_error("softdep_journal_freeblks", error);
6784 			return;
6785 		}
6786 		ip->i_size = length;
6787 		DIP_SET(ip, i_size, length);
6788 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6789 		allocbuf(bp, frags);
6790 		ffs_update(vp, 0);
6791 		bawrite(bp);
6792 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6793 		int size;
6794 
6795 		/*
6796 		 * Zero the end of a truncated frag or block.
6797 		 */
6798 		size = sblksize(fs, length, lastlbn);
6799 		error = bread(vp, lastlbn, size, cred, &bp);
6800 		if (error) {
6801 			softdep_error("softdep_journal_freeblks", error);
6802 			return;
6803 		}
6804 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6805 		bawrite(bp);
6806 
6807 	}
6808 	ACQUIRE_LOCK(ump);
6809 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6810 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6811 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6812 	/*
6813 	 * We zero earlier truncations so they don't erroneously
6814 	 * update i_blocks.
6815 	 */
6816 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6817 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6818 			fbn->fb_len = 0;
6819 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6820 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6821 		freeblks->fb_state |= INPROGRESS;
6822 	else
6823 		freeblks = NULL;
6824 	FREE_LOCK(ump);
6825 	if (freeblks)
6826 		handle_workitem_freeblocks(freeblks, 0);
6827 	trunc_pages(ip, length, extblocks, flags);
6828 
6829 }
6830 
6831 /*
6832  * Flush a JOP_SYNC to the journal.
6833  */
6834 void
6835 softdep_journal_fsync(ip)
6836 	struct inode *ip;
6837 {
6838 	struct jfsync *jfsync;
6839 	struct ufsmount *ump;
6840 
6841 	ump = ITOUMP(ip);
6842 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6843 	    ("softdep_journal_fsync called on non-softdep filesystem"));
6844 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6845 		return;
6846 	ip->i_flag &= ~IN_TRUNCATED;
6847 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6848 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6849 	jfsync->jfs_size = ip->i_size;
6850 	jfsync->jfs_ino = ip->i_number;
6851 	ACQUIRE_LOCK(ump);
6852 	add_to_journal(&jfsync->jfs_list);
6853 	jwait(&jfsync->jfs_list, MNT_WAIT);
6854 	FREE_LOCK(ump);
6855 }
6856 
6857 /*
6858  * Block de-allocation dependencies.
6859  *
6860  * When blocks are de-allocated, the on-disk pointers must be nullified before
6861  * the blocks are made available for use by other files.  (The true
6862  * requirement is that old pointers must be nullified before new on-disk
6863  * pointers are set.  We chose this slightly more stringent requirement to
6864  * reduce complexity.) Our implementation handles this dependency by updating
6865  * the inode (or indirect block) appropriately but delaying the actual block
6866  * de-allocation (i.e., freemap and free space count manipulation) until
6867  * after the updated versions reach stable storage.  After the disk is
6868  * updated, the blocks can be safely de-allocated whenever it is convenient.
6869  * This implementation handles only the common case of reducing a file's
6870  * length to zero. Other cases are handled by the conventional synchronous
6871  * write approach.
6872  *
6873  * The ffs implementation with which we worked double-checks
6874  * the state of the block pointers and file size as it reduces
6875  * a file's length.  Some of this code is replicated here in our
6876  * soft updates implementation.  The freeblks->fb_chkcnt field is
6877  * used to transfer a part of this information to the procedure
6878  * that eventually de-allocates the blocks.
6879  *
6880  * This routine should be called from the routine that shortens
6881  * a file's length, before the inode's size or block pointers
6882  * are modified. It will save the block pointer information for
6883  * later release and zero the inode so that the calling routine
6884  * can release it.
6885  */
6886 void
6887 softdep_setup_freeblocks(ip, length, flags)
6888 	struct inode *ip;	/* The inode whose length is to be reduced */
6889 	off_t length;		/* The new length for the file */
6890 	int flags;		/* IO_EXT and/or IO_NORMAL */
6891 {
6892 	struct ufs1_dinode *dp1;
6893 	struct ufs2_dinode *dp2;
6894 	struct freeblks *freeblks;
6895 	struct inodedep *inodedep;
6896 	struct allocdirect *adp;
6897 	struct ufsmount *ump;
6898 	struct buf *bp;
6899 	struct fs *fs;
6900 	ufs2_daddr_t extblocks, datablocks;
6901 	struct mount *mp;
6902 	int i, delay, error;
6903 	ufs_lbn_t tmpval;
6904 	ufs_lbn_t lbn;
6905 
6906 	ump = ITOUMP(ip);
6907 	mp = UFSTOVFS(ump);
6908 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6909 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6910 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6911 	    ip->i_number, length);
6912 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6913 	fs = ump->um_fs;
6914 	if ((error = bread(ump->um_devvp,
6915 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6916 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6917 		brelse(bp);
6918 		softdep_error("softdep_setup_freeblocks", error);
6919 		return;
6920 	}
6921 	freeblks = newfreeblks(mp, ip);
6922 	extblocks = 0;
6923 	datablocks = 0;
6924 	if (fs->fs_magic == FS_UFS2_MAGIC)
6925 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6926 	if ((flags & IO_NORMAL) != 0) {
6927 		for (i = 0; i < UFS_NDADDR; i++)
6928 			setup_freedirect(freeblks, ip, i, 0);
6929 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6930 		    i < UFS_NIADDR;
6931 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6932 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6933 		ip->i_size = 0;
6934 		DIP_SET(ip, i_size, 0);
6935 		datablocks = DIP(ip, i_blocks) - extblocks;
6936 	}
6937 	if ((flags & IO_EXT) != 0) {
6938 		for (i = 0; i < UFS_NXADDR; i++)
6939 			setup_freeext(freeblks, ip, i, 0);
6940 		ip->i_din2->di_extsize = 0;
6941 		datablocks += extblocks;
6942 	}
6943 #ifdef QUOTA
6944 	/* Reference the quotas in case the block count is wrong in the end. */
6945 	quotaref(ITOV(ip), freeblks->fb_quota);
6946 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6947 #endif
6948 	freeblks->fb_chkcnt = -datablocks;
6949 	UFS_LOCK(ump);
6950 	fs->fs_pendingblocks += datablocks;
6951 	UFS_UNLOCK(ump);
6952 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6953 	/*
6954 	 * Push the zero'ed inode to its disk buffer so that we are free
6955 	 * to delete its dependencies below. Once the dependencies are gone
6956 	 * the buffer can be safely released.
6957 	 */
6958 	if (ump->um_fstype == UFS1) {
6959 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6960 		    ino_to_fsbo(fs, ip->i_number));
6961 		ip->i_din1->di_freelink = dp1->di_freelink;
6962 		*dp1 = *ip->i_din1;
6963 	} else {
6964 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6965 		    ino_to_fsbo(fs, ip->i_number));
6966 		ip->i_din2->di_freelink = dp2->di_freelink;
6967 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6968 		*dp2 = *ip->i_din2;
6969 	}
6970 	/*
6971 	 * Find and eliminate any inode dependencies.
6972 	 */
6973 	ACQUIRE_LOCK(ump);
6974 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6975 	if ((inodedep->id_state & IOSTARTED) != 0)
6976 		panic("softdep_setup_freeblocks: inode busy");
6977 	/*
6978 	 * Add the freeblks structure to the list of operations that
6979 	 * must await the zero'ed inode being written to disk. If we
6980 	 * still have a bitmap dependency (delay == 0), then the inode
6981 	 * has never been written to disk, so we can process the
6982 	 * freeblks below once we have deleted the dependencies.
6983 	 */
6984 	delay = (inodedep->id_state & DEPCOMPLETE);
6985 	if (delay)
6986 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6987 	else
6988 		freeblks->fb_state |= COMPLETE;
6989 	/*
6990 	 * Because the file length has been truncated to zero, any
6991 	 * pending block allocation dependency structures associated
6992 	 * with this inode are obsolete and can simply be de-allocated.
6993 	 * We must first merge the two dependency lists to get rid of
6994 	 * any duplicate freefrag structures, then purge the merged list.
6995 	 * If we still have a bitmap dependency, then the inode has never
6996 	 * been written to disk, so we can free any fragments without delay.
6997 	 */
6998 	if (flags & IO_NORMAL) {
6999 		merge_inode_lists(&inodedep->id_newinoupdt,
7000 		    &inodedep->id_inoupdt);
7001 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7002 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7003 			    freeblks);
7004 	}
7005 	if (flags & IO_EXT) {
7006 		merge_inode_lists(&inodedep->id_newextupdt,
7007 		    &inodedep->id_extupdt);
7008 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7009 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7010 			    freeblks);
7011 	}
7012 	FREE_LOCK(ump);
7013 	bdwrite(bp);
7014 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7015 	ACQUIRE_LOCK(ump);
7016 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7017 		(void) free_inodedep(inodedep);
7018 	freeblks->fb_state |= DEPCOMPLETE;
7019 	/*
7020 	 * If the inode with zeroed block pointers is now on disk
7021 	 * we can start freeing blocks.
7022 	 */
7023 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7024 		freeblks->fb_state |= INPROGRESS;
7025 	else
7026 		freeblks = NULL;
7027 	FREE_LOCK(ump);
7028 	if (freeblks)
7029 		handle_workitem_freeblocks(freeblks, 0);
7030 	trunc_pages(ip, length, extblocks, flags);
7031 }
7032 
7033 /*
7034  * Eliminate pages from the page cache that back parts of this inode and
7035  * adjust the vnode pager's idea of our size.  This prevents stale data
7036  * from hanging around in the page cache.
7037  */
7038 static void
7039 trunc_pages(ip, length, extblocks, flags)
7040 	struct inode *ip;
7041 	off_t length;
7042 	ufs2_daddr_t extblocks;
7043 	int flags;
7044 {
7045 	struct vnode *vp;
7046 	struct fs *fs;
7047 	ufs_lbn_t lbn;
7048 	off_t end, extend;
7049 
7050 	vp = ITOV(ip);
7051 	fs = ITOFS(ip);
7052 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7053 	if ((flags & IO_EXT) != 0)
7054 		vn_pages_remove(vp, extend, 0);
7055 	if ((flags & IO_NORMAL) == 0)
7056 		return;
7057 	BO_LOCK(&vp->v_bufobj);
7058 	drain_output(vp);
7059 	BO_UNLOCK(&vp->v_bufobj);
7060 	/*
7061 	 * The vnode pager eliminates file pages we eliminate indirects
7062 	 * below.
7063 	 */
7064 	vnode_pager_setsize(vp, length);
7065 	/*
7066 	 * Calculate the end based on the last indirect we want to keep.  If
7067 	 * the block extends into indirects we can just use the negative of
7068 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7069 	 * be careful not to remove those, if they exist.  double and triple
7070 	 * indirect lbns do not overlap with others so it is not important
7071 	 * to verify how many levels are required.
7072 	 */
7073 	lbn = lblkno(fs, length);
7074 	if (lbn >= UFS_NDADDR) {
7075 		/* Calculate the virtual lbn of the triple indirect. */
7076 		lbn = -lbn - (UFS_NIADDR - 1);
7077 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7078 	} else
7079 		end = extend;
7080 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7081 }
7082 
7083 /*
7084  * See if the buf bp is in the range eliminated by truncation.
7085  */
7086 static int
7087 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7088 	struct buf *bp;
7089 	int *blkoffp;
7090 	ufs_lbn_t lastlbn;
7091 	int lastoff;
7092 	int flags;
7093 {
7094 	ufs_lbn_t lbn;
7095 
7096 	*blkoffp = 0;
7097 	/* Only match ext/normal blocks as appropriate. */
7098 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7099 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7100 		return (0);
7101 	/* ALTDATA is always a full truncation. */
7102 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7103 		return (1);
7104 	/* -1 is full truncation. */
7105 	if (lastlbn == -1)
7106 		return (1);
7107 	/*
7108 	 * If this is a partial truncate we only want those
7109 	 * blocks and indirect blocks that cover the range
7110 	 * we're after.
7111 	 */
7112 	lbn = bp->b_lblkno;
7113 	if (lbn < 0)
7114 		lbn = -(lbn + lbn_level(lbn));
7115 	if (lbn < lastlbn)
7116 		return (0);
7117 	/* Here we only truncate lblkno if it's partial. */
7118 	if (lbn == lastlbn) {
7119 		if (lastoff == 0)
7120 			return (0);
7121 		*blkoffp = lastoff;
7122 	}
7123 	return (1);
7124 }
7125 
7126 /*
7127  * Eliminate any dependencies that exist in memory beyond lblkno:off
7128  */
7129 static void
7130 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7131 	struct inode *ip;
7132 	struct freeblks *freeblks;
7133 	ufs_lbn_t lastlbn;
7134 	int lastoff;
7135 	int flags;
7136 {
7137 	struct bufobj *bo;
7138 	struct vnode *vp;
7139 	struct buf *bp;
7140 	int blkoff;
7141 
7142 	/*
7143 	 * We must wait for any I/O in progress to finish so that
7144 	 * all potential buffers on the dirty list will be visible.
7145 	 * Once they are all there, walk the list and get rid of
7146 	 * any dependencies.
7147 	 */
7148 	vp = ITOV(ip);
7149 	bo = &vp->v_bufobj;
7150 	BO_LOCK(bo);
7151 	drain_output(vp);
7152 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7153 		bp->b_vflags &= ~BV_SCANNED;
7154 restart:
7155 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7156 		if (bp->b_vflags & BV_SCANNED)
7157 			continue;
7158 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7159 			bp->b_vflags |= BV_SCANNED;
7160 			continue;
7161 		}
7162 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7163 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7164 			goto restart;
7165 		BO_UNLOCK(bo);
7166 		if (deallocate_dependencies(bp, freeblks, blkoff))
7167 			bqrelse(bp);
7168 		else
7169 			brelse(bp);
7170 		BO_LOCK(bo);
7171 		goto restart;
7172 	}
7173 	/*
7174 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7175 	 */
7176 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7177 		bp->b_vflags &= ~BV_SCANNED;
7178 cleanrestart:
7179 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7180 		if (bp->b_vflags & BV_SCANNED)
7181 			continue;
7182 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7183 			bp->b_vflags |= BV_SCANNED;
7184 			continue;
7185 		}
7186 		if (BUF_LOCK(bp,
7187 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7188 		    BO_LOCKPTR(bo)) == ENOLCK) {
7189 			BO_LOCK(bo);
7190 			goto cleanrestart;
7191 		}
7192 		bp->b_vflags |= BV_SCANNED;
7193 		bremfree(bp);
7194 		if (blkoff != 0) {
7195 			allocbuf(bp, blkoff);
7196 			bqrelse(bp);
7197 		} else {
7198 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7199 			brelse(bp);
7200 		}
7201 		BO_LOCK(bo);
7202 		goto cleanrestart;
7203 	}
7204 	drain_output(vp);
7205 	BO_UNLOCK(bo);
7206 }
7207 
7208 static int
7209 cancel_pagedep(pagedep, freeblks, blkoff)
7210 	struct pagedep *pagedep;
7211 	struct freeblks *freeblks;
7212 	int blkoff;
7213 {
7214 	struct jremref *jremref;
7215 	struct jmvref *jmvref;
7216 	struct dirrem *dirrem, *tmp;
7217 	int i;
7218 
7219 	/*
7220 	 * Copy any directory remove dependencies to the list
7221 	 * to be processed after the freeblks proceeds.  If
7222 	 * directory entry never made it to disk they
7223 	 * can be dumped directly onto the work list.
7224 	 */
7225 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7226 		/* Skip this directory removal if it is intended to remain. */
7227 		if (dirrem->dm_offset < blkoff)
7228 			continue;
7229 		/*
7230 		 * If there are any dirrems we wait for the journal write
7231 		 * to complete and then restart the buf scan as the lock
7232 		 * has been dropped.
7233 		 */
7234 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7235 			jwait(&jremref->jr_list, MNT_WAIT);
7236 			return (ERESTART);
7237 		}
7238 		LIST_REMOVE(dirrem, dm_next);
7239 		dirrem->dm_dirinum = pagedep->pd_ino;
7240 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7241 	}
7242 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7243 		jwait(&jmvref->jm_list, MNT_WAIT);
7244 		return (ERESTART);
7245 	}
7246 	/*
7247 	 * When we're partially truncating a pagedep we just want to flush
7248 	 * journal entries and return.  There can not be any adds in the
7249 	 * truncated portion of the directory and newblk must remain if
7250 	 * part of the block remains.
7251 	 */
7252 	if (blkoff != 0) {
7253 		struct diradd *dap;
7254 
7255 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7256 			if (dap->da_offset > blkoff)
7257 				panic("cancel_pagedep: diradd %p off %d > %d",
7258 				    dap, dap->da_offset, blkoff);
7259 		for (i = 0; i < DAHASHSZ; i++)
7260 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7261 				if (dap->da_offset > blkoff)
7262 					panic("cancel_pagedep: diradd %p off %d > %d",
7263 					    dap, dap->da_offset, blkoff);
7264 		return (0);
7265 	}
7266 	/*
7267 	 * There should be no directory add dependencies present
7268 	 * as the directory could not be truncated until all
7269 	 * children were removed.
7270 	 */
7271 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7272 	    ("deallocate_dependencies: pendinghd != NULL"));
7273 	for (i = 0; i < DAHASHSZ; i++)
7274 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7275 		    ("deallocate_dependencies: diraddhd != NULL"));
7276 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7277 		free_newdirblk(pagedep->pd_newdirblk);
7278 	if (free_pagedep(pagedep) == 0)
7279 		panic("Failed to free pagedep %p", pagedep);
7280 	return (0);
7281 }
7282 
7283 /*
7284  * Reclaim any dependency structures from a buffer that is about to
7285  * be reallocated to a new vnode. The buffer must be locked, thus,
7286  * no I/O completion operations can occur while we are manipulating
7287  * its associated dependencies. The mutex is held so that other I/O's
7288  * associated with related dependencies do not occur.
7289  */
7290 static int
7291 deallocate_dependencies(bp, freeblks, off)
7292 	struct buf *bp;
7293 	struct freeblks *freeblks;
7294 	int off;
7295 {
7296 	struct indirdep *indirdep;
7297 	struct pagedep *pagedep;
7298 	struct worklist *wk, *wkn;
7299 	struct ufsmount *ump;
7300 
7301 	ump = softdep_bp_to_mp(bp);
7302 	if (ump == NULL)
7303 		goto done;
7304 	ACQUIRE_LOCK(ump);
7305 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7306 		switch (wk->wk_type) {
7307 		case D_INDIRDEP:
7308 			indirdep = WK_INDIRDEP(wk);
7309 			if (bp->b_lblkno >= 0 ||
7310 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7311 				panic("deallocate_dependencies: not indir");
7312 			cancel_indirdep(indirdep, bp, freeblks);
7313 			continue;
7314 
7315 		case D_PAGEDEP:
7316 			pagedep = WK_PAGEDEP(wk);
7317 			if (cancel_pagedep(pagedep, freeblks, off)) {
7318 				FREE_LOCK(ump);
7319 				return (ERESTART);
7320 			}
7321 			continue;
7322 
7323 		case D_ALLOCINDIR:
7324 			/*
7325 			 * Simply remove the allocindir, we'll find it via
7326 			 * the indirdep where we can clear pointers if
7327 			 * needed.
7328 			 */
7329 			WORKLIST_REMOVE(wk);
7330 			continue;
7331 
7332 		case D_FREEWORK:
7333 			/*
7334 			 * A truncation is waiting for the zero'd pointers
7335 			 * to be written.  It can be freed when the freeblks
7336 			 * is journaled.
7337 			 */
7338 			WORKLIST_REMOVE(wk);
7339 			wk->wk_state |= ONDEPLIST;
7340 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7341 			break;
7342 
7343 		case D_ALLOCDIRECT:
7344 			if (off != 0)
7345 				continue;
7346 			/* FALLTHROUGH */
7347 		default:
7348 			panic("deallocate_dependencies: Unexpected type %s",
7349 			    TYPENAME(wk->wk_type));
7350 			/* NOTREACHED */
7351 		}
7352 	}
7353 	FREE_LOCK(ump);
7354 done:
7355 	/*
7356 	 * Don't throw away this buf, we were partially truncating and
7357 	 * some deps may always remain.
7358 	 */
7359 	if (off) {
7360 		allocbuf(bp, off);
7361 		bp->b_vflags |= BV_SCANNED;
7362 		return (EBUSY);
7363 	}
7364 	bp->b_flags |= B_INVAL | B_NOCACHE;
7365 
7366 	return (0);
7367 }
7368 
7369 /*
7370  * An allocdirect is being canceled due to a truncate.  We must make sure
7371  * the journal entry is released in concert with the blkfree that releases
7372  * the storage.  Completed journal entries must not be released until the
7373  * space is no longer pointed to by the inode or in the bitmap.
7374  */
7375 static void
7376 cancel_allocdirect(adphead, adp, freeblks)
7377 	struct allocdirectlst *adphead;
7378 	struct allocdirect *adp;
7379 	struct freeblks *freeblks;
7380 {
7381 	struct freework *freework;
7382 	struct newblk *newblk;
7383 	struct worklist *wk;
7384 
7385 	TAILQ_REMOVE(adphead, adp, ad_next);
7386 	newblk = (struct newblk *)adp;
7387 	freework = NULL;
7388 	/*
7389 	 * Find the correct freework structure.
7390 	 */
7391 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7392 		if (wk->wk_type != D_FREEWORK)
7393 			continue;
7394 		freework = WK_FREEWORK(wk);
7395 		if (freework->fw_blkno == newblk->nb_newblkno)
7396 			break;
7397 	}
7398 	if (freework == NULL)
7399 		panic("cancel_allocdirect: Freework not found");
7400 	/*
7401 	 * If a newblk exists at all we still have the journal entry that
7402 	 * initiated the allocation so we do not need to journal the free.
7403 	 */
7404 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7405 	/*
7406 	 * If the journal hasn't been written the jnewblk must be passed
7407 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7408 	 * this by linking the journal dependency into the freework to be
7409 	 * freed when freework_freeblock() is called.  If the journal has
7410 	 * been written we can simply reclaim the journal space when the
7411 	 * freeblks work is complete.
7412 	 */
7413 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7414 	    &freeblks->fb_jwork);
7415 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7416 }
7417 
7418 
7419 /*
7420  * Cancel a new block allocation.  May be an indirect or direct block.  We
7421  * remove it from various lists and return any journal record that needs to
7422  * be resolved by the caller.
7423  *
7424  * A special consideration is made for indirects which were never pointed
7425  * at on disk and will never be found once this block is released.
7426  */
7427 static struct jnewblk *
7428 cancel_newblk(newblk, wk, wkhd)
7429 	struct newblk *newblk;
7430 	struct worklist *wk;
7431 	struct workhead *wkhd;
7432 {
7433 	struct jnewblk *jnewblk;
7434 
7435 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7436 
7437 	newblk->nb_state |= GOINGAWAY;
7438 	/*
7439 	 * Previously we traversed the completedhd on each indirdep
7440 	 * attached to this newblk to cancel them and gather journal
7441 	 * work.  Since we need only the oldest journal segment and
7442 	 * the lowest point on the tree will always have the oldest
7443 	 * journal segment we are free to release the segments
7444 	 * of any subordinates and may leave the indirdep list to
7445 	 * indirdep_complete() when this newblk is freed.
7446 	 */
7447 	if (newblk->nb_state & ONDEPLIST) {
7448 		newblk->nb_state &= ~ONDEPLIST;
7449 		LIST_REMOVE(newblk, nb_deps);
7450 	}
7451 	if (newblk->nb_state & ONWORKLIST)
7452 		WORKLIST_REMOVE(&newblk->nb_list);
7453 	/*
7454 	 * If the journal entry hasn't been written we save a pointer to
7455 	 * the dependency that frees it until it is written or the
7456 	 * superseding operation completes.
7457 	 */
7458 	jnewblk = newblk->nb_jnewblk;
7459 	if (jnewblk != NULL && wk != NULL) {
7460 		newblk->nb_jnewblk = NULL;
7461 		jnewblk->jn_dep = wk;
7462 	}
7463 	if (!LIST_EMPTY(&newblk->nb_jwork))
7464 		jwork_move(wkhd, &newblk->nb_jwork);
7465 	/*
7466 	 * When truncating we must free the newdirblk early to remove
7467 	 * the pagedep from the hash before returning.
7468 	 */
7469 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7470 		free_newdirblk(WK_NEWDIRBLK(wk));
7471 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7472 		panic("cancel_newblk: extra newdirblk");
7473 
7474 	return (jnewblk);
7475 }
7476 
7477 /*
7478  * Schedule the freefrag associated with a newblk to be released once
7479  * the pointers are written and the previous block is no longer needed.
7480  */
7481 static void
7482 newblk_freefrag(newblk)
7483 	struct newblk *newblk;
7484 {
7485 	struct freefrag *freefrag;
7486 
7487 	if (newblk->nb_freefrag == NULL)
7488 		return;
7489 	freefrag = newblk->nb_freefrag;
7490 	newblk->nb_freefrag = NULL;
7491 	freefrag->ff_state |= COMPLETE;
7492 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7493 		add_to_worklist(&freefrag->ff_list, 0);
7494 }
7495 
7496 /*
7497  * Free a newblk. Generate a new freefrag work request if appropriate.
7498  * This must be called after the inode pointer and any direct block pointers
7499  * are valid or fully removed via truncate or frag extension.
7500  */
7501 static void
7502 free_newblk(newblk)
7503 	struct newblk *newblk;
7504 {
7505 	struct indirdep *indirdep;
7506 	struct worklist *wk;
7507 
7508 	KASSERT(newblk->nb_jnewblk == NULL,
7509 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7510 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7511 	    ("free_newblk: unclaimed newblk"));
7512 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7513 	newblk_freefrag(newblk);
7514 	if (newblk->nb_state & ONDEPLIST)
7515 		LIST_REMOVE(newblk, nb_deps);
7516 	if (newblk->nb_state & ONWORKLIST)
7517 		WORKLIST_REMOVE(&newblk->nb_list);
7518 	LIST_REMOVE(newblk, nb_hash);
7519 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7520 		free_newdirblk(WK_NEWDIRBLK(wk));
7521 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7522 		panic("free_newblk: extra newdirblk");
7523 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7524 		indirdep_complete(indirdep);
7525 	handle_jwork(&newblk->nb_jwork);
7526 	WORKITEM_FREE(newblk, D_NEWBLK);
7527 }
7528 
7529 /*
7530  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7531  */
7532 static void
7533 free_newdirblk(newdirblk)
7534 	struct newdirblk *newdirblk;
7535 {
7536 	struct pagedep *pagedep;
7537 	struct diradd *dap;
7538 	struct worklist *wk;
7539 
7540 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7541 	WORKLIST_REMOVE(&newdirblk->db_list);
7542 	/*
7543 	 * If the pagedep is still linked onto the directory buffer
7544 	 * dependency chain, then some of the entries on the
7545 	 * pd_pendinghd list may not be committed to disk yet. In
7546 	 * this case, we will simply clear the NEWBLOCK flag and
7547 	 * let the pd_pendinghd list be processed when the pagedep
7548 	 * is next written. If the pagedep is no longer on the buffer
7549 	 * dependency chain, then all the entries on the pd_pending
7550 	 * list are committed to disk and we can free them here.
7551 	 */
7552 	pagedep = newdirblk->db_pagedep;
7553 	pagedep->pd_state &= ~NEWBLOCK;
7554 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7555 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7556 			free_diradd(dap, NULL);
7557 		/*
7558 		 * If no dependencies remain, the pagedep will be freed.
7559 		 */
7560 		free_pagedep(pagedep);
7561 	}
7562 	/* Should only ever be one item in the list. */
7563 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7564 		WORKLIST_REMOVE(wk);
7565 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7566 	}
7567 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7568 }
7569 
7570 /*
7571  * Prepare an inode to be freed. The actual free operation is not
7572  * done until the zero'ed inode has been written to disk.
7573  */
7574 void
7575 softdep_freefile(pvp, ino, mode)
7576 	struct vnode *pvp;
7577 	ino_t ino;
7578 	int mode;
7579 {
7580 	struct inode *ip = VTOI(pvp);
7581 	struct inodedep *inodedep;
7582 	struct freefile *freefile;
7583 	struct freeblks *freeblks;
7584 	struct ufsmount *ump;
7585 
7586 	ump = ITOUMP(ip);
7587 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7588 	    ("softdep_freefile called on non-softdep filesystem"));
7589 	/*
7590 	 * This sets up the inode de-allocation dependency.
7591 	 */
7592 	freefile = malloc(sizeof(struct freefile),
7593 		M_FREEFILE, M_SOFTDEP_FLAGS);
7594 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7595 	freefile->fx_mode = mode;
7596 	freefile->fx_oldinum = ino;
7597 	freefile->fx_devvp = ump->um_devvp;
7598 	LIST_INIT(&freefile->fx_jwork);
7599 	UFS_LOCK(ump);
7600 	ump->um_fs->fs_pendinginodes += 1;
7601 	UFS_UNLOCK(ump);
7602 
7603 	/*
7604 	 * If the inodedep does not exist, then the zero'ed inode has
7605 	 * been written to disk. If the allocated inode has never been
7606 	 * written to disk, then the on-disk inode is zero'ed. In either
7607 	 * case we can free the file immediately.  If the journal was
7608 	 * canceled before being written the inode will never make it to
7609 	 * disk and we must send the canceled journal entrys to
7610 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7611 	 * Any blocks waiting on the inode to write can be safely freed
7612 	 * here as it will never been written.
7613 	 */
7614 	ACQUIRE_LOCK(ump);
7615 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7616 	if (inodedep) {
7617 		/*
7618 		 * Clear out freeblks that no longer need to reference
7619 		 * this inode.
7620 		 */
7621 		while ((freeblks =
7622 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7623 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7624 			    fb_next);
7625 			freeblks->fb_state &= ~ONDEPLIST;
7626 		}
7627 		/*
7628 		 * Remove this inode from the unlinked list.
7629 		 */
7630 		if (inodedep->id_state & UNLINKED) {
7631 			/*
7632 			 * Save the journal work to be freed with the bitmap
7633 			 * before we clear UNLINKED.  Otherwise it can be lost
7634 			 * if the inode block is written.
7635 			 */
7636 			handle_bufwait(inodedep, &freefile->fx_jwork);
7637 			clear_unlinked_inodedep(inodedep);
7638 			/*
7639 			 * Re-acquire inodedep as we've dropped the
7640 			 * per-filesystem lock in clear_unlinked_inodedep().
7641 			 */
7642 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7643 		}
7644 	}
7645 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7646 		FREE_LOCK(ump);
7647 		handle_workitem_freefile(freefile);
7648 		return;
7649 	}
7650 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7651 		inodedep->id_state |= GOINGAWAY;
7652 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7653 	FREE_LOCK(ump);
7654 	if (ip->i_number == ino)
7655 		ip->i_flag |= IN_MODIFIED;
7656 }
7657 
7658 /*
7659  * Check to see if an inode has never been written to disk. If
7660  * so free the inodedep and return success, otherwise return failure.
7661  *
7662  * If we still have a bitmap dependency, then the inode has never
7663  * been written to disk. Drop the dependency as it is no longer
7664  * necessary since the inode is being deallocated. We set the
7665  * ALLCOMPLETE flags since the bitmap now properly shows that the
7666  * inode is not allocated. Even if the inode is actively being
7667  * written, it has been rolled back to its zero'ed state, so we
7668  * are ensured that a zero inode is what is on the disk. For short
7669  * lived files, this change will usually result in removing all the
7670  * dependencies from the inode so that it can be freed immediately.
7671  */
7672 static int
7673 check_inode_unwritten(inodedep)
7674 	struct inodedep *inodedep;
7675 {
7676 
7677 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7678 
7679 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7680 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7681 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7682 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7683 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7684 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7685 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7686 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7687 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7688 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7689 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7690 	    inodedep->id_mkdiradd != NULL ||
7691 	    inodedep->id_nlinkdelta != 0)
7692 		return (0);
7693 	/*
7694 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7695 	 * trying to allocate memory without holding "Softdep Lock".
7696 	 */
7697 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7698 	    inodedep->id_savedino1 == NULL)
7699 		return (0);
7700 
7701 	if (inodedep->id_state & ONDEPLIST)
7702 		LIST_REMOVE(inodedep, id_deps);
7703 	inodedep->id_state &= ~ONDEPLIST;
7704 	inodedep->id_state |= ALLCOMPLETE;
7705 	inodedep->id_bmsafemap = NULL;
7706 	if (inodedep->id_state & ONWORKLIST)
7707 		WORKLIST_REMOVE(&inodedep->id_list);
7708 	if (inodedep->id_savedino1 != NULL) {
7709 		free(inodedep->id_savedino1, M_SAVEDINO);
7710 		inodedep->id_savedino1 = NULL;
7711 	}
7712 	if (free_inodedep(inodedep) == 0)
7713 		panic("check_inode_unwritten: busy inode");
7714 	return (1);
7715 }
7716 
7717 static int
7718 check_inodedep_free(inodedep)
7719 	struct inodedep *inodedep;
7720 {
7721 
7722 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7723 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7724 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7725 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7726 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7727 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7728 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7729 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7730 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7731 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7732 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7733 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7734 	    inodedep->id_mkdiradd != NULL ||
7735 	    inodedep->id_nlinkdelta != 0 ||
7736 	    inodedep->id_savedino1 != NULL)
7737 		return (0);
7738 	return (1);
7739 }
7740 
7741 /*
7742  * Try to free an inodedep structure. Return 1 if it could be freed.
7743  */
7744 static int
7745 free_inodedep(inodedep)
7746 	struct inodedep *inodedep;
7747 {
7748 
7749 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7750 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7751 	    !check_inodedep_free(inodedep))
7752 		return (0);
7753 	if (inodedep->id_state & ONDEPLIST)
7754 		LIST_REMOVE(inodedep, id_deps);
7755 	LIST_REMOVE(inodedep, id_hash);
7756 	WORKITEM_FREE(inodedep, D_INODEDEP);
7757 	return (1);
7758 }
7759 
7760 /*
7761  * Free the block referenced by a freework structure.  The parent freeblks
7762  * structure is released and completed when the final cg bitmap reaches
7763  * the disk.  This routine may be freeing a jnewblk which never made it to
7764  * disk in which case we do not have to wait as the operation is undone
7765  * in memory immediately.
7766  */
7767 static void
7768 freework_freeblock(freework, key)
7769 	struct freework *freework;
7770 	u_long key;
7771 {
7772 	struct freeblks *freeblks;
7773 	struct jnewblk *jnewblk;
7774 	struct ufsmount *ump;
7775 	struct workhead wkhd;
7776 	struct fs *fs;
7777 	int bsize;
7778 	int needj;
7779 
7780 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7781 	LOCK_OWNED(ump);
7782 	/*
7783 	 * Handle partial truncate separately.
7784 	 */
7785 	if (freework->fw_indir) {
7786 		complete_trunc_indir(freework);
7787 		return;
7788 	}
7789 	freeblks = freework->fw_freeblks;
7790 	fs = ump->um_fs;
7791 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7792 	bsize = lfragtosize(fs, freework->fw_frags);
7793 	LIST_INIT(&wkhd);
7794 	/*
7795 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7796 	 * on the indirblk hashtable and prevents premature freeing.
7797 	 */
7798 	freework->fw_state |= DEPCOMPLETE;
7799 	/*
7800 	 * SUJ needs to wait for the segment referencing freed indirect
7801 	 * blocks to expire so that we know the checker will not confuse
7802 	 * a re-allocated indirect block with its old contents.
7803 	 */
7804 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7805 		indirblk_insert(freework);
7806 	/*
7807 	 * If we are canceling an existing jnewblk pass it to the free
7808 	 * routine, otherwise pass the freeblk which will ultimately
7809 	 * release the freeblks.  If we're not journaling, we can just
7810 	 * free the freeblks immediately.
7811 	 */
7812 	jnewblk = freework->fw_jnewblk;
7813 	if (jnewblk != NULL) {
7814 		cancel_jnewblk(jnewblk, &wkhd);
7815 		needj = 0;
7816 	} else if (needj) {
7817 		freework->fw_state |= DELAYEDFREE;
7818 		freeblks->fb_cgwait++;
7819 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7820 	}
7821 	FREE_LOCK(ump);
7822 	freeblks_free(ump, freeblks, btodb(bsize));
7823 	CTR4(KTR_SUJ,
7824 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
7825 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7826 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7827 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
7828 	ACQUIRE_LOCK(ump);
7829 	/*
7830 	 * The jnewblk will be discarded and the bits in the map never
7831 	 * made it to disk.  We can immediately free the freeblk.
7832 	 */
7833 	if (needj == 0)
7834 		handle_written_freework(freework);
7835 }
7836 
7837 /*
7838  * We enqueue freework items that need processing back on the freeblks and
7839  * add the freeblks to the worklist.  This makes it easier to find all work
7840  * required to flush a truncation in process_truncates().
7841  */
7842 static void
7843 freework_enqueue(freework)
7844 	struct freework *freework;
7845 {
7846 	struct freeblks *freeblks;
7847 
7848 	freeblks = freework->fw_freeblks;
7849 	if ((freework->fw_state & INPROGRESS) == 0)
7850 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7851 	if ((freeblks->fb_state &
7852 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7853 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7854 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7855 }
7856 
7857 /*
7858  * Start, continue, or finish the process of freeing an indirect block tree.
7859  * The free operation may be paused at any point with fw_off containing the
7860  * offset to restart from.  This enables us to implement some flow control
7861  * for large truncates which may fan out and generate a huge number of
7862  * dependencies.
7863  */
7864 static void
7865 handle_workitem_indirblk(freework)
7866 	struct freework *freework;
7867 {
7868 	struct freeblks *freeblks;
7869 	struct ufsmount *ump;
7870 	struct fs *fs;
7871 
7872 	freeblks = freework->fw_freeblks;
7873 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7874 	fs = ump->um_fs;
7875 	if (freework->fw_state & DEPCOMPLETE) {
7876 		handle_written_freework(freework);
7877 		return;
7878 	}
7879 	if (freework->fw_off == NINDIR(fs)) {
7880 		freework_freeblock(freework, SINGLETON_KEY);
7881 		return;
7882 	}
7883 	freework->fw_state |= INPROGRESS;
7884 	FREE_LOCK(ump);
7885 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7886 	    freework->fw_lbn);
7887 	ACQUIRE_LOCK(ump);
7888 }
7889 
7890 /*
7891  * Called when a freework structure attached to a cg buf is written.  The
7892  * ref on either the parent or the freeblks structure is released and
7893  * the freeblks is added back to the worklist if there is more work to do.
7894  */
7895 static void
7896 handle_written_freework(freework)
7897 	struct freework *freework;
7898 {
7899 	struct freeblks *freeblks;
7900 	struct freework *parent;
7901 
7902 	freeblks = freework->fw_freeblks;
7903 	parent = freework->fw_parent;
7904 	if (freework->fw_state & DELAYEDFREE)
7905 		freeblks->fb_cgwait--;
7906 	freework->fw_state |= COMPLETE;
7907 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7908 		WORKITEM_FREE(freework, D_FREEWORK);
7909 	if (parent) {
7910 		if (--parent->fw_ref == 0)
7911 			freework_enqueue(parent);
7912 		return;
7913 	}
7914 	if (--freeblks->fb_ref != 0)
7915 		return;
7916 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7917 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7918 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7919 }
7920 
7921 /*
7922  * This workitem routine performs the block de-allocation.
7923  * The workitem is added to the pending list after the updated
7924  * inode block has been written to disk.  As mentioned above,
7925  * checks regarding the number of blocks de-allocated (compared
7926  * to the number of blocks allocated for the file) are also
7927  * performed in this function.
7928  */
7929 static int
7930 handle_workitem_freeblocks(freeblks, flags)
7931 	struct freeblks *freeblks;
7932 	int flags;
7933 {
7934 	struct freework *freework;
7935 	struct newblk *newblk;
7936 	struct allocindir *aip;
7937 	struct ufsmount *ump;
7938 	struct worklist *wk;
7939 	u_long key;
7940 
7941 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7942 	    ("handle_workitem_freeblocks: Journal entries not written."));
7943 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7944 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
7945 	ACQUIRE_LOCK(ump);
7946 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7947 		WORKLIST_REMOVE(wk);
7948 		switch (wk->wk_type) {
7949 		case D_DIRREM:
7950 			wk->wk_state |= COMPLETE;
7951 			add_to_worklist(wk, 0);
7952 			continue;
7953 
7954 		case D_ALLOCDIRECT:
7955 			free_newblk(WK_NEWBLK(wk));
7956 			continue;
7957 
7958 		case D_ALLOCINDIR:
7959 			aip = WK_ALLOCINDIR(wk);
7960 			freework = NULL;
7961 			if (aip->ai_state & DELAYEDFREE) {
7962 				FREE_LOCK(ump);
7963 				freework = newfreework(ump, freeblks, NULL,
7964 				    aip->ai_lbn, aip->ai_newblkno,
7965 				    ump->um_fs->fs_frag, 0, 0);
7966 				ACQUIRE_LOCK(ump);
7967 			}
7968 			newblk = WK_NEWBLK(wk);
7969 			if (newblk->nb_jnewblk) {
7970 				freework->fw_jnewblk = newblk->nb_jnewblk;
7971 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7972 				newblk->nb_jnewblk = NULL;
7973 			}
7974 			free_newblk(newblk);
7975 			continue;
7976 
7977 		case D_FREEWORK:
7978 			freework = WK_FREEWORK(wk);
7979 			if (freework->fw_lbn <= -UFS_NDADDR)
7980 				handle_workitem_indirblk(freework);
7981 			else
7982 				freework_freeblock(freework, key);
7983 			continue;
7984 		default:
7985 			panic("handle_workitem_freeblocks: Unknown type %s",
7986 			    TYPENAME(wk->wk_type));
7987 		}
7988 	}
7989 	if (freeblks->fb_ref != 0) {
7990 		freeblks->fb_state &= ~INPROGRESS;
7991 		wake_worklist(&freeblks->fb_list);
7992 		freeblks = NULL;
7993 	}
7994 	FREE_LOCK(ump);
7995 	ffs_blkrelease_finish(ump, key);
7996 	if (freeblks)
7997 		return handle_complete_freeblocks(freeblks, flags);
7998 	return (0);
7999 }
8000 
8001 /*
8002  * Handle completion of block free via truncate.  This allows fs_pending
8003  * to track the actual free block count more closely than if we only updated
8004  * it at the end.  We must be careful to handle cases where the block count
8005  * on free was incorrect.
8006  */
8007 static void
8008 freeblks_free(ump, freeblks, blocks)
8009 	struct ufsmount *ump;
8010 	struct freeblks *freeblks;
8011 	int blocks;
8012 {
8013 	struct fs *fs;
8014 	ufs2_daddr_t remain;
8015 
8016 	UFS_LOCK(ump);
8017 	remain = -freeblks->fb_chkcnt;
8018 	freeblks->fb_chkcnt += blocks;
8019 	if (remain > 0) {
8020 		if (remain < blocks)
8021 			blocks = remain;
8022 		fs = ump->um_fs;
8023 		fs->fs_pendingblocks -= blocks;
8024 	}
8025 	UFS_UNLOCK(ump);
8026 }
8027 
8028 /*
8029  * Once all of the freework workitems are complete we can retire the
8030  * freeblocks dependency and any journal work awaiting completion.  This
8031  * can not be called until all other dependencies are stable on disk.
8032  */
8033 static int
8034 handle_complete_freeblocks(freeblks, flags)
8035 	struct freeblks *freeblks;
8036 	int flags;
8037 {
8038 	struct inodedep *inodedep;
8039 	struct inode *ip;
8040 	struct vnode *vp;
8041 	struct fs *fs;
8042 	struct ufsmount *ump;
8043 	ufs2_daddr_t spare;
8044 
8045 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8046 	fs = ump->um_fs;
8047 	flags = LK_EXCLUSIVE | flags;
8048 	spare = freeblks->fb_chkcnt;
8049 
8050 	/*
8051 	 * If we did not release the expected number of blocks we may have
8052 	 * to adjust the inode block count here.  Only do so if it wasn't
8053 	 * a truncation to zero and the modrev still matches.
8054 	 */
8055 	if (spare && freeblks->fb_len != 0) {
8056 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8057 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8058 			return (EBUSY);
8059 		ip = VTOI(vp);
8060 		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8061 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8062 			ip->i_flag |= IN_CHANGE;
8063 			/*
8064 			 * We must wait so this happens before the
8065 			 * journal is reclaimed.
8066 			 */
8067 			ffs_update(vp, 1);
8068 		}
8069 		vput(vp);
8070 	}
8071 	if (spare < 0) {
8072 		UFS_LOCK(ump);
8073 		fs->fs_pendingblocks += spare;
8074 		UFS_UNLOCK(ump);
8075 	}
8076 #ifdef QUOTA
8077 	/* Handle spare. */
8078 	if (spare)
8079 		quotaadj(freeblks->fb_quota, ump, -spare);
8080 	quotarele(freeblks->fb_quota);
8081 #endif
8082 	ACQUIRE_LOCK(ump);
8083 	if (freeblks->fb_state & ONDEPLIST) {
8084 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8085 		    0, &inodedep);
8086 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8087 		freeblks->fb_state &= ~ONDEPLIST;
8088 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8089 			free_inodedep(inodedep);
8090 	}
8091 	/*
8092 	 * All of the freeblock deps must be complete prior to this call
8093 	 * so it's now safe to complete earlier outstanding journal entries.
8094 	 */
8095 	handle_jwork(&freeblks->fb_jwork);
8096 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8097 	FREE_LOCK(ump);
8098 	return (0);
8099 }
8100 
8101 /*
8102  * Release blocks associated with the freeblks and stored in the indirect
8103  * block dbn. If level is greater than SINGLE, the block is an indirect block
8104  * and recursive calls to indirtrunc must be used to cleanse other indirect
8105  * blocks.
8106  *
8107  * This handles partial and complete truncation of blocks.  Partial is noted
8108  * with goingaway == 0.  In this case the freework is completed after the
8109  * zero'd indirects are written to disk.  For full truncation the freework
8110  * is completed after the block is freed.
8111  */
8112 static void
8113 indir_trunc(freework, dbn, lbn)
8114 	struct freework *freework;
8115 	ufs2_daddr_t dbn;
8116 	ufs_lbn_t lbn;
8117 {
8118 	struct freework *nfreework;
8119 	struct workhead wkhd;
8120 	struct freeblks *freeblks;
8121 	struct buf *bp;
8122 	struct fs *fs;
8123 	struct indirdep *indirdep;
8124 	struct mount *mp;
8125 	struct ufsmount *ump;
8126 	ufs1_daddr_t *bap1;
8127 	ufs2_daddr_t nb, nnb, *bap2;
8128 	ufs_lbn_t lbnadd, nlbn;
8129 	u_long key;
8130 	int nblocks, ufs1fmt, freedblocks;
8131 	int goingaway, freedeps, needj, level, cnt, i;
8132 
8133 	freeblks = freework->fw_freeblks;
8134 	mp = freeblks->fb_list.wk_mp;
8135 	ump = VFSTOUFS(mp);
8136 	fs = ump->um_fs;
8137 	/*
8138 	 * Get buffer of block pointers to be freed.  There are three cases:
8139 	 *
8140 	 * 1) Partial truncate caches the indirdep pointer in the freework
8141 	 *    which provides us a back copy to the save bp which holds the
8142 	 *    pointers we want to clear.  When this completes the zero
8143 	 *    pointers are written to the real copy.
8144 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8145 	 *    eliminated the real copy and placed the indirdep on the saved
8146 	 *    copy.  The indirdep and buf are discarded when this completes.
8147 	 * 3) The indirect was not in memory, we read a copy off of the disk
8148 	 *    using the devvp and drop and invalidate the buffer when we're
8149 	 *    done.
8150 	 */
8151 	goingaway = 1;
8152 	indirdep = NULL;
8153 	if (freework->fw_indir != NULL) {
8154 		goingaway = 0;
8155 		indirdep = freework->fw_indir;
8156 		bp = indirdep->ir_savebp;
8157 		if (bp == NULL || bp->b_blkno != dbn)
8158 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8159 			    bp, (intmax_t)dbn);
8160 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8161 		/*
8162 		 * The lock prevents the buf dep list from changing and
8163 	 	 * indirects on devvp should only ever have one dependency.
8164 		 */
8165 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8166 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8167 			panic("indir_trunc: Bad indirdep %p from buf %p",
8168 			    indirdep, bp);
8169 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8170 	    NOCRED, &bp) != 0) {
8171 		brelse(bp);
8172 		return;
8173 	}
8174 	ACQUIRE_LOCK(ump);
8175 	/* Protects against a race with complete_trunc_indir(). */
8176 	freework->fw_state &= ~INPROGRESS;
8177 	/*
8178 	 * If we have an indirdep we need to enforce the truncation order
8179 	 * and discard it when it is complete.
8180 	 */
8181 	if (indirdep) {
8182 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8183 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8184 			/*
8185 			 * Add the complete truncate to the list on the
8186 			 * indirdep to enforce in-order processing.
8187 			 */
8188 			if (freework->fw_indir == NULL)
8189 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8190 				    freework, fw_next);
8191 			FREE_LOCK(ump);
8192 			return;
8193 		}
8194 		/*
8195 		 * If we're goingaway, free the indirdep.  Otherwise it will
8196 		 * linger until the write completes.
8197 		 */
8198 		if (goingaway)
8199 			free_indirdep(indirdep);
8200 	}
8201 	FREE_LOCK(ump);
8202 	/* Initialize pointers depending on block size. */
8203 	if (ump->um_fstype == UFS1) {
8204 		bap1 = (ufs1_daddr_t *)bp->b_data;
8205 		nb = bap1[freework->fw_off];
8206 		ufs1fmt = 1;
8207 		bap2 = NULL;
8208 	} else {
8209 		bap2 = (ufs2_daddr_t *)bp->b_data;
8210 		nb = bap2[freework->fw_off];
8211 		ufs1fmt = 0;
8212 		bap1 = NULL;
8213 	}
8214 	level = lbn_level(lbn);
8215 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8216 	lbnadd = lbn_offset(fs, level);
8217 	nblocks = btodb(fs->fs_bsize);
8218 	nfreework = freework;
8219 	freedeps = 0;
8220 	cnt = 0;
8221 	/*
8222 	 * Reclaim blocks.  Traverses into nested indirect levels and
8223 	 * arranges for the current level to be freed when subordinates
8224 	 * are free when journaling.
8225 	 */
8226 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8227 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8228 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8229 		    fs->fs_bsize) != 0)
8230 			nb = 0;
8231 		if (i != NINDIR(fs) - 1) {
8232 			if (ufs1fmt)
8233 				nnb = bap1[i+1];
8234 			else
8235 				nnb = bap2[i+1];
8236 		} else
8237 			nnb = 0;
8238 		if (nb == 0)
8239 			continue;
8240 		cnt++;
8241 		if (level != 0) {
8242 			nlbn = (lbn + 1) - (i * lbnadd);
8243 			if (needj != 0) {
8244 				nfreework = newfreework(ump, freeblks, freework,
8245 				    nlbn, nb, fs->fs_frag, 0, 0);
8246 				freedeps++;
8247 			}
8248 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8249 		} else {
8250 			struct freedep *freedep;
8251 
8252 			/*
8253 			 * Attempt to aggregate freedep dependencies for
8254 			 * all blocks being released to the same CG.
8255 			 */
8256 			LIST_INIT(&wkhd);
8257 			if (needj != 0 &&
8258 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8259 				freedep = newfreedep(freework);
8260 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8261 				    &freedep->fd_list);
8262 				freedeps++;
8263 			}
8264 			CTR3(KTR_SUJ,
8265 			    "indir_trunc: ino %jd blkno %jd size %d",
8266 			    freeblks->fb_inum, nb, fs->fs_bsize);
8267 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8268 			    fs->fs_bsize, freeblks->fb_inum,
8269 			    freeblks->fb_vtype, &wkhd, key);
8270 		}
8271 	}
8272 	ffs_blkrelease_finish(ump, key);
8273 	if (goingaway) {
8274 		bp->b_flags |= B_INVAL | B_NOCACHE;
8275 		brelse(bp);
8276 	}
8277 	freedblocks = 0;
8278 	if (level == 0)
8279 		freedblocks = (nblocks * cnt);
8280 	if (needj == 0)
8281 		freedblocks += nblocks;
8282 	freeblks_free(ump, freeblks, freedblocks);
8283 	/*
8284 	 * If we are journaling set up the ref counts and offset so this
8285 	 * indirect can be completed when its children are free.
8286 	 */
8287 	if (needj) {
8288 		ACQUIRE_LOCK(ump);
8289 		freework->fw_off = i;
8290 		freework->fw_ref += freedeps;
8291 		freework->fw_ref -= NINDIR(fs) + 1;
8292 		if (level == 0)
8293 			freeblks->fb_cgwait += freedeps;
8294 		if (freework->fw_ref == 0)
8295 			freework_freeblock(freework, SINGLETON_KEY);
8296 		FREE_LOCK(ump);
8297 		return;
8298 	}
8299 	/*
8300 	 * If we're not journaling we can free the indirect now.
8301 	 */
8302 	dbn = dbtofsb(fs, dbn);
8303 	CTR3(KTR_SUJ,
8304 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8305 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8306 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8307 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8308 	/* Non SUJ softdep does single-threaded truncations. */
8309 	if (freework->fw_blkno == dbn) {
8310 		freework->fw_state |= ALLCOMPLETE;
8311 		ACQUIRE_LOCK(ump);
8312 		handle_written_freework(freework);
8313 		FREE_LOCK(ump);
8314 	}
8315 	return;
8316 }
8317 
8318 /*
8319  * Cancel an allocindir when it is removed via truncation.  When bp is not
8320  * NULL the indirect never appeared on disk and is scheduled to be freed
8321  * independently of the indir so we can more easily track journal work.
8322  */
8323 static void
8324 cancel_allocindir(aip, bp, freeblks, trunc)
8325 	struct allocindir *aip;
8326 	struct buf *bp;
8327 	struct freeblks *freeblks;
8328 	int trunc;
8329 {
8330 	struct indirdep *indirdep;
8331 	struct freefrag *freefrag;
8332 	struct newblk *newblk;
8333 
8334 	newblk = (struct newblk *)aip;
8335 	LIST_REMOVE(aip, ai_next);
8336 	/*
8337 	 * We must eliminate the pointer in bp if it must be freed on its
8338 	 * own due to partial truncate or pending journal work.
8339 	 */
8340 	if (bp && (trunc || newblk->nb_jnewblk)) {
8341 		/*
8342 		 * Clear the pointer and mark the aip to be freed
8343 		 * directly if it never existed on disk.
8344 		 */
8345 		aip->ai_state |= DELAYEDFREE;
8346 		indirdep = aip->ai_indirdep;
8347 		if (indirdep->ir_state & UFS1FMT)
8348 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8349 		else
8350 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8351 	}
8352 	/*
8353 	 * When truncating the previous pointer will be freed via
8354 	 * savedbp.  Eliminate the freefrag which would dup free.
8355 	 */
8356 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8357 		newblk->nb_freefrag = NULL;
8358 		if (freefrag->ff_jdep)
8359 			cancel_jfreefrag(
8360 			    WK_JFREEFRAG(freefrag->ff_jdep));
8361 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8362 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8363 	}
8364 	/*
8365 	 * If the journal hasn't been written the jnewblk must be passed
8366 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8367 	 * this by leaving the journal dependency on the newblk to be freed
8368 	 * when a freework is created in handle_workitem_freeblocks().
8369 	 */
8370 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8371 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8372 }
8373 
8374 /*
8375  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8376  * in to a newdirblk so any subsequent additions are tracked properly.  The
8377  * caller is responsible for adding the mkdir1 dependency to the journal
8378  * and updating id_mkdiradd.  This function returns with the per-filesystem
8379  * lock held.
8380  */
8381 static struct mkdir *
8382 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8383 	struct diradd *dap;
8384 	ino_t newinum;
8385 	ino_t dinum;
8386 	struct buf *newdirbp;
8387 	struct mkdir **mkdirp;
8388 {
8389 	struct newblk *newblk;
8390 	struct pagedep *pagedep;
8391 	struct inodedep *inodedep;
8392 	struct newdirblk *newdirblk;
8393 	struct mkdir *mkdir1, *mkdir2;
8394 	struct worklist *wk;
8395 	struct jaddref *jaddref;
8396 	struct ufsmount *ump;
8397 	struct mount *mp;
8398 
8399 	mp = dap->da_list.wk_mp;
8400 	ump = VFSTOUFS(mp);
8401 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8402 	    M_SOFTDEP_FLAGS);
8403 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8404 	LIST_INIT(&newdirblk->db_mkdir);
8405 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8406 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8407 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8408 	mkdir1->md_diradd = dap;
8409 	mkdir1->md_jaddref = NULL;
8410 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8411 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8412 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8413 	mkdir2->md_diradd = dap;
8414 	mkdir2->md_jaddref = NULL;
8415 	if (MOUNTEDSUJ(mp) == 0) {
8416 		mkdir1->md_state |= DEPCOMPLETE;
8417 		mkdir2->md_state |= DEPCOMPLETE;
8418 	}
8419 	/*
8420 	 * Dependency on "." and ".." being written to disk.
8421 	 */
8422 	mkdir1->md_buf = newdirbp;
8423 	ACQUIRE_LOCK(VFSTOUFS(mp));
8424 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8425 	/*
8426 	 * We must link the pagedep, allocdirect, and newdirblk for
8427 	 * the initial file page so the pointer to the new directory
8428 	 * is not written until the directory contents are live and
8429 	 * any subsequent additions are not marked live until the
8430 	 * block is reachable via the inode.
8431 	 */
8432 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8433 		panic("setup_newdir: lost pagedep");
8434 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8435 		if (wk->wk_type == D_ALLOCDIRECT)
8436 			break;
8437 	if (wk == NULL)
8438 		panic("setup_newdir: lost allocdirect");
8439 	if (pagedep->pd_state & NEWBLOCK)
8440 		panic("setup_newdir: NEWBLOCK already set");
8441 	newblk = WK_NEWBLK(wk);
8442 	pagedep->pd_state |= NEWBLOCK;
8443 	pagedep->pd_newdirblk = newdirblk;
8444 	newdirblk->db_pagedep = pagedep;
8445 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8446 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8447 	/*
8448 	 * Look up the inodedep for the parent directory so that we
8449 	 * can link mkdir2 into the pending dotdot jaddref or
8450 	 * the inode write if there is none.  If the inode is
8451 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8452 	 * been satisfied and mkdir2 can be freed.
8453 	 */
8454 	inodedep_lookup(mp, dinum, 0, &inodedep);
8455 	if (MOUNTEDSUJ(mp)) {
8456 		if (inodedep == NULL)
8457 			panic("setup_newdir: Lost parent.");
8458 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8459 		    inoreflst);
8460 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8461 		    (jaddref->ja_state & MKDIR_PARENT),
8462 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8463 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8464 		mkdir2->md_jaddref = jaddref;
8465 		jaddref->ja_mkdir = mkdir2;
8466 	} else if (inodedep == NULL ||
8467 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8468 		dap->da_state &= ~MKDIR_PARENT;
8469 		WORKITEM_FREE(mkdir2, D_MKDIR);
8470 		mkdir2 = NULL;
8471 	} else {
8472 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8473 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8474 	}
8475 	*mkdirp = mkdir2;
8476 
8477 	return (mkdir1);
8478 }
8479 
8480 /*
8481  * Directory entry addition dependencies.
8482  *
8483  * When adding a new directory entry, the inode (with its incremented link
8484  * count) must be written to disk before the directory entry's pointer to it.
8485  * Also, if the inode is newly allocated, the corresponding freemap must be
8486  * updated (on disk) before the directory entry's pointer. These requirements
8487  * are met via undo/redo on the directory entry's pointer, which consists
8488  * simply of the inode number.
8489  *
8490  * As directory entries are added and deleted, the free space within a
8491  * directory block can become fragmented.  The ufs filesystem will compact
8492  * a fragmented directory block to make space for a new entry. When this
8493  * occurs, the offsets of previously added entries change. Any "diradd"
8494  * dependency structures corresponding to these entries must be updated with
8495  * the new offsets.
8496  */
8497 
8498 /*
8499  * This routine is called after the in-memory inode's link
8500  * count has been incremented, but before the directory entry's
8501  * pointer to the inode has been set.
8502  */
8503 int
8504 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8505 	struct buf *bp;		/* buffer containing directory block */
8506 	struct inode *dp;	/* inode for directory */
8507 	off_t diroffset;	/* offset of new entry in directory */
8508 	ino_t newinum;		/* inode referenced by new directory entry */
8509 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8510 	int isnewblk;		/* entry is in a newly allocated block */
8511 {
8512 	int offset;		/* offset of new entry within directory block */
8513 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8514 	struct fs *fs;
8515 	struct diradd *dap;
8516 	struct newblk *newblk;
8517 	struct pagedep *pagedep;
8518 	struct inodedep *inodedep;
8519 	struct newdirblk *newdirblk;
8520 	struct mkdir *mkdir1, *mkdir2;
8521 	struct jaddref *jaddref;
8522 	struct ufsmount *ump;
8523 	struct mount *mp;
8524 	int isindir;
8525 
8526 	mp = ITOVFS(dp);
8527 	ump = VFSTOUFS(mp);
8528 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8529 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8530 	/*
8531 	 * Whiteouts have no dependencies.
8532 	 */
8533 	if (newinum == UFS_WINO) {
8534 		if (newdirbp != NULL)
8535 			bdwrite(newdirbp);
8536 		return (0);
8537 	}
8538 	jaddref = NULL;
8539 	mkdir1 = mkdir2 = NULL;
8540 	fs = ump->um_fs;
8541 	lbn = lblkno(fs, diroffset);
8542 	offset = blkoff(fs, diroffset);
8543 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8544 		M_SOFTDEP_FLAGS|M_ZERO);
8545 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8546 	dap->da_offset = offset;
8547 	dap->da_newinum = newinum;
8548 	dap->da_state = ATTACHED;
8549 	LIST_INIT(&dap->da_jwork);
8550 	isindir = bp->b_lblkno >= UFS_NDADDR;
8551 	newdirblk = NULL;
8552 	if (isnewblk &&
8553 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8554 		newdirblk = malloc(sizeof(struct newdirblk),
8555 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8556 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8557 		LIST_INIT(&newdirblk->db_mkdir);
8558 	}
8559 	/*
8560 	 * If we're creating a new directory setup the dependencies and set
8561 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8562 	 * we can move on.
8563 	 */
8564 	if (newdirbp == NULL) {
8565 		dap->da_state |= DEPCOMPLETE;
8566 		ACQUIRE_LOCK(ump);
8567 	} else {
8568 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8569 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8570 		    &mkdir2);
8571 	}
8572 	/*
8573 	 * Link into parent directory pagedep to await its being written.
8574 	 */
8575 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8576 #ifdef INVARIANTS
8577 	if (diradd_lookup(pagedep, offset) != NULL)
8578 		panic("softdep_setup_directory_add: %p already at off %d\n",
8579 		    diradd_lookup(pagedep, offset), offset);
8580 #endif
8581 	dap->da_pagedep = pagedep;
8582 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8583 	    da_pdlist);
8584 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8585 	/*
8586 	 * If we're journaling, link the diradd into the jaddref so it
8587 	 * may be completed after the journal entry is written.  Otherwise,
8588 	 * link the diradd into its inodedep.  If the inode is not yet
8589 	 * written place it on the bufwait list, otherwise do the post-inode
8590 	 * write processing to put it on the id_pendinghd list.
8591 	 */
8592 	if (MOUNTEDSUJ(mp)) {
8593 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8594 		    inoreflst);
8595 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8596 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8597 		jaddref->ja_diroff = diroffset;
8598 		jaddref->ja_diradd = dap;
8599 		add_to_journal(&jaddref->ja_list);
8600 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8601 		diradd_inode_written(dap, inodedep);
8602 	else
8603 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8604 	/*
8605 	 * Add the journal entries for . and .. links now that the primary
8606 	 * link is written.
8607 	 */
8608 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8609 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8610 		    inoreflst, if_deps);
8611 		KASSERT(jaddref != NULL &&
8612 		    jaddref->ja_ino == jaddref->ja_parent &&
8613 		    (jaddref->ja_state & MKDIR_BODY),
8614 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8615 		    jaddref));
8616 		mkdir1->md_jaddref = jaddref;
8617 		jaddref->ja_mkdir = mkdir1;
8618 		/*
8619 		 * It is important that the dotdot journal entry
8620 		 * is added prior to the dot entry since dot writes
8621 		 * both the dot and dotdot links.  These both must
8622 		 * be added after the primary link for the journal
8623 		 * to remain consistent.
8624 		 */
8625 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8626 		add_to_journal(&jaddref->ja_list);
8627 	}
8628 	/*
8629 	 * If we are adding a new directory remember this diradd so that if
8630 	 * we rename it we can keep the dot and dotdot dependencies.  If
8631 	 * we are adding a new name for an inode that has a mkdiradd we
8632 	 * must be in rename and we have to move the dot and dotdot
8633 	 * dependencies to this new name.  The old name is being orphaned
8634 	 * soon.
8635 	 */
8636 	if (mkdir1 != NULL) {
8637 		if (inodedep->id_mkdiradd != NULL)
8638 			panic("softdep_setup_directory_add: Existing mkdir");
8639 		inodedep->id_mkdiradd = dap;
8640 	} else if (inodedep->id_mkdiradd)
8641 		merge_diradd(inodedep, dap);
8642 	if (newdirblk != NULL) {
8643 		/*
8644 		 * There is nothing to do if we are already tracking
8645 		 * this block.
8646 		 */
8647 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8648 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8649 			FREE_LOCK(ump);
8650 			return (0);
8651 		}
8652 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8653 		    == 0)
8654 			panic("softdep_setup_directory_add: lost entry");
8655 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8656 		pagedep->pd_state |= NEWBLOCK;
8657 		pagedep->pd_newdirblk = newdirblk;
8658 		newdirblk->db_pagedep = pagedep;
8659 		FREE_LOCK(ump);
8660 		/*
8661 		 * If we extended into an indirect signal direnter to sync.
8662 		 */
8663 		if (isindir)
8664 			return (1);
8665 		return (0);
8666 	}
8667 	FREE_LOCK(ump);
8668 	return (0);
8669 }
8670 
8671 /*
8672  * This procedure is called to change the offset of a directory
8673  * entry when compacting a directory block which must be owned
8674  * exclusively by the caller. Note that the actual entry movement
8675  * must be done in this procedure to ensure that no I/O completions
8676  * occur while the move is in progress.
8677  */
8678 void
8679 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8680 	struct buf *bp;		/* Buffer holding directory block. */
8681 	struct inode *dp;	/* inode for directory */
8682 	caddr_t base;		/* address of dp->i_offset */
8683 	caddr_t oldloc;		/* address of old directory location */
8684 	caddr_t newloc;		/* address of new directory location */
8685 	int entrysize;		/* size of directory entry */
8686 {
8687 	int offset, oldoffset, newoffset;
8688 	struct pagedep *pagedep;
8689 	struct jmvref *jmvref;
8690 	struct diradd *dap;
8691 	struct direct *de;
8692 	struct mount *mp;
8693 	struct ufsmount *ump;
8694 	ufs_lbn_t lbn;
8695 	int flags;
8696 
8697 	mp = ITOVFS(dp);
8698 	ump = VFSTOUFS(mp);
8699 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8700 	    ("softdep_change_directoryentry_offset called on "
8701 	     "non-softdep filesystem"));
8702 	de = (struct direct *)oldloc;
8703 	jmvref = NULL;
8704 	flags = 0;
8705 	/*
8706 	 * Moves are always journaled as it would be too complex to
8707 	 * determine if any affected adds or removes are present in the
8708 	 * journal.
8709 	 */
8710 	if (MOUNTEDSUJ(mp)) {
8711 		flags = DEPALLOC;
8712 		jmvref = newjmvref(dp, de->d_ino,
8713 		    dp->i_offset + (oldloc - base),
8714 		    dp->i_offset + (newloc - base));
8715 	}
8716 	lbn = lblkno(ump->um_fs, dp->i_offset);
8717 	offset = blkoff(ump->um_fs, dp->i_offset);
8718 	oldoffset = offset + (oldloc - base);
8719 	newoffset = offset + (newloc - base);
8720 	ACQUIRE_LOCK(ump);
8721 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8722 		goto done;
8723 	dap = diradd_lookup(pagedep, oldoffset);
8724 	if (dap) {
8725 		dap->da_offset = newoffset;
8726 		newoffset = DIRADDHASH(newoffset);
8727 		oldoffset = DIRADDHASH(oldoffset);
8728 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8729 		    newoffset != oldoffset) {
8730 			LIST_REMOVE(dap, da_pdlist);
8731 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8732 			    dap, da_pdlist);
8733 		}
8734 	}
8735 done:
8736 	if (jmvref) {
8737 		jmvref->jm_pagedep = pagedep;
8738 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8739 		add_to_journal(&jmvref->jm_list);
8740 	}
8741 	bcopy(oldloc, newloc, entrysize);
8742 	FREE_LOCK(ump);
8743 }
8744 
8745 /*
8746  * Move the mkdir dependencies and journal work from one diradd to another
8747  * when renaming a directory.  The new name must depend on the mkdir deps
8748  * completing as the old name did.  Directories can only have one valid link
8749  * at a time so one must be canonical.
8750  */
8751 static void
8752 merge_diradd(inodedep, newdap)
8753 	struct inodedep *inodedep;
8754 	struct diradd *newdap;
8755 {
8756 	struct diradd *olddap;
8757 	struct mkdir *mkdir, *nextmd;
8758 	struct ufsmount *ump;
8759 	short state;
8760 
8761 	olddap = inodedep->id_mkdiradd;
8762 	inodedep->id_mkdiradd = newdap;
8763 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8764 		newdap->da_state &= ~DEPCOMPLETE;
8765 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8766 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8767 		     mkdir = nextmd) {
8768 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8769 			if (mkdir->md_diradd != olddap)
8770 				continue;
8771 			mkdir->md_diradd = newdap;
8772 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8773 			newdap->da_state |= state;
8774 			olddap->da_state &= ~state;
8775 			if ((olddap->da_state &
8776 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8777 				break;
8778 		}
8779 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8780 			panic("merge_diradd: unfound ref");
8781 	}
8782 	/*
8783 	 * Any mkdir related journal items are not safe to be freed until
8784 	 * the new name is stable.
8785 	 */
8786 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8787 	olddap->da_state |= DEPCOMPLETE;
8788 	complete_diradd(olddap);
8789 }
8790 
8791 /*
8792  * Move the diradd to the pending list when all diradd dependencies are
8793  * complete.
8794  */
8795 static void
8796 complete_diradd(dap)
8797 	struct diradd *dap;
8798 {
8799 	struct pagedep *pagedep;
8800 
8801 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8802 		if (dap->da_state & DIRCHG)
8803 			pagedep = dap->da_previous->dm_pagedep;
8804 		else
8805 			pagedep = dap->da_pagedep;
8806 		LIST_REMOVE(dap, da_pdlist);
8807 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8808 	}
8809 }
8810 
8811 /*
8812  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8813  * add entries and conditonally journal the remove.
8814  */
8815 static void
8816 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8817 	struct diradd *dap;
8818 	struct dirrem *dirrem;
8819 	struct jremref *jremref;
8820 	struct jremref *dotremref;
8821 	struct jremref *dotdotremref;
8822 {
8823 	struct inodedep *inodedep;
8824 	struct jaddref *jaddref;
8825 	struct inoref *inoref;
8826 	struct ufsmount *ump;
8827 	struct mkdir *mkdir;
8828 
8829 	/*
8830 	 * If no remove references were allocated we're on a non-journaled
8831 	 * filesystem and can skip the cancel step.
8832 	 */
8833 	if (jremref == NULL) {
8834 		free_diradd(dap, NULL);
8835 		return;
8836 	}
8837 	/*
8838 	 * Cancel the primary name an free it if it does not require
8839 	 * journaling.
8840 	 */
8841 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8842 	    0, &inodedep) != 0) {
8843 		/* Abort the addref that reference this diradd.  */
8844 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8845 			if (inoref->if_list.wk_type != D_JADDREF)
8846 				continue;
8847 			jaddref = (struct jaddref *)inoref;
8848 			if (jaddref->ja_diradd != dap)
8849 				continue;
8850 			if (cancel_jaddref(jaddref, inodedep,
8851 			    &dirrem->dm_jwork) == 0) {
8852 				free_jremref(jremref);
8853 				jremref = NULL;
8854 			}
8855 			break;
8856 		}
8857 	}
8858 	/*
8859 	 * Cancel subordinate names and free them if they do not require
8860 	 * journaling.
8861 	 */
8862 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8863 		ump = VFSTOUFS(dap->da_list.wk_mp);
8864 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8865 			if (mkdir->md_diradd != dap)
8866 				continue;
8867 			if ((jaddref = mkdir->md_jaddref) == NULL)
8868 				continue;
8869 			mkdir->md_jaddref = NULL;
8870 			if (mkdir->md_state & MKDIR_PARENT) {
8871 				if (cancel_jaddref(jaddref, NULL,
8872 				    &dirrem->dm_jwork) == 0) {
8873 					free_jremref(dotdotremref);
8874 					dotdotremref = NULL;
8875 				}
8876 			} else {
8877 				if (cancel_jaddref(jaddref, inodedep,
8878 				    &dirrem->dm_jwork) == 0) {
8879 					free_jremref(dotremref);
8880 					dotremref = NULL;
8881 				}
8882 			}
8883 		}
8884 	}
8885 
8886 	if (jremref)
8887 		journal_jremref(dirrem, jremref, inodedep);
8888 	if (dotremref)
8889 		journal_jremref(dirrem, dotremref, inodedep);
8890 	if (dotdotremref)
8891 		journal_jremref(dirrem, dotdotremref, NULL);
8892 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8893 	free_diradd(dap, &dirrem->dm_jwork);
8894 }
8895 
8896 /*
8897  * Free a diradd dependency structure.
8898  */
8899 static void
8900 free_diradd(dap, wkhd)
8901 	struct diradd *dap;
8902 	struct workhead *wkhd;
8903 {
8904 	struct dirrem *dirrem;
8905 	struct pagedep *pagedep;
8906 	struct inodedep *inodedep;
8907 	struct mkdir *mkdir, *nextmd;
8908 	struct ufsmount *ump;
8909 
8910 	ump = VFSTOUFS(dap->da_list.wk_mp);
8911 	LOCK_OWNED(ump);
8912 	LIST_REMOVE(dap, da_pdlist);
8913 	if (dap->da_state & ONWORKLIST)
8914 		WORKLIST_REMOVE(&dap->da_list);
8915 	if ((dap->da_state & DIRCHG) == 0) {
8916 		pagedep = dap->da_pagedep;
8917 	} else {
8918 		dirrem = dap->da_previous;
8919 		pagedep = dirrem->dm_pagedep;
8920 		dirrem->dm_dirinum = pagedep->pd_ino;
8921 		dirrem->dm_state |= COMPLETE;
8922 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8923 			add_to_worklist(&dirrem->dm_list, 0);
8924 	}
8925 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8926 	    0, &inodedep) != 0)
8927 		if (inodedep->id_mkdiradd == dap)
8928 			inodedep->id_mkdiradd = NULL;
8929 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8930 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8931 		     mkdir = nextmd) {
8932 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8933 			if (mkdir->md_diradd != dap)
8934 				continue;
8935 			dap->da_state &=
8936 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8937 			LIST_REMOVE(mkdir, md_mkdirs);
8938 			if (mkdir->md_state & ONWORKLIST)
8939 				WORKLIST_REMOVE(&mkdir->md_list);
8940 			if (mkdir->md_jaddref != NULL)
8941 				panic("free_diradd: Unexpected jaddref");
8942 			WORKITEM_FREE(mkdir, D_MKDIR);
8943 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8944 				break;
8945 		}
8946 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8947 			panic("free_diradd: unfound ref");
8948 	}
8949 	if (inodedep)
8950 		free_inodedep(inodedep);
8951 	/*
8952 	 * Free any journal segments waiting for the directory write.
8953 	 */
8954 	handle_jwork(&dap->da_jwork);
8955 	WORKITEM_FREE(dap, D_DIRADD);
8956 }
8957 
8958 /*
8959  * Directory entry removal dependencies.
8960  *
8961  * When removing a directory entry, the entry's inode pointer must be
8962  * zero'ed on disk before the corresponding inode's link count is decremented
8963  * (possibly freeing the inode for re-use). This dependency is handled by
8964  * updating the directory entry but delaying the inode count reduction until
8965  * after the directory block has been written to disk. After this point, the
8966  * inode count can be decremented whenever it is convenient.
8967  */
8968 
8969 /*
8970  * This routine should be called immediately after removing
8971  * a directory entry.  The inode's link count should not be
8972  * decremented by the calling procedure -- the soft updates
8973  * code will do this task when it is safe.
8974  */
8975 void
8976 softdep_setup_remove(bp, dp, ip, isrmdir)
8977 	struct buf *bp;		/* buffer containing directory block */
8978 	struct inode *dp;	/* inode for the directory being modified */
8979 	struct inode *ip;	/* inode for directory entry being removed */
8980 	int isrmdir;		/* indicates if doing RMDIR */
8981 {
8982 	struct dirrem *dirrem, *prevdirrem;
8983 	struct inodedep *inodedep;
8984 	struct ufsmount *ump;
8985 	int direct;
8986 
8987 	ump = ITOUMP(ip);
8988 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8989 	    ("softdep_setup_remove called on non-softdep filesystem"));
8990 	/*
8991 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8992 	 * newdirrem() to setup the full directory remove which requires
8993 	 * isrmdir > 1.
8994 	 */
8995 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8996 	/*
8997 	 * Add the dirrem to the inodedep's pending remove list for quick
8998 	 * discovery later.
8999 	 */
9000 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9001 		panic("softdep_setup_remove: Lost inodedep.");
9002 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9003 	dirrem->dm_state |= ONDEPLIST;
9004 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9005 
9006 	/*
9007 	 * If the COMPLETE flag is clear, then there were no active
9008 	 * entries and we want to roll back to a zeroed entry until
9009 	 * the new inode is committed to disk. If the COMPLETE flag is
9010 	 * set then we have deleted an entry that never made it to
9011 	 * disk. If the entry we deleted resulted from a name change,
9012 	 * then the old name still resides on disk. We cannot delete
9013 	 * its inode (returned to us in prevdirrem) until the zeroed
9014 	 * directory entry gets to disk. The new inode has never been
9015 	 * referenced on the disk, so can be deleted immediately.
9016 	 */
9017 	if ((dirrem->dm_state & COMPLETE) == 0) {
9018 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9019 		    dm_next);
9020 		FREE_LOCK(ump);
9021 	} else {
9022 		if (prevdirrem != NULL)
9023 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9024 			    prevdirrem, dm_next);
9025 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9026 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9027 		FREE_LOCK(ump);
9028 		if (direct)
9029 			handle_workitem_remove(dirrem, 0);
9030 	}
9031 }
9032 
9033 /*
9034  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9035  * pd_pendinghd list of a pagedep.
9036  */
9037 static struct diradd *
9038 diradd_lookup(pagedep, offset)
9039 	struct pagedep *pagedep;
9040 	int offset;
9041 {
9042 	struct diradd *dap;
9043 
9044 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9045 		if (dap->da_offset == offset)
9046 			return (dap);
9047 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9048 		if (dap->da_offset == offset)
9049 			return (dap);
9050 	return (NULL);
9051 }
9052 
9053 /*
9054  * Search for a .. diradd dependency in a directory that is being removed.
9055  * If the directory was renamed to a new parent we have a diradd rather
9056  * than a mkdir for the .. entry.  We need to cancel it now before
9057  * it is found in truncate().
9058  */
9059 static struct jremref *
9060 cancel_diradd_dotdot(ip, dirrem, jremref)
9061 	struct inode *ip;
9062 	struct dirrem *dirrem;
9063 	struct jremref *jremref;
9064 {
9065 	struct pagedep *pagedep;
9066 	struct diradd *dap;
9067 	struct worklist *wk;
9068 
9069 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9070 		return (jremref);
9071 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9072 	if (dap == NULL)
9073 		return (jremref);
9074 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9075 	/*
9076 	 * Mark any journal work as belonging to the parent so it is freed
9077 	 * with the .. reference.
9078 	 */
9079 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9080 		wk->wk_state |= MKDIR_PARENT;
9081 	return (NULL);
9082 }
9083 
9084 /*
9085  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9086  * replace it with a dirrem/diradd pair as a result of re-parenting a
9087  * directory.  This ensures that we don't simultaneously have a mkdir and
9088  * a diradd for the same .. entry.
9089  */
9090 static struct jremref *
9091 cancel_mkdir_dotdot(ip, dirrem, jremref)
9092 	struct inode *ip;
9093 	struct dirrem *dirrem;
9094 	struct jremref *jremref;
9095 {
9096 	struct inodedep *inodedep;
9097 	struct jaddref *jaddref;
9098 	struct ufsmount *ump;
9099 	struct mkdir *mkdir;
9100 	struct diradd *dap;
9101 	struct mount *mp;
9102 
9103 	mp = ITOVFS(ip);
9104 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9105 		return (jremref);
9106 	dap = inodedep->id_mkdiradd;
9107 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9108 		return (jremref);
9109 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9110 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9111 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9112 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9113 			break;
9114 	if (mkdir == NULL)
9115 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9116 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9117 		mkdir->md_jaddref = NULL;
9118 		jaddref->ja_state &= ~MKDIR_PARENT;
9119 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9120 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9121 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9122 			journal_jremref(dirrem, jremref, inodedep);
9123 			jremref = NULL;
9124 		}
9125 	}
9126 	if (mkdir->md_state & ONWORKLIST)
9127 		WORKLIST_REMOVE(&mkdir->md_list);
9128 	mkdir->md_state |= ALLCOMPLETE;
9129 	complete_mkdir(mkdir);
9130 	return (jremref);
9131 }
9132 
9133 static void
9134 journal_jremref(dirrem, jremref, inodedep)
9135 	struct dirrem *dirrem;
9136 	struct jremref *jremref;
9137 	struct inodedep *inodedep;
9138 {
9139 
9140 	if (inodedep == NULL)
9141 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9142 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9143 			panic("journal_jremref: Lost inodedep");
9144 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9145 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9146 	add_to_journal(&jremref->jr_list);
9147 }
9148 
9149 static void
9150 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9151 	struct dirrem *dirrem;
9152 	struct jremref *jremref;
9153 	struct jremref *dotremref;
9154 	struct jremref *dotdotremref;
9155 {
9156 	struct inodedep *inodedep;
9157 
9158 
9159 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9160 	    &inodedep) == 0)
9161 		panic("dirrem_journal: Lost inodedep");
9162 	journal_jremref(dirrem, jremref, inodedep);
9163 	if (dotremref)
9164 		journal_jremref(dirrem, dotremref, inodedep);
9165 	if (dotdotremref)
9166 		journal_jremref(dirrem, dotdotremref, NULL);
9167 }
9168 
9169 /*
9170  * Allocate a new dirrem if appropriate and return it along with
9171  * its associated pagedep. Called without a lock, returns with lock.
9172  */
9173 static struct dirrem *
9174 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9175 	struct buf *bp;		/* buffer containing directory block */
9176 	struct inode *dp;	/* inode for the directory being modified */
9177 	struct inode *ip;	/* inode for directory entry being removed */
9178 	int isrmdir;		/* indicates if doing RMDIR */
9179 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9180 {
9181 	int offset;
9182 	ufs_lbn_t lbn;
9183 	struct diradd *dap;
9184 	struct dirrem *dirrem;
9185 	struct pagedep *pagedep;
9186 	struct jremref *jremref;
9187 	struct jremref *dotremref;
9188 	struct jremref *dotdotremref;
9189 	struct vnode *dvp;
9190 	struct ufsmount *ump;
9191 
9192 	/*
9193 	 * Whiteouts have no deletion dependencies.
9194 	 */
9195 	if (ip == NULL)
9196 		panic("newdirrem: whiteout");
9197 	dvp = ITOV(dp);
9198 	ump = ITOUMP(dp);
9199 
9200 	/*
9201 	 * If the system is over its limit and our filesystem is
9202 	 * responsible for more than our share of that usage and
9203 	 * we are not a snapshot, request some inodedep cleanup.
9204 	 * Limiting the number of dirrem structures will also limit
9205 	 * the number of freefile and freeblks structures.
9206 	 */
9207 	ACQUIRE_LOCK(ump);
9208 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9209 		schedule_cleanup(UFSTOVFS(ump));
9210 	else
9211 		FREE_LOCK(ump);
9212 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9213 	    M_ZERO);
9214 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9215 	LIST_INIT(&dirrem->dm_jremrefhd);
9216 	LIST_INIT(&dirrem->dm_jwork);
9217 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9218 	dirrem->dm_oldinum = ip->i_number;
9219 	*prevdirremp = NULL;
9220 	/*
9221 	 * Allocate remove reference structures to track journal write
9222 	 * dependencies.  We will always have one for the link and
9223 	 * when doing directories we will always have one more for dot.
9224 	 * When renaming a directory we skip the dotdot link change so
9225 	 * this is not needed.
9226 	 */
9227 	jremref = dotremref = dotdotremref = NULL;
9228 	if (DOINGSUJ(dvp)) {
9229 		if (isrmdir) {
9230 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9231 			    ip->i_effnlink + 2);
9232 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9233 			    ip->i_effnlink + 1);
9234 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9235 			    dp->i_effnlink + 1);
9236 			dotdotremref->jr_state |= MKDIR_PARENT;
9237 		} else
9238 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9239 			    ip->i_effnlink + 1);
9240 	}
9241 	ACQUIRE_LOCK(ump);
9242 	lbn = lblkno(ump->um_fs, dp->i_offset);
9243 	offset = blkoff(ump->um_fs, dp->i_offset);
9244 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9245 	    &pagedep);
9246 	dirrem->dm_pagedep = pagedep;
9247 	dirrem->dm_offset = offset;
9248 	/*
9249 	 * If we're renaming a .. link to a new directory, cancel any
9250 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9251 	 * the jremref is preserved for any potential diradd in this
9252 	 * location.  This can not coincide with a rmdir.
9253 	 */
9254 	if (dp->i_offset == DOTDOT_OFFSET) {
9255 		if (isrmdir)
9256 			panic("newdirrem: .. directory change during remove?");
9257 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9258 	}
9259 	/*
9260 	 * If we're removing a directory search for the .. dependency now and
9261 	 * cancel it.  Any pending journal work will be added to the dirrem
9262 	 * to be completed when the workitem remove completes.
9263 	 */
9264 	if (isrmdir)
9265 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9266 	/*
9267 	 * Check for a diradd dependency for the same directory entry.
9268 	 * If present, then both dependencies become obsolete and can
9269 	 * be de-allocated.
9270 	 */
9271 	dap = diradd_lookup(pagedep, offset);
9272 	if (dap == NULL) {
9273 		/*
9274 		 * Link the jremref structures into the dirrem so they are
9275 		 * written prior to the pagedep.
9276 		 */
9277 		if (jremref)
9278 			dirrem_journal(dirrem, jremref, dotremref,
9279 			    dotdotremref);
9280 		return (dirrem);
9281 	}
9282 	/*
9283 	 * Must be ATTACHED at this point.
9284 	 */
9285 	if ((dap->da_state & ATTACHED) == 0)
9286 		panic("newdirrem: not ATTACHED");
9287 	if (dap->da_newinum != ip->i_number)
9288 		panic("newdirrem: inum %ju should be %ju",
9289 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9290 	/*
9291 	 * If we are deleting a changed name that never made it to disk,
9292 	 * then return the dirrem describing the previous inode (which
9293 	 * represents the inode currently referenced from this entry on disk).
9294 	 */
9295 	if ((dap->da_state & DIRCHG) != 0) {
9296 		*prevdirremp = dap->da_previous;
9297 		dap->da_state &= ~DIRCHG;
9298 		dap->da_pagedep = pagedep;
9299 	}
9300 	/*
9301 	 * We are deleting an entry that never made it to disk.
9302 	 * Mark it COMPLETE so we can delete its inode immediately.
9303 	 */
9304 	dirrem->dm_state |= COMPLETE;
9305 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9306 #ifdef INVARIANTS
9307 	if (isrmdir == 0) {
9308 		struct worklist *wk;
9309 
9310 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9311 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9312 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9313 	}
9314 #endif
9315 
9316 	return (dirrem);
9317 }
9318 
9319 /*
9320  * Directory entry change dependencies.
9321  *
9322  * Changing an existing directory entry requires that an add operation
9323  * be completed first followed by a deletion. The semantics for the addition
9324  * are identical to the description of adding a new entry above except
9325  * that the rollback is to the old inode number rather than zero. Once
9326  * the addition dependency is completed, the removal is done as described
9327  * in the removal routine above.
9328  */
9329 
9330 /*
9331  * This routine should be called immediately after changing
9332  * a directory entry.  The inode's link count should not be
9333  * decremented by the calling procedure -- the soft updates
9334  * code will perform this task when it is safe.
9335  */
9336 void
9337 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9338 	struct buf *bp;		/* buffer containing directory block */
9339 	struct inode *dp;	/* inode for the directory being modified */
9340 	struct inode *ip;	/* inode for directory entry being removed */
9341 	ino_t newinum;		/* new inode number for changed entry */
9342 	int isrmdir;		/* indicates if doing RMDIR */
9343 {
9344 	int offset;
9345 	struct diradd *dap = NULL;
9346 	struct dirrem *dirrem, *prevdirrem;
9347 	struct pagedep *pagedep;
9348 	struct inodedep *inodedep;
9349 	struct jaddref *jaddref;
9350 	struct mount *mp;
9351 	struct ufsmount *ump;
9352 
9353 	mp = ITOVFS(dp);
9354 	ump = VFSTOUFS(mp);
9355 	offset = blkoff(ump->um_fs, dp->i_offset);
9356 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9357 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9358 
9359 	/*
9360 	 * Whiteouts do not need diradd dependencies.
9361 	 */
9362 	if (newinum != UFS_WINO) {
9363 		dap = malloc(sizeof(struct diradd),
9364 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9365 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9366 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9367 		dap->da_offset = offset;
9368 		dap->da_newinum = newinum;
9369 		LIST_INIT(&dap->da_jwork);
9370 	}
9371 
9372 	/*
9373 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9374 	 */
9375 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9376 	pagedep = dirrem->dm_pagedep;
9377 	/*
9378 	 * The possible values for isrmdir:
9379 	 *	0 - non-directory file rename
9380 	 *	1 - directory rename within same directory
9381 	 *   inum - directory rename to new directory of given inode number
9382 	 * When renaming to a new directory, we are both deleting and
9383 	 * creating a new directory entry, so the link count on the new
9384 	 * directory should not change. Thus we do not need the followup
9385 	 * dirrem which is usually done in handle_workitem_remove. We set
9386 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9387 	 * followup dirrem.
9388 	 */
9389 	if (isrmdir > 1)
9390 		dirrem->dm_state |= DIRCHG;
9391 
9392 	/*
9393 	 * Whiteouts have no additional dependencies,
9394 	 * so just put the dirrem on the correct list.
9395 	 */
9396 	if (newinum == UFS_WINO) {
9397 		if ((dirrem->dm_state & COMPLETE) == 0) {
9398 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9399 			    dm_next);
9400 		} else {
9401 			dirrem->dm_dirinum = pagedep->pd_ino;
9402 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9403 				add_to_worklist(&dirrem->dm_list, 0);
9404 		}
9405 		FREE_LOCK(ump);
9406 		return;
9407 	}
9408 	/*
9409 	 * Add the dirrem to the inodedep's pending remove list for quick
9410 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9411 	 * will not fail.
9412 	 */
9413 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9414 		panic("softdep_setup_directory_change: Lost inodedep.");
9415 	dirrem->dm_state |= ONDEPLIST;
9416 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9417 
9418 	/*
9419 	 * If the COMPLETE flag is clear, then there were no active
9420 	 * entries and we want to roll back to the previous inode until
9421 	 * the new inode is committed to disk. If the COMPLETE flag is
9422 	 * set, then we have deleted an entry that never made it to disk.
9423 	 * If the entry we deleted resulted from a name change, then the old
9424 	 * inode reference still resides on disk. Any rollback that we do
9425 	 * needs to be to that old inode (returned to us in prevdirrem). If
9426 	 * the entry we deleted resulted from a create, then there is
9427 	 * no entry on the disk, so we want to roll back to zero rather
9428 	 * than the uncommitted inode. In either of the COMPLETE cases we
9429 	 * want to immediately free the unwritten and unreferenced inode.
9430 	 */
9431 	if ((dirrem->dm_state & COMPLETE) == 0) {
9432 		dap->da_previous = dirrem;
9433 	} else {
9434 		if (prevdirrem != NULL) {
9435 			dap->da_previous = prevdirrem;
9436 		} else {
9437 			dap->da_state &= ~DIRCHG;
9438 			dap->da_pagedep = pagedep;
9439 		}
9440 		dirrem->dm_dirinum = pagedep->pd_ino;
9441 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9442 			add_to_worklist(&dirrem->dm_list, 0);
9443 	}
9444 	/*
9445 	 * Lookup the jaddref for this journal entry.  We must finish
9446 	 * initializing it and make the diradd write dependent on it.
9447 	 * If we're not journaling, put it on the id_bufwait list if the
9448 	 * inode is not yet written. If it is written, do the post-inode
9449 	 * write processing to put it on the id_pendinghd list.
9450 	 */
9451 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9452 	if (MOUNTEDSUJ(mp)) {
9453 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9454 		    inoreflst);
9455 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9456 		    ("softdep_setup_directory_change: bad jaddref %p",
9457 		    jaddref));
9458 		jaddref->ja_diroff = dp->i_offset;
9459 		jaddref->ja_diradd = dap;
9460 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9461 		    dap, da_pdlist);
9462 		add_to_journal(&jaddref->ja_list);
9463 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9464 		dap->da_state |= COMPLETE;
9465 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9466 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9467 	} else {
9468 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9469 		    dap, da_pdlist);
9470 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9471 	}
9472 	/*
9473 	 * If we're making a new name for a directory that has not been
9474 	 * committed when need to move the dot and dotdot references to
9475 	 * this new name.
9476 	 */
9477 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9478 		merge_diradd(inodedep, dap);
9479 	FREE_LOCK(ump);
9480 }
9481 
9482 /*
9483  * Called whenever the link count on an inode is changed.
9484  * It creates an inode dependency so that the new reference(s)
9485  * to the inode cannot be committed to disk until the updated
9486  * inode has been written.
9487  */
9488 void
9489 softdep_change_linkcnt(ip)
9490 	struct inode *ip;	/* the inode with the increased link count */
9491 {
9492 	struct inodedep *inodedep;
9493 	struct ufsmount *ump;
9494 
9495 	ump = ITOUMP(ip);
9496 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9497 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9498 	ACQUIRE_LOCK(ump);
9499 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9500 	if (ip->i_nlink < ip->i_effnlink)
9501 		panic("softdep_change_linkcnt: bad delta");
9502 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9503 	FREE_LOCK(ump);
9504 }
9505 
9506 /*
9507  * Attach a sbdep dependency to the superblock buf so that we can keep
9508  * track of the head of the linked list of referenced but unlinked inodes.
9509  */
9510 void
9511 softdep_setup_sbupdate(ump, fs, bp)
9512 	struct ufsmount *ump;
9513 	struct fs *fs;
9514 	struct buf *bp;
9515 {
9516 	struct sbdep *sbdep;
9517 	struct worklist *wk;
9518 
9519 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9520 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9521 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9522 		if (wk->wk_type == D_SBDEP)
9523 			break;
9524 	if (wk != NULL)
9525 		return;
9526 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9527 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9528 	sbdep->sb_fs = fs;
9529 	sbdep->sb_ump = ump;
9530 	ACQUIRE_LOCK(ump);
9531 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9532 	FREE_LOCK(ump);
9533 }
9534 
9535 /*
9536  * Return the first unlinked inodedep which is ready to be the head of the
9537  * list.  The inodedep and all those after it must have valid next pointers.
9538  */
9539 static struct inodedep *
9540 first_unlinked_inodedep(ump)
9541 	struct ufsmount *ump;
9542 {
9543 	struct inodedep *inodedep;
9544 	struct inodedep *idp;
9545 
9546 	LOCK_OWNED(ump);
9547 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9548 	    inodedep; inodedep = idp) {
9549 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9550 			return (NULL);
9551 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9552 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9553 			break;
9554 		if ((inodedep->id_state & UNLINKPREV) == 0)
9555 			break;
9556 	}
9557 	return (inodedep);
9558 }
9559 
9560 /*
9561  * Set the sujfree unlinked head pointer prior to writing a superblock.
9562  */
9563 static void
9564 initiate_write_sbdep(sbdep)
9565 	struct sbdep *sbdep;
9566 {
9567 	struct inodedep *inodedep;
9568 	struct fs *bpfs;
9569 	struct fs *fs;
9570 
9571 	bpfs = sbdep->sb_fs;
9572 	fs = sbdep->sb_ump->um_fs;
9573 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9574 	if (inodedep) {
9575 		fs->fs_sujfree = inodedep->id_ino;
9576 		inodedep->id_state |= UNLINKPREV;
9577 	} else
9578 		fs->fs_sujfree = 0;
9579 	bpfs->fs_sujfree = fs->fs_sujfree;
9580 }
9581 
9582 /*
9583  * After a superblock is written determine whether it must be written again
9584  * due to a changing unlinked list head.
9585  */
9586 static int
9587 handle_written_sbdep(sbdep, bp)
9588 	struct sbdep *sbdep;
9589 	struct buf *bp;
9590 {
9591 	struct inodedep *inodedep;
9592 	struct fs *fs;
9593 
9594 	LOCK_OWNED(sbdep->sb_ump);
9595 	fs = sbdep->sb_fs;
9596 	/*
9597 	 * If the superblock doesn't match the in-memory list start over.
9598 	 */
9599 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9600 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9601 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9602 		bdirty(bp);
9603 		return (1);
9604 	}
9605 	WORKITEM_FREE(sbdep, D_SBDEP);
9606 	if (fs->fs_sujfree == 0)
9607 		return (0);
9608 	/*
9609 	 * Now that we have a record of this inode in stable store allow it
9610 	 * to be written to free up pending work.  Inodes may see a lot of
9611 	 * write activity after they are unlinked which we must not hold up.
9612 	 */
9613 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9614 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9615 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9616 			    inodedep, inodedep->id_state);
9617 		if (inodedep->id_state & UNLINKONLIST)
9618 			break;
9619 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9620 	}
9621 
9622 	return (0);
9623 }
9624 
9625 /*
9626  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9627  */
9628 static void
9629 unlinked_inodedep(mp, inodedep)
9630 	struct mount *mp;
9631 	struct inodedep *inodedep;
9632 {
9633 	struct ufsmount *ump;
9634 
9635 	ump = VFSTOUFS(mp);
9636 	LOCK_OWNED(ump);
9637 	if (MOUNTEDSUJ(mp) == 0)
9638 		return;
9639 	ump->um_fs->fs_fmod = 1;
9640 	if (inodedep->id_state & UNLINKED)
9641 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9642 	inodedep->id_state |= UNLINKED;
9643 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9644 }
9645 
9646 /*
9647  * Remove an inodedep from the unlinked inodedep list.  This may require
9648  * disk writes if the inode has made it that far.
9649  */
9650 static void
9651 clear_unlinked_inodedep(inodedep)
9652 	struct inodedep *inodedep;
9653 {
9654 	struct ufs2_dinode *dip;
9655 	struct ufsmount *ump;
9656 	struct inodedep *idp;
9657 	struct inodedep *idn;
9658 	struct fs *fs;
9659 	struct buf *bp;
9660 	ino_t ino;
9661 	ino_t nino;
9662 	ino_t pino;
9663 	int error;
9664 
9665 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9666 	fs = ump->um_fs;
9667 	ino = inodedep->id_ino;
9668 	error = 0;
9669 	for (;;) {
9670 		LOCK_OWNED(ump);
9671 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9672 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9673 		    inodedep));
9674 		/*
9675 		 * If nothing has yet been written simply remove us from
9676 		 * the in memory list and return.  This is the most common
9677 		 * case where handle_workitem_remove() loses the final
9678 		 * reference.
9679 		 */
9680 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9681 			break;
9682 		/*
9683 		 * If we have a NEXT pointer and no PREV pointer we can simply
9684 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9685 		 * careful not to clear PREV if the superblock points at
9686 		 * next as well.
9687 		 */
9688 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9689 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9690 			if (idn && fs->fs_sujfree != idn->id_ino)
9691 				idn->id_state &= ~UNLINKPREV;
9692 			break;
9693 		}
9694 		/*
9695 		 * Here we have an inodedep which is actually linked into
9696 		 * the list.  We must remove it by forcing a write to the
9697 		 * link before us, whether it be the superblock or an inode.
9698 		 * Unfortunately the list may change while we're waiting
9699 		 * on the buf lock for either resource so we must loop until
9700 		 * we lock the right one.  If both the superblock and an
9701 		 * inode point to this inode we must clear the inode first
9702 		 * followed by the superblock.
9703 		 */
9704 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9705 		pino = 0;
9706 		if (idp && (idp->id_state & UNLINKNEXT))
9707 			pino = idp->id_ino;
9708 		FREE_LOCK(ump);
9709 		if (pino == 0) {
9710 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9711 			    (int)fs->fs_sbsize, 0, 0, 0);
9712 		} else {
9713 			error = bread(ump->um_devvp,
9714 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9715 			    (int)fs->fs_bsize, NOCRED, &bp);
9716 			if (error)
9717 				brelse(bp);
9718 		}
9719 		ACQUIRE_LOCK(ump);
9720 		if (error)
9721 			break;
9722 		/* If the list has changed restart the loop. */
9723 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9724 		nino = 0;
9725 		if (idp && (idp->id_state & UNLINKNEXT))
9726 			nino = idp->id_ino;
9727 		if (nino != pino ||
9728 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9729 			FREE_LOCK(ump);
9730 			brelse(bp);
9731 			ACQUIRE_LOCK(ump);
9732 			continue;
9733 		}
9734 		nino = 0;
9735 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9736 		if (idn)
9737 			nino = idn->id_ino;
9738 		/*
9739 		 * Remove us from the in memory list.  After this we cannot
9740 		 * access the inodedep.
9741 		 */
9742 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9743 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9744 		    inodedep));
9745 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9746 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9747 		FREE_LOCK(ump);
9748 		/*
9749 		 * The predecessor's next pointer is manually updated here
9750 		 * so that the NEXT flag is never cleared for an element
9751 		 * that is in the list.
9752 		 */
9753 		if (pino == 0) {
9754 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9755 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9756 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9757 			    bp);
9758 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
9759 			((struct ufs1_dinode *)bp->b_data +
9760 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9761 		} else {
9762 			dip = (struct ufs2_dinode *)bp->b_data +
9763 			    ino_to_fsbo(fs, pino);
9764 			dip->di_freelink = nino;
9765 			ffs_update_dinode_ckhash(fs, dip);
9766 		}
9767 		/*
9768 		 * If the bwrite fails we have no recourse to recover.  The
9769 		 * filesystem is corrupted already.
9770 		 */
9771 		bwrite(bp);
9772 		ACQUIRE_LOCK(ump);
9773 		/*
9774 		 * If the superblock pointer still needs to be cleared force
9775 		 * a write here.
9776 		 */
9777 		if (fs->fs_sujfree == ino) {
9778 			FREE_LOCK(ump);
9779 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9780 			    (int)fs->fs_sbsize, 0, 0, 0);
9781 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9782 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9783 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9784 			    bp);
9785 			bwrite(bp);
9786 			ACQUIRE_LOCK(ump);
9787 		}
9788 
9789 		if (fs->fs_sujfree != ino)
9790 			return;
9791 		panic("clear_unlinked_inodedep: Failed to clear free head");
9792 	}
9793 	if (inodedep->id_ino == fs->fs_sujfree)
9794 		panic("clear_unlinked_inodedep: Freeing head of free list");
9795 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9796 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9797 	return;
9798 }
9799 
9800 /*
9801  * This workitem decrements the inode's link count.
9802  * If the link count reaches zero, the file is removed.
9803  */
9804 static int
9805 handle_workitem_remove(dirrem, flags)
9806 	struct dirrem *dirrem;
9807 	int flags;
9808 {
9809 	struct inodedep *inodedep;
9810 	struct workhead dotdotwk;
9811 	struct worklist *wk;
9812 	struct ufsmount *ump;
9813 	struct mount *mp;
9814 	struct vnode *vp;
9815 	struct inode *ip;
9816 	ino_t oldinum;
9817 
9818 	if (dirrem->dm_state & ONWORKLIST)
9819 		panic("handle_workitem_remove: dirrem %p still on worklist",
9820 		    dirrem);
9821 	oldinum = dirrem->dm_oldinum;
9822 	mp = dirrem->dm_list.wk_mp;
9823 	ump = VFSTOUFS(mp);
9824 	flags |= LK_EXCLUSIVE;
9825 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9826 		return (EBUSY);
9827 	ip = VTOI(vp);
9828 	ACQUIRE_LOCK(ump);
9829 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9830 		panic("handle_workitem_remove: lost inodedep");
9831 	if (dirrem->dm_state & ONDEPLIST)
9832 		LIST_REMOVE(dirrem, dm_inonext);
9833 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9834 	    ("handle_workitem_remove:  Journal entries not written."));
9835 
9836 	/*
9837 	 * Move all dependencies waiting on the remove to complete
9838 	 * from the dirrem to the inode inowait list to be completed
9839 	 * after the inode has been updated and written to disk.  Any
9840 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9841 	 * is removed.
9842 	 */
9843 	LIST_INIT(&dotdotwk);
9844 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9845 		WORKLIST_REMOVE(wk);
9846 		if (wk->wk_state & MKDIR_PARENT) {
9847 			wk->wk_state &= ~MKDIR_PARENT;
9848 			WORKLIST_INSERT(&dotdotwk, wk);
9849 			continue;
9850 		}
9851 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9852 	}
9853 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9854 	/*
9855 	 * Normal file deletion.
9856 	 */
9857 	if ((dirrem->dm_state & RMDIR) == 0) {
9858 		ip->i_nlink--;
9859 		DIP_SET(ip, i_nlink, ip->i_nlink);
9860 		ip->i_flag |= IN_CHANGE;
9861 		if (ip->i_nlink < ip->i_effnlink)
9862 			panic("handle_workitem_remove: bad file delta");
9863 		if (ip->i_nlink == 0)
9864 			unlinked_inodedep(mp, inodedep);
9865 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9866 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9867 		    ("handle_workitem_remove: worklist not empty. %s",
9868 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9869 		WORKITEM_FREE(dirrem, D_DIRREM);
9870 		FREE_LOCK(ump);
9871 		goto out;
9872 	}
9873 	/*
9874 	 * Directory deletion. Decrement reference count for both the
9875 	 * just deleted parent directory entry and the reference for ".".
9876 	 * Arrange to have the reference count on the parent decremented
9877 	 * to account for the loss of "..".
9878 	 */
9879 	ip->i_nlink -= 2;
9880 	DIP_SET(ip, i_nlink, ip->i_nlink);
9881 	ip->i_flag |= IN_CHANGE;
9882 	if (ip->i_nlink < ip->i_effnlink)
9883 		panic("handle_workitem_remove: bad dir delta");
9884 	if (ip->i_nlink == 0)
9885 		unlinked_inodedep(mp, inodedep);
9886 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9887 	/*
9888 	 * Rename a directory to a new parent. Since, we are both deleting
9889 	 * and creating a new directory entry, the link count on the new
9890 	 * directory should not change. Thus we skip the followup dirrem.
9891 	 */
9892 	if (dirrem->dm_state & DIRCHG) {
9893 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9894 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9895 		WORKITEM_FREE(dirrem, D_DIRREM);
9896 		FREE_LOCK(ump);
9897 		goto out;
9898 	}
9899 	dirrem->dm_state = ONDEPLIST;
9900 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9901 	/*
9902 	 * Place the dirrem on the parent's diremhd list.
9903 	 */
9904 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9905 		panic("handle_workitem_remove: lost dir inodedep");
9906 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9907 	/*
9908 	 * If the allocated inode has never been written to disk, then
9909 	 * the on-disk inode is zero'ed and we can remove the file
9910 	 * immediately.  When journaling if the inode has been marked
9911 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9912 	 */
9913 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9914 	if (inodedep == NULL ||
9915 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9916 	    check_inode_unwritten(inodedep)) {
9917 		FREE_LOCK(ump);
9918 		vput(vp);
9919 		return handle_workitem_remove(dirrem, flags);
9920 	}
9921 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9922 	FREE_LOCK(ump);
9923 	ip->i_flag |= IN_CHANGE;
9924 out:
9925 	ffs_update(vp, 0);
9926 	vput(vp);
9927 	return (0);
9928 }
9929 
9930 /*
9931  * Inode de-allocation dependencies.
9932  *
9933  * When an inode's link count is reduced to zero, it can be de-allocated. We
9934  * found it convenient to postpone de-allocation until after the inode is
9935  * written to disk with its new link count (zero).  At this point, all of the
9936  * on-disk inode's block pointers are nullified and, with careful dependency
9937  * list ordering, all dependencies related to the inode will be satisfied and
9938  * the corresponding dependency structures de-allocated.  So, if/when the
9939  * inode is reused, there will be no mixing of old dependencies with new
9940  * ones.  This artificial dependency is set up by the block de-allocation
9941  * procedure above (softdep_setup_freeblocks) and completed by the
9942  * following procedure.
9943  */
9944 static void
9945 handle_workitem_freefile(freefile)
9946 	struct freefile *freefile;
9947 {
9948 	struct workhead wkhd;
9949 	struct fs *fs;
9950 	struct ufsmount *ump;
9951 	int error;
9952 #ifdef INVARIANTS
9953 	struct inodedep *idp;
9954 #endif
9955 
9956 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9957 	fs = ump->um_fs;
9958 #ifdef INVARIANTS
9959 	ACQUIRE_LOCK(ump);
9960 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9961 	FREE_LOCK(ump);
9962 	if (error)
9963 		panic("handle_workitem_freefile: inodedep %p survived", idp);
9964 #endif
9965 	UFS_LOCK(ump);
9966 	fs->fs_pendinginodes -= 1;
9967 	UFS_UNLOCK(ump);
9968 	LIST_INIT(&wkhd);
9969 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9970 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9971 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9972 		softdep_error("handle_workitem_freefile", error);
9973 	ACQUIRE_LOCK(ump);
9974 	WORKITEM_FREE(freefile, D_FREEFILE);
9975 	FREE_LOCK(ump);
9976 }
9977 
9978 
9979 /*
9980  * Helper function which unlinks marker element from work list and returns
9981  * the next element on the list.
9982  */
9983 static __inline struct worklist *
9984 markernext(struct worklist *marker)
9985 {
9986 	struct worklist *next;
9987 
9988 	next = LIST_NEXT(marker, wk_list);
9989 	LIST_REMOVE(marker, wk_list);
9990 	return next;
9991 }
9992 
9993 /*
9994  * Disk writes.
9995  *
9996  * The dependency structures constructed above are most actively used when file
9997  * system blocks are written to disk.  No constraints are placed on when a
9998  * block can be written, but unsatisfied update dependencies are made safe by
9999  * modifying (or replacing) the source memory for the duration of the disk
10000  * write.  When the disk write completes, the memory block is again brought
10001  * up-to-date.
10002  *
10003  * In-core inode structure reclamation.
10004  *
10005  * Because there are a finite number of "in-core" inode structures, they are
10006  * reused regularly.  By transferring all inode-related dependencies to the
10007  * in-memory inode block and indexing them separately (via "inodedep"s), we
10008  * can allow "in-core" inode structures to be reused at any time and avoid
10009  * any increase in contention.
10010  *
10011  * Called just before entering the device driver to initiate a new disk I/O.
10012  * The buffer must be locked, thus, no I/O completion operations can occur
10013  * while we are manipulating its associated dependencies.
10014  */
10015 static void
10016 softdep_disk_io_initiation(bp)
10017 	struct buf *bp;		/* structure describing disk write to occur */
10018 {
10019 	struct worklist *wk;
10020 	struct worklist marker;
10021 	struct inodedep *inodedep;
10022 	struct freeblks *freeblks;
10023 	struct jblkdep *jblkdep;
10024 	struct newblk *newblk;
10025 	struct ufsmount *ump;
10026 
10027 	/*
10028 	 * We only care about write operations. There should never
10029 	 * be dependencies for reads.
10030 	 */
10031 	if (bp->b_iocmd != BIO_WRITE)
10032 		panic("softdep_disk_io_initiation: not write");
10033 
10034 	if (bp->b_vflags & BV_BKGRDINPROG)
10035 		panic("softdep_disk_io_initiation: Writing buffer with "
10036 		    "background write in progress: %p", bp);
10037 
10038 	ump = softdep_bp_to_mp(bp);
10039 	if (ump == NULL)
10040 		return;
10041 
10042 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10043 	PHOLD(curproc);			/* Don't swap out kernel stack */
10044 	ACQUIRE_LOCK(ump);
10045 	/*
10046 	 * Do any necessary pre-I/O processing.
10047 	 */
10048 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10049 	     wk = markernext(&marker)) {
10050 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10051 		switch (wk->wk_type) {
10052 
10053 		case D_PAGEDEP:
10054 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10055 			continue;
10056 
10057 		case D_INODEDEP:
10058 			inodedep = WK_INODEDEP(wk);
10059 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10060 				initiate_write_inodeblock_ufs1(inodedep, bp);
10061 			else
10062 				initiate_write_inodeblock_ufs2(inodedep, bp);
10063 			continue;
10064 
10065 		case D_INDIRDEP:
10066 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10067 			continue;
10068 
10069 		case D_BMSAFEMAP:
10070 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10071 			continue;
10072 
10073 		case D_JSEG:
10074 			WK_JSEG(wk)->js_buf = NULL;
10075 			continue;
10076 
10077 		case D_FREEBLKS:
10078 			freeblks = WK_FREEBLKS(wk);
10079 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10080 			/*
10081 			 * We have to wait for the freeblks to be journaled
10082 			 * before we can write an inodeblock with updated
10083 			 * pointers.  Be careful to arrange the marker so
10084 			 * we revisit the freeblks if it's not removed by
10085 			 * the first jwait().
10086 			 */
10087 			if (jblkdep != NULL) {
10088 				LIST_REMOVE(&marker, wk_list);
10089 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10090 				jwait(&jblkdep->jb_list, MNT_WAIT);
10091 			}
10092 			continue;
10093 		case D_ALLOCDIRECT:
10094 		case D_ALLOCINDIR:
10095 			/*
10096 			 * We have to wait for the jnewblk to be journaled
10097 			 * before we can write to a block if the contents
10098 			 * may be confused with an earlier file's indirect
10099 			 * at recovery time.  Handle the marker as described
10100 			 * above.
10101 			 */
10102 			newblk = WK_NEWBLK(wk);
10103 			if (newblk->nb_jnewblk != NULL &&
10104 			    indirblk_lookup(newblk->nb_list.wk_mp,
10105 			    newblk->nb_newblkno)) {
10106 				LIST_REMOVE(&marker, wk_list);
10107 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10108 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10109 			}
10110 			continue;
10111 
10112 		case D_SBDEP:
10113 			initiate_write_sbdep(WK_SBDEP(wk));
10114 			continue;
10115 
10116 		case D_MKDIR:
10117 		case D_FREEWORK:
10118 		case D_FREEDEP:
10119 		case D_JSEGDEP:
10120 			continue;
10121 
10122 		default:
10123 			panic("handle_disk_io_initiation: Unexpected type %s",
10124 			    TYPENAME(wk->wk_type));
10125 			/* NOTREACHED */
10126 		}
10127 	}
10128 	FREE_LOCK(ump);
10129 	PRELE(curproc);			/* Allow swapout of kernel stack */
10130 }
10131 
10132 /*
10133  * Called from within the procedure above to deal with unsatisfied
10134  * allocation dependencies in a directory. The buffer must be locked,
10135  * thus, no I/O completion operations can occur while we are
10136  * manipulating its associated dependencies.
10137  */
10138 static void
10139 initiate_write_filepage(pagedep, bp)
10140 	struct pagedep *pagedep;
10141 	struct buf *bp;
10142 {
10143 	struct jremref *jremref;
10144 	struct jmvref *jmvref;
10145 	struct dirrem *dirrem;
10146 	struct diradd *dap;
10147 	struct direct *ep;
10148 	int i;
10149 
10150 	if (pagedep->pd_state & IOSTARTED) {
10151 		/*
10152 		 * This can only happen if there is a driver that does not
10153 		 * understand chaining. Here biodone will reissue the call
10154 		 * to strategy for the incomplete buffers.
10155 		 */
10156 		printf("initiate_write_filepage: already started\n");
10157 		return;
10158 	}
10159 	pagedep->pd_state |= IOSTARTED;
10160 	/*
10161 	 * Wait for all journal remove dependencies to hit the disk.
10162 	 * We can not allow any potentially conflicting directory adds
10163 	 * to be visible before removes and rollback is too difficult.
10164 	 * The per-filesystem lock may be dropped and re-acquired, however
10165 	 * we hold the buf locked so the dependency can not go away.
10166 	 */
10167 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10168 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10169 			jwait(&jremref->jr_list, MNT_WAIT);
10170 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10171 		jwait(&jmvref->jm_list, MNT_WAIT);
10172 	for (i = 0; i < DAHASHSZ; i++) {
10173 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10174 			ep = (struct direct *)
10175 			    ((char *)bp->b_data + dap->da_offset);
10176 			if (ep->d_ino != dap->da_newinum)
10177 				panic("%s: dir inum %ju != new %ju",
10178 				    "initiate_write_filepage",
10179 				    (uintmax_t)ep->d_ino,
10180 				    (uintmax_t)dap->da_newinum);
10181 			if (dap->da_state & DIRCHG)
10182 				ep->d_ino = dap->da_previous->dm_oldinum;
10183 			else
10184 				ep->d_ino = 0;
10185 			dap->da_state &= ~ATTACHED;
10186 			dap->da_state |= UNDONE;
10187 		}
10188 	}
10189 }
10190 
10191 /*
10192  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10193  * Note that any bug fixes made to this routine must be done in the
10194  * version found below.
10195  *
10196  * Called from within the procedure above to deal with unsatisfied
10197  * allocation dependencies in an inodeblock. The buffer must be
10198  * locked, thus, no I/O completion operations can occur while we
10199  * are manipulating its associated dependencies.
10200  */
10201 static void
10202 initiate_write_inodeblock_ufs1(inodedep, bp)
10203 	struct inodedep *inodedep;
10204 	struct buf *bp;			/* The inode block */
10205 {
10206 	struct allocdirect *adp, *lastadp;
10207 	struct ufs1_dinode *dp;
10208 	struct ufs1_dinode *sip;
10209 	struct inoref *inoref;
10210 	struct ufsmount *ump;
10211 	struct fs *fs;
10212 	ufs_lbn_t i;
10213 #ifdef INVARIANTS
10214 	ufs_lbn_t prevlbn = 0;
10215 #endif
10216 	int deplist;
10217 
10218 	if (inodedep->id_state & IOSTARTED)
10219 		panic("initiate_write_inodeblock_ufs1: already started");
10220 	inodedep->id_state |= IOSTARTED;
10221 	fs = inodedep->id_fs;
10222 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10223 	LOCK_OWNED(ump);
10224 	dp = (struct ufs1_dinode *)bp->b_data +
10225 	    ino_to_fsbo(fs, inodedep->id_ino);
10226 
10227 	/*
10228 	 * If we're on the unlinked list but have not yet written our
10229 	 * next pointer initialize it here.
10230 	 */
10231 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10232 		struct inodedep *inon;
10233 
10234 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10235 		dp->di_freelink = inon ? inon->id_ino : 0;
10236 	}
10237 	/*
10238 	 * If the bitmap is not yet written, then the allocated
10239 	 * inode cannot be written to disk.
10240 	 */
10241 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10242 		if (inodedep->id_savedino1 != NULL)
10243 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10244 		FREE_LOCK(ump);
10245 		sip = malloc(sizeof(struct ufs1_dinode),
10246 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10247 		ACQUIRE_LOCK(ump);
10248 		inodedep->id_savedino1 = sip;
10249 		*inodedep->id_savedino1 = *dp;
10250 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10251 		dp->di_gen = inodedep->id_savedino1->di_gen;
10252 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10253 		return;
10254 	}
10255 	/*
10256 	 * If no dependencies, then there is nothing to roll back.
10257 	 */
10258 	inodedep->id_savedsize = dp->di_size;
10259 	inodedep->id_savedextsize = 0;
10260 	inodedep->id_savednlink = dp->di_nlink;
10261 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10262 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10263 		return;
10264 	/*
10265 	 * Revert the link count to that of the first unwritten journal entry.
10266 	 */
10267 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10268 	if (inoref)
10269 		dp->di_nlink = inoref->if_nlink;
10270 	/*
10271 	 * Set the dependencies to busy.
10272 	 */
10273 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10274 	     adp = TAILQ_NEXT(adp, ad_next)) {
10275 #ifdef INVARIANTS
10276 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10277 			panic("softdep_write_inodeblock: lbn order");
10278 		prevlbn = adp->ad_offset;
10279 		if (adp->ad_offset < UFS_NDADDR &&
10280 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10281 			panic("initiate_write_inodeblock_ufs1: "
10282 			    "direct pointer #%jd mismatch %d != %jd",
10283 			    (intmax_t)adp->ad_offset,
10284 			    dp->di_db[adp->ad_offset],
10285 			    (intmax_t)adp->ad_newblkno);
10286 		if (adp->ad_offset >= UFS_NDADDR &&
10287 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10288 			panic("initiate_write_inodeblock_ufs1: "
10289 			    "indirect pointer #%jd mismatch %d != %jd",
10290 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10291 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10292 			    (intmax_t)adp->ad_newblkno);
10293 		deplist |= 1 << adp->ad_offset;
10294 		if ((adp->ad_state & ATTACHED) == 0)
10295 			panic("initiate_write_inodeblock_ufs1: "
10296 			    "Unknown state 0x%x", adp->ad_state);
10297 #endif /* INVARIANTS */
10298 		adp->ad_state &= ~ATTACHED;
10299 		adp->ad_state |= UNDONE;
10300 	}
10301 	/*
10302 	 * The on-disk inode cannot claim to be any larger than the last
10303 	 * fragment that has been written. Otherwise, the on-disk inode
10304 	 * might have fragments that were not the last block in the file
10305 	 * which would corrupt the filesystem.
10306 	 */
10307 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10308 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10309 		if (adp->ad_offset >= UFS_NDADDR)
10310 			break;
10311 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10312 		/* keep going until hitting a rollback to a frag */
10313 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10314 			continue;
10315 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10316 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10317 #ifdef INVARIANTS
10318 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10319 				panic("initiate_write_inodeblock_ufs1: "
10320 				    "lost dep1");
10321 #endif /* INVARIANTS */
10322 			dp->di_db[i] = 0;
10323 		}
10324 		for (i = 0; i < UFS_NIADDR; i++) {
10325 #ifdef INVARIANTS
10326 			if (dp->di_ib[i] != 0 &&
10327 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10328 				panic("initiate_write_inodeblock_ufs1: "
10329 				    "lost dep2");
10330 #endif /* INVARIANTS */
10331 			dp->di_ib[i] = 0;
10332 		}
10333 		return;
10334 	}
10335 	/*
10336 	 * If we have zero'ed out the last allocated block of the file,
10337 	 * roll back the size to the last currently allocated block.
10338 	 * We know that this last allocated block is a full-sized as
10339 	 * we already checked for fragments in the loop above.
10340 	 */
10341 	if (lastadp != NULL &&
10342 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10343 		for (i = lastadp->ad_offset; i >= 0; i--)
10344 			if (dp->di_db[i] != 0)
10345 				break;
10346 		dp->di_size = (i + 1) * fs->fs_bsize;
10347 	}
10348 	/*
10349 	 * The only dependencies are for indirect blocks.
10350 	 *
10351 	 * The file size for indirect block additions is not guaranteed.
10352 	 * Such a guarantee would be non-trivial to achieve. The conventional
10353 	 * synchronous write implementation also does not make this guarantee.
10354 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10355 	 * can be over-estimated without destroying integrity when the file
10356 	 * moves into the indirect blocks (i.e., is large). If we want to
10357 	 * postpone fsck, we are stuck with this argument.
10358 	 */
10359 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10360 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10361 }
10362 
10363 /*
10364  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10365  * Note that any bug fixes made to this routine must be done in the
10366  * version found above.
10367  *
10368  * Called from within the procedure above to deal with unsatisfied
10369  * allocation dependencies in an inodeblock. The buffer must be
10370  * locked, thus, no I/O completion operations can occur while we
10371  * are manipulating its associated dependencies.
10372  */
10373 static void
10374 initiate_write_inodeblock_ufs2(inodedep, bp)
10375 	struct inodedep *inodedep;
10376 	struct buf *bp;			/* The inode block */
10377 {
10378 	struct allocdirect *adp, *lastadp;
10379 	struct ufs2_dinode *dp;
10380 	struct ufs2_dinode *sip;
10381 	struct inoref *inoref;
10382 	struct ufsmount *ump;
10383 	struct fs *fs;
10384 	ufs_lbn_t i;
10385 #ifdef INVARIANTS
10386 	ufs_lbn_t prevlbn = 0;
10387 #endif
10388 	int deplist;
10389 
10390 	if (inodedep->id_state & IOSTARTED)
10391 		panic("initiate_write_inodeblock_ufs2: already started");
10392 	inodedep->id_state |= IOSTARTED;
10393 	fs = inodedep->id_fs;
10394 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10395 	LOCK_OWNED(ump);
10396 	dp = (struct ufs2_dinode *)bp->b_data +
10397 	    ino_to_fsbo(fs, inodedep->id_ino);
10398 
10399 	/*
10400 	 * If we're on the unlinked list but have not yet written our
10401 	 * next pointer initialize it here.
10402 	 */
10403 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10404 		struct inodedep *inon;
10405 
10406 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10407 		dp->di_freelink = inon ? inon->id_ino : 0;
10408 		ffs_update_dinode_ckhash(fs, dp);
10409 	}
10410 	/*
10411 	 * If the bitmap is not yet written, then the allocated
10412 	 * inode cannot be written to disk.
10413 	 */
10414 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10415 		if (inodedep->id_savedino2 != NULL)
10416 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10417 		FREE_LOCK(ump);
10418 		sip = malloc(sizeof(struct ufs2_dinode),
10419 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10420 		ACQUIRE_LOCK(ump);
10421 		inodedep->id_savedino2 = sip;
10422 		*inodedep->id_savedino2 = *dp;
10423 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10424 		dp->di_gen = inodedep->id_savedino2->di_gen;
10425 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10426 		return;
10427 	}
10428 	/*
10429 	 * If no dependencies, then there is nothing to roll back.
10430 	 */
10431 	inodedep->id_savedsize = dp->di_size;
10432 	inodedep->id_savedextsize = dp->di_extsize;
10433 	inodedep->id_savednlink = dp->di_nlink;
10434 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10435 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10436 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10437 		return;
10438 	/*
10439 	 * Revert the link count to that of the first unwritten journal entry.
10440 	 */
10441 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10442 	if (inoref)
10443 		dp->di_nlink = inoref->if_nlink;
10444 
10445 	/*
10446 	 * Set the ext data dependencies to busy.
10447 	 */
10448 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10449 	     adp = TAILQ_NEXT(adp, ad_next)) {
10450 #ifdef INVARIANTS
10451 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10452 			panic("initiate_write_inodeblock_ufs2: lbn order");
10453 		prevlbn = adp->ad_offset;
10454 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10455 			panic("initiate_write_inodeblock_ufs2: "
10456 			    "ext pointer #%jd mismatch %jd != %jd",
10457 			    (intmax_t)adp->ad_offset,
10458 			    (intmax_t)dp->di_extb[adp->ad_offset],
10459 			    (intmax_t)adp->ad_newblkno);
10460 		deplist |= 1 << adp->ad_offset;
10461 		if ((adp->ad_state & ATTACHED) == 0)
10462 			panic("initiate_write_inodeblock_ufs2: Unknown "
10463 			    "state 0x%x", adp->ad_state);
10464 #endif /* INVARIANTS */
10465 		adp->ad_state &= ~ATTACHED;
10466 		adp->ad_state |= UNDONE;
10467 	}
10468 	/*
10469 	 * The on-disk inode cannot claim to be any larger than the last
10470 	 * fragment that has been written. Otherwise, the on-disk inode
10471 	 * might have fragments that were not the last block in the ext
10472 	 * data which would corrupt the filesystem.
10473 	 */
10474 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10475 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10476 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10477 		/* keep going until hitting a rollback to a frag */
10478 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10479 			continue;
10480 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10481 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10482 #ifdef INVARIANTS
10483 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10484 				panic("initiate_write_inodeblock_ufs2: "
10485 				    "lost dep1");
10486 #endif /* INVARIANTS */
10487 			dp->di_extb[i] = 0;
10488 		}
10489 		lastadp = NULL;
10490 		break;
10491 	}
10492 	/*
10493 	 * If we have zero'ed out the last allocated block of the ext
10494 	 * data, roll back the size to the last currently allocated block.
10495 	 * We know that this last allocated block is a full-sized as
10496 	 * we already checked for fragments in the loop above.
10497 	 */
10498 	if (lastadp != NULL &&
10499 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10500 		for (i = lastadp->ad_offset; i >= 0; i--)
10501 			if (dp->di_extb[i] != 0)
10502 				break;
10503 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10504 	}
10505 	/*
10506 	 * Set the file data dependencies to busy.
10507 	 */
10508 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10509 	     adp = TAILQ_NEXT(adp, ad_next)) {
10510 #ifdef INVARIANTS
10511 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10512 			panic("softdep_write_inodeblock: lbn order");
10513 		if ((adp->ad_state & ATTACHED) == 0)
10514 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10515 		prevlbn = adp->ad_offset;
10516 		if (adp->ad_offset < UFS_NDADDR &&
10517 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10518 			panic("initiate_write_inodeblock_ufs2: "
10519 			    "direct pointer #%jd mismatch %jd != %jd",
10520 			    (intmax_t)adp->ad_offset,
10521 			    (intmax_t)dp->di_db[adp->ad_offset],
10522 			    (intmax_t)adp->ad_newblkno);
10523 		if (adp->ad_offset >= UFS_NDADDR &&
10524 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10525 			panic("initiate_write_inodeblock_ufs2: "
10526 			    "indirect pointer #%jd mismatch %jd != %jd",
10527 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10528 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10529 			    (intmax_t)adp->ad_newblkno);
10530 		deplist |= 1 << adp->ad_offset;
10531 		if ((adp->ad_state & ATTACHED) == 0)
10532 			panic("initiate_write_inodeblock_ufs2: Unknown "
10533 			     "state 0x%x", adp->ad_state);
10534 #endif /* INVARIANTS */
10535 		adp->ad_state &= ~ATTACHED;
10536 		adp->ad_state |= UNDONE;
10537 	}
10538 	/*
10539 	 * The on-disk inode cannot claim to be any larger than the last
10540 	 * fragment that has been written. Otherwise, the on-disk inode
10541 	 * might have fragments that were not the last block in the file
10542 	 * which would corrupt the filesystem.
10543 	 */
10544 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10545 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10546 		if (adp->ad_offset >= UFS_NDADDR)
10547 			break;
10548 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10549 		/* keep going until hitting a rollback to a frag */
10550 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10551 			continue;
10552 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10553 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10554 #ifdef INVARIANTS
10555 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10556 				panic("initiate_write_inodeblock_ufs2: "
10557 				    "lost dep2");
10558 #endif /* INVARIANTS */
10559 			dp->di_db[i] = 0;
10560 		}
10561 		for (i = 0; i < UFS_NIADDR; i++) {
10562 #ifdef INVARIANTS
10563 			if (dp->di_ib[i] != 0 &&
10564 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10565 				panic("initiate_write_inodeblock_ufs2: "
10566 				    "lost dep3");
10567 #endif /* INVARIANTS */
10568 			dp->di_ib[i] = 0;
10569 		}
10570 		ffs_update_dinode_ckhash(fs, dp);
10571 		return;
10572 	}
10573 	/*
10574 	 * If we have zero'ed out the last allocated block of the file,
10575 	 * roll back the size to the last currently allocated block.
10576 	 * We know that this last allocated block is a full-sized as
10577 	 * we already checked for fragments in the loop above.
10578 	 */
10579 	if (lastadp != NULL &&
10580 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10581 		for (i = lastadp->ad_offset; i >= 0; i--)
10582 			if (dp->di_db[i] != 0)
10583 				break;
10584 		dp->di_size = (i + 1) * fs->fs_bsize;
10585 	}
10586 	/*
10587 	 * The only dependencies are for indirect blocks.
10588 	 *
10589 	 * The file size for indirect block additions is not guaranteed.
10590 	 * Such a guarantee would be non-trivial to achieve. The conventional
10591 	 * synchronous write implementation also does not make this guarantee.
10592 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10593 	 * can be over-estimated without destroying integrity when the file
10594 	 * moves into the indirect blocks (i.e., is large). If we want to
10595 	 * postpone fsck, we are stuck with this argument.
10596 	 */
10597 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10598 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10599 	ffs_update_dinode_ckhash(fs, dp);
10600 }
10601 
10602 /*
10603  * Cancel an indirdep as a result of truncation.  Release all of the
10604  * children allocindirs and place their journal work on the appropriate
10605  * list.
10606  */
10607 static void
10608 cancel_indirdep(indirdep, bp, freeblks)
10609 	struct indirdep *indirdep;
10610 	struct buf *bp;
10611 	struct freeblks *freeblks;
10612 {
10613 	struct allocindir *aip;
10614 
10615 	/*
10616 	 * None of the indirect pointers will ever be visible,
10617 	 * so they can simply be tossed. GOINGAWAY ensures
10618 	 * that allocated pointers will be saved in the buffer
10619 	 * cache until they are freed. Note that they will
10620 	 * only be able to be found by their physical address
10621 	 * since the inode mapping the logical address will
10622 	 * be gone. The save buffer used for the safe copy
10623 	 * was allocated in setup_allocindir_phase2 using
10624 	 * the physical address so it could be used for this
10625 	 * purpose. Hence we swap the safe copy with the real
10626 	 * copy, allowing the safe copy to be freed and holding
10627 	 * on to the real copy for later use in indir_trunc.
10628 	 */
10629 	if (indirdep->ir_state & GOINGAWAY)
10630 		panic("cancel_indirdep: already gone");
10631 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10632 		indirdep->ir_state |= DEPCOMPLETE;
10633 		LIST_REMOVE(indirdep, ir_next);
10634 	}
10635 	indirdep->ir_state |= GOINGAWAY;
10636 	/*
10637 	 * Pass in bp for blocks still have journal writes
10638 	 * pending so we can cancel them on their own.
10639 	 */
10640 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10641 		cancel_allocindir(aip, bp, freeblks, 0);
10642 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10643 		cancel_allocindir(aip, NULL, freeblks, 0);
10644 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10645 		cancel_allocindir(aip, NULL, freeblks, 0);
10646 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10647 		cancel_allocindir(aip, NULL, freeblks, 0);
10648 	/*
10649 	 * If there are pending partial truncations we need to keep the
10650 	 * old block copy around until they complete.  This is because
10651 	 * the current b_data is not a perfect superset of the available
10652 	 * blocks.
10653 	 */
10654 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10655 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10656 	else
10657 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10658 	WORKLIST_REMOVE(&indirdep->ir_list);
10659 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10660 	indirdep->ir_bp = NULL;
10661 	indirdep->ir_freeblks = freeblks;
10662 }
10663 
10664 /*
10665  * Free an indirdep once it no longer has new pointers to track.
10666  */
10667 static void
10668 free_indirdep(indirdep)
10669 	struct indirdep *indirdep;
10670 {
10671 
10672 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10673 	    ("free_indirdep: Indir trunc list not empty."));
10674 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10675 	    ("free_indirdep: Complete head not empty."));
10676 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10677 	    ("free_indirdep: write head not empty."));
10678 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10679 	    ("free_indirdep: done head not empty."));
10680 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10681 	    ("free_indirdep: deplist head not empty."));
10682 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10683 	    ("free_indirdep: %p still on newblk list.", indirdep));
10684 	KASSERT(indirdep->ir_saveddata == NULL,
10685 	    ("free_indirdep: %p still has saved data.", indirdep));
10686 	if (indirdep->ir_state & ONWORKLIST)
10687 		WORKLIST_REMOVE(&indirdep->ir_list);
10688 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10689 }
10690 
10691 /*
10692  * Called before a write to an indirdep.  This routine is responsible for
10693  * rolling back pointers to a safe state which includes only those
10694  * allocindirs which have been completed.
10695  */
10696 static void
10697 initiate_write_indirdep(indirdep, bp)
10698 	struct indirdep *indirdep;
10699 	struct buf *bp;
10700 {
10701 	struct ufsmount *ump;
10702 
10703 	indirdep->ir_state |= IOSTARTED;
10704 	if (indirdep->ir_state & GOINGAWAY)
10705 		panic("disk_io_initiation: indirdep gone");
10706 	/*
10707 	 * If there are no remaining dependencies, this will be writing
10708 	 * the real pointers.
10709 	 */
10710 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10711 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10712 		return;
10713 	/*
10714 	 * Replace up-to-date version with safe version.
10715 	 */
10716 	if (indirdep->ir_saveddata == NULL) {
10717 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10718 		LOCK_OWNED(ump);
10719 		FREE_LOCK(ump);
10720 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10721 		    M_SOFTDEP_FLAGS);
10722 		ACQUIRE_LOCK(ump);
10723 	}
10724 	indirdep->ir_state &= ~ATTACHED;
10725 	indirdep->ir_state |= UNDONE;
10726 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10727 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10728 	    bp->b_bcount);
10729 }
10730 
10731 /*
10732  * Called when an inode has been cleared in a cg bitmap.  This finally
10733  * eliminates any canceled jaddrefs
10734  */
10735 void
10736 softdep_setup_inofree(mp, bp, ino, wkhd)
10737 	struct mount *mp;
10738 	struct buf *bp;
10739 	ino_t ino;
10740 	struct workhead *wkhd;
10741 {
10742 	struct worklist *wk, *wkn;
10743 	struct inodedep *inodedep;
10744 	struct ufsmount *ump;
10745 	uint8_t *inosused;
10746 	struct cg *cgp;
10747 	struct fs *fs;
10748 
10749 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10750 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10751 	ump = VFSTOUFS(mp);
10752 	ACQUIRE_LOCK(ump);
10753 	fs = ump->um_fs;
10754 	cgp = (struct cg *)bp->b_data;
10755 	inosused = cg_inosused(cgp);
10756 	if (isset(inosused, ino % fs->fs_ipg))
10757 		panic("softdep_setup_inofree: inode %ju not freed.",
10758 		    (uintmax_t)ino);
10759 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10760 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10761 		    (uintmax_t)ino, inodedep);
10762 	if (wkhd) {
10763 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10764 			if (wk->wk_type != D_JADDREF)
10765 				continue;
10766 			WORKLIST_REMOVE(wk);
10767 			/*
10768 			 * We can free immediately even if the jaddref
10769 			 * isn't attached in a background write as now
10770 			 * the bitmaps are reconciled.
10771 			 */
10772 			wk->wk_state |= COMPLETE | ATTACHED;
10773 			free_jaddref(WK_JADDREF(wk));
10774 		}
10775 		jwork_move(&bp->b_dep, wkhd);
10776 	}
10777 	FREE_LOCK(ump);
10778 }
10779 
10780 
10781 /*
10782  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10783  * map.  Any dependencies waiting for the write to clear are added to the
10784  * buf's list and any jnewblks that are being canceled are discarded
10785  * immediately.
10786  */
10787 void
10788 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10789 	struct mount *mp;
10790 	struct buf *bp;
10791 	ufs2_daddr_t blkno;
10792 	int frags;
10793 	struct workhead *wkhd;
10794 {
10795 	struct bmsafemap *bmsafemap;
10796 	struct jnewblk *jnewblk;
10797 	struct ufsmount *ump;
10798 	struct worklist *wk;
10799 	struct fs *fs;
10800 #ifdef INVARIANTS
10801 	uint8_t *blksfree;
10802 	struct cg *cgp;
10803 	ufs2_daddr_t jstart;
10804 	ufs2_daddr_t jend;
10805 	ufs2_daddr_t end;
10806 	long bno;
10807 	int i;
10808 #endif
10809 
10810 	CTR3(KTR_SUJ,
10811 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10812 	    blkno, frags, wkhd);
10813 
10814 	ump = VFSTOUFS(mp);
10815 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10816 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10817 	ACQUIRE_LOCK(ump);
10818 	/* Lookup the bmsafemap so we track when it is dirty. */
10819 	fs = ump->um_fs;
10820 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10821 	/*
10822 	 * Detach any jnewblks which have been canceled.  They must linger
10823 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10824 	 * an unjournaled allocation from hitting the disk.
10825 	 */
10826 	if (wkhd) {
10827 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10828 			CTR2(KTR_SUJ,
10829 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10830 			    blkno, wk->wk_type);
10831 			WORKLIST_REMOVE(wk);
10832 			if (wk->wk_type != D_JNEWBLK) {
10833 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10834 				continue;
10835 			}
10836 			jnewblk = WK_JNEWBLK(wk);
10837 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10838 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10839 #ifdef INVARIANTS
10840 			/*
10841 			 * Assert that this block is free in the bitmap
10842 			 * before we discard the jnewblk.
10843 			 */
10844 			cgp = (struct cg *)bp->b_data;
10845 			blksfree = cg_blksfree(cgp);
10846 			bno = dtogd(fs, jnewblk->jn_blkno);
10847 			for (i = jnewblk->jn_oldfrags;
10848 			    i < jnewblk->jn_frags; i++) {
10849 				if (isset(blksfree, bno + i))
10850 					continue;
10851 				panic("softdep_setup_blkfree: not free");
10852 			}
10853 #endif
10854 			/*
10855 			 * Even if it's not attached we can free immediately
10856 			 * as the new bitmap is correct.
10857 			 */
10858 			wk->wk_state |= COMPLETE | ATTACHED;
10859 			free_jnewblk(jnewblk);
10860 		}
10861 	}
10862 
10863 #ifdef INVARIANTS
10864 	/*
10865 	 * Assert that we are not freeing a block which has an outstanding
10866 	 * allocation dependency.
10867 	 */
10868 	fs = VFSTOUFS(mp)->um_fs;
10869 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10870 	end = blkno + frags;
10871 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10872 		/*
10873 		 * Don't match against blocks that will be freed when the
10874 		 * background write is done.
10875 		 */
10876 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10877 		    (COMPLETE | DEPCOMPLETE))
10878 			continue;
10879 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10880 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10881 		if ((blkno >= jstart && blkno < jend) ||
10882 		    (end > jstart && end <= jend)) {
10883 			printf("state 0x%X %jd - %d %d dep %p\n",
10884 			    jnewblk->jn_state, jnewblk->jn_blkno,
10885 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10886 			    jnewblk->jn_dep);
10887 			panic("softdep_setup_blkfree: "
10888 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10889 			    blkno, end, frags, jstart, jend);
10890 		}
10891 	}
10892 #endif
10893 	FREE_LOCK(ump);
10894 }
10895 
10896 /*
10897  * Revert a block allocation when the journal record that describes it
10898  * is not yet written.
10899  */
10900 static int
10901 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10902 	struct jnewblk *jnewblk;
10903 	struct fs *fs;
10904 	struct cg *cgp;
10905 	uint8_t *blksfree;
10906 {
10907 	ufs1_daddr_t fragno;
10908 	long cgbno, bbase;
10909 	int frags, blk;
10910 	int i;
10911 
10912 	frags = 0;
10913 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10914 	/*
10915 	 * We have to test which frags need to be rolled back.  We may
10916 	 * be operating on a stale copy when doing background writes.
10917 	 */
10918 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10919 		if (isclr(blksfree, cgbno + i))
10920 			frags++;
10921 	if (frags == 0)
10922 		return (0);
10923 	/*
10924 	 * This is mostly ffs_blkfree() sans some validation and
10925 	 * superblock updates.
10926 	 */
10927 	if (frags == fs->fs_frag) {
10928 		fragno = fragstoblks(fs, cgbno);
10929 		ffs_setblock(fs, blksfree, fragno);
10930 		ffs_clusteracct(fs, cgp, fragno, 1);
10931 		cgp->cg_cs.cs_nbfree++;
10932 	} else {
10933 		cgbno += jnewblk->jn_oldfrags;
10934 		bbase = cgbno - fragnum(fs, cgbno);
10935 		/* Decrement the old frags.  */
10936 		blk = blkmap(fs, blksfree, bbase);
10937 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10938 		/* Deallocate the fragment */
10939 		for (i = 0; i < frags; i++)
10940 			setbit(blksfree, cgbno + i);
10941 		cgp->cg_cs.cs_nffree += frags;
10942 		/* Add back in counts associated with the new frags */
10943 		blk = blkmap(fs, blksfree, bbase);
10944 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10945 		/* If a complete block has been reassembled, account for it. */
10946 		fragno = fragstoblks(fs, bbase);
10947 		if (ffs_isblock(fs, blksfree, fragno)) {
10948 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10949 			ffs_clusteracct(fs, cgp, fragno, 1);
10950 			cgp->cg_cs.cs_nbfree++;
10951 		}
10952 	}
10953 	stat_jnewblk++;
10954 	jnewblk->jn_state &= ~ATTACHED;
10955 	jnewblk->jn_state |= UNDONE;
10956 
10957 	return (frags);
10958 }
10959 
10960 static void
10961 initiate_write_bmsafemap(bmsafemap, bp)
10962 	struct bmsafemap *bmsafemap;
10963 	struct buf *bp;			/* The cg block. */
10964 {
10965 	struct jaddref *jaddref;
10966 	struct jnewblk *jnewblk;
10967 	uint8_t *inosused;
10968 	uint8_t *blksfree;
10969 	struct cg *cgp;
10970 	struct fs *fs;
10971 	ino_t ino;
10972 
10973 	/*
10974 	 * If this is a background write, we did this at the time that
10975 	 * the copy was made, so do not need to do it again.
10976 	 */
10977 	if (bmsafemap->sm_state & IOSTARTED)
10978 		return;
10979 	bmsafemap->sm_state |= IOSTARTED;
10980 	/*
10981 	 * Clear any inode allocations which are pending journal writes.
10982 	 */
10983 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10984 		cgp = (struct cg *)bp->b_data;
10985 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10986 		inosused = cg_inosused(cgp);
10987 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10988 			ino = jaddref->ja_ino % fs->fs_ipg;
10989 			if (isset(inosused, ino)) {
10990 				if ((jaddref->ja_mode & IFMT) == IFDIR)
10991 					cgp->cg_cs.cs_ndir--;
10992 				cgp->cg_cs.cs_nifree++;
10993 				clrbit(inosused, ino);
10994 				jaddref->ja_state &= ~ATTACHED;
10995 				jaddref->ja_state |= UNDONE;
10996 				stat_jaddref++;
10997 			} else
10998 				panic("initiate_write_bmsafemap: inode %ju "
10999 				    "marked free", (uintmax_t)jaddref->ja_ino);
11000 		}
11001 	}
11002 	/*
11003 	 * Clear any block allocations which are pending journal writes.
11004 	 */
11005 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11006 		cgp = (struct cg *)bp->b_data;
11007 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11008 		blksfree = cg_blksfree(cgp);
11009 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11010 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11011 				continue;
11012 			panic("initiate_write_bmsafemap: block %jd "
11013 			    "marked free", jnewblk->jn_blkno);
11014 		}
11015 	}
11016 	/*
11017 	 * Move allocation lists to the written lists so they can be
11018 	 * cleared once the block write is complete.
11019 	 */
11020 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11021 	    inodedep, id_deps);
11022 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11023 	    newblk, nb_deps);
11024 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11025 	    wk_list);
11026 }
11027 
11028 /*
11029  * This routine is called during the completion interrupt
11030  * service routine for a disk write (from the procedure called
11031  * by the device driver to inform the filesystem caches of
11032  * a request completion).  It should be called early in this
11033  * procedure, before the block is made available to other
11034  * processes or other routines are called.
11035  *
11036  */
11037 static void
11038 softdep_disk_write_complete(bp)
11039 	struct buf *bp;		/* describes the completed disk write */
11040 {
11041 	struct worklist *wk;
11042 	struct worklist *owk;
11043 	struct ufsmount *ump;
11044 	struct workhead reattach;
11045 	struct freeblks *freeblks;
11046 	struct buf *sbp;
11047 
11048 	ump = softdep_bp_to_mp(bp);
11049 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11050 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11051 	     "with outstanding dependencies for buffer %p", bp));
11052 	if (ump == NULL)
11053 		return;
11054 	/*
11055 	 * If an error occurred while doing the write, then the data
11056 	 * has not hit the disk and the dependencies cannot be processed.
11057 	 * But we do have to go through and roll forward any dependencies
11058 	 * that were rolled back before the disk write.
11059 	 */
11060 	sbp = NULL;
11061 	ACQUIRE_LOCK(ump);
11062 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11063 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11064 			switch (wk->wk_type) {
11065 
11066 			case D_PAGEDEP:
11067 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11068 				continue;
11069 
11070 			case D_INODEDEP:
11071 				handle_written_inodeblock(WK_INODEDEP(wk),
11072 				    bp, 0);
11073 				continue;
11074 
11075 			case D_BMSAFEMAP:
11076 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11077 				    bp, 0);
11078 				continue;
11079 
11080 			case D_INDIRDEP:
11081 				handle_written_indirdep(WK_INDIRDEP(wk),
11082 				    bp, &sbp, 0);
11083 				continue;
11084 			default:
11085 				/* nothing to roll forward */
11086 				continue;
11087 			}
11088 		}
11089 		FREE_LOCK(ump);
11090 		if (sbp)
11091 			brelse(sbp);
11092 		return;
11093 	}
11094 	LIST_INIT(&reattach);
11095 
11096 	/*
11097 	 * Ump SU lock must not be released anywhere in this code segment.
11098 	 */
11099 	owk = NULL;
11100 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11101 		WORKLIST_REMOVE(wk);
11102 		atomic_add_long(&dep_write[wk->wk_type], 1);
11103 		if (wk == owk)
11104 			panic("duplicate worklist: %p\n", wk);
11105 		owk = wk;
11106 		switch (wk->wk_type) {
11107 
11108 		case D_PAGEDEP:
11109 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11110 			    WRITESUCCEEDED))
11111 				WORKLIST_INSERT(&reattach, wk);
11112 			continue;
11113 
11114 		case D_INODEDEP:
11115 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11116 			    WRITESUCCEEDED))
11117 				WORKLIST_INSERT(&reattach, wk);
11118 			continue;
11119 
11120 		case D_BMSAFEMAP:
11121 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11122 			    WRITESUCCEEDED))
11123 				WORKLIST_INSERT(&reattach, wk);
11124 			continue;
11125 
11126 		case D_MKDIR:
11127 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11128 			continue;
11129 
11130 		case D_ALLOCDIRECT:
11131 			wk->wk_state |= COMPLETE;
11132 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11133 			continue;
11134 
11135 		case D_ALLOCINDIR:
11136 			wk->wk_state |= COMPLETE;
11137 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11138 			continue;
11139 
11140 		case D_INDIRDEP:
11141 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11142 			    WRITESUCCEEDED))
11143 				WORKLIST_INSERT(&reattach, wk);
11144 			continue;
11145 
11146 		case D_FREEBLKS:
11147 			wk->wk_state |= COMPLETE;
11148 			freeblks = WK_FREEBLKS(wk);
11149 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11150 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11151 				add_to_worklist(wk, WK_NODELAY);
11152 			continue;
11153 
11154 		case D_FREEWORK:
11155 			handle_written_freework(WK_FREEWORK(wk));
11156 			break;
11157 
11158 		case D_JSEGDEP:
11159 			free_jsegdep(WK_JSEGDEP(wk));
11160 			continue;
11161 
11162 		case D_JSEG:
11163 			handle_written_jseg(WK_JSEG(wk), bp);
11164 			continue;
11165 
11166 		case D_SBDEP:
11167 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11168 				WORKLIST_INSERT(&reattach, wk);
11169 			continue;
11170 
11171 		case D_FREEDEP:
11172 			free_freedep(WK_FREEDEP(wk));
11173 			continue;
11174 
11175 		default:
11176 			panic("handle_disk_write_complete: Unknown type %s",
11177 			    TYPENAME(wk->wk_type));
11178 			/* NOTREACHED */
11179 		}
11180 	}
11181 	/*
11182 	 * Reattach any requests that must be redone.
11183 	 */
11184 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11185 		WORKLIST_REMOVE(wk);
11186 		WORKLIST_INSERT(&bp->b_dep, wk);
11187 	}
11188 	FREE_LOCK(ump);
11189 	if (sbp)
11190 		brelse(sbp);
11191 }
11192 
11193 /*
11194  * Called from within softdep_disk_write_complete above.
11195  */
11196 static void
11197 handle_allocdirect_partdone(adp, wkhd)
11198 	struct allocdirect *adp;	/* the completed allocdirect */
11199 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11200 {
11201 	struct allocdirectlst *listhead;
11202 	struct allocdirect *listadp;
11203 	struct inodedep *inodedep;
11204 	long bsize;
11205 
11206 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11207 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11208 		return;
11209 	/*
11210 	 * The on-disk inode cannot claim to be any larger than the last
11211 	 * fragment that has been written. Otherwise, the on-disk inode
11212 	 * might have fragments that were not the last block in the file
11213 	 * which would corrupt the filesystem. Thus, we cannot free any
11214 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11215 	 * these blocks must be rolled back to zero before writing the inode.
11216 	 * We check the currently active set of allocdirects in id_inoupdt
11217 	 * or id_extupdt as appropriate.
11218 	 */
11219 	inodedep = adp->ad_inodedep;
11220 	bsize = inodedep->id_fs->fs_bsize;
11221 	if (adp->ad_state & EXTDATA)
11222 		listhead = &inodedep->id_extupdt;
11223 	else
11224 		listhead = &inodedep->id_inoupdt;
11225 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11226 		/* found our block */
11227 		if (listadp == adp)
11228 			break;
11229 		/* continue if ad_oldlbn is not a fragment */
11230 		if (listadp->ad_oldsize == 0 ||
11231 		    listadp->ad_oldsize == bsize)
11232 			continue;
11233 		/* hit a fragment */
11234 		return;
11235 	}
11236 	/*
11237 	 * If we have reached the end of the current list without
11238 	 * finding the just finished dependency, then it must be
11239 	 * on the future dependency list. Future dependencies cannot
11240 	 * be freed until they are moved to the current list.
11241 	 */
11242 	if (listadp == NULL) {
11243 #ifdef INVARIANTS
11244 		if (adp->ad_state & EXTDATA)
11245 			listhead = &inodedep->id_newextupdt;
11246 		else
11247 			listhead = &inodedep->id_newinoupdt;
11248 		TAILQ_FOREACH(listadp, listhead, ad_next)
11249 			/* found our block */
11250 			if (listadp == adp)
11251 				break;
11252 		if (listadp == NULL)
11253 			panic("handle_allocdirect_partdone: lost dep");
11254 #endif /* INVARIANTS */
11255 		return;
11256 	}
11257 	/*
11258 	 * If we have found the just finished dependency, then queue
11259 	 * it along with anything that follows it that is complete.
11260 	 * Since the pointer has not yet been written in the inode
11261 	 * as the dependency prevents it, place the allocdirect on the
11262 	 * bufwait list where it will be freed once the pointer is
11263 	 * valid.
11264 	 */
11265 	if (wkhd == NULL)
11266 		wkhd = &inodedep->id_bufwait;
11267 	for (; adp; adp = listadp) {
11268 		listadp = TAILQ_NEXT(adp, ad_next);
11269 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11270 			return;
11271 		TAILQ_REMOVE(listhead, adp, ad_next);
11272 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11273 	}
11274 }
11275 
11276 /*
11277  * Called from within softdep_disk_write_complete above.  This routine
11278  * completes successfully written allocindirs.
11279  */
11280 static void
11281 handle_allocindir_partdone(aip)
11282 	struct allocindir *aip;		/* the completed allocindir */
11283 {
11284 	struct indirdep *indirdep;
11285 
11286 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11287 		return;
11288 	indirdep = aip->ai_indirdep;
11289 	LIST_REMOVE(aip, ai_next);
11290 	/*
11291 	 * Don't set a pointer while the buffer is undergoing IO or while
11292 	 * we have active truncations.
11293 	 */
11294 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11295 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11296 		return;
11297 	}
11298 	if (indirdep->ir_state & UFS1FMT)
11299 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11300 		    aip->ai_newblkno;
11301 	else
11302 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11303 		    aip->ai_newblkno;
11304 	/*
11305 	 * Await the pointer write before freeing the allocindir.
11306 	 */
11307 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11308 }
11309 
11310 /*
11311  * Release segments held on a jwork list.
11312  */
11313 static void
11314 handle_jwork(wkhd)
11315 	struct workhead *wkhd;
11316 {
11317 	struct worklist *wk;
11318 
11319 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11320 		WORKLIST_REMOVE(wk);
11321 		switch (wk->wk_type) {
11322 		case D_JSEGDEP:
11323 			free_jsegdep(WK_JSEGDEP(wk));
11324 			continue;
11325 		case D_FREEDEP:
11326 			free_freedep(WK_FREEDEP(wk));
11327 			continue;
11328 		case D_FREEFRAG:
11329 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11330 			WORKITEM_FREE(wk, D_FREEFRAG);
11331 			continue;
11332 		case D_FREEWORK:
11333 			handle_written_freework(WK_FREEWORK(wk));
11334 			continue;
11335 		default:
11336 			panic("handle_jwork: Unknown type %s\n",
11337 			    TYPENAME(wk->wk_type));
11338 		}
11339 	}
11340 }
11341 
11342 /*
11343  * Handle the bufwait list on an inode when it is safe to release items
11344  * held there.  This normally happens after an inode block is written but
11345  * may be delayed and handled later if there are pending journal items that
11346  * are not yet safe to be released.
11347  */
11348 static struct freefile *
11349 handle_bufwait(inodedep, refhd)
11350 	struct inodedep *inodedep;
11351 	struct workhead *refhd;
11352 {
11353 	struct jaddref *jaddref;
11354 	struct freefile *freefile;
11355 	struct worklist *wk;
11356 
11357 	freefile = NULL;
11358 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11359 		WORKLIST_REMOVE(wk);
11360 		switch (wk->wk_type) {
11361 		case D_FREEFILE:
11362 			/*
11363 			 * We defer adding freefile to the worklist
11364 			 * until all other additions have been made to
11365 			 * ensure that it will be done after all the
11366 			 * old blocks have been freed.
11367 			 */
11368 			if (freefile != NULL)
11369 				panic("handle_bufwait: freefile");
11370 			freefile = WK_FREEFILE(wk);
11371 			continue;
11372 
11373 		case D_MKDIR:
11374 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11375 			continue;
11376 
11377 		case D_DIRADD:
11378 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11379 			continue;
11380 
11381 		case D_FREEFRAG:
11382 			wk->wk_state |= COMPLETE;
11383 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11384 				add_to_worklist(wk, 0);
11385 			continue;
11386 
11387 		case D_DIRREM:
11388 			wk->wk_state |= COMPLETE;
11389 			add_to_worklist(wk, 0);
11390 			continue;
11391 
11392 		case D_ALLOCDIRECT:
11393 		case D_ALLOCINDIR:
11394 			free_newblk(WK_NEWBLK(wk));
11395 			continue;
11396 
11397 		case D_JNEWBLK:
11398 			wk->wk_state |= COMPLETE;
11399 			free_jnewblk(WK_JNEWBLK(wk));
11400 			continue;
11401 
11402 		/*
11403 		 * Save freed journal segments and add references on
11404 		 * the supplied list which will delay their release
11405 		 * until the cg bitmap is cleared on disk.
11406 		 */
11407 		case D_JSEGDEP:
11408 			if (refhd == NULL)
11409 				free_jsegdep(WK_JSEGDEP(wk));
11410 			else
11411 				WORKLIST_INSERT(refhd, wk);
11412 			continue;
11413 
11414 		case D_JADDREF:
11415 			jaddref = WK_JADDREF(wk);
11416 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11417 			    if_deps);
11418 			/*
11419 			 * Transfer any jaddrefs to the list to be freed with
11420 			 * the bitmap if we're handling a removed file.
11421 			 */
11422 			if (refhd == NULL) {
11423 				wk->wk_state |= COMPLETE;
11424 				free_jaddref(jaddref);
11425 			} else
11426 				WORKLIST_INSERT(refhd, wk);
11427 			continue;
11428 
11429 		default:
11430 			panic("handle_bufwait: Unknown type %p(%s)",
11431 			    wk, TYPENAME(wk->wk_type));
11432 			/* NOTREACHED */
11433 		}
11434 	}
11435 	return (freefile);
11436 }
11437 /*
11438  * Called from within softdep_disk_write_complete above to restore
11439  * in-memory inode block contents to their most up-to-date state. Note
11440  * that this routine is always called from interrupt level with further
11441  * interrupts from this device blocked.
11442  *
11443  * If the write did not succeed, we will do all the roll-forward
11444  * operations, but we will not take the actions that will allow its
11445  * dependencies to be processed.
11446  */
11447 static int
11448 handle_written_inodeblock(inodedep, bp, flags)
11449 	struct inodedep *inodedep;
11450 	struct buf *bp;		/* buffer containing the inode block */
11451 	int flags;
11452 {
11453 	struct freefile *freefile;
11454 	struct allocdirect *adp, *nextadp;
11455 	struct ufs1_dinode *dp1 = NULL;
11456 	struct ufs2_dinode *dp2 = NULL;
11457 	struct workhead wkhd;
11458 	int hadchanges, fstype;
11459 	ino_t freelink;
11460 
11461 	LIST_INIT(&wkhd);
11462 	hadchanges = 0;
11463 	freefile = NULL;
11464 	if ((inodedep->id_state & IOSTARTED) == 0)
11465 		panic("handle_written_inodeblock: not started");
11466 	inodedep->id_state &= ~IOSTARTED;
11467 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11468 		fstype = UFS1;
11469 		dp1 = (struct ufs1_dinode *)bp->b_data +
11470 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11471 		freelink = dp1->di_freelink;
11472 	} else {
11473 		fstype = UFS2;
11474 		dp2 = (struct ufs2_dinode *)bp->b_data +
11475 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11476 		freelink = dp2->di_freelink;
11477 	}
11478 	/*
11479 	 * Leave this inodeblock dirty until it's in the list.
11480 	 */
11481 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11482 	    (flags & WRITESUCCEEDED)) {
11483 		struct inodedep *inon;
11484 
11485 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11486 		if ((inon == NULL && freelink == 0) ||
11487 		    (inon && inon->id_ino == freelink)) {
11488 			if (inon)
11489 				inon->id_state |= UNLINKPREV;
11490 			inodedep->id_state |= UNLINKNEXT;
11491 		}
11492 		hadchanges = 1;
11493 	}
11494 	/*
11495 	 * If we had to rollback the inode allocation because of
11496 	 * bitmaps being incomplete, then simply restore it.
11497 	 * Keep the block dirty so that it will not be reclaimed until
11498 	 * all associated dependencies have been cleared and the
11499 	 * corresponding updates written to disk.
11500 	 */
11501 	if (inodedep->id_savedino1 != NULL) {
11502 		hadchanges = 1;
11503 		if (fstype == UFS1)
11504 			*dp1 = *inodedep->id_savedino1;
11505 		else
11506 			*dp2 = *inodedep->id_savedino2;
11507 		free(inodedep->id_savedino1, M_SAVEDINO);
11508 		inodedep->id_savedino1 = NULL;
11509 		if ((bp->b_flags & B_DELWRI) == 0)
11510 			stat_inode_bitmap++;
11511 		bdirty(bp);
11512 		/*
11513 		 * If the inode is clear here and GOINGAWAY it will never
11514 		 * be written.  Process the bufwait and clear any pending
11515 		 * work which may include the freefile.
11516 		 */
11517 		if (inodedep->id_state & GOINGAWAY)
11518 			goto bufwait;
11519 		return (1);
11520 	}
11521 	if (flags & WRITESUCCEEDED)
11522 		inodedep->id_state |= COMPLETE;
11523 	/*
11524 	 * Roll forward anything that had to be rolled back before
11525 	 * the inode could be updated.
11526 	 */
11527 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11528 		nextadp = TAILQ_NEXT(adp, ad_next);
11529 		if (adp->ad_state & ATTACHED)
11530 			panic("handle_written_inodeblock: new entry");
11531 		if (fstype == UFS1) {
11532 			if (adp->ad_offset < UFS_NDADDR) {
11533 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11534 					panic("%s %s #%jd mismatch %d != %jd",
11535 					    "handle_written_inodeblock:",
11536 					    "direct pointer",
11537 					    (intmax_t)adp->ad_offset,
11538 					    dp1->di_db[adp->ad_offset],
11539 					    (intmax_t)adp->ad_oldblkno);
11540 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11541 			} else {
11542 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11543 				    0)
11544 					panic("%s: %s #%jd allocated as %d",
11545 					    "handle_written_inodeblock",
11546 					    "indirect pointer",
11547 					    (intmax_t)adp->ad_offset -
11548 					    UFS_NDADDR,
11549 					    dp1->di_ib[adp->ad_offset -
11550 					    UFS_NDADDR]);
11551 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11552 				    adp->ad_newblkno;
11553 			}
11554 		} else {
11555 			if (adp->ad_offset < UFS_NDADDR) {
11556 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11557 					panic("%s: %s #%jd %s %jd != %jd",
11558 					    "handle_written_inodeblock",
11559 					    "direct pointer",
11560 					    (intmax_t)adp->ad_offset, "mismatch",
11561 					    (intmax_t)dp2->di_db[adp->ad_offset],
11562 					    (intmax_t)adp->ad_oldblkno);
11563 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11564 			} else {
11565 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11566 				    0)
11567 					panic("%s: %s #%jd allocated as %jd",
11568 					    "handle_written_inodeblock",
11569 					    "indirect pointer",
11570 					    (intmax_t)adp->ad_offset -
11571 					    UFS_NDADDR,
11572 					    (intmax_t)
11573 					    dp2->di_ib[adp->ad_offset -
11574 					    UFS_NDADDR]);
11575 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11576 				    adp->ad_newblkno;
11577 			}
11578 		}
11579 		adp->ad_state &= ~UNDONE;
11580 		adp->ad_state |= ATTACHED;
11581 		hadchanges = 1;
11582 	}
11583 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11584 		nextadp = TAILQ_NEXT(adp, ad_next);
11585 		if (adp->ad_state & ATTACHED)
11586 			panic("handle_written_inodeblock: new entry");
11587 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11588 			panic("%s: direct pointers #%jd %s %jd != %jd",
11589 			    "handle_written_inodeblock",
11590 			    (intmax_t)adp->ad_offset, "mismatch",
11591 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11592 			    (intmax_t)adp->ad_oldblkno);
11593 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11594 		adp->ad_state &= ~UNDONE;
11595 		adp->ad_state |= ATTACHED;
11596 		hadchanges = 1;
11597 	}
11598 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11599 		stat_direct_blk_ptrs++;
11600 	/*
11601 	 * Reset the file size to its most up-to-date value.
11602 	 */
11603 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11604 		panic("handle_written_inodeblock: bad size");
11605 	if (inodedep->id_savednlink > UFS_LINK_MAX)
11606 		panic("handle_written_inodeblock: Invalid link count "
11607 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11608 		    inodedep);
11609 	if (fstype == UFS1) {
11610 		if (dp1->di_nlink != inodedep->id_savednlink) {
11611 			dp1->di_nlink = inodedep->id_savednlink;
11612 			hadchanges = 1;
11613 		}
11614 		if (dp1->di_size != inodedep->id_savedsize) {
11615 			dp1->di_size = inodedep->id_savedsize;
11616 			hadchanges = 1;
11617 		}
11618 	} else {
11619 		if (dp2->di_nlink != inodedep->id_savednlink) {
11620 			dp2->di_nlink = inodedep->id_savednlink;
11621 			hadchanges = 1;
11622 		}
11623 		if (dp2->di_size != inodedep->id_savedsize) {
11624 			dp2->di_size = inodedep->id_savedsize;
11625 			hadchanges = 1;
11626 		}
11627 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11628 			dp2->di_extsize = inodedep->id_savedextsize;
11629 			hadchanges = 1;
11630 		}
11631 	}
11632 	inodedep->id_savedsize = -1;
11633 	inodedep->id_savedextsize = -1;
11634 	inodedep->id_savednlink = -1;
11635 	/*
11636 	 * If there were any rollbacks in the inode block, then it must be
11637 	 * marked dirty so that its will eventually get written back in
11638 	 * its correct form.
11639 	 */
11640 	if (hadchanges) {
11641 		if (fstype == UFS2)
11642 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11643 		bdirty(bp);
11644 	}
11645 bufwait:
11646 	/*
11647 	 * If the write did not succeed, we have done all the roll-forward
11648 	 * operations, but we cannot take the actions that will allow its
11649 	 * dependencies to be processed.
11650 	 */
11651 	if ((flags & WRITESUCCEEDED) == 0)
11652 		return (hadchanges);
11653 	/*
11654 	 * Process any allocdirects that completed during the update.
11655 	 */
11656 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11657 		handle_allocdirect_partdone(adp, &wkhd);
11658 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11659 		handle_allocdirect_partdone(adp, &wkhd);
11660 	/*
11661 	 * Process deallocations that were held pending until the
11662 	 * inode had been written to disk. Freeing of the inode
11663 	 * is delayed until after all blocks have been freed to
11664 	 * avoid creation of new <vfsid, inum, lbn> triples
11665 	 * before the old ones have been deleted.  Completely
11666 	 * unlinked inodes are not processed until the unlinked
11667 	 * inode list is written or the last reference is removed.
11668 	 */
11669 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11670 		freefile = handle_bufwait(inodedep, NULL);
11671 		if (freefile && !LIST_EMPTY(&wkhd)) {
11672 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11673 			freefile = NULL;
11674 		}
11675 	}
11676 	/*
11677 	 * Move rolled forward dependency completions to the bufwait list
11678 	 * now that those that were already written have been processed.
11679 	 */
11680 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11681 		panic("handle_written_inodeblock: bufwait but no changes");
11682 	jwork_move(&inodedep->id_bufwait, &wkhd);
11683 
11684 	if (freefile != NULL) {
11685 		/*
11686 		 * If the inode is goingaway it was never written.  Fake up
11687 		 * the state here so free_inodedep() can succeed.
11688 		 */
11689 		if (inodedep->id_state & GOINGAWAY)
11690 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11691 		if (free_inodedep(inodedep) == 0)
11692 			panic("handle_written_inodeblock: live inodedep %p",
11693 			    inodedep);
11694 		add_to_worklist(&freefile->fx_list, 0);
11695 		return (0);
11696 	}
11697 
11698 	/*
11699 	 * If no outstanding dependencies, free it.
11700 	 */
11701 	if (free_inodedep(inodedep) ||
11702 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11703 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11704 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11705 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11706 		return (0);
11707 	return (hadchanges);
11708 }
11709 
11710 /*
11711  * Perform needed roll-forwards and kick off any dependencies that
11712  * can now be processed.
11713  *
11714  * If the write did not succeed, we will do all the roll-forward
11715  * operations, but we will not take the actions that will allow its
11716  * dependencies to be processed.
11717  */
11718 static int
11719 handle_written_indirdep(indirdep, bp, bpp, flags)
11720 	struct indirdep *indirdep;
11721 	struct buf *bp;
11722 	struct buf **bpp;
11723 	int flags;
11724 {
11725 	struct allocindir *aip;
11726 	struct buf *sbp;
11727 	int chgs;
11728 
11729 	if (indirdep->ir_state & GOINGAWAY)
11730 		panic("handle_written_indirdep: indirdep gone");
11731 	if ((indirdep->ir_state & IOSTARTED) == 0)
11732 		panic("handle_written_indirdep: IO not started");
11733 	chgs = 0;
11734 	/*
11735 	 * If there were rollbacks revert them here.
11736 	 */
11737 	if (indirdep->ir_saveddata) {
11738 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11739 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11740 			free(indirdep->ir_saveddata, M_INDIRDEP);
11741 			indirdep->ir_saveddata = NULL;
11742 		}
11743 		chgs = 1;
11744 	}
11745 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11746 	indirdep->ir_state |= ATTACHED;
11747 	/*
11748 	 * If the write did not succeed, we have done all the roll-forward
11749 	 * operations, but we cannot take the actions that will allow its
11750 	 * dependencies to be processed.
11751 	 */
11752 	if ((flags & WRITESUCCEEDED) == 0) {
11753 		stat_indir_blk_ptrs++;
11754 		bdirty(bp);
11755 		return (1);
11756 	}
11757 	/*
11758 	 * Move allocindirs with written pointers to the completehd if
11759 	 * the indirdep's pointer is not yet written.  Otherwise
11760 	 * free them here.
11761 	 */
11762 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11763 		LIST_REMOVE(aip, ai_next);
11764 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11765 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11766 			    ai_next);
11767 			newblk_freefrag(&aip->ai_block);
11768 			continue;
11769 		}
11770 		free_newblk(&aip->ai_block);
11771 	}
11772 	/*
11773 	 * Move allocindirs that have finished dependency processing from
11774 	 * the done list to the write list after updating the pointers.
11775 	 */
11776 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11777 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11778 			handle_allocindir_partdone(aip);
11779 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11780 				panic("disk_write_complete: not gone");
11781 			chgs = 1;
11782 		}
11783 	}
11784 	/*
11785 	 * Preserve the indirdep if there were any changes or if it is not
11786 	 * yet valid on disk.
11787 	 */
11788 	if (chgs) {
11789 		stat_indir_blk_ptrs++;
11790 		bdirty(bp);
11791 		return (1);
11792 	}
11793 	/*
11794 	 * If there were no changes we can discard the savedbp and detach
11795 	 * ourselves from the buf.  We are only carrying completed pointers
11796 	 * in this case.
11797 	 */
11798 	sbp = indirdep->ir_savebp;
11799 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11800 	indirdep->ir_savebp = NULL;
11801 	indirdep->ir_bp = NULL;
11802 	if (*bpp != NULL)
11803 		panic("handle_written_indirdep: bp already exists.");
11804 	*bpp = sbp;
11805 	/*
11806 	 * The indirdep may not be freed until its parent points at it.
11807 	 */
11808 	if (indirdep->ir_state & DEPCOMPLETE)
11809 		free_indirdep(indirdep);
11810 
11811 	return (0);
11812 }
11813 
11814 /*
11815  * Process a diradd entry after its dependent inode has been written.
11816  */
11817 static void
11818 diradd_inode_written(dap, inodedep)
11819 	struct diradd *dap;
11820 	struct inodedep *inodedep;
11821 {
11822 
11823 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
11824 	dap->da_state |= COMPLETE;
11825 	complete_diradd(dap);
11826 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11827 }
11828 
11829 /*
11830  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11831  * be called with the per-filesystem lock and the buf lock on the cg held.
11832  */
11833 static int
11834 bmsafemap_backgroundwrite(bmsafemap, bp)
11835 	struct bmsafemap *bmsafemap;
11836 	struct buf *bp;
11837 {
11838 	int dirty;
11839 
11840 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11841 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11842 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11843 	/*
11844 	 * If we're initiating a background write we need to process the
11845 	 * rollbacks as they exist now, not as they exist when IO starts.
11846 	 * No other consumers will look at the contents of the shadowed
11847 	 * buf so this is safe to do here.
11848 	 */
11849 	if (bp->b_xflags & BX_BKGRDMARKER)
11850 		initiate_write_bmsafemap(bmsafemap, bp);
11851 
11852 	return (dirty);
11853 }
11854 
11855 /*
11856  * Re-apply an allocation when a cg write is complete.
11857  */
11858 static int
11859 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11860 	struct jnewblk *jnewblk;
11861 	struct fs *fs;
11862 	struct cg *cgp;
11863 	uint8_t *blksfree;
11864 {
11865 	ufs1_daddr_t fragno;
11866 	ufs2_daddr_t blkno;
11867 	long cgbno, bbase;
11868 	int frags, blk;
11869 	int i;
11870 
11871 	frags = 0;
11872 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11873 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11874 		if (isclr(blksfree, cgbno + i))
11875 			panic("jnewblk_rollforward: re-allocated fragment");
11876 		frags++;
11877 	}
11878 	if (frags == fs->fs_frag) {
11879 		blkno = fragstoblks(fs, cgbno);
11880 		ffs_clrblock(fs, blksfree, (long)blkno);
11881 		ffs_clusteracct(fs, cgp, blkno, -1);
11882 		cgp->cg_cs.cs_nbfree--;
11883 	} else {
11884 		bbase = cgbno - fragnum(fs, cgbno);
11885 		cgbno += jnewblk->jn_oldfrags;
11886                 /* If a complete block had been reassembled, account for it. */
11887 		fragno = fragstoblks(fs, bbase);
11888 		if (ffs_isblock(fs, blksfree, fragno)) {
11889 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11890 			ffs_clusteracct(fs, cgp, fragno, -1);
11891 			cgp->cg_cs.cs_nbfree--;
11892 		}
11893 		/* Decrement the old frags.  */
11894 		blk = blkmap(fs, blksfree, bbase);
11895 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11896 		/* Allocate the fragment */
11897 		for (i = 0; i < frags; i++)
11898 			clrbit(blksfree, cgbno + i);
11899 		cgp->cg_cs.cs_nffree -= frags;
11900 		/* Add back in counts associated with the new frags */
11901 		blk = blkmap(fs, blksfree, bbase);
11902 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11903 	}
11904 	return (frags);
11905 }
11906 
11907 /*
11908  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11909  * changes if it's not a background write.  Set all written dependencies
11910  * to DEPCOMPLETE and free the structure if possible.
11911  *
11912  * If the write did not succeed, we will do all the roll-forward
11913  * operations, but we will not take the actions that will allow its
11914  * dependencies to be processed.
11915  */
11916 static int
11917 handle_written_bmsafemap(bmsafemap, bp, flags)
11918 	struct bmsafemap *bmsafemap;
11919 	struct buf *bp;
11920 	int flags;
11921 {
11922 	struct newblk *newblk;
11923 	struct inodedep *inodedep;
11924 	struct jaddref *jaddref, *jatmp;
11925 	struct jnewblk *jnewblk, *jntmp;
11926 	struct ufsmount *ump;
11927 	uint8_t *inosused;
11928 	uint8_t *blksfree;
11929 	struct cg *cgp;
11930 	struct fs *fs;
11931 	ino_t ino;
11932 	int foreground;
11933 	int chgs;
11934 
11935 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11936 		panic("handle_written_bmsafemap: Not started\n");
11937 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11938 	chgs = 0;
11939 	bmsafemap->sm_state &= ~IOSTARTED;
11940 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11941 	/*
11942 	 * If write was successful, release journal work that was waiting
11943 	 * on the write. Otherwise move the work back.
11944 	 */
11945 	if (flags & WRITESUCCEEDED)
11946 		handle_jwork(&bmsafemap->sm_freewr);
11947 	else
11948 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11949 		    worklist, wk_list);
11950 
11951 	/*
11952 	 * Restore unwritten inode allocation pending jaddref writes.
11953 	 */
11954 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11955 		cgp = (struct cg *)bp->b_data;
11956 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11957 		inosused = cg_inosused(cgp);
11958 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11959 		    ja_bmdeps, jatmp) {
11960 			if ((jaddref->ja_state & UNDONE) == 0)
11961 				continue;
11962 			ino = jaddref->ja_ino % fs->fs_ipg;
11963 			if (isset(inosused, ino))
11964 				panic("handle_written_bmsafemap: "
11965 				    "re-allocated inode");
11966 			/* Do the roll-forward only if it's a real copy. */
11967 			if (foreground) {
11968 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11969 					cgp->cg_cs.cs_ndir++;
11970 				cgp->cg_cs.cs_nifree--;
11971 				setbit(inosused, ino);
11972 				chgs = 1;
11973 			}
11974 			jaddref->ja_state &= ~UNDONE;
11975 			jaddref->ja_state |= ATTACHED;
11976 			free_jaddref(jaddref);
11977 		}
11978 	}
11979 	/*
11980 	 * Restore any block allocations which are pending journal writes.
11981 	 */
11982 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11983 		cgp = (struct cg *)bp->b_data;
11984 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11985 		blksfree = cg_blksfree(cgp);
11986 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11987 		    jntmp) {
11988 			if ((jnewblk->jn_state & UNDONE) == 0)
11989 				continue;
11990 			/* Do the roll-forward only if it's a real copy. */
11991 			if (foreground &&
11992 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11993 				chgs = 1;
11994 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11995 			jnewblk->jn_state |= ATTACHED;
11996 			free_jnewblk(jnewblk);
11997 		}
11998 	}
11999 	/*
12000 	 * If the write did not succeed, we have done all the roll-forward
12001 	 * operations, but we cannot take the actions that will allow its
12002 	 * dependencies to be processed.
12003 	 */
12004 	if ((flags & WRITESUCCEEDED) == 0) {
12005 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12006 		    newblk, nb_deps);
12007 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12008 		    worklist, wk_list);
12009 		if (foreground)
12010 			bdirty(bp);
12011 		return (1);
12012 	}
12013 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12014 		newblk->nb_state |= DEPCOMPLETE;
12015 		newblk->nb_state &= ~ONDEPLIST;
12016 		newblk->nb_bmsafemap = NULL;
12017 		LIST_REMOVE(newblk, nb_deps);
12018 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12019 			handle_allocdirect_partdone(
12020 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12021 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12022 			handle_allocindir_partdone(
12023 			    WK_ALLOCINDIR(&newblk->nb_list));
12024 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12025 			panic("handle_written_bmsafemap: Unexpected type: %s",
12026 			    TYPENAME(newblk->nb_list.wk_type));
12027 	}
12028 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12029 		inodedep->id_state |= DEPCOMPLETE;
12030 		inodedep->id_state &= ~ONDEPLIST;
12031 		LIST_REMOVE(inodedep, id_deps);
12032 		inodedep->id_bmsafemap = NULL;
12033 	}
12034 	LIST_REMOVE(bmsafemap, sm_next);
12035 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12036 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12037 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12038 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12039 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12040 		LIST_REMOVE(bmsafemap, sm_hash);
12041 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12042 		return (0);
12043 	}
12044 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12045 	if (foreground)
12046 		bdirty(bp);
12047 	return (1);
12048 }
12049 
12050 /*
12051  * Try to free a mkdir dependency.
12052  */
12053 static void
12054 complete_mkdir(mkdir)
12055 	struct mkdir *mkdir;
12056 {
12057 	struct diradd *dap;
12058 
12059 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12060 		return;
12061 	LIST_REMOVE(mkdir, md_mkdirs);
12062 	dap = mkdir->md_diradd;
12063 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12064 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12065 		dap->da_state |= DEPCOMPLETE;
12066 		complete_diradd(dap);
12067 	}
12068 	WORKITEM_FREE(mkdir, D_MKDIR);
12069 }
12070 
12071 /*
12072  * Handle the completion of a mkdir dependency.
12073  */
12074 static void
12075 handle_written_mkdir(mkdir, type)
12076 	struct mkdir *mkdir;
12077 	int type;
12078 {
12079 
12080 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12081 		panic("handle_written_mkdir: bad type");
12082 	mkdir->md_state |= COMPLETE;
12083 	complete_mkdir(mkdir);
12084 }
12085 
12086 static int
12087 free_pagedep(pagedep)
12088 	struct pagedep *pagedep;
12089 {
12090 	int i;
12091 
12092 	if (pagedep->pd_state & NEWBLOCK)
12093 		return (0);
12094 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12095 		return (0);
12096 	for (i = 0; i < DAHASHSZ; i++)
12097 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12098 			return (0);
12099 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12100 		return (0);
12101 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12102 		return (0);
12103 	if (pagedep->pd_state & ONWORKLIST)
12104 		WORKLIST_REMOVE(&pagedep->pd_list);
12105 	LIST_REMOVE(pagedep, pd_hash);
12106 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12107 
12108 	return (1);
12109 }
12110 
12111 /*
12112  * Called from within softdep_disk_write_complete above.
12113  * A write operation was just completed. Removed inodes can
12114  * now be freed and associated block pointers may be committed.
12115  * Note that this routine is always called from interrupt level
12116  * with further interrupts from this device blocked.
12117  *
12118  * If the write did not succeed, we will do all the roll-forward
12119  * operations, but we will not take the actions that will allow its
12120  * dependencies to be processed.
12121  */
12122 static int
12123 handle_written_filepage(pagedep, bp, flags)
12124 	struct pagedep *pagedep;
12125 	struct buf *bp;		/* buffer containing the written page */
12126 	int flags;
12127 {
12128 	struct dirrem *dirrem;
12129 	struct diradd *dap, *nextdap;
12130 	struct direct *ep;
12131 	int i, chgs;
12132 
12133 	if ((pagedep->pd_state & IOSTARTED) == 0)
12134 		panic("handle_written_filepage: not started");
12135 	pagedep->pd_state &= ~IOSTARTED;
12136 	if ((flags & WRITESUCCEEDED) == 0)
12137 		goto rollforward;
12138 	/*
12139 	 * Process any directory removals that have been committed.
12140 	 */
12141 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12142 		LIST_REMOVE(dirrem, dm_next);
12143 		dirrem->dm_state |= COMPLETE;
12144 		dirrem->dm_dirinum = pagedep->pd_ino;
12145 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12146 		    ("handle_written_filepage: Journal entries not written."));
12147 		add_to_worklist(&dirrem->dm_list, 0);
12148 	}
12149 	/*
12150 	 * Free any directory additions that have been committed.
12151 	 * If it is a newly allocated block, we have to wait until
12152 	 * the on-disk directory inode claims the new block.
12153 	 */
12154 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12155 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12156 			free_diradd(dap, NULL);
12157 rollforward:
12158 	/*
12159 	 * Uncommitted directory entries must be restored.
12160 	 */
12161 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12162 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12163 		     dap = nextdap) {
12164 			nextdap = LIST_NEXT(dap, da_pdlist);
12165 			if (dap->da_state & ATTACHED)
12166 				panic("handle_written_filepage: attached");
12167 			ep = (struct direct *)
12168 			    ((char *)bp->b_data + dap->da_offset);
12169 			ep->d_ino = dap->da_newinum;
12170 			dap->da_state &= ~UNDONE;
12171 			dap->da_state |= ATTACHED;
12172 			chgs = 1;
12173 			/*
12174 			 * If the inode referenced by the directory has
12175 			 * been written out, then the dependency can be
12176 			 * moved to the pending list.
12177 			 */
12178 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12179 				LIST_REMOVE(dap, da_pdlist);
12180 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12181 				    da_pdlist);
12182 			}
12183 		}
12184 	}
12185 	/*
12186 	 * If there were any rollbacks in the directory, then it must be
12187 	 * marked dirty so that its will eventually get written back in
12188 	 * its correct form.
12189 	 */
12190 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12191 		if ((bp->b_flags & B_DELWRI) == 0)
12192 			stat_dir_entry++;
12193 		bdirty(bp);
12194 		return (1);
12195 	}
12196 	/*
12197 	 * If we are not waiting for a new directory block to be
12198 	 * claimed by its inode, then the pagedep will be freed.
12199 	 * Otherwise it will remain to track any new entries on
12200 	 * the page in case they are fsync'ed.
12201 	 */
12202 	free_pagedep(pagedep);
12203 	return (0);
12204 }
12205 
12206 /*
12207  * Writing back in-core inode structures.
12208  *
12209  * The filesystem only accesses an inode's contents when it occupies an
12210  * "in-core" inode structure.  These "in-core" structures are separate from
12211  * the page frames used to cache inode blocks.  Only the latter are
12212  * transferred to/from the disk.  So, when the updated contents of the
12213  * "in-core" inode structure are copied to the corresponding in-memory inode
12214  * block, the dependencies are also transferred.  The following procedure is
12215  * called when copying a dirty "in-core" inode to a cached inode block.
12216  */
12217 
12218 /*
12219  * Called when an inode is loaded from disk. If the effective link count
12220  * differed from the actual link count when it was last flushed, then we
12221  * need to ensure that the correct effective link count is put back.
12222  */
12223 void
12224 softdep_load_inodeblock(ip)
12225 	struct inode *ip;	/* the "in_core" copy of the inode */
12226 {
12227 	struct inodedep *inodedep;
12228 	struct ufsmount *ump;
12229 
12230 	ump = ITOUMP(ip);
12231 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12232 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12233 	/*
12234 	 * Check for alternate nlink count.
12235 	 */
12236 	ip->i_effnlink = ip->i_nlink;
12237 	ACQUIRE_LOCK(ump);
12238 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12239 		FREE_LOCK(ump);
12240 		return;
12241 	}
12242 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12243 	FREE_LOCK(ump);
12244 }
12245 
12246 /*
12247  * This routine is called just before the "in-core" inode
12248  * information is to be copied to the in-memory inode block.
12249  * Recall that an inode block contains several inodes. If
12250  * the force flag is set, then the dependencies will be
12251  * cleared so that the update can always be made. Note that
12252  * the buffer is locked when this routine is called, so we
12253  * will never be in the middle of writing the inode block
12254  * to disk.
12255  */
12256 void
12257 softdep_update_inodeblock(ip, bp, waitfor)
12258 	struct inode *ip;	/* the "in_core" copy of the inode */
12259 	struct buf *bp;		/* the buffer containing the inode block */
12260 	int waitfor;		/* nonzero => update must be allowed */
12261 {
12262 	struct inodedep *inodedep;
12263 	struct inoref *inoref;
12264 	struct ufsmount *ump;
12265 	struct worklist *wk;
12266 	struct mount *mp;
12267 	struct buf *ibp;
12268 	struct fs *fs;
12269 	int error;
12270 
12271 	ump = ITOUMP(ip);
12272 	mp = UFSTOVFS(ump);
12273 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12274 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12275 	fs = ump->um_fs;
12276 	/*
12277 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12278 	 * does not have access to the in-core ip so must write directly into
12279 	 * the inode block buffer when setting freelink.
12280 	 */
12281 	if (fs->fs_magic == FS_UFS1_MAGIC)
12282 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12283 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12284 	else
12285 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12286 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12287 	/*
12288 	 * If the effective link count is not equal to the actual link
12289 	 * count, then we must track the difference in an inodedep while
12290 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12291 	 * if there is no existing inodedep, then there are no dependencies
12292 	 * to track.
12293 	 */
12294 	ACQUIRE_LOCK(ump);
12295 again:
12296 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12297 		FREE_LOCK(ump);
12298 		if (ip->i_effnlink != ip->i_nlink)
12299 			panic("softdep_update_inodeblock: bad link count");
12300 		return;
12301 	}
12302 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12303 		panic("softdep_update_inodeblock: bad delta");
12304 	/*
12305 	 * If we're flushing all dependencies we must also move any waiting
12306 	 * for journal writes onto the bufwait list prior to I/O.
12307 	 */
12308 	if (waitfor) {
12309 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12310 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12311 			    == DEPCOMPLETE) {
12312 				jwait(&inoref->if_list, MNT_WAIT);
12313 				goto again;
12314 			}
12315 		}
12316 	}
12317 	/*
12318 	 * Changes have been initiated. Anything depending on these
12319 	 * changes cannot occur until this inode has been written.
12320 	 */
12321 	inodedep->id_state &= ~COMPLETE;
12322 	if ((inodedep->id_state & ONWORKLIST) == 0)
12323 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12324 	/*
12325 	 * Any new dependencies associated with the incore inode must
12326 	 * now be moved to the list associated with the buffer holding
12327 	 * the in-memory copy of the inode. Once merged process any
12328 	 * allocdirects that are completed by the merger.
12329 	 */
12330 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12331 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12332 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12333 		    NULL);
12334 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12335 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12336 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12337 		    NULL);
12338 	/*
12339 	 * Now that the inode has been pushed into the buffer, the
12340 	 * operations dependent on the inode being written to disk
12341 	 * can be moved to the id_bufwait so that they will be
12342 	 * processed when the buffer I/O completes.
12343 	 */
12344 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12345 		WORKLIST_REMOVE(wk);
12346 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12347 	}
12348 	/*
12349 	 * Newly allocated inodes cannot be written until the bitmap
12350 	 * that allocates them have been written (indicated by
12351 	 * DEPCOMPLETE being set in id_state). If we are doing a
12352 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12353 	 * to be written so that the update can be done.
12354 	 */
12355 	if (waitfor == 0) {
12356 		FREE_LOCK(ump);
12357 		return;
12358 	}
12359 retry:
12360 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12361 		FREE_LOCK(ump);
12362 		return;
12363 	}
12364 	ibp = inodedep->id_bmsafemap->sm_buf;
12365 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12366 	if (ibp == NULL) {
12367 		/*
12368 		 * If ibp came back as NULL, the dependency could have been
12369 		 * freed while we slept.  Look it up again, and check to see
12370 		 * that it has completed.
12371 		 */
12372 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12373 			goto retry;
12374 		FREE_LOCK(ump);
12375 		return;
12376 	}
12377 	FREE_LOCK(ump);
12378 	if ((error = bwrite(ibp)) != 0)
12379 		softdep_error("softdep_update_inodeblock: bwrite", error);
12380 }
12381 
12382 /*
12383  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12384  * old inode dependency list (such as id_inoupdt).
12385  */
12386 static void
12387 merge_inode_lists(newlisthead, oldlisthead)
12388 	struct allocdirectlst *newlisthead;
12389 	struct allocdirectlst *oldlisthead;
12390 {
12391 	struct allocdirect *listadp, *newadp;
12392 
12393 	newadp = TAILQ_FIRST(newlisthead);
12394 	if (newadp != NULL)
12395 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12396 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12397 		if (listadp->ad_offset < newadp->ad_offset) {
12398 			listadp = TAILQ_NEXT(listadp, ad_next);
12399 			continue;
12400 		}
12401 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12402 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12403 		if (listadp->ad_offset == newadp->ad_offset) {
12404 			allocdirect_merge(oldlisthead, newadp,
12405 			    listadp);
12406 			listadp = newadp;
12407 		}
12408 		newadp = TAILQ_FIRST(newlisthead);
12409 	}
12410 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12411 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12412 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12413 	}
12414 }
12415 
12416 /*
12417  * If we are doing an fsync, then we must ensure that any directory
12418  * entries for the inode have been written after the inode gets to disk.
12419  */
12420 int
12421 softdep_fsync(vp)
12422 	struct vnode *vp;	/* the "in_core" copy of the inode */
12423 {
12424 	struct inodedep *inodedep;
12425 	struct pagedep *pagedep;
12426 	struct inoref *inoref;
12427 	struct ufsmount *ump;
12428 	struct worklist *wk;
12429 	struct diradd *dap;
12430 	struct mount *mp;
12431 	struct vnode *pvp;
12432 	struct inode *ip;
12433 	struct buf *bp;
12434 	struct fs *fs;
12435 	struct thread *td = curthread;
12436 	int error, flushparent, pagedep_new_block;
12437 	ino_t parentino;
12438 	ufs_lbn_t lbn;
12439 
12440 	ip = VTOI(vp);
12441 	mp = vp->v_mount;
12442 	ump = VFSTOUFS(mp);
12443 	fs = ump->um_fs;
12444 	if (MOUNTEDSOFTDEP(mp) == 0)
12445 		return (0);
12446 	ACQUIRE_LOCK(ump);
12447 restart:
12448 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12449 		FREE_LOCK(ump);
12450 		return (0);
12451 	}
12452 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12453 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12454 		    == DEPCOMPLETE) {
12455 			jwait(&inoref->if_list, MNT_WAIT);
12456 			goto restart;
12457 		}
12458 	}
12459 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12460 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12461 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12462 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12463 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12464 		panic("softdep_fsync: pending ops %p", inodedep);
12465 	for (error = 0, flushparent = 0; ; ) {
12466 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12467 			break;
12468 		if (wk->wk_type != D_DIRADD)
12469 			panic("softdep_fsync: Unexpected type %s",
12470 			    TYPENAME(wk->wk_type));
12471 		dap = WK_DIRADD(wk);
12472 		/*
12473 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12474 		 * dependency or is contained in a newly allocated block.
12475 		 */
12476 		if (dap->da_state & DIRCHG)
12477 			pagedep = dap->da_previous->dm_pagedep;
12478 		else
12479 			pagedep = dap->da_pagedep;
12480 		parentino = pagedep->pd_ino;
12481 		lbn = pagedep->pd_lbn;
12482 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12483 			panic("softdep_fsync: dirty");
12484 		if ((dap->da_state & MKDIR_PARENT) ||
12485 		    (pagedep->pd_state & NEWBLOCK))
12486 			flushparent = 1;
12487 		else
12488 			flushparent = 0;
12489 		/*
12490 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12491 		 * then we will not be able to release and recover the
12492 		 * vnode below, so we just have to give up on writing its
12493 		 * directory entry out. It will eventually be written, just
12494 		 * not now, but then the user was not asking to have it
12495 		 * written, so we are not breaking any promises.
12496 		 */
12497 		if (vp->v_iflag & VI_DOOMED)
12498 			break;
12499 		/*
12500 		 * We prevent deadlock by always fetching inodes from the
12501 		 * root, moving down the directory tree. Thus, when fetching
12502 		 * our parent directory, we first try to get the lock. If
12503 		 * that fails, we must unlock ourselves before requesting
12504 		 * the lock on our parent. See the comment in ufs_lookup
12505 		 * for details on possible races.
12506 		 */
12507 		FREE_LOCK(ump);
12508 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12509 		    FFSV_FORCEINSMQ)) {
12510 			/*
12511 			 * Unmount cannot proceed after unlock because
12512 			 * caller must have called vn_start_write().
12513 			 */
12514 			VOP_UNLOCK(vp, 0);
12515 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12516 			    &pvp, FFSV_FORCEINSMQ);
12517 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12518 			if (vp->v_iflag & VI_DOOMED) {
12519 				if (error == 0)
12520 					vput(pvp);
12521 				error = ENOENT;
12522 			}
12523 			if (error != 0)
12524 				return (error);
12525 		}
12526 		/*
12527 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12528 		 * that are contained in direct blocks will be resolved by
12529 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12530 		 * may require a complete sync'ing of the directory. So, we
12531 		 * try the cheap and fast ffs_update first, and if that fails,
12532 		 * then we do the slower ffs_syncvnode of the directory.
12533 		 */
12534 		if (flushparent) {
12535 			int locked;
12536 
12537 			if ((error = ffs_update(pvp, 1)) != 0) {
12538 				vput(pvp);
12539 				return (error);
12540 			}
12541 			ACQUIRE_LOCK(ump);
12542 			locked = 1;
12543 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12544 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12545 					if (wk->wk_type != D_DIRADD)
12546 						panic("softdep_fsync: Unexpected type %s",
12547 						      TYPENAME(wk->wk_type));
12548 					dap = WK_DIRADD(wk);
12549 					if (dap->da_state & DIRCHG)
12550 						pagedep = dap->da_previous->dm_pagedep;
12551 					else
12552 						pagedep = dap->da_pagedep;
12553 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12554 					FREE_LOCK(ump);
12555 					locked = 0;
12556 					if (pagedep_new_block && (error =
12557 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12558 						vput(pvp);
12559 						return (error);
12560 					}
12561 				}
12562 			}
12563 			if (locked)
12564 				FREE_LOCK(ump);
12565 		}
12566 		/*
12567 		 * Flush directory page containing the inode's name.
12568 		 */
12569 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12570 		    &bp);
12571 		if (error == 0)
12572 			error = bwrite(bp);
12573 		else
12574 			brelse(bp);
12575 		vput(pvp);
12576 		if (error != 0)
12577 			return (error);
12578 		ACQUIRE_LOCK(ump);
12579 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12580 			break;
12581 	}
12582 	FREE_LOCK(ump);
12583 	return (0);
12584 }
12585 
12586 /*
12587  * Flush all the dirty bitmaps associated with the block device
12588  * before flushing the rest of the dirty blocks so as to reduce
12589  * the number of dependencies that will have to be rolled back.
12590  *
12591  * XXX Unused?
12592  */
12593 void
12594 softdep_fsync_mountdev(vp)
12595 	struct vnode *vp;
12596 {
12597 	struct buf *bp, *nbp;
12598 	struct worklist *wk;
12599 	struct bufobj *bo;
12600 
12601 	if (!vn_isdisk(vp, NULL))
12602 		panic("softdep_fsync_mountdev: vnode not a disk");
12603 	bo = &vp->v_bufobj;
12604 restart:
12605 	BO_LOCK(bo);
12606 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12607 		/*
12608 		 * If it is already scheduled, skip to the next buffer.
12609 		 */
12610 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12611 			continue;
12612 
12613 		if ((bp->b_flags & B_DELWRI) == 0)
12614 			panic("softdep_fsync_mountdev: not dirty");
12615 		/*
12616 		 * We are only interested in bitmaps with outstanding
12617 		 * dependencies.
12618 		 */
12619 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12620 		    wk->wk_type != D_BMSAFEMAP ||
12621 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12622 			BUF_UNLOCK(bp);
12623 			continue;
12624 		}
12625 		BO_UNLOCK(bo);
12626 		bremfree(bp);
12627 		(void) bawrite(bp);
12628 		goto restart;
12629 	}
12630 	drain_output(vp);
12631 	BO_UNLOCK(bo);
12632 }
12633 
12634 /*
12635  * Sync all cylinder groups that were dirty at the time this function is
12636  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12637  * is used to flush freedep activity that may be holding up writes to a
12638  * indirect block.
12639  */
12640 static int
12641 sync_cgs(mp, waitfor)
12642 	struct mount *mp;
12643 	int waitfor;
12644 {
12645 	struct bmsafemap *bmsafemap;
12646 	struct bmsafemap *sentinel;
12647 	struct ufsmount *ump;
12648 	struct buf *bp;
12649 	int error;
12650 
12651 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12652 	sentinel->sm_cg = -1;
12653 	ump = VFSTOUFS(mp);
12654 	error = 0;
12655 	ACQUIRE_LOCK(ump);
12656 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12657 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12658 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12659 		/* Skip sentinels and cgs with no work to release. */
12660 		if (bmsafemap->sm_cg == -1 ||
12661 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12662 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12663 			LIST_REMOVE(sentinel, sm_next);
12664 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12665 			continue;
12666 		}
12667 		/*
12668 		 * If we don't get the lock and we're waiting try again, if
12669 		 * not move on to the next buf and try to sync it.
12670 		 */
12671 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12672 		if (bp == NULL && waitfor == MNT_WAIT)
12673 			continue;
12674 		LIST_REMOVE(sentinel, sm_next);
12675 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12676 		if (bp == NULL)
12677 			continue;
12678 		FREE_LOCK(ump);
12679 		if (waitfor == MNT_NOWAIT)
12680 			bawrite(bp);
12681 		else
12682 			error = bwrite(bp);
12683 		ACQUIRE_LOCK(ump);
12684 		if (error)
12685 			break;
12686 	}
12687 	LIST_REMOVE(sentinel, sm_next);
12688 	FREE_LOCK(ump);
12689 	free(sentinel, M_BMSAFEMAP);
12690 	return (error);
12691 }
12692 
12693 /*
12694  * This routine is called when we are trying to synchronously flush a
12695  * file. This routine must eliminate any filesystem metadata dependencies
12696  * so that the syncing routine can succeed.
12697  */
12698 int
12699 softdep_sync_metadata(struct vnode *vp)
12700 {
12701 	struct inode *ip;
12702 	int error;
12703 
12704 	ip = VTOI(vp);
12705 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12706 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12707 	/*
12708 	 * Ensure that any direct block dependencies have been cleared,
12709 	 * truncations are started, and inode references are journaled.
12710 	 */
12711 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12712 	/*
12713 	 * Write all journal records to prevent rollbacks on devvp.
12714 	 */
12715 	if (vp->v_type == VCHR)
12716 		softdep_flushjournal(vp->v_mount);
12717 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12718 	/*
12719 	 * Ensure that all truncates are written so we won't find deps on
12720 	 * indirect blocks.
12721 	 */
12722 	process_truncates(vp);
12723 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12724 
12725 	return (error);
12726 }
12727 
12728 /*
12729  * This routine is called when we are attempting to sync a buf with
12730  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12731  * other IO it can but returns EBUSY if the buffer is not yet able to
12732  * be written.  Dependencies which will not cause rollbacks will always
12733  * return 0.
12734  */
12735 int
12736 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12737 {
12738 	struct indirdep *indirdep;
12739 	struct pagedep *pagedep;
12740 	struct allocindir *aip;
12741 	struct newblk *newblk;
12742 	struct ufsmount *ump;
12743 	struct buf *nbp;
12744 	struct worklist *wk;
12745 	int i, error;
12746 
12747 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12748 	    ("softdep_sync_buf called on non-softdep filesystem"));
12749 	/*
12750 	 * For VCHR we just don't want to force flush any dependencies that
12751 	 * will cause rollbacks.
12752 	 */
12753 	if (vp->v_type == VCHR) {
12754 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12755 			return (EBUSY);
12756 		return (0);
12757 	}
12758 	ump = VFSTOUFS(vp->v_mount);
12759 	ACQUIRE_LOCK(ump);
12760 	/*
12761 	 * As we hold the buffer locked, none of its dependencies
12762 	 * will disappear.
12763 	 */
12764 	error = 0;
12765 top:
12766 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12767 		switch (wk->wk_type) {
12768 
12769 		case D_ALLOCDIRECT:
12770 		case D_ALLOCINDIR:
12771 			newblk = WK_NEWBLK(wk);
12772 			if (newblk->nb_jnewblk != NULL) {
12773 				if (waitfor == MNT_NOWAIT) {
12774 					error = EBUSY;
12775 					goto out_unlock;
12776 				}
12777 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12778 				goto top;
12779 			}
12780 			if (newblk->nb_state & DEPCOMPLETE ||
12781 			    waitfor == MNT_NOWAIT)
12782 				continue;
12783 			nbp = newblk->nb_bmsafemap->sm_buf;
12784 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12785 			if (nbp == NULL)
12786 				goto top;
12787 			FREE_LOCK(ump);
12788 			if ((error = bwrite(nbp)) != 0)
12789 				goto out;
12790 			ACQUIRE_LOCK(ump);
12791 			continue;
12792 
12793 		case D_INDIRDEP:
12794 			indirdep = WK_INDIRDEP(wk);
12795 			if (waitfor == MNT_NOWAIT) {
12796 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12797 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12798 					error = EBUSY;
12799 					goto out_unlock;
12800 				}
12801 			}
12802 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12803 				panic("softdep_sync_buf: truncation pending.");
12804 		restart:
12805 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12806 				newblk = (struct newblk *)aip;
12807 				if (newblk->nb_jnewblk != NULL) {
12808 					jwait(&newblk->nb_jnewblk->jn_list,
12809 					    waitfor);
12810 					goto restart;
12811 				}
12812 				if (newblk->nb_state & DEPCOMPLETE)
12813 					continue;
12814 				nbp = newblk->nb_bmsafemap->sm_buf;
12815 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12816 				if (nbp == NULL)
12817 					goto restart;
12818 				FREE_LOCK(ump);
12819 				if ((error = bwrite(nbp)) != 0)
12820 					goto out;
12821 				ACQUIRE_LOCK(ump);
12822 				goto restart;
12823 			}
12824 			continue;
12825 
12826 		case D_PAGEDEP:
12827 			/*
12828 			 * Only flush directory entries in synchronous passes.
12829 			 */
12830 			if (waitfor != MNT_WAIT) {
12831 				error = EBUSY;
12832 				goto out_unlock;
12833 			}
12834 			/*
12835 			 * While syncing snapshots, we must allow recursive
12836 			 * lookups.
12837 			 */
12838 			BUF_AREC(bp);
12839 			/*
12840 			 * We are trying to sync a directory that may
12841 			 * have dependencies on both its own metadata
12842 			 * and/or dependencies on the inodes of any
12843 			 * recently allocated files. We walk its diradd
12844 			 * lists pushing out the associated inode.
12845 			 */
12846 			pagedep = WK_PAGEDEP(wk);
12847 			for (i = 0; i < DAHASHSZ; i++) {
12848 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12849 					continue;
12850 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12851 				    &pagedep->pd_diraddhd[i]))) {
12852 					BUF_NOREC(bp);
12853 					goto out_unlock;
12854 				}
12855 			}
12856 			BUF_NOREC(bp);
12857 			continue;
12858 
12859 		case D_FREEWORK:
12860 		case D_FREEDEP:
12861 		case D_JSEGDEP:
12862 		case D_JNEWBLK:
12863 			continue;
12864 
12865 		default:
12866 			panic("softdep_sync_buf: Unknown type %s",
12867 			    TYPENAME(wk->wk_type));
12868 			/* NOTREACHED */
12869 		}
12870 	}
12871 out_unlock:
12872 	FREE_LOCK(ump);
12873 out:
12874 	return (error);
12875 }
12876 
12877 /*
12878  * Flush the dependencies associated with an inodedep.
12879  */
12880 static int
12881 flush_inodedep_deps(vp, mp, ino)
12882 	struct vnode *vp;
12883 	struct mount *mp;
12884 	ino_t ino;
12885 {
12886 	struct inodedep *inodedep;
12887 	struct inoref *inoref;
12888 	struct ufsmount *ump;
12889 	int error, waitfor;
12890 
12891 	/*
12892 	 * This work is done in two passes. The first pass grabs most
12893 	 * of the buffers and begins asynchronously writing them. The
12894 	 * only way to wait for these asynchronous writes is to sleep
12895 	 * on the filesystem vnode which may stay busy for a long time
12896 	 * if the filesystem is active. So, instead, we make a second
12897 	 * pass over the dependencies blocking on each write. In the
12898 	 * usual case we will be blocking against a write that we
12899 	 * initiated, so when it is done the dependency will have been
12900 	 * resolved. Thus the second pass is expected to end quickly.
12901 	 * We give a brief window at the top of the loop to allow
12902 	 * any pending I/O to complete.
12903 	 */
12904 	ump = VFSTOUFS(mp);
12905 	LOCK_OWNED(ump);
12906 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12907 		if (error)
12908 			return (error);
12909 		FREE_LOCK(ump);
12910 		ACQUIRE_LOCK(ump);
12911 restart:
12912 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12913 			return (0);
12914 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12915 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12916 			    == DEPCOMPLETE) {
12917 				jwait(&inoref->if_list, MNT_WAIT);
12918 				goto restart;
12919 			}
12920 		}
12921 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12922 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12923 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12924 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12925 			continue;
12926 		/*
12927 		 * If pass2, we are done, otherwise do pass 2.
12928 		 */
12929 		if (waitfor == MNT_WAIT)
12930 			break;
12931 		waitfor = MNT_WAIT;
12932 	}
12933 	/*
12934 	 * Try freeing inodedep in case all dependencies have been removed.
12935 	 */
12936 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12937 		(void) free_inodedep(inodedep);
12938 	return (0);
12939 }
12940 
12941 /*
12942  * Flush an inode dependency list.
12943  */
12944 static int
12945 flush_deplist(listhead, waitfor, errorp)
12946 	struct allocdirectlst *listhead;
12947 	int waitfor;
12948 	int *errorp;
12949 {
12950 	struct allocdirect *adp;
12951 	struct newblk *newblk;
12952 	struct ufsmount *ump;
12953 	struct buf *bp;
12954 
12955 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
12956 		return (0);
12957 	ump = VFSTOUFS(adp->ad_list.wk_mp);
12958 	LOCK_OWNED(ump);
12959 	TAILQ_FOREACH(adp, listhead, ad_next) {
12960 		newblk = (struct newblk *)adp;
12961 		if (newblk->nb_jnewblk != NULL) {
12962 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12963 			return (1);
12964 		}
12965 		if (newblk->nb_state & DEPCOMPLETE)
12966 			continue;
12967 		bp = newblk->nb_bmsafemap->sm_buf;
12968 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12969 		if (bp == NULL) {
12970 			if (waitfor == MNT_NOWAIT)
12971 				continue;
12972 			return (1);
12973 		}
12974 		FREE_LOCK(ump);
12975 		if (waitfor == MNT_NOWAIT)
12976 			bawrite(bp);
12977 		else
12978 			*errorp = bwrite(bp);
12979 		ACQUIRE_LOCK(ump);
12980 		return (1);
12981 	}
12982 	return (0);
12983 }
12984 
12985 /*
12986  * Flush dependencies associated with an allocdirect block.
12987  */
12988 static int
12989 flush_newblk_dep(vp, mp, lbn)
12990 	struct vnode *vp;
12991 	struct mount *mp;
12992 	ufs_lbn_t lbn;
12993 {
12994 	struct newblk *newblk;
12995 	struct ufsmount *ump;
12996 	struct bufobj *bo;
12997 	struct inode *ip;
12998 	struct buf *bp;
12999 	ufs2_daddr_t blkno;
13000 	int error;
13001 
13002 	error = 0;
13003 	bo = &vp->v_bufobj;
13004 	ip = VTOI(vp);
13005 	blkno = DIP(ip, i_db[lbn]);
13006 	if (blkno == 0)
13007 		panic("flush_newblk_dep: Missing block");
13008 	ump = VFSTOUFS(mp);
13009 	ACQUIRE_LOCK(ump);
13010 	/*
13011 	 * Loop until all dependencies related to this block are satisfied.
13012 	 * We must be careful to restart after each sleep in case a write
13013 	 * completes some part of this process for us.
13014 	 */
13015 	for (;;) {
13016 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13017 			FREE_LOCK(ump);
13018 			break;
13019 		}
13020 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13021 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13022 		/*
13023 		 * Flush the journal.
13024 		 */
13025 		if (newblk->nb_jnewblk != NULL) {
13026 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13027 			continue;
13028 		}
13029 		/*
13030 		 * Write the bitmap dependency.
13031 		 */
13032 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13033 			bp = newblk->nb_bmsafemap->sm_buf;
13034 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13035 			if (bp == NULL)
13036 				continue;
13037 			FREE_LOCK(ump);
13038 			error = bwrite(bp);
13039 			if (error)
13040 				break;
13041 			ACQUIRE_LOCK(ump);
13042 			continue;
13043 		}
13044 		/*
13045 		 * Write the buffer.
13046 		 */
13047 		FREE_LOCK(ump);
13048 		BO_LOCK(bo);
13049 		bp = gbincore(bo, lbn);
13050 		if (bp != NULL) {
13051 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13052 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13053 			if (error == ENOLCK) {
13054 				ACQUIRE_LOCK(ump);
13055 				error = 0;
13056 				continue; /* Slept, retry */
13057 			}
13058 			if (error != 0)
13059 				break;	/* Failed */
13060 			if (bp->b_flags & B_DELWRI) {
13061 				bremfree(bp);
13062 				error = bwrite(bp);
13063 				if (error)
13064 					break;
13065 			} else
13066 				BUF_UNLOCK(bp);
13067 		} else
13068 			BO_UNLOCK(bo);
13069 		/*
13070 		 * We have to wait for the direct pointers to
13071 		 * point at the newdirblk before the dependency
13072 		 * will go away.
13073 		 */
13074 		error = ffs_update(vp, 1);
13075 		if (error)
13076 			break;
13077 		ACQUIRE_LOCK(ump);
13078 	}
13079 	return (error);
13080 }
13081 
13082 /*
13083  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13084  */
13085 static int
13086 flush_pagedep_deps(pvp, mp, diraddhdp)
13087 	struct vnode *pvp;
13088 	struct mount *mp;
13089 	struct diraddhd *diraddhdp;
13090 {
13091 	struct inodedep *inodedep;
13092 	struct inoref *inoref;
13093 	struct ufsmount *ump;
13094 	struct diradd *dap;
13095 	struct vnode *vp;
13096 	int error = 0;
13097 	struct buf *bp;
13098 	ino_t inum;
13099 	struct diraddhd unfinished;
13100 
13101 	LIST_INIT(&unfinished);
13102 	ump = VFSTOUFS(mp);
13103 	LOCK_OWNED(ump);
13104 restart:
13105 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13106 		/*
13107 		 * Flush ourselves if this directory entry
13108 		 * has a MKDIR_PARENT dependency.
13109 		 */
13110 		if (dap->da_state & MKDIR_PARENT) {
13111 			FREE_LOCK(ump);
13112 			if ((error = ffs_update(pvp, 1)) != 0)
13113 				break;
13114 			ACQUIRE_LOCK(ump);
13115 			/*
13116 			 * If that cleared dependencies, go on to next.
13117 			 */
13118 			if (dap != LIST_FIRST(diraddhdp))
13119 				continue;
13120 			/*
13121 			 * All MKDIR_PARENT dependencies and all the
13122 			 * NEWBLOCK pagedeps that are contained in direct
13123 			 * blocks were resolved by doing above ffs_update.
13124 			 * Pagedeps contained in indirect blocks may
13125 			 * require a complete sync'ing of the directory.
13126 			 * We are in the midst of doing a complete sync,
13127 			 * so if they are not resolved in this pass we
13128 			 * defer them for now as they will be sync'ed by
13129 			 * our caller shortly.
13130 			 */
13131 			LIST_REMOVE(dap, da_pdlist);
13132 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13133 			continue;
13134 		}
13135 		/*
13136 		 * A newly allocated directory must have its "." and
13137 		 * ".." entries written out before its name can be
13138 		 * committed in its parent.
13139 		 */
13140 		inum = dap->da_newinum;
13141 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13142 			panic("flush_pagedep_deps: lost inode1");
13143 		/*
13144 		 * Wait for any pending journal adds to complete so we don't
13145 		 * cause rollbacks while syncing.
13146 		 */
13147 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13148 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13149 			    == DEPCOMPLETE) {
13150 				jwait(&inoref->if_list, MNT_WAIT);
13151 				goto restart;
13152 			}
13153 		}
13154 		if (dap->da_state & MKDIR_BODY) {
13155 			FREE_LOCK(ump);
13156 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13157 			    FFSV_FORCEINSMQ)))
13158 				break;
13159 			error = flush_newblk_dep(vp, mp, 0);
13160 			/*
13161 			 * If we still have the dependency we might need to
13162 			 * update the vnode to sync the new link count to
13163 			 * disk.
13164 			 */
13165 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13166 				error = ffs_update(vp, 1);
13167 			vput(vp);
13168 			if (error != 0)
13169 				break;
13170 			ACQUIRE_LOCK(ump);
13171 			/*
13172 			 * If that cleared dependencies, go on to next.
13173 			 */
13174 			if (dap != LIST_FIRST(diraddhdp))
13175 				continue;
13176 			if (dap->da_state & MKDIR_BODY) {
13177 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13178 				    &inodedep);
13179 				panic("flush_pagedep_deps: MKDIR_BODY "
13180 				    "inodedep %p dap %p vp %p",
13181 				    inodedep, dap, vp);
13182 			}
13183 		}
13184 		/*
13185 		 * Flush the inode on which the directory entry depends.
13186 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13187 		 * the only remaining dependency is that the updated inode
13188 		 * count must get pushed to disk. The inode has already
13189 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13190 		 * the time of the reference count change. So we need only
13191 		 * locate that buffer, ensure that there will be no rollback
13192 		 * caused by a bitmap dependency, then write the inode buffer.
13193 		 */
13194 retry:
13195 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13196 			panic("flush_pagedep_deps: lost inode");
13197 		/*
13198 		 * If the inode still has bitmap dependencies,
13199 		 * push them to disk.
13200 		 */
13201 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13202 			bp = inodedep->id_bmsafemap->sm_buf;
13203 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13204 			if (bp == NULL)
13205 				goto retry;
13206 			FREE_LOCK(ump);
13207 			if ((error = bwrite(bp)) != 0)
13208 				break;
13209 			ACQUIRE_LOCK(ump);
13210 			if (dap != LIST_FIRST(diraddhdp))
13211 				continue;
13212 		}
13213 		/*
13214 		 * If the inode is still sitting in a buffer waiting
13215 		 * to be written or waiting for the link count to be
13216 		 * adjusted update it here to flush it to disk.
13217 		 */
13218 		if (dap == LIST_FIRST(diraddhdp)) {
13219 			FREE_LOCK(ump);
13220 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13221 			    FFSV_FORCEINSMQ)))
13222 				break;
13223 			error = ffs_update(vp, 1);
13224 			vput(vp);
13225 			if (error)
13226 				break;
13227 			ACQUIRE_LOCK(ump);
13228 		}
13229 		/*
13230 		 * If we have failed to get rid of all the dependencies
13231 		 * then something is seriously wrong.
13232 		 */
13233 		if (dap == LIST_FIRST(diraddhdp)) {
13234 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13235 			panic("flush_pagedep_deps: failed to flush "
13236 			    "inodedep %p ino %ju dap %p",
13237 			    inodedep, (uintmax_t)inum, dap);
13238 		}
13239 	}
13240 	if (error)
13241 		ACQUIRE_LOCK(ump);
13242 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13243 		LIST_REMOVE(dap, da_pdlist);
13244 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13245 	}
13246 	return (error);
13247 }
13248 
13249 /*
13250  * A large burst of file addition or deletion activity can drive the
13251  * memory load excessively high. First attempt to slow things down
13252  * using the techniques below. If that fails, this routine requests
13253  * the offending operations to fall back to running synchronously
13254  * until the memory load returns to a reasonable level.
13255  */
13256 int
13257 softdep_slowdown(vp)
13258 	struct vnode *vp;
13259 {
13260 	struct ufsmount *ump;
13261 	int jlow;
13262 	int max_softdeps_hard;
13263 
13264 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13265 	    ("softdep_slowdown called on non-softdep filesystem"));
13266 	ump = VFSTOUFS(vp->v_mount);
13267 	ACQUIRE_LOCK(ump);
13268 	jlow = 0;
13269 	/*
13270 	 * Check for journal space if needed.
13271 	 */
13272 	if (DOINGSUJ(vp)) {
13273 		if (journal_space(ump, 0) == 0)
13274 			jlow = 1;
13275 	}
13276 	/*
13277 	 * If the system is under its limits and our filesystem is
13278 	 * not responsible for more than our share of the usage and
13279 	 * we are not low on journal space, then no need to slow down.
13280 	 */
13281 	max_softdeps_hard = max_softdeps * 11 / 10;
13282 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13283 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13284 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13285 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13286 	    ump->softdep_curdeps[D_DIRREM] <
13287 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13288 	    ump->softdep_curdeps[D_INODEDEP] <
13289 	    max_softdeps_hard / stat_flush_threads &&
13290 	    ump->softdep_curdeps[D_INDIRDEP] <
13291 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13292 	    ump->softdep_curdeps[D_FREEBLKS] <
13293 	    max_softdeps_hard / stat_flush_threads) {
13294 		FREE_LOCK(ump);
13295   		return (0);
13296 	}
13297 	/*
13298 	 * If the journal is low or our filesystem is over its limit
13299 	 * then speedup the cleanup.
13300 	 */
13301 	if (ump->softdep_curdeps[D_INDIRDEP] <
13302 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13303 		softdep_speedup(ump);
13304 	stat_sync_limit_hit += 1;
13305 	FREE_LOCK(ump);
13306 	/*
13307 	 * We only slow down the rate at which new dependencies are
13308 	 * generated if we are not using journaling. With journaling,
13309 	 * the cleanup should always be sufficient to keep things
13310 	 * under control.
13311 	 */
13312 	if (DOINGSUJ(vp))
13313 		return (0);
13314 	return (1);
13315 }
13316 
13317 /*
13318  * Called by the allocation routines when they are about to fail
13319  * in the hope that we can free up the requested resource (inodes
13320  * or disk space).
13321  *
13322  * First check to see if the work list has anything on it. If it has,
13323  * clean up entries until we successfully free the requested resource.
13324  * Because this process holds inodes locked, we cannot handle any remove
13325  * requests that might block on a locked inode as that could lead to
13326  * deadlock. If the worklist yields none of the requested resource,
13327  * start syncing out vnodes to free up the needed space.
13328  */
13329 int
13330 softdep_request_cleanup(fs, vp, cred, resource)
13331 	struct fs *fs;
13332 	struct vnode *vp;
13333 	struct ucred *cred;
13334 	int resource;
13335 {
13336 	struct ufsmount *ump;
13337 	struct mount *mp;
13338 	long starttime;
13339 	ufs2_daddr_t needed;
13340 	int error, failed_vnode;
13341 
13342 	/*
13343 	 * If we are being called because of a process doing a
13344 	 * copy-on-write, then it is not safe to process any
13345 	 * worklist items as we will recurse into the copyonwrite
13346 	 * routine.  This will result in an incoherent snapshot.
13347 	 * If the vnode that we hold is a snapshot, we must avoid
13348 	 * handling other resources that could cause deadlock.
13349 	 */
13350 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13351 		return (0);
13352 
13353 	if (resource == FLUSH_BLOCKS_WAIT)
13354 		stat_cleanup_blkrequests += 1;
13355 	else
13356 		stat_cleanup_inorequests += 1;
13357 
13358 	mp = vp->v_mount;
13359 	ump = VFSTOUFS(mp);
13360 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13361 	UFS_UNLOCK(ump);
13362 	error = ffs_update(vp, 1);
13363 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13364 		UFS_LOCK(ump);
13365 		return (0);
13366 	}
13367 	/*
13368 	 * If we are in need of resources, start by cleaning up
13369 	 * any block removals associated with our inode.
13370 	 */
13371 	ACQUIRE_LOCK(ump);
13372 	process_removes(vp);
13373 	process_truncates(vp);
13374 	FREE_LOCK(ump);
13375 	/*
13376 	 * Now clean up at least as many resources as we will need.
13377 	 *
13378 	 * When requested to clean up inodes, the number that are needed
13379 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13380 	 * plus a bit of slop (2) in case some more writers show up while
13381 	 * we are cleaning.
13382 	 *
13383 	 * When requested to free up space, the amount of space that
13384 	 * we need is enough blocks to allocate a full-sized segment
13385 	 * (fs_contigsumsize). The number of such segments that will
13386 	 * be needed is set by the number of simultaneous writers
13387 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13388 	 * writers show up while we are cleaning.
13389 	 *
13390 	 * Additionally, if we are unpriviledged and allocating space,
13391 	 * we need to ensure that we clean up enough blocks to get the
13392 	 * needed number of blocks over the threshold of the minimum
13393 	 * number of blocks required to be kept free by the filesystem
13394 	 * (fs_minfree).
13395 	 */
13396 	if (resource == FLUSH_INODES_WAIT) {
13397 		needed = vp->v_mount->mnt_writeopcount + 2;
13398 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13399 		needed = (vp->v_mount->mnt_writeopcount + 2) *
13400 		    fs->fs_contigsumsize;
13401 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13402 			needed += fragstoblks(fs,
13403 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13404 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13405 	} else {
13406 		UFS_LOCK(ump);
13407 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13408 		    resource);
13409 		return (0);
13410 	}
13411 	starttime = time_second;
13412 retry:
13413 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13414 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13415 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13416 	    fs->fs_cstotal.cs_nifree <= needed)) {
13417 		ACQUIRE_LOCK(ump);
13418 		if (ump->softdep_on_worklist > 0 &&
13419 		    process_worklist_item(UFSTOVFS(ump),
13420 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13421 			stat_worklist_push += 1;
13422 		FREE_LOCK(ump);
13423 	}
13424 	/*
13425 	 * If we still need resources and there are no more worklist
13426 	 * entries to process to obtain them, we have to start flushing
13427 	 * the dirty vnodes to force the release of additional requests
13428 	 * to the worklist that we can then process to reap addition
13429 	 * resources. We walk the vnodes associated with the mount point
13430 	 * until we get the needed worklist requests that we can reap.
13431 	 *
13432 	 * If there are several threads all needing to clean the same
13433 	 * mount point, only one is allowed to walk the mount list.
13434 	 * When several threads all try to walk the same mount list,
13435 	 * they end up competing with each other and often end up in
13436 	 * livelock. This approach ensures that forward progress is
13437 	 * made at the cost of occational ENOSPC errors being returned
13438 	 * that might otherwise have been avoided.
13439 	 */
13440 	error = 1;
13441 	if ((resource == FLUSH_BLOCKS_WAIT &&
13442 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13443 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13444 	     fs->fs_cstotal.cs_nifree <= needed)) {
13445 		ACQUIRE_LOCK(ump);
13446 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13447 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13448 			FREE_LOCK(ump);
13449 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13450 			ACQUIRE_LOCK(ump);
13451 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13452 			FREE_LOCK(ump);
13453 			if (ump->softdep_on_worklist > 0) {
13454 				stat_cleanup_retries += 1;
13455 				if (!failed_vnode)
13456 					goto retry;
13457 			}
13458 		} else {
13459 			FREE_LOCK(ump);
13460 			error = 0;
13461 		}
13462 		stat_cleanup_failures += 1;
13463 	}
13464 	if (time_second - starttime > stat_cleanup_high_delay)
13465 		stat_cleanup_high_delay = time_second - starttime;
13466 	UFS_LOCK(ump);
13467 	return (error);
13468 }
13469 
13470 /*
13471  * Scan the vnodes for the specified mount point flushing out any
13472  * vnodes that can be locked without waiting. Finally, try to flush
13473  * the device associated with the mount point if it can be locked
13474  * without waiting.
13475  *
13476  * We return 0 if we were able to lock every vnode in our scan.
13477  * If we had to skip one or more vnodes, we return 1.
13478  */
13479 static int
13480 softdep_request_cleanup_flush(mp, ump)
13481 	struct mount *mp;
13482 	struct ufsmount *ump;
13483 {
13484 	struct thread *td;
13485 	struct vnode *lvp, *mvp;
13486 	int failed_vnode;
13487 
13488 	failed_vnode = 0;
13489 	td = curthread;
13490 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13491 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13492 			VI_UNLOCK(lvp);
13493 			continue;
13494 		}
13495 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13496 		    td) != 0) {
13497 			failed_vnode = 1;
13498 			continue;
13499 		}
13500 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13501 			vput(lvp);
13502 			continue;
13503 		}
13504 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13505 		vput(lvp);
13506 	}
13507 	lvp = ump->um_devvp;
13508 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13509 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13510 		VOP_UNLOCK(lvp, 0);
13511 	}
13512 	return (failed_vnode);
13513 }
13514 
13515 static bool
13516 softdep_excess_items(struct ufsmount *ump, int item)
13517 {
13518 
13519 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13520 	return (dep_current[item] > max_softdeps &&
13521 	    ump->softdep_curdeps[item] > max_softdeps /
13522 	    stat_flush_threads);
13523 }
13524 
13525 static void
13526 schedule_cleanup(struct mount *mp)
13527 {
13528 	struct ufsmount *ump;
13529 	struct thread *td;
13530 
13531 	ump = VFSTOUFS(mp);
13532 	LOCK_OWNED(ump);
13533 	FREE_LOCK(ump);
13534 	td = curthread;
13535 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13536 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13537 		/*
13538 		 * No ast is delivered to kernel threads, so nobody
13539 		 * would deref the mp.  Some kernel threads
13540 		 * explicitely check for AST, e.g. NFS daemon does
13541 		 * this in the serving loop.
13542 		 */
13543 		return;
13544 	}
13545 	if (td->td_su != NULL)
13546 		vfs_rel(td->td_su);
13547 	vfs_ref(mp);
13548 	td->td_su = mp;
13549 	thread_lock(td);
13550 	td->td_flags |= TDF_ASTPENDING;
13551 	thread_unlock(td);
13552 }
13553 
13554 static void
13555 softdep_ast_cleanup_proc(struct thread *td)
13556 {
13557 	struct mount *mp;
13558 	struct ufsmount *ump;
13559 	int error;
13560 	bool req;
13561 
13562 	while ((mp = td->td_su) != NULL) {
13563 		td->td_su = NULL;
13564 		error = vfs_busy(mp, MBF_NOWAIT);
13565 		vfs_rel(mp);
13566 		if (error != 0)
13567 			return;
13568 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13569 			ump = VFSTOUFS(mp);
13570 			for (;;) {
13571 				req = false;
13572 				ACQUIRE_LOCK(ump);
13573 				if (softdep_excess_items(ump, D_INODEDEP)) {
13574 					req = true;
13575 					request_cleanup(mp, FLUSH_INODES);
13576 				}
13577 				if (softdep_excess_items(ump, D_DIRREM)) {
13578 					req = true;
13579 					request_cleanup(mp, FLUSH_BLOCKS);
13580 				}
13581 				FREE_LOCK(ump);
13582 				if (softdep_excess_items(ump, D_NEWBLK) ||
13583 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13584 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13585 					error = vn_start_write(NULL, &mp,
13586 					    V_WAIT);
13587 					if (error == 0) {
13588 						req = true;
13589 						VFS_SYNC(mp, MNT_WAIT);
13590 						vn_finished_write(mp);
13591 					}
13592 				}
13593 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13594 					break;
13595 			}
13596 		}
13597 		vfs_unbusy(mp);
13598 	}
13599 	if ((mp = td->td_su) != NULL) {
13600 		td->td_su = NULL;
13601 		vfs_rel(mp);
13602 	}
13603 }
13604 
13605 /*
13606  * If memory utilization has gotten too high, deliberately slow things
13607  * down and speed up the I/O processing.
13608  */
13609 static int
13610 request_cleanup(mp, resource)
13611 	struct mount *mp;
13612 	int resource;
13613 {
13614 	struct thread *td = curthread;
13615 	struct ufsmount *ump;
13616 
13617 	ump = VFSTOUFS(mp);
13618 	LOCK_OWNED(ump);
13619 	/*
13620 	 * We never hold up the filesystem syncer or buf daemon.
13621 	 */
13622 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13623 		return (0);
13624 	/*
13625 	 * First check to see if the work list has gotten backlogged.
13626 	 * If it has, co-opt this process to help clean up two entries.
13627 	 * Because this process may hold inodes locked, we cannot
13628 	 * handle any remove requests that might block on a locked
13629 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13630 	 * to avoid recursively processing the worklist.
13631 	 */
13632 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13633 		td->td_pflags |= TDP_SOFTDEP;
13634 		process_worklist_item(mp, 2, LK_NOWAIT);
13635 		td->td_pflags &= ~TDP_SOFTDEP;
13636 		stat_worklist_push += 2;
13637 		return(1);
13638 	}
13639 	/*
13640 	 * Next, we attempt to speed up the syncer process. If that
13641 	 * is successful, then we allow the process to continue.
13642 	 */
13643 	if (softdep_speedup(ump) &&
13644 	    resource != FLUSH_BLOCKS_WAIT &&
13645 	    resource != FLUSH_INODES_WAIT)
13646 		return(0);
13647 	/*
13648 	 * If we are resource constrained on inode dependencies, try
13649 	 * flushing some dirty inodes. Otherwise, we are constrained
13650 	 * by file deletions, so try accelerating flushes of directories
13651 	 * with removal dependencies. We would like to do the cleanup
13652 	 * here, but we probably hold an inode locked at this point and
13653 	 * that might deadlock against one that we try to clean. So,
13654 	 * the best that we can do is request the syncer daemon to do
13655 	 * the cleanup for us.
13656 	 */
13657 	switch (resource) {
13658 
13659 	case FLUSH_INODES:
13660 	case FLUSH_INODES_WAIT:
13661 		ACQUIRE_GBLLOCK(&lk);
13662 		stat_ino_limit_push += 1;
13663 		req_clear_inodedeps += 1;
13664 		FREE_GBLLOCK(&lk);
13665 		stat_countp = &stat_ino_limit_hit;
13666 		break;
13667 
13668 	case FLUSH_BLOCKS:
13669 	case FLUSH_BLOCKS_WAIT:
13670 		ACQUIRE_GBLLOCK(&lk);
13671 		stat_blk_limit_push += 1;
13672 		req_clear_remove += 1;
13673 		FREE_GBLLOCK(&lk);
13674 		stat_countp = &stat_blk_limit_hit;
13675 		break;
13676 
13677 	default:
13678 		panic("request_cleanup: unknown type");
13679 	}
13680 	/*
13681 	 * Hopefully the syncer daemon will catch up and awaken us.
13682 	 * We wait at most tickdelay before proceeding in any case.
13683 	 */
13684 	ACQUIRE_GBLLOCK(&lk);
13685 	FREE_LOCK(ump);
13686 	proc_waiting += 1;
13687 	if (callout_pending(&softdep_callout) == FALSE)
13688 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13689 		    pause_timer, 0);
13690 
13691 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13692 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13693 	proc_waiting -= 1;
13694 	FREE_GBLLOCK(&lk);
13695 	ACQUIRE_LOCK(ump);
13696 	return (1);
13697 }
13698 
13699 /*
13700  * Awaken processes pausing in request_cleanup and clear proc_waiting
13701  * to indicate that there is no longer a timer running. Pause_timer
13702  * will be called with the global softdep mutex (&lk) locked.
13703  */
13704 static void
13705 pause_timer(arg)
13706 	void *arg;
13707 {
13708 
13709 	GBLLOCK_OWNED(&lk);
13710 	/*
13711 	 * The callout_ API has acquired mtx and will hold it around this
13712 	 * function call.
13713 	 */
13714 	*stat_countp += proc_waiting;
13715 	wakeup(&proc_waiting);
13716 }
13717 
13718 /*
13719  * If requested, try removing inode or removal dependencies.
13720  */
13721 static void
13722 check_clear_deps(mp)
13723 	struct mount *mp;
13724 {
13725 
13726 	/*
13727 	 * If we are suspended, it may be because of our using
13728 	 * too many inodedeps, so help clear them out.
13729 	 */
13730 	if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13731 		clear_inodedeps(mp);
13732 	/*
13733 	 * General requests for cleanup of backed up dependencies
13734 	 */
13735 	ACQUIRE_GBLLOCK(&lk);
13736 	if (req_clear_inodedeps) {
13737 		req_clear_inodedeps -= 1;
13738 		FREE_GBLLOCK(&lk);
13739 		clear_inodedeps(mp);
13740 		ACQUIRE_GBLLOCK(&lk);
13741 		wakeup(&proc_waiting);
13742 	}
13743 	if (req_clear_remove) {
13744 		req_clear_remove -= 1;
13745 		FREE_GBLLOCK(&lk);
13746 		clear_remove(mp);
13747 		ACQUIRE_GBLLOCK(&lk);
13748 		wakeup(&proc_waiting);
13749 	}
13750 	FREE_GBLLOCK(&lk);
13751 }
13752 
13753 /*
13754  * Flush out a directory with at least one removal dependency in an effort to
13755  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13756  */
13757 static void
13758 clear_remove(mp)
13759 	struct mount *mp;
13760 {
13761 	struct pagedep_hashhead *pagedephd;
13762 	struct pagedep *pagedep;
13763 	struct ufsmount *ump;
13764 	struct vnode *vp;
13765 	struct bufobj *bo;
13766 	int error, cnt;
13767 	ino_t ino;
13768 
13769 	ump = VFSTOUFS(mp);
13770 	LOCK_OWNED(ump);
13771 
13772 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13773 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13774 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13775 			ump->pagedep_nextclean = 0;
13776 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13777 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13778 				continue;
13779 			ino = pagedep->pd_ino;
13780 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13781 				continue;
13782 			FREE_LOCK(ump);
13783 
13784 			/*
13785 			 * Let unmount clear deps
13786 			 */
13787 			error = vfs_busy(mp, MBF_NOWAIT);
13788 			if (error != 0)
13789 				goto finish_write;
13790 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13791 			     FFSV_FORCEINSMQ);
13792 			vfs_unbusy(mp);
13793 			if (error != 0) {
13794 				softdep_error("clear_remove: vget", error);
13795 				goto finish_write;
13796 			}
13797 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13798 				softdep_error("clear_remove: fsync", error);
13799 			bo = &vp->v_bufobj;
13800 			BO_LOCK(bo);
13801 			drain_output(vp);
13802 			BO_UNLOCK(bo);
13803 			vput(vp);
13804 		finish_write:
13805 			vn_finished_write(mp);
13806 			ACQUIRE_LOCK(ump);
13807 			return;
13808 		}
13809 	}
13810 }
13811 
13812 /*
13813  * Clear out a block of dirty inodes in an effort to reduce
13814  * the number of inodedep dependency structures.
13815  */
13816 static void
13817 clear_inodedeps(mp)
13818 	struct mount *mp;
13819 {
13820 	struct inodedep_hashhead *inodedephd;
13821 	struct inodedep *inodedep;
13822 	struct ufsmount *ump;
13823 	struct vnode *vp;
13824 	struct fs *fs;
13825 	int error, cnt;
13826 	ino_t firstino, lastino, ino;
13827 
13828 	ump = VFSTOUFS(mp);
13829 	fs = ump->um_fs;
13830 	LOCK_OWNED(ump);
13831 	/*
13832 	 * Pick a random inode dependency to be cleared.
13833 	 * We will then gather up all the inodes in its block
13834 	 * that have dependencies and flush them out.
13835 	 */
13836 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13837 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13838 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13839 			ump->inodedep_nextclean = 0;
13840 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13841 			break;
13842 	}
13843 	if (inodedep == NULL)
13844 		return;
13845 	/*
13846 	 * Find the last inode in the block with dependencies.
13847 	 */
13848 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13849 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13850 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13851 			break;
13852 	/*
13853 	 * Asynchronously push all but the last inode with dependencies.
13854 	 * Synchronously push the last inode with dependencies to ensure
13855 	 * that the inode block gets written to free up the inodedeps.
13856 	 */
13857 	for (ino = firstino; ino <= lastino; ino++) {
13858 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13859 			continue;
13860 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13861 			continue;
13862 		FREE_LOCK(ump);
13863 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13864 		if (error != 0) {
13865 			vn_finished_write(mp);
13866 			ACQUIRE_LOCK(ump);
13867 			return;
13868 		}
13869 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13870 		    FFSV_FORCEINSMQ)) != 0) {
13871 			softdep_error("clear_inodedeps: vget", error);
13872 			vfs_unbusy(mp);
13873 			vn_finished_write(mp);
13874 			ACQUIRE_LOCK(ump);
13875 			return;
13876 		}
13877 		vfs_unbusy(mp);
13878 		if (ino == lastino) {
13879 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13880 				softdep_error("clear_inodedeps: fsync1", error);
13881 		} else {
13882 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13883 				softdep_error("clear_inodedeps: fsync2", error);
13884 			BO_LOCK(&vp->v_bufobj);
13885 			drain_output(vp);
13886 			BO_UNLOCK(&vp->v_bufobj);
13887 		}
13888 		vput(vp);
13889 		vn_finished_write(mp);
13890 		ACQUIRE_LOCK(ump);
13891 	}
13892 }
13893 
13894 void
13895 softdep_buf_append(bp, wkhd)
13896 	struct buf *bp;
13897 	struct workhead *wkhd;
13898 {
13899 	struct worklist *wk;
13900 	struct ufsmount *ump;
13901 
13902 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13903 		return;
13904 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13905 	    ("softdep_buf_append called on non-softdep filesystem"));
13906 	ump = VFSTOUFS(wk->wk_mp);
13907 	ACQUIRE_LOCK(ump);
13908 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13909 		WORKLIST_REMOVE(wk);
13910 		WORKLIST_INSERT(&bp->b_dep, wk);
13911 	}
13912 	FREE_LOCK(ump);
13913 
13914 }
13915 
13916 void
13917 softdep_inode_append(ip, cred, wkhd)
13918 	struct inode *ip;
13919 	struct ucred *cred;
13920 	struct workhead *wkhd;
13921 {
13922 	struct buf *bp;
13923 	struct fs *fs;
13924 	struct ufsmount *ump;
13925 	int error;
13926 
13927 	ump = ITOUMP(ip);
13928 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13929 	    ("softdep_inode_append called on non-softdep filesystem"));
13930 	fs = ump->um_fs;
13931 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13932 	    (int)fs->fs_bsize, cred, &bp);
13933 	if (error) {
13934 		bqrelse(bp);
13935 		softdep_freework(wkhd);
13936 		return;
13937 	}
13938 	softdep_buf_append(bp, wkhd);
13939 	bqrelse(bp);
13940 }
13941 
13942 void
13943 softdep_freework(wkhd)
13944 	struct workhead *wkhd;
13945 {
13946 	struct worklist *wk;
13947 	struct ufsmount *ump;
13948 
13949 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13950 		return;
13951 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13952 	    ("softdep_freework called on non-softdep filesystem"));
13953 	ump = VFSTOUFS(wk->wk_mp);
13954 	ACQUIRE_LOCK(ump);
13955 	handle_jwork(wkhd);
13956 	FREE_LOCK(ump);
13957 }
13958 
13959 static struct ufsmount *
13960 softdep_bp_to_mp(bp)
13961 	struct buf *bp;
13962 {
13963 	struct mount *mp;
13964 	struct vnode *vp;
13965 
13966 	if (LIST_EMPTY(&bp->b_dep))
13967 		return (NULL);
13968 	vp = bp->b_vp;
13969 	KASSERT(vp != NULL,
13970 	    ("%s, buffer with dependencies lacks vnode", __func__));
13971 
13972 	/*
13973 	 * The ump mount point is stable after we get a correct
13974 	 * pointer, since bp is locked and this prevents unmount from
13975 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
13976 	 * head wk_mp, because we do not yet own SU ump lock and
13977 	 * workitem might be freed while dereferenced.
13978 	 */
13979 retry:
13980 	switch (vp->v_type) {
13981 	case VCHR:
13982 		VI_LOCK(vp);
13983 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
13984 		VI_UNLOCK(vp);
13985 		if (mp == NULL)
13986 			goto retry;
13987 		break;
13988 	case VREG:
13989 	case VDIR:
13990 	case VLNK:
13991 	case VFIFO:
13992 	case VSOCK:
13993 		mp = vp->v_mount;
13994 		break;
13995 	case VBLK:
13996 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
13997 		/* FALLTHROUGH */
13998 	case VNON:
13999 	case VBAD:
14000 	case VMARKER:
14001 		mp = NULL;
14002 		break;
14003 	default:
14004 		vn_printf(vp, "unknown vnode type");
14005 		mp = NULL;
14006 		break;
14007 	}
14008 	return (VFSTOUFS(mp));
14009 }
14010 
14011 /*
14012  * Function to determine if the buffer has outstanding dependencies
14013  * that will cause a roll-back if the buffer is written. If wantcount
14014  * is set, return number of dependencies, otherwise just yes or no.
14015  */
14016 static int
14017 softdep_count_dependencies(bp, wantcount)
14018 	struct buf *bp;
14019 	int wantcount;
14020 {
14021 	struct worklist *wk;
14022 	struct ufsmount *ump;
14023 	struct bmsafemap *bmsafemap;
14024 	struct freework *freework;
14025 	struct inodedep *inodedep;
14026 	struct indirdep *indirdep;
14027 	struct freeblks *freeblks;
14028 	struct allocindir *aip;
14029 	struct pagedep *pagedep;
14030 	struct dirrem *dirrem;
14031 	struct newblk *newblk;
14032 	struct mkdir *mkdir;
14033 	struct diradd *dap;
14034 	int i, retval;
14035 
14036 	ump = softdep_bp_to_mp(bp);
14037 	if (ump == NULL)
14038 		return (0);
14039 	retval = 0;
14040 	ACQUIRE_LOCK(ump);
14041 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14042 		switch (wk->wk_type) {
14043 
14044 		case D_INODEDEP:
14045 			inodedep = WK_INODEDEP(wk);
14046 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14047 				/* bitmap allocation dependency */
14048 				retval += 1;
14049 				if (!wantcount)
14050 					goto out;
14051 			}
14052 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14053 				/* direct block pointer dependency */
14054 				retval += 1;
14055 				if (!wantcount)
14056 					goto out;
14057 			}
14058 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14059 				/* direct block pointer dependency */
14060 				retval += 1;
14061 				if (!wantcount)
14062 					goto out;
14063 			}
14064 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14065 				/* Add reference dependency. */
14066 				retval += 1;
14067 				if (!wantcount)
14068 					goto out;
14069 			}
14070 			continue;
14071 
14072 		case D_INDIRDEP:
14073 			indirdep = WK_INDIRDEP(wk);
14074 
14075 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14076 				/* indirect truncation dependency */
14077 				retval += 1;
14078 				if (!wantcount)
14079 					goto out;
14080 			}
14081 
14082 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14083 				/* indirect block pointer dependency */
14084 				retval += 1;
14085 				if (!wantcount)
14086 					goto out;
14087 			}
14088 			continue;
14089 
14090 		case D_PAGEDEP:
14091 			pagedep = WK_PAGEDEP(wk);
14092 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14093 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14094 					/* Journal remove ref dependency. */
14095 					retval += 1;
14096 					if (!wantcount)
14097 						goto out;
14098 				}
14099 			}
14100 			for (i = 0; i < DAHASHSZ; i++) {
14101 
14102 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14103 					/* directory entry dependency */
14104 					retval += 1;
14105 					if (!wantcount)
14106 						goto out;
14107 				}
14108 			}
14109 			continue;
14110 
14111 		case D_BMSAFEMAP:
14112 			bmsafemap = WK_BMSAFEMAP(wk);
14113 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14114 				/* Add reference dependency. */
14115 				retval += 1;
14116 				if (!wantcount)
14117 					goto out;
14118 			}
14119 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14120 				/* Allocate block dependency. */
14121 				retval += 1;
14122 				if (!wantcount)
14123 					goto out;
14124 			}
14125 			continue;
14126 
14127 		case D_FREEBLKS:
14128 			freeblks = WK_FREEBLKS(wk);
14129 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14130 				/* Freeblk journal dependency. */
14131 				retval += 1;
14132 				if (!wantcount)
14133 					goto out;
14134 			}
14135 			continue;
14136 
14137 		case D_ALLOCDIRECT:
14138 		case D_ALLOCINDIR:
14139 			newblk = WK_NEWBLK(wk);
14140 			if (newblk->nb_jnewblk) {
14141 				/* Journal allocate dependency. */
14142 				retval += 1;
14143 				if (!wantcount)
14144 					goto out;
14145 			}
14146 			continue;
14147 
14148 		case D_MKDIR:
14149 			mkdir = WK_MKDIR(wk);
14150 			if (mkdir->md_jaddref) {
14151 				/* Journal reference dependency. */
14152 				retval += 1;
14153 				if (!wantcount)
14154 					goto out;
14155 			}
14156 			continue;
14157 
14158 		case D_FREEWORK:
14159 		case D_FREEDEP:
14160 		case D_JSEGDEP:
14161 		case D_JSEG:
14162 		case D_SBDEP:
14163 			/* never a dependency on these blocks */
14164 			continue;
14165 
14166 		default:
14167 			panic("softdep_count_dependencies: Unexpected type %s",
14168 			    TYPENAME(wk->wk_type));
14169 			/* NOTREACHED */
14170 		}
14171 	}
14172 out:
14173 	FREE_LOCK(ump);
14174 	return (retval);
14175 }
14176 
14177 /*
14178  * Acquire exclusive access to a buffer.
14179  * Must be called with a locked mtx parameter.
14180  * Return acquired buffer or NULL on failure.
14181  */
14182 static struct buf *
14183 getdirtybuf(bp, lock, waitfor)
14184 	struct buf *bp;
14185 	struct rwlock *lock;
14186 	int waitfor;
14187 {
14188 	int error;
14189 
14190 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14191 		if (waitfor != MNT_WAIT)
14192 			return (NULL);
14193 		error = BUF_LOCK(bp,
14194 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14195 		/*
14196 		 * Even if we successfully acquire bp here, we have dropped
14197 		 * lock, which may violates our guarantee.
14198 		 */
14199 		if (error == 0)
14200 			BUF_UNLOCK(bp);
14201 		else if (error != ENOLCK)
14202 			panic("getdirtybuf: inconsistent lock: %d", error);
14203 		rw_wlock(lock);
14204 		return (NULL);
14205 	}
14206 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14207 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14208 			rw_wunlock(lock);
14209 			BO_LOCK(bp->b_bufobj);
14210 			BUF_UNLOCK(bp);
14211 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14212 				bp->b_vflags |= BV_BKGRDWAIT;
14213 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14214 				       PRIBIO | PDROP, "getbuf", 0);
14215 			} else
14216 				BO_UNLOCK(bp->b_bufobj);
14217 			rw_wlock(lock);
14218 			return (NULL);
14219 		}
14220 		BUF_UNLOCK(bp);
14221 		if (waitfor != MNT_WAIT)
14222 			return (NULL);
14223 #ifdef DEBUG_VFS_LOCKS
14224 		if (bp->b_vp->v_type != VCHR)
14225 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14226 #endif
14227 		bp->b_vflags |= BV_BKGRDWAIT;
14228 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14229 		return (NULL);
14230 	}
14231 	if ((bp->b_flags & B_DELWRI) == 0) {
14232 		BUF_UNLOCK(bp);
14233 		return (NULL);
14234 	}
14235 	bremfree(bp);
14236 	return (bp);
14237 }
14238 
14239 
14240 /*
14241  * Check if it is safe to suspend the file system now.  On entry,
14242  * the vnode interlock for devvp should be held.  Return 0 with
14243  * the mount interlock held if the file system can be suspended now,
14244  * otherwise return EAGAIN with the mount interlock held.
14245  */
14246 int
14247 softdep_check_suspend(struct mount *mp,
14248 		      struct vnode *devvp,
14249 		      int softdep_depcnt,
14250 		      int softdep_accdepcnt,
14251 		      int secondary_writes,
14252 		      int secondary_accwrites)
14253 {
14254 	struct bufobj *bo;
14255 	struct ufsmount *ump;
14256 	struct inodedep *inodedep;
14257 	int error, unlinked;
14258 
14259 	bo = &devvp->v_bufobj;
14260 	ASSERT_BO_WLOCKED(bo);
14261 
14262 	/*
14263 	 * If we are not running with soft updates, then we need only
14264 	 * deal with secondary writes as we try to suspend.
14265 	 */
14266 	if (MOUNTEDSOFTDEP(mp) == 0) {
14267 		MNT_ILOCK(mp);
14268 		while (mp->mnt_secondary_writes != 0) {
14269 			BO_UNLOCK(bo);
14270 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14271 			    (PUSER - 1) | PDROP, "secwr", 0);
14272 			BO_LOCK(bo);
14273 			MNT_ILOCK(mp);
14274 		}
14275 
14276 		/*
14277 		 * Reasons for needing more work before suspend:
14278 		 * - Dirty buffers on devvp.
14279 		 * - Secondary writes occurred after start of vnode sync loop
14280 		 */
14281 		error = 0;
14282 		if (bo->bo_numoutput > 0 ||
14283 		    bo->bo_dirty.bv_cnt > 0 ||
14284 		    secondary_writes != 0 ||
14285 		    mp->mnt_secondary_writes != 0 ||
14286 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14287 			error = EAGAIN;
14288 		BO_UNLOCK(bo);
14289 		return (error);
14290 	}
14291 
14292 	/*
14293 	 * If we are running with soft updates, then we need to coordinate
14294 	 * with them as we try to suspend.
14295 	 */
14296 	ump = VFSTOUFS(mp);
14297 	for (;;) {
14298 		if (!TRY_ACQUIRE_LOCK(ump)) {
14299 			BO_UNLOCK(bo);
14300 			ACQUIRE_LOCK(ump);
14301 			FREE_LOCK(ump);
14302 			BO_LOCK(bo);
14303 			continue;
14304 		}
14305 		MNT_ILOCK(mp);
14306 		if (mp->mnt_secondary_writes != 0) {
14307 			FREE_LOCK(ump);
14308 			BO_UNLOCK(bo);
14309 			msleep(&mp->mnt_secondary_writes,
14310 			       MNT_MTX(mp),
14311 			       (PUSER - 1) | PDROP, "secwr", 0);
14312 			BO_LOCK(bo);
14313 			continue;
14314 		}
14315 		break;
14316 	}
14317 
14318 	unlinked = 0;
14319 	if (MOUNTEDSUJ(mp)) {
14320 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14321 		    inodedep != NULL;
14322 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14323 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14324 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14325 			    UNLINKONLIST) ||
14326 			    !check_inodedep_free(inodedep))
14327 				continue;
14328 			unlinked++;
14329 		}
14330 	}
14331 
14332 	/*
14333 	 * Reasons for needing more work before suspend:
14334 	 * - Dirty buffers on devvp.
14335 	 * - Softdep activity occurred after start of vnode sync loop
14336 	 * - Secondary writes occurred after start of vnode sync loop
14337 	 */
14338 	error = 0;
14339 	if (bo->bo_numoutput > 0 ||
14340 	    bo->bo_dirty.bv_cnt > 0 ||
14341 	    softdep_depcnt != unlinked ||
14342 	    ump->softdep_deps != unlinked ||
14343 	    softdep_accdepcnt != ump->softdep_accdeps ||
14344 	    secondary_writes != 0 ||
14345 	    mp->mnt_secondary_writes != 0 ||
14346 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14347 		error = EAGAIN;
14348 	FREE_LOCK(ump);
14349 	BO_UNLOCK(bo);
14350 	return (error);
14351 }
14352 
14353 
14354 /*
14355  * Get the number of dependency structures for the file system, both
14356  * the current number and the total number allocated.  These will
14357  * later be used to detect that softdep processing has occurred.
14358  */
14359 void
14360 softdep_get_depcounts(struct mount *mp,
14361 		      int *softdep_depsp,
14362 		      int *softdep_accdepsp)
14363 {
14364 	struct ufsmount *ump;
14365 
14366 	if (MOUNTEDSOFTDEP(mp) == 0) {
14367 		*softdep_depsp = 0;
14368 		*softdep_accdepsp = 0;
14369 		return;
14370 	}
14371 	ump = VFSTOUFS(mp);
14372 	ACQUIRE_LOCK(ump);
14373 	*softdep_depsp = ump->softdep_deps;
14374 	*softdep_accdepsp = ump->softdep_accdeps;
14375 	FREE_LOCK(ump);
14376 }
14377 
14378 /*
14379  * Wait for pending output on a vnode to complete.
14380  */
14381 static void
14382 drain_output(vp)
14383 	struct vnode *vp;
14384 {
14385 
14386 	ASSERT_VOP_LOCKED(vp, "drain_output");
14387 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14388 }
14389 
14390 /*
14391  * Called whenever a buffer that is being invalidated or reallocated
14392  * contains dependencies. This should only happen if an I/O error has
14393  * occurred. The routine is called with the buffer locked.
14394  */
14395 static void
14396 softdep_deallocate_dependencies(bp)
14397 	struct buf *bp;
14398 {
14399 
14400 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14401 		panic("softdep_deallocate_dependencies: dangling deps");
14402 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14403 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14404 	else
14405 		printf("softdep_deallocate_dependencies: "
14406 		    "got error %d while accessing filesystem\n", bp->b_error);
14407 	if (bp->b_error != ENXIO)
14408 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14409 }
14410 
14411 /*
14412  * Function to handle asynchronous write errors in the filesystem.
14413  */
14414 static void
14415 softdep_error(func, error)
14416 	char *func;
14417 	int error;
14418 {
14419 
14420 	/* XXX should do something better! */
14421 	printf("%s: got error %d while accessing filesystem\n", func, error);
14422 }
14423 
14424 #ifdef DDB
14425 
14426 /* exported to ffs_vfsops.c */
14427 extern void db_print_ffs(struct ufsmount *ump);
14428 void
14429 db_print_ffs(struct ufsmount *ump)
14430 {
14431 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14432 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14433 	db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14434 	    ump->um_fs, ump->softdep_on_worklist,
14435 	    ump->softdep_deps, ump->softdep_req);
14436 }
14437 
14438 static void
14439 worklist_print(struct worklist *wk, int verbose)
14440 {
14441 
14442 	if (!verbose) {
14443 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14444 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14445 		return;
14446 	}
14447 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14448 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14449 	    LIST_NEXT(wk, wk_list));
14450 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14451 }
14452 
14453 static void
14454 inodedep_print(struct inodedep *inodedep, int verbose)
14455 {
14456 
14457 	worklist_print(&inodedep->id_list, 0);
14458 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14459 	    inodedep->id_fs,
14460 	    (intmax_t)inodedep->id_ino,
14461 	    (intmax_t)fsbtodb(inodedep->id_fs,
14462 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14463 	    (intmax_t)inodedep->id_nlinkdelta,
14464 	    (intmax_t)inodedep->id_savednlink);
14465 
14466 	if (verbose == 0)
14467 		return;
14468 
14469 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14470 	    inodedep->id_bmsafemap,
14471 	    inodedep->id_mkdiradd,
14472 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14473 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14474 	    LIST_FIRST(&inodedep->id_dirremhd),
14475 	    LIST_FIRST(&inodedep->id_pendinghd),
14476 	    LIST_FIRST(&inodedep->id_bufwait));
14477 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14478 	    LIST_FIRST(&inodedep->id_inowait),
14479 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14480 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14481 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14482 	    TAILQ_FIRST(&inodedep->id_extupdt),
14483 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14484 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14485 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14486 	    inodedep->id_savedino1,
14487 	    (intmax_t)inodedep->id_savedsize,
14488 	    (intmax_t)inodedep->id_savedextsize);
14489 }
14490 
14491 static void
14492 newblk_print(struct newblk *nbp)
14493 {
14494 
14495 	worklist_print(&nbp->nb_list, 0);
14496 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14497 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14498 	    &nbp->nb_jnewblk,
14499 	    &nbp->nb_bmsafemap,
14500 	    &nbp->nb_freefrag);
14501 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14502 	    LIST_FIRST(&nbp->nb_indirdeps),
14503 	    LIST_FIRST(&nbp->nb_newdirblk),
14504 	    LIST_FIRST(&nbp->nb_jwork));
14505 }
14506 
14507 static void
14508 allocdirect_print(struct allocdirect *adp)
14509 {
14510 
14511 	newblk_print(&adp->ad_block);
14512 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14513 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14514 	db_printf("    offset %d, inodedep %p\n",
14515 	    adp->ad_offset, adp->ad_inodedep);
14516 }
14517 
14518 static void
14519 allocindir_print(struct allocindir *aip)
14520 {
14521 
14522 	newblk_print(&aip->ai_block);
14523 	db_printf("    oldblkno %jd, lbn %jd\n",
14524 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14525 	db_printf("    offset %d, indirdep %p\n",
14526 	    aip->ai_offset, aip->ai_indirdep);
14527 }
14528 
14529 static void
14530 mkdir_print(struct mkdir *mkdir)
14531 {
14532 
14533 	worklist_print(&mkdir->md_list, 0);
14534 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14535 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14536 }
14537 
14538 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14539 {
14540 
14541 	if (have_addr == 0) {
14542 		db_printf("inodedep address required\n");
14543 		return;
14544 	}
14545 	inodedep_print((struct inodedep*)addr, 1);
14546 }
14547 
14548 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14549 {
14550 	struct inodedep_hashhead *inodedephd;
14551 	struct inodedep *inodedep;
14552 	struct ufsmount *ump;
14553 	int cnt;
14554 
14555 	if (have_addr == 0) {
14556 		db_printf("ufsmount address required\n");
14557 		return;
14558 	}
14559 	ump = (struct ufsmount *)addr;
14560 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14561 		inodedephd = &ump->inodedep_hashtbl[cnt];
14562 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14563 			inodedep_print(inodedep, 0);
14564 		}
14565 	}
14566 }
14567 
14568 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14569 {
14570 
14571 	if (have_addr == 0) {
14572 		db_printf("worklist address required\n");
14573 		return;
14574 	}
14575 	worklist_print((struct worklist *)addr, 1);
14576 }
14577 
14578 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14579 {
14580 	struct worklist *wk;
14581 	struct workhead *wkhd;
14582 
14583 	if (have_addr == 0) {
14584 		db_printf("worklist address required "
14585 		    "(for example value in bp->b_dep)\n");
14586 		return;
14587 	}
14588 	/*
14589 	 * We often do not have the address of the worklist head but
14590 	 * instead a pointer to its first entry (e.g., we have the
14591 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
14592 	 * pointer of bp->b_dep will point at the head of the list, so
14593 	 * we cheat and use that instead. If we are in the middle of
14594 	 * a list we will still get the same result, so nothing
14595 	 * unexpected will result.
14596 	 */
14597 	wk = (struct worklist *)addr;
14598 	if (wk == NULL)
14599 		return;
14600 	wkhd = (struct workhead *)wk->wk_list.le_prev;
14601 	LIST_FOREACH(wk, wkhd, wk_list) {
14602 		switch(wk->wk_type) {
14603 		case D_INODEDEP:
14604 			inodedep_print(WK_INODEDEP(wk), 0);
14605 			continue;
14606 		case D_ALLOCDIRECT:
14607 			allocdirect_print(WK_ALLOCDIRECT(wk));
14608 			continue;
14609 		case D_ALLOCINDIR:
14610 			allocindir_print(WK_ALLOCINDIR(wk));
14611 			continue;
14612 		case D_MKDIR:
14613 			mkdir_print(WK_MKDIR(wk));
14614 			continue;
14615 		default:
14616 			worklist_print(wk, 0);
14617 			continue;
14618 		}
14619 	}
14620 }
14621 
14622 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14623 {
14624 	if (have_addr == 0) {
14625 		db_printf("mkdir address required\n");
14626 		return;
14627 	}
14628 	mkdir_print((struct mkdir *)addr);
14629 }
14630 
14631 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14632 {
14633 	struct mkdirlist *mkdirlisthd;
14634 	struct mkdir *mkdir;
14635 
14636 	if (have_addr == 0) {
14637 		db_printf("mkdir listhead address required\n");
14638 		return;
14639 	}
14640 	mkdirlisthd = (struct mkdirlist *)addr;
14641 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14642 		mkdir_print(mkdir);
14643 		if (mkdir->md_diradd != NULL) {
14644 			db_printf("    ");
14645 			worklist_print(&mkdir->md_diradd->da_list, 0);
14646 		}
14647 		if (mkdir->md_jaddref != NULL) {
14648 			db_printf("    ");
14649 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
14650 		}
14651 	}
14652 }
14653 
14654 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
14655 {
14656 	if (have_addr == 0) {
14657 		db_printf("allocdirect address required\n");
14658 		return;
14659 	}
14660 	allocdirect_print((struct allocdirect *)addr);
14661 }
14662 
14663 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
14664 {
14665 	if (have_addr == 0) {
14666 		db_printf("allocindir address required\n");
14667 		return;
14668 	}
14669 	allocindir_print((struct allocindir *)addr);
14670 }
14671 
14672 #endif /* DDB */
14673 
14674 #endif /* SOFTUPDATES */
14675