xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision f5147e312f43a9050468de539aeafa072caa1a60)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1998, 2000 Marshall Kirk McKusick.
5  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
6  * All rights reserved.
7  *
8  * The soft updates code is derived from the appendix of a University
9  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
10  * "Soft Updates: A Solution to the Metadata Update Problem in File
11  * Systems", CSE-TR-254-95, August 1995).
12  *
13  * Further information about soft updates can be obtained from:
14  *
15  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
16  *	1614 Oxford Street		mckusick@mckusick.com
17  *	Berkeley, CA 94709-1608		+1-510-843-9542
18  *	USA
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
35  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
36  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
42  */
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include "opt_ffs.h"
48 #include "opt_quota.h"
49 #include "opt_ddb.h"
50 
51 /*
52  * For now we want the safety net that the DEBUG flag provides.
53  */
54 #ifndef DEBUG
55 #define DEBUG
56 #endif
57 
58 #include <sys/param.h>
59 #include <sys/kernel.h>
60 #include <sys/systm.h>
61 #include <sys/bio.h>
62 #include <sys/buf.h>
63 #include <sys/kdb.h>
64 #include <sys/kthread.h>
65 #include <sys/ktr.h>
66 #include <sys/limits.h>
67 #include <sys/lock.h>
68 #include <sys/malloc.h>
69 #include <sys/mount.h>
70 #include <sys/mutex.h>
71 #include <sys/namei.h>
72 #include <sys/priv.h>
73 #include <sys/proc.h>
74 #include <sys/racct.h>
75 #include <sys/rwlock.h>
76 #include <sys/stat.h>
77 #include <sys/sysctl.h>
78 #include <sys/syslog.h>
79 #include <sys/vnode.h>
80 #include <sys/conf.h>
81 
82 #include <ufs/ufs/dir.h>
83 #include <ufs/ufs/extattr.h>
84 #include <ufs/ufs/quota.h>
85 #include <ufs/ufs/inode.h>
86 #include <ufs/ufs/ufsmount.h>
87 #include <ufs/ffs/fs.h>
88 #include <ufs/ffs/softdep.h>
89 #include <ufs/ffs/ffs_extern.h>
90 #include <ufs/ufs/ufs_extern.h>
91 
92 #include <vm/vm.h>
93 #include <vm/vm_extern.h>
94 #include <vm/vm_object.h>
95 
96 #include <geom/geom.h>
97 
98 #include <ddb/ddb.h>
99 
100 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
101 
102 #ifndef SOFTUPDATES
103 
104 int
105 softdep_flushfiles(oldmnt, flags, td)
106 	struct mount *oldmnt;
107 	int flags;
108 	struct thread *td;
109 {
110 
111 	panic("softdep_flushfiles called");
112 }
113 
114 int
115 softdep_mount(devvp, mp, fs, cred)
116 	struct vnode *devvp;
117 	struct mount *mp;
118 	struct fs *fs;
119 	struct ucred *cred;
120 {
121 
122 	return (0);
123 }
124 
125 void
126 softdep_initialize()
127 {
128 
129 	return;
130 }
131 
132 void
133 softdep_uninitialize()
134 {
135 
136 	return;
137 }
138 
139 void
140 softdep_unmount(mp)
141 	struct mount *mp;
142 {
143 
144 	panic("softdep_unmount called");
145 }
146 
147 void
148 softdep_setup_sbupdate(ump, fs, bp)
149 	struct ufsmount *ump;
150 	struct fs *fs;
151 	struct buf *bp;
152 {
153 
154 	panic("softdep_setup_sbupdate called");
155 }
156 
157 void
158 softdep_setup_inomapdep(bp, ip, newinum, mode)
159 	struct buf *bp;
160 	struct inode *ip;
161 	ino_t newinum;
162 	int mode;
163 {
164 
165 	panic("softdep_setup_inomapdep called");
166 }
167 
168 void
169 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
170 	struct buf *bp;
171 	struct mount *mp;
172 	ufs2_daddr_t newblkno;
173 	int frags;
174 	int oldfrags;
175 {
176 
177 	panic("softdep_setup_blkmapdep called");
178 }
179 
180 void
181 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
182 	struct inode *ip;
183 	ufs_lbn_t lbn;
184 	ufs2_daddr_t newblkno;
185 	ufs2_daddr_t oldblkno;
186 	long newsize;
187 	long oldsize;
188 	struct buf *bp;
189 {
190 
191 	panic("softdep_setup_allocdirect called");
192 }
193 
194 void
195 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
196 	struct inode *ip;
197 	ufs_lbn_t lbn;
198 	ufs2_daddr_t newblkno;
199 	ufs2_daddr_t oldblkno;
200 	long newsize;
201 	long oldsize;
202 	struct buf *bp;
203 {
204 
205 	panic("softdep_setup_allocext called");
206 }
207 
208 void
209 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
210 	struct inode *ip;
211 	ufs_lbn_t lbn;
212 	struct buf *bp;
213 	int ptrno;
214 	ufs2_daddr_t newblkno;
215 	ufs2_daddr_t oldblkno;
216 	struct buf *nbp;
217 {
218 
219 	panic("softdep_setup_allocindir_page called");
220 }
221 
222 void
223 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
224 	struct buf *nbp;
225 	struct inode *ip;
226 	struct buf *bp;
227 	int ptrno;
228 	ufs2_daddr_t newblkno;
229 {
230 
231 	panic("softdep_setup_allocindir_meta called");
232 }
233 
234 void
235 softdep_journal_freeblocks(ip, cred, length, flags)
236 	struct inode *ip;
237 	struct ucred *cred;
238 	off_t length;
239 	int flags;
240 {
241 
242 	panic("softdep_journal_freeblocks called");
243 }
244 
245 void
246 softdep_journal_fsync(ip)
247 	struct inode *ip;
248 {
249 
250 	panic("softdep_journal_fsync called");
251 }
252 
253 void
254 softdep_setup_freeblocks(ip, length, flags)
255 	struct inode *ip;
256 	off_t length;
257 	int flags;
258 {
259 
260 	panic("softdep_setup_freeblocks called");
261 }
262 
263 void
264 softdep_freefile(pvp, ino, mode)
265 		struct vnode *pvp;
266 		ino_t ino;
267 		int mode;
268 {
269 
270 	panic("softdep_freefile called");
271 }
272 
273 int
274 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
275 	struct buf *bp;
276 	struct inode *dp;
277 	off_t diroffset;
278 	ino_t newinum;
279 	struct buf *newdirbp;
280 	int isnewblk;
281 {
282 
283 	panic("softdep_setup_directory_add called");
284 }
285 
286 void
287 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
288 	struct buf *bp;
289 	struct inode *dp;
290 	caddr_t base;
291 	caddr_t oldloc;
292 	caddr_t newloc;
293 	int entrysize;
294 {
295 
296 	panic("softdep_change_directoryentry_offset called");
297 }
298 
299 void
300 softdep_setup_remove(bp, dp, ip, isrmdir)
301 	struct buf *bp;
302 	struct inode *dp;
303 	struct inode *ip;
304 	int isrmdir;
305 {
306 
307 	panic("softdep_setup_remove called");
308 }
309 
310 void
311 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
312 	struct buf *bp;
313 	struct inode *dp;
314 	struct inode *ip;
315 	ino_t newinum;
316 	int isrmdir;
317 {
318 
319 	panic("softdep_setup_directory_change called");
320 }
321 
322 void
323 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
324 	struct mount *mp;
325 	struct buf *bp;
326 	ufs2_daddr_t blkno;
327 	int frags;
328 	struct workhead *wkhd;
329 {
330 
331 	panic("%s called", __FUNCTION__);
332 }
333 
334 void
335 softdep_setup_inofree(mp, bp, ino, wkhd)
336 	struct mount *mp;
337 	struct buf *bp;
338 	ino_t ino;
339 	struct workhead *wkhd;
340 {
341 
342 	panic("%s called", __FUNCTION__);
343 }
344 
345 void
346 softdep_setup_unlink(dp, ip)
347 	struct inode *dp;
348 	struct inode *ip;
349 {
350 
351 	panic("%s called", __FUNCTION__);
352 }
353 
354 void
355 softdep_setup_link(dp, ip)
356 	struct inode *dp;
357 	struct inode *ip;
358 {
359 
360 	panic("%s called", __FUNCTION__);
361 }
362 
363 void
364 softdep_revert_link(dp, ip)
365 	struct inode *dp;
366 	struct inode *ip;
367 {
368 
369 	panic("%s called", __FUNCTION__);
370 }
371 
372 void
373 softdep_setup_rmdir(dp, ip)
374 	struct inode *dp;
375 	struct inode *ip;
376 {
377 
378 	panic("%s called", __FUNCTION__);
379 }
380 
381 void
382 softdep_revert_rmdir(dp, ip)
383 	struct inode *dp;
384 	struct inode *ip;
385 {
386 
387 	panic("%s called", __FUNCTION__);
388 }
389 
390 void
391 softdep_setup_create(dp, ip)
392 	struct inode *dp;
393 	struct inode *ip;
394 {
395 
396 	panic("%s called", __FUNCTION__);
397 }
398 
399 void
400 softdep_revert_create(dp, ip)
401 	struct inode *dp;
402 	struct inode *ip;
403 {
404 
405 	panic("%s called", __FUNCTION__);
406 }
407 
408 void
409 softdep_setup_mkdir(dp, ip)
410 	struct inode *dp;
411 	struct inode *ip;
412 {
413 
414 	panic("%s called", __FUNCTION__);
415 }
416 
417 void
418 softdep_revert_mkdir(dp, ip)
419 	struct inode *dp;
420 	struct inode *ip;
421 {
422 
423 	panic("%s called", __FUNCTION__);
424 }
425 
426 void
427 softdep_setup_dotdot_link(dp, ip)
428 	struct inode *dp;
429 	struct inode *ip;
430 {
431 
432 	panic("%s called", __FUNCTION__);
433 }
434 
435 int
436 softdep_prealloc(vp, waitok)
437 	struct vnode *vp;
438 	int waitok;
439 {
440 
441 	panic("%s called", __FUNCTION__);
442 }
443 
444 int
445 softdep_journal_lookup(mp, vpp)
446 	struct mount *mp;
447 	struct vnode **vpp;
448 {
449 
450 	return (ENOENT);
451 }
452 
453 void
454 softdep_change_linkcnt(ip)
455 	struct inode *ip;
456 {
457 
458 	panic("softdep_change_linkcnt called");
459 }
460 
461 void
462 softdep_load_inodeblock(ip)
463 	struct inode *ip;
464 {
465 
466 	panic("softdep_load_inodeblock called");
467 }
468 
469 void
470 softdep_update_inodeblock(ip, bp, waitfor)
471 	struct inode *ip;
472 	struct buf *bp;
473 	int waitfor;
474 {
475 
476 	panic("softdep_update_inodeblock called");
477 }
478 
479 int
480 softdep_fsync(vp)
481 	struct vnode *vp;	/* the "in_core" copy of the inode */
482 {
483 
484 	return (0);
485 }
486 
487 void
488 softdep_fsync_mountdev(vp)
489 	struct vnode *vp;
490 {
491 
492 	return;
493 }
494 
495 int
496 softdep_flushworklist(oldmnt, countp, td)
497 	struct mount *oldmnt;
498 	int *countp;
499 	struct thread *td;
500 {
501 
502 	*countp = 0;
503 	return (0);
504 }
505 
506 int
507 softdep_sync_metadata(struct vnode *vp)
508 {
509 
510 	panic("softdep_sync_metadata called");
511 }
512 
513 int
514 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
515 {
516 
517 	panic("softdep_sync_buf called");
518 }
519 
520 int
521 softdep_slowdown(vp)
522 	struct vnode *vp;
523 {
524 
525 	panic("softdep_slowdown called");
526 }
527 
528 int
529 softdep_request_cleanup(fs, vp, cred, resource)
530 	struct fs *fs;
531 	struct vnode *vp;
532 	struct ucred *cred;
533 	int resource;
534 {
535 
536 	return (0);
537 }
538 
539 int
540 softdep_check_suspend(struct mount *mp,
541 		      struct vnode *devvp,
542 		      int softdep_depcnt,
543 		      int softdep_accdepcnt,
544 		      int secondary_writes,
545 		      int secondary_accwrites)
546 {
547 	struct bufobj *bo;
548 	int error;
549 
550 	(void) softdep_depcnt,
551 	(void) softdep_accdepcnt;
552 
553 	bo = &devvp->v_bufobj;
554 	ASSERT_BO_WLOCKED(bo);
555 
556 	MNT_ILOCK(mp);
557 	while (mp->mnt_secondary_writes != 0) {
558 		BO_UNLOCK(bo);
559 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
560 		    (PUSER - 1) | PDROP, "secwr", 0);
561 		BO_LOCK(bo);
562 		MNT_ILOCK(mp);
563 	}
564 
565 	/*
566 	 * Reasons for needing more work before suspend:
567 	 * - Dirty buffers on devvp.
568 	 * - Secondary writes occurred after start of vnode sync loop
569 	 */
570 	error = 0;
571 	if (bo->bo_numoutput > 0 ||
572 	    bo->bo_dirty.bv_cnt > 0 ||
573 	    secondary_writes != 0 ||
574 	    mp->mnt_secondary_writes != 0 ||
575 	    secondary_accwrites != mp->mnt_secondary_accwrites)
576 		error = EAGAIN;
577 	BO_UNLOCK(bo);
578 	return (error);
579 }
580 
581 void
582 softdep_get_depcounts(struct mount *mp,
583 		      int *softdepactivep,
584 		      int *softdepactiveaccp)
585 {
586 	(void) mp;
587 	*softdepactivep = 0;
588 	*softdepactiveaccp = 0;
589 }
590 
591 void
592 softdep_buf_append(bp, wkhd)
593 	struct buf *bp;
594 	struct workhead *wkhd;
595 {
596 
597 	panic("softdep_buf_appendwork called");
598 }
599 
600 void
601 softdep_inode_append(ip, cred, wkhd)
602 	struct inode *ip;
603 	struct ucred *cred;
604 	struct workhead *wkhd;
605 {
606 
607 	panic("softdep_inode_appendwork called");
608 }
609 
610 void
611 softdep_freework(wkhd)
612 	struct workhead *wkhd;
613 {
614 
615 	panic("softdep_freework called");
616 }
617 
618 #else
619 
620 FEATURE(softupdates, "FFS soft-updates support");
621 
622 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
623     "soft updates stats");
624 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
625     "total dependencies allocated");
626 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
627     "high use dependencies allocated");
628 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
629     "current dependencies allocated");
630 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
631     "current dependencies written");
632 
633 unsigned long dep_current[D_LAST + 1];
634 unsigned long dep_highuse[D_LAST + 1];
635 unsigned long dep_total[D_LAST + 1];
636 unsigned long dep_write[D_LAST + 1];
637 
638 #define	SOFTDEP_TYPE(type, str, long)					\
639     static MALLOC_DEFINE(M_ ## type, #str, long);			\
640     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
641 	&dep_total[D_ ## type], 0, "");					\
642     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
643 	&dep_current[D_ ## type], 0, "");				\
644     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
645 	&dep_highuse[D_ ## type], 0, "");				\
646     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
647 	&dep_write[D_ ## type], 0, "");
648 
649 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
650 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
651 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
652     "Block or frag allocated from cyl group map");
653 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
654 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
655 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
656 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
657 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
658 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
659 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
660 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
661 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
662 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
663 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
664 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
665 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
666 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
667 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
668 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
669 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
670 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
671 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
672 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
673 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
674 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
675 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
676 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
677 
678 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
679 
680 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
681 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
682 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
683 
684 #define M_SOFTDEP_FLAGS	(M_WAITOK)
685 
686 /*
687  * translate from workitem type to memory type
688  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
689  */
690 static struct malloc_type *memtype[] = {
691 	M_PAGEDEP,
692 	M_INODEDEP,
693 	M_BMSAFEMAP,
694 	M_NEWBLK,
695 	M_ALLOCDIRECT,
696 	M_INDIRDEP,
697 	M_ALLOCINDIR,
698 	M_FREEFRAG,
699 	M_FREEBLKS,
700 	M_FREEFILE,
701 	M_DIRADD,
702 	M_MKDIR,
703 	M_DIRREM,
704 	M_NEWDIRBLK,
705 	M_FREEWORK,
706 	M_FREEDEP,
707 	M_JADDREF,
708 	M_JREMREF,
709 	M_JMVREF,
710 	M_JNEWBLK,
711 	M_JFREEBLK,
712 	M_JFREEFRAG,
713 	M_JSEG,
714 	M_JSEGDEP,
715 	M_SBDEP,
716 	M_JTRUNC,
717 	M_JFSYNC,
718 	M_SENTINEL
719 };
720 
721 #define DtoM(type) (memtype[type])
722 
723 /*
724  * Names of malloc types.
725  */
726 #define TYPENAME(type)  \
727 	((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
728 /*
729  * End system adaptation definitions.
730  */
731 
732 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
733 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
734 
735 /*
736  * Internal function prototypes.
737  */
738 static	void check_clear_deps(struct mount *);
739 static	void softdep_error(char *, int);
740 static	int softdep_process_worklist(struct mount *, int);
741 static	int softdep_waitidle(struct mount *, int);
742 static	void drain_output(struct vnode *);
743 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
744 static	int check_inodedep_free(struct inodedep *);
745 static	void clear_remove(struct mount *);
746 static	void clear_inodedeps(struct mount *);
747 static	void unlinked_inodedep(struct mount *, struct inodedep *);
748 static	void clear_unlinked_inodedep(struct inodedep *);
749 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
750 static	int flush_pagedep_deps(struct vnode *, struct mount *,
751 	    struct diraddhd *);
752 static	int free_pagedep(struct pagedep *);
753 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
754 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
755 static	int flush_deplist(struct allocdirectlst *, int, int *);
756 static	int sync_cgs(struct mount *, int);
757 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
758 static	int handle_written_sbdep(struct sbdep *, struct buf *);
759 static	void initiate_write_sbdep(struct sbdep *);
760 static	void diradd_inode_written(struct diradd *, struct inodedep *);
761 static	int handle_written_indirdep(struct indirdep *, struct buf *,
762 	    struct buf**, int);
763 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
764 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
765 	    uint8_t *);
766 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
767 static	void handle_written_jaddref(struct jaddref *);
768 static	void handle_written_jremref(struct jremref *);
769 static	void handle_written_jseg(struct jseg *, struct buf *);
770 static	void handle_written_jnewblk(struct jnewblk *);
771 static	void handle_written_jblkdep(struct jblkdep *);
772 static	void handle_written_jfreefrag(struct jfreefrag *);
773 static	void complete_jseg(struct jseg *);
774 static	void complete_jsegs(struct jseg *);
775 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
776 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
777 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
778 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
779 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
780 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
781 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
782 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
783 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
784 static	inline void inoref_write(struct inoref *, struct jseg *,
785 	    struct jrefrec *);
786 static	void handle_allocdirect_partdone(struct allocdirect *,
787 	    struct workhead *);
788 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
789 	    struct workhead *);
790 static	void indirdep_complete(struct indirdep *);
791 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
792 static	void indirblk_insert(struct freework *);
793 static	void indirblk_remove(struct freework *);
794 static	void handle_allocindir_partdone(struct allocindir *);
795 static	void initiate_write_filepage(struct pagedep *, struct buf *);
796 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
797 static	void handle_written_mkdir(struct mkdir *, int);
798 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
799 	    uint8_t *);
800 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
801 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
802 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
803 static	void handle_workitem_freefile(struct freefile *);
804 static	int handle_workitem_remove(struct dirrem *, int);
805 static	struct dirrem *newdirrem(struct buf *, struct inode *,
806 	    struct inode *, int, struct dirrem **);
807 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
808 	    struct buf *);
809 static	void cancel_indirdep(struct indirdep *, struct buf *,
810 	    struct freeblks *);
811 static	void free_indirdep(struct indirdep *);
812 static	void free_diradd(struct diradd *, struct workhead *);
813 static	void merge_diradd(struct inodedep *, struct diradd *);
814 static	void complete_diradd(struct diradd *);
815 static	struct diradd *diradd_lookup(struct pagedep *, int);
816 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
817 	    struct jremref *);
818 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
819 	    struct jremref *);
820 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
821 	    struct jremref *, struct jremref *);
822 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
823 	    struct jremref *);
824 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
825 	    struct freeblks *, int);
826 static	int setup_trunc_indir(struct freeblks *, struct inode *,
827 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
828 static	void complete_trunc_indir(struct freework *);
829 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
830 	    int);
831 static	void complete_mkdir(struct mkdir *);
832 static	void free_newdirblk(struct newdirblk *);
833 static	void free_jremref(struct jremref *);
834 static	void free_jaddref(struct jaddref *);
835 static	void free_jsegdep(struct jsegdep *);
836 static	void free_jsegs(struct jblocks *);
837 static	void rele_jseg(struct jseg *);
838 static	void free_jseg(struct jseg *, struct jblocks *);
839 static	void free_jnewblk(struct jnewblk *);
840 static	void free_jblkdep(struct jblkdep *);
841 static	void free_jfreefrag(struct jfreefrag *);
842 static	void free_freedep(struct freedep *);
843 static	void journal_jremref(struct dirrem *, struct jremref *,
844 	    struct inodedep *);
845 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
846 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
847 	    struct workhead *);
848 static	void cancel_jfreefrag(struct jfreefrag *);
849 static	inline void setup_freedirect(struct freeblks *, struct inode *,
850 	    int, int);
851 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
852 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
853 	    ufs_lbn_t, int);
854 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
855 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
856 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
857 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
858 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
859 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
860 	    int, int);
861 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
862 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
863 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
864 static	void newblk_freefrag(struct newblk*);
865 static	void free_newblk(struct newblk *);
866 static	void cancel_allocdirect(struct allocdirectlst *,
867 	    struct allocdirect *, struct freeblks *);
868 static	int check_inode_unwritten(struct inodedep *);
869 static	int free_inodedep(struct inodedep *);
870 static	void freework_freeblock(struct freework *);
871 static	void freework_enqueue(struct freework *);
872 static	int handle_workitem_freeblocks(struct freeblks *, int);
873 static	int handle_complete_freeblocks(struct freeblks *, int);
874 static	void handle_workitem_indirblk(struct freework *);
875 static	void handle_written_freework(struct freework *);
876 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
877 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
878 	    struct workhead *);
879 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
880 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
881 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
882 	    ufs2_daddr_t, ufs_lbn_t);
883 static	void handle_workitem_freefrag(struct freefrag *);
884 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
885 	    ufs_lbn_t);
886 static	void allocdirect_merge(struct allocdirectlst *,
887 	    struct allocdirect *, struct allocdirect *);
888 static	struct freefrag *allocindir_merge(struct allocindir *,
889 	    struct allocindir *);
890 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
891 	    struct bmsafemap **);
892 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
893 	    int cg, struct bmsafemap *);
894 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
895 	    struct newblk **);
896 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
897 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
898 	    struct inodedep **);
899 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
900 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
901 	    int, struct pagedep **);
902 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
903 	    struct pagedep **);
904 static	void pause_timer(void *);
905 static	int request_cleanup(struct mount *, int);
906 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
907 static	void schedule_cleanup(struct mount *);
908 static void softdep_ast_cleanup_proc(struct thread *);
909 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
910 static	int process_worklist_item(struct mount *, int, int);
911 static	void process_removes(struct vnode *);
912 static	void process_truncates(struct vnode *);
913 static	void jwork_move(struct workhead *, struct workhead *);
914 static	void jwork_insert(struct workhead *, struct jsegdep *);
915 static	void add_to_worklist(struct worklist *, int);
916 static	void wake_worklist(struct worklist *);
917 static	void wait_worklist(struct worklist *, char *);
918 static	void remove_from_worklist(struct worklist *);
919 static	void softdep_flush(void *);
920 static	void softdep_flushjournal(struct mount *);
921 static	int softdep_speedup(struct ufsmount *);
922 static	void worklist_speedup(struct mount *);
923 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
924 static	void journal_unmount(struct ufsmount *);
925 static	int journal_space(struct ufsmount *, int);
926 static	void journal_suspend(struct ufsmount *);
927 static	int journal_unsuspend(struct ufsmount *ump);
928 static	void softdep_prelink(struct vnode *, struct vnode *);
929 static	void add_to_journal(struct worklist *);
930 static	void remove_from_journal(struct worklist *);
931 static	bool softdep_excess_items(struct ufsmount *, int);
932 static	void softdep_process_journal(struct mount *, struct worklist *, int);
933 static	struct jremref *newjremref(struct dirrem *, struct inode *,
934 	    struct inode *ip, off_t, nlink_t);
935 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
936 	    uint16_t);
937 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
938 	    uint16_t);
939 static	inline struct jsegdep *inoref_jseg(struct inoref *);
940 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
941 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
942 	    ufs2_daddr_t, int);
943 static	void adjust_newfreework(struct freeblks *, int);
944 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
945 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
946 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
947 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
948 	    ufs2_daddr_t, long, ufs_lbn_t);
949 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
950 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
951 static	int jwait(struct worklist *, int);
952 static	struct inodedep *inodedep_lookup_ip(struct inode *);
953 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
954 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
955 static	void handle_jwork(struct workhead *);
956 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
957 	    struct mkdir **);
958 static	struct jblocks *jblocks_create(void);
959 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
960 static	void jblocks_free(struct jblocks *, struct mount *, int);
961 static	void jblocks_destroy(struct jblocks *);
962 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
963 
964 /*
965  * Exported softdep operations.
966  */
967 static	void softdep_disk_io_initiation(struct buf *);
968 static	void softdep_disk_write_complete(struct buf *);
969 static	void softdep_deallocate_dependencies(struct buf *);
970 static	int softdep_count_dependencies(struct buf *bp, int);
971 
972 /*
973  * Global lock over all of soft updates.
974  */
975 static struct mtx lk;
976 MTX_SYSINIT(softdep_lock, &lk, "Global Softdep Lock", MTX_DEF);
977 
978 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
979 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
980 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
981 
982 /*
983  * Per-filesystem soft-updates locking.
984  */
985 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
986 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
987 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
988 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
989 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
990 				    RA_WLOCKED)
991 
992 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
993 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
994 
995 /*
996  * Worklist queue management.
997  * These routines require that the lock be held.
998  */
999 #ifndef /* NOT */ DEBUG
1000 #define WORKLIST_INSERT(head, item) do {	\
1001 	(item)->wk_state |= ONWORKLIST;		\
1002 	LIST_INSERT_HEAD(head, item, wk_list);	\
1003 } while (0)
1004 #define WORKLIST_REMOVE(item) do {		\
1005 	(item)->wk_state &= ~ONWORKLIST;	\
1006 	LIST_REMOVE(item, wk_list);		\
1007 } while (0)
1008 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1009 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1010 
1011 #else /* DEBUG */
1012 static	void worklist_insert(struct workhead *, struct worklist *, int);
1013 static	void worklist_remove(struct worklist *, int);
1014 
1015 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1016 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1017 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1018 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1019 
1020 static void
1021 worklist_insert(head, item, locked)
1022 	struct workhead *head;
1023 	struct worklist *item;
1024 	int locked;
1025 {
1026 
1027 	if (locked)
1028 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1029 	if (item->wk_state & ONWORKLIST)
1030 		panic("worklist_insert: %p %s(0x%X) already on list",
1031 		    item, TYPENAME(item->wk_type), item->wk_state);
1032 	item->wk_state |= ONWORKLIST;
1033 	LIST_INSERT_HEAD(head, item, wk_list);
1034 }
1035 
1036 static void
1037 worklist_remove(item, locked)
1038 	struct worklist *item;
1039 	int locked;
1040 {
1041 
1042 	if (locked)
1043 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1044 	if ((item->wk_state & ONWORKLIST) == 0)
1045 		panic("worklist_remove: %p %s(0x%X) not on list",
1046 		    item, TYPENAME(item->wk_type), item->wk_state);
1047 	item->wk_state &= ~ONWORKLIST;
1048 	LIST_REMOVE(item, wk_list);
1049 }
1050 #endif /* DEBUG */
1051 
1052 /*
1053  * Merge two jsegdeps keeping only the oldest one as newer references
1054  * can't be discarded until after older references.
1055  */
1056 static inline struct jsegdep *
1057 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1058 {
1059 	struct jsegdep *swp;
1060 
1061 	if (two == NULL)
1062 		return (one);
1063 
1064 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1065 		swp = one;
1066 		one = two;
1067 		two = swp;
1068 	}
1069 	WORKLIST_REMOVE(&two->jd_list);
1070 	free_jsegdep(two);
1071 
1072 	return (one);
1073 }
1074 
1075 /*
1076  * If two freedeps are compatible free one to reduce list size.
1077  */
1078 static inline struct freedep *
1079 freedep_merge(struct freedep *one, struct freedep *two)
1080 {
1081 	if (two == NULL)
1082 		return (one);
1083 
1084 	if (one->fd_freework == two->fd_freework) {
1085 		WORKLIST_REMOVE(&two->fd_list);
1086 		free_freedep(two);
1087 	}
1088 	return (one);
1089 }
1090 
1091 /*
1092  * Move journal work from one list to another.  Duplicate freedeps and
1093  * jsegdeps are coalesced to keep the lists as small as possible.
1094  */
1095 static void
1096 jwork_move(dst, src)
1097 	struct workhead *dst;
1098 	struct workhead *src;
1099 {
1100 	struct freedep *freedep;
1101 	struct jsegdep *jsegdep;
1102 	struct worklist *wkn;
1103 	struct worklist *wk;
1104 
1105 	KASSERT(dst != src,
1106 	    ("jwork_move: dst == src"));
1107 	freedep = NULL;
1108 	jsegdep = NULL;
1109 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1110 		if (wk->wk_type == D_JSEGDEP)
1111 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1112 		else if (wk->wk_type == D_FREEDEP)
1113 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1114 	}
1115 
1116 	while ((wk = LIST_FIRST(src)) != NULL) {
1117 		WORKLIST_REMOVE(wk);
1118 		WORKLIST_INSERT(dst, wk);
1119 		if (wk->wk_type == D_JSEGDEP) {
1120 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1121 			continue;
1122 		}
1123 		if (wk->wk_type == D_FREEDEP)
1124 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1125 	}
1126 }
1127 
1128 static void
1129 jwork_insert(dst, jsegdep)
1130 	struct workhead *dst;
1131 	struct jsegdep *jsegdep;
1132 {
1133 	struct jsegdep *jsegdepn;
1134 	struct worklist *wk;
1135 
1136 	LIST_FOREACH(wk, dst, wk_list)
1137 		if (wk->wk_type == D_JSEGDEP)
1138 			break;
1139 	if (wk == NULL) {
1140 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1141 		return;
1142 	}
1143 	jsegdepn = WK_JSEGDEP(wk);
1144 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1145 		WORKLIST_REMOVE(wk);
1146 		free_jsegdep(jsegdepn);
1147 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1148 	} else
1149 		free_jsegdep(jsegdep);
1150 }
1151 
1152 /*
1153  * Routines for tracking and managing workitems.
1154  */
1155 static	void workitem_free(struct worklist *, int);
1156 static	void workitem_alloc(struct worklist *, int, struct mount *);
1157 static	void workitem_reassign(struct worklist *, int);
1158 
1159 #define	WORKITEM_FREE(item, type) \
1160 	workitem_free((struct worklist *)(item), (type))
1161 #define	WORKITEM_REASSIGN(item, type) \
1162 	workitem_reassign((struct worklist *)(item), (type))
1163 
1164 static void
1165 workitem_free(item, type)
1166 	struct worklist *item;
1167 	int type;
1168 {
1169 	struct ufsmount *ump;
1170 
1171 #ifdef DEBUG
1172 	if (item->wk_state & ONWORKLIST)
1173 		panic("workitem_free: %s(0x%X) still on list",
1174 		    TYPENAME(item->wk_type), item->wk_state);
1175 	if (item->wk_type != type && type != D_NEWBLK)
1176 		panic("workitem_free: type mismatch %s != %s",
1177 		    TYPENAME(item->wk_type), TYPENAME(type));
1178 #endif
1179 	if (item->wk_state & IOWAITING)
1180 		wakeup(item);
1181 	ump = VFSTOUFS(item->wk_mp);
1182 	LOCK_OWNED(ump);
1183 	KASSERT(ump->softdep_deps > 0,
1184 	    ("workitem_free: %s: softdep_deps going negative",
1185 	    ump->um_fs->fs_fsmnt));
1186 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1187 		wakeup(&ump->softdep_deps);
1188 	KASSERT(dep_current[item->wk_type] > 0,
1189 	    ("workitem_free: %s: dep_current[%s] going negative",
1190 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1191 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1192 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1193 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1194 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1195 	ump->softdep_curdeps[item->wk_type] -= 1;
1196 	free(item, DtoM(type));
1197 }
1198 
1199 static void
1200 workitem_alloc(item, type, mp)
1201 	struct worklist *item;
1202 	int type;
1203 	struct mount *mp;
1204 {
1205 	struct ufsmount *ump;
1206 
1207 	item->wk_type = type;
1208 	item->wk_mp = mp;
1209 	item->wk_state = 0;
1210 
1211 	ump = VFSTOUFS(mp);
1212 	ACQUIRE_GBLLOCK(&lk);
1213 	dep_current[type]++;
1214 	if (dep_current[type] > dep_highuse[type])
1215 		dep_highuse[type] = dep_current[type];
1216 	dep_total[type]++;
1217 	FREE_GBLLOCK(&lk);
1218 	ACQUIRE_LOCK(ump);
1219 	ump->softdep_curdeps[type] += 1;
1220 	ump->softdep_deps++;
1221 	ump->softdep_accdeps++;
1222 	FREE_LOCK(ump);
1223 }
1224 
1225 static void
1226 workitem_reassign(item, newtype)
1227 	struct worklist *item;
1228 	int newtype;
1229 {
1230 	struct ufsmount *ump;
1231 
1232 	ump = VFSTOUFS(item->wk_mp);
1233 	LOCK_OWNED(ump);
1234 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1235 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1236 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1237 	ump->softdep_curdeps[item->wk_type] -= 1;
1238 	ump->softdep_curdeps[newtype] += 1;
1239 	KASSERT(dep_current[item->wk_type] > 0,
1240 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1241 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1242 	ACQUIRE_GBLLOCK(&lk);
1243 	dep_current[newtype]++;
1244 	dep_current[item->wk_type]--;
1245 	if (dep_current[newtype] > dep_highuse[newtype])
1246 		dep_highuse[newtype] = dep_current[newtype];
1247 	dep_total[newtype]++;
1248 	FREE_GBLLOCK(&lk);
1249 	item->wk_type = newtype;
1250 }
1251 
1252 /*
1253  * Workitem queue management
1254  */
1255 static int max_softdeps;	/* maximum number of structs before slowdown */
1256 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1257 static int proc_waiting;	/* tracks whether we have a timeout posted */
1258 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1259 static struct callout softdep_callout;
1260 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1261 static int req_clear_remove;	/* syncer process flush some freeblks */
1262 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1263 
1264 /*
1265  * runtime statistics
1266  */
1267 static int stat_flush_threads;	/* number of softdep flushing threads */
1268 static int stat_worklist_push;	/* number of worklist cleanups */
1269 static int stat_blk_limit_push;	/* number of times block limit neared */
1270 static int stat_ino_limit_push;	/* number of times inode limit neared */
1271 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1272 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1273 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1274 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1275 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1276 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1277 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1278 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1279 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1280 static int stat_journal_min;	/* Times hit journal min threshold */
1281 static int stat_journal_low;	/* Times hit journal low threshold */
1282 static int stat_journal_wait;	/* Times blocked in jwait(). */
1283 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1284 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1285 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1286 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1287 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1288 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1289 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1290 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1291 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1292 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1293 
1294 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1295     &max_softdeps, 0, "");
1296 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1297     &tickdelay, 0, "");
1298 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1299     &stat_flush_threads, 0, "");
1300 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1301     &stat_worklist_push, 0,"");
1302 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1303     &stat_blk_limit_push, 0,"");
1304 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1305     &stat_ino_limit_push, 0,"");
1306 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1307     &stat_blk_limit_hit, 0, "");
1308 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1309     &stat_ino_limit_hit, 0, "");
1310 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1311     &stat_sync_limit_hit, 0, "");
1312 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1313     &stat_indir_blk_ptrs, 0, "");
1314 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1315     &stat_inode_bitmap, 0, "");
1316 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1317     &stat_direct_blk_ptrs, 0, "");
1318 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1319     &stat_dir_entry, 0, "");
1320 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1321     &stat_jaddref, 0, "");
1322 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1323     &stat_jnewblk, 0, "");
1324 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1325     &stat_journal_low, 0, "");
1326 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1327     &stat_journal_min, 0, "");
1328 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1329     &stat_journal_wait, 0, "");
1330 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1331     &stat_jwait_filepage, 0, "");
1332 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1333     &stat_jwait_freeblks, 0, "");
1334 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1335     &stat_jwait_inode, 0, "");
1336 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1337     &stat_jwait_newblk, 0, "");
1338 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1339     &stat_cleanup_blkrequests, 0, "");
1340 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1341     &stat_cleanup_inorequests, 0, "");
1342 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1343     &stat_cleanup_high_delay, 0, "");
1344 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1345     &stat_cleanup_retries, 0, "");
1346 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1347     &stat_cleanup_failures, 0, "");
1348 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1349     &softdep_flushcache, 0, "");
1350 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1351     &stat_emptyjblocks, 0, "");
1352 
1353 SYSCTL_DECL(_vfs_ffs);
1354 
1355 /* Whether to recompute the summary at mount time */
1356 static int compute_summary_at_mount = 0;
1357 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1358 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1359 static int print_threads = 0;
1360 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1361     &print_threads, 0, "Notify flusher thread start/stop");
1362 
1363 /* List of all filesystems mounted with soft updates */
1364 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1365 
1366 /*
1367  * This function cleans the worklist for a filesystem.
1368  * Each filesystem running with soft dependencies gets its own
1369  * thread to run in this function. The thread is started up in
1370  * softdep_mount and shutdown in softdep_unmount. They show up
1371  * as part of the kernel "bufdaemon" process whose process
1372  * entry is available in bufdaemonproc.
1373  */
1374 static int searchfailed;
1375 extern struct proc *bufdaemonproc;
1376 static void
1377 softdep_flush(addr)
1378 	void *addr;
1379 {
1380 	struct mount *mp;
1381 	struct thread *td;
1382 	struct ufsmount *ump;
1383 
1384 	td = curthread;
1385 	td->td_pflags |= TDP_NORUNNINGBUF;
1386 	mp = (struct mount *)addr;
1387 	ump = VFSTOUFS(mp);
1388 	atomic_add_int(&stat_flush_threads, 1);
1389 	ACQUIRE_LOCK(ump);
1390 	ump->softdep_flags &= ~FLUSH_STARTING;
1391 	wakeup(&ump->softdep_flushtd);
1392 	FREE_LOCK(ump);
1393 	if (print_threads) {
1394 		if (stat_flush_threads == 1)
1395 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1396 			    bufdaemonproc->p_pid);
1397 		printf("Start thread %s\n", td->td_name);
1398 	}
1399 	for (;;) {
1400 		while (softdep_process_worklist(mp, 0) > 0 ||
1401 		    (MOUNTEDSUJ(mp) &&
1402 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1403 			kthread_suspend_check();
1404 		ACQUIRE_LOCK(ump);
1405 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1406 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1407 			    "sdflush", hz / 2);
1408 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1409 		/*
1410 		 * Check to see if we are done and need to exit.
1411 		 */
1412 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1413 			FREE_LOCK(ump);
1414 			continue;
1415 		}
1416 		ump->softdep_flags &= ~FLUSH_EXIT;
1417 		FREE_LOCK(ump);
1418 		wakeup(&ump->softdep_flags);
1419 		if (print_threads)
1420 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1421 		atomic_subtract_int(&stat_flush_threads, 1);
1422 		kthread_exit();
1423 		panic("kthread_exit failed\n");
1424 	}
1425 }
1426 
1427 static void
1428 worklist_speedup(mp)
1429 	struct mount *mp;
1430 {
1431 	struct ufsmount *ump;
1432 
1433 	ump = VFSTOUFS(mp);
1434 	LOCK_OWNED(ump);
1435 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1436 		ump->softdep_flags |= FLUSH_CLEANUP;
1437 	wakeup(&ump->softdep_flushtd);
1438 }
1439 
1440 static int
1441 softdep_speedup(ump)
1442 	struct ufsmount *ump;
1443 {
1444 	struct ufsmount *altump;
1445 	struct mount_softdeps *sdp;
1446 
1447 	LOCK_OWNED(ump);
1448 	worklist_speedup(ump->um_mountp);
1449 	bd_speedup();
1450 	/*
1451 	 * If we have global shortages, then we need other
1452 	 * filesystems to help with the cleanup. Here we wakeup a
1453 	 * flusher thread for a filesystem that is over its fair
1454 	 * share of resources.
1455 	 */
1456 	if (req_clear_inodedeps || req_clear_remove) {
1457 		ACQUIRE_GBLLOCK(&lk);
1458 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1459 			if ((altump = sdp->sd_ump) == ump)
1460 				continue;
1461 			if (((req_clear_inodedeps &&
1462 			    altump->softdep_curdeps[D_INODEDEP] >
1463 			    max_softdeps / stat_flush_threads) ||
1464 			    (req_clear_remove &&
1465 			    altump->softdep_curdeps[D_DIRREM] >
1466 			    (max_softdeps / 2) / stat_flush_threads)) &&
1467 			    TRY_ACQUIRE_LOCK(altump))
1468 				break;
1469 		}
1470 		if (sdp == NULL) {
1471 			searchfailed++;
1472 			FREE_GBLLOCK(&lk);
1473 		} else {
1474 			/*
1475 			 * Move to the end of the list so we pick a
1476 			 * different one on out next try.
1477 			 */
1478 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1479 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1480 			FREE_GBLLOCK(&lk);
1481 			if ((altump->softdep_flags &
1482 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1483 				altump->softdep_flags |= FLUSH_CLEANUP;
1484 			altump->um_softdep->sd_cleanups++;
1485 			wakeup(&altump->softdep_flushtd);
1486 			FREE_LOCK(altump);
1487 		}
1488 	}
1489 	return (speedup_syncer());
1490 }
1491 
1492 /*
1493  * Add an item to the end of the work queue.
1494  * This routine requires that the lock be held.
1495  * This is the only routine that adds items to the list.
1496  * The following routine is the only one that removes items
1497  * and does so in order from first to last.
1498  */
1499 
1500 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1501 #define	WK_NODELAY	0x0002	/* Process immediately. */
1502 
1503 static void
1504 add_to_worklist(wk, flags)
1505 	struct worklist *wk;
1506 	int flags;
1507 {
1508 	struct ufsmount *ump;
1509 
1510 	ump = VFSTOUFS(wk->wk_mp);
1511 	LOCK_OWNED(ump);
1512 	if (wk->wk_state & ONWORKLIST)
1513 		panic("add_to_worklist: %s(0x%X) already on list",
1514 		    TYPENAME(wk->wk_type), wk->wk_state);
1515 	wk->wk_state |= ONWORKLIST;
1516 	if (ump->softdep_on_worklist == 0) {
1517 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1518 		ump->softdep_worklist_tail = wk;
1519 	} else if (flags & WK_HEAD) {
1520 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1521 	} else {
1522 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1523 		ump->softdep_worklist_tail = wk;
1524 	}
1525 	ump->softdep_on_worklist += 1;
1526 	if (flags & WK_NODELAY)
1527 		worklist_speedup(wk->wk_mp);
1528 }
1529 
1530 /*
1531  * Remove the item to be processed. If we are removing the last
1532  * item on the list, we need to recalculate the tail pointer.
1533  */
1534 static void
1535 remove_from_worklist(wk)
1536 	struct worklist *wk;
1537 {
1538 	struct ufsmount *ump;
1539 
1540 	ump = VFSTOUFS(wk->wk_mp);
1541 	if (ump->softdep_worklist_tail == wk)
1542 		ump->softdep_worklist_tail =
1543 		    (struct worklist *)wk->wk_list.le_prev;
1544 	WORKLIST_REMOVE(wk);
1545 	ump->softdep_on_worklist -= 1;
1546 }
1547 
1548 static void
1549 wake_worklist(wk)
1550 	struct worklist *wk;
1551 {
1552 	if (wk->wk_state & IOWAITING) {
1553 		wk->wk_state &= ~IOWAITING;
1554 		wakeup(wk);
1555 	}
1556 }
1557 
1558 static void
1559 wait_worklist(wk, wmesg)
1560 	struct worklist *wk;
1561 	char *wmesg;
1562 {
1563 	struct ufsmount *ump;
1564 
1565 	ump = VFSTOUFS(wk->wk_mp);
1566 	wk->wk_state |= IOWAITING;
1567 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1568 }
1569 
1570 /*
1571  * Process that runs once per second to handle items in the background queue.
1572  *
1573  * Note that we ensure that everything is done in the order in which they
1574  * appear in the queue. The code below depends on this property to ensure
1575  * that blocks of a file are freed before the inode itself is freed. This
1576  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1577  * until all the old ones have been purged from the dependency lists.
1578  */
1579 static int
1580 softdep_process_worklist(mp, full)
1581 	struct mount *mp;
1582 	int full;
1583 {
1584 	int cnt, matchcnt;
1585 	struct ufsmount *ump;
1586 	long starttime;
1587 
1588 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1589 	if (MOUNTEDSOFTDEP(mp) == 0)
1590 		return (0);
1591 	matchcnt = 0;
1592 	ump = VFSTOUFS(mp);
1593 	ACQUIRE_LOCK(ump);
1594 	starttime = time_second;
1595 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1596 	check_clear_deps(mp);
1597 	while (ump->softdep_on_worklist > 0) {
1598 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1599 			break;
1600 		else
1601 			matchcnt += cnt;
1602 		check_clear_deps(mp);
1603 		/*
1604 		 * We do not generally want to stop for buffer space, but if
1605 		 * we are really being a buffer hog, we will stop and wait.
1606 		 */
1607 		if (should_yield()) {
1608 			FREE_LOCK(ump);
1609 			kern_yield(PRI_USER);
1610 			bwillwrite();
1611 			ACQUIRE_LOCK(ump);
1612 		}
1613 		/*
1614 		 * Never allow processing to run for more than one
1615 		 * second. This gives the syncer thread the opportunity
1616 		 * to pause if appropriate.
1617 		 */
1618 		if (!full && starttime != time_second)
1619 			break;
1620 	}
1621 	if (full == 0)
1622 		journal_unsuspend(ump);
1623 	FREE_LOCK(ump);
1624 	return (matchcnt);
1625 }
1626 
1627 /*
1628  * Process all removes associated with a vnode if we are running out of
1629  * journal space.  Any other process which attempts to flush these will
1630  * be unable as we have the vnodes locked.
1631  */
1632 static void
1633 process_removes(vp)
1634 	struct vnode *vp;
1635 {
1636 	struct inodedep *inodedep;
1637 	struct dirrem *dirrem;
1638 	struct ufsmount *ump;
1639 	struct mount *mp;
1640 	ino_t inum;
1641 
1642 	mp = vp->v_mount;
1643 	ump = VFSTOUFS(mp);
1644 	LOCK_OWNED(ump);
1645 	inum = VTOI(vp)->i_number;
1646 	for (;;) {
1647 top:
1648 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1649 			return;
1650 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1651 			/*
1652 			 * If another thread is trying to lock this vnode
1653 			 * it will fail but we must wait for it to do so
1654 			 * before we can proceed.
1655 			 */
1656 			if (dirrem->dm_state & INPROGRESS) {
1657 				wait_worklist(&dirrem->dm_list, "pwrwait");
1658 				goto top;
1659 			}
1660 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1661 			    (COMPLETE | ONWORKLIST))
1662 				break;
1663 		}
1664 		if (dirrem == NULL)
1665 			return;
1666 		remove_from_worklist(&dirrem->dm_list);
1667 		FREE_LOCK(ump);
1668 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1669 			panic("process_removes: suspended filesystem");
1670 		handle_workitem_remove(dirrem, 0);
1671 		vn_finished_secondary_write(mp);
1672 		ACQUIRE_LOCK(ump);
1673 	}
1674 }
1675 
1676 /*
1677  * Process all truncations associated with a vnode if we are running out
1678  * of journal space.  This is called when the vnode lock is already held
1679  * and no other process can clear the truncation.  This function returns
1680  * a value greater than zero if it did any work.
1681  */
1682 static void
1683 process_truncates(vp)
1684 	struct vnode *vp;
1685 {
1686 	struct inodedep *inodedep;
1687 	struct freeblks *freeblks;
1688 	struct ufsmount *ump;
1689 	struct mount *mp;
1690 	ino_t inum;
1691 	int cgwait;
1692 
1693 	mp = vp->v_mount;
1694 	ump = VFSTOUFS(mp);
1695 	LOCK_OWNED(ump);
1696 	inum = VTOI(vp)->i_number;
1697 	for (;;) {
1698 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1699 			return;
1700 		cgwait = 0;
1701 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1702 			/* Journal entries not yet written.  */
1703 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1704 				jwait(&LIST_FIRST(
1705 				    &freeblks->fb_jblkdephd)->jb_list,
1706 				    MNT_WAIT);
1707 				break;
1708 			}
1709 			/* Another thread is executing this item. */
1710 			if (freeblks->fb_state & INPROGRESS) {
1711 				wait_worklist(&freeblks->fb_list, "ptrwait");
1712 				break;
1713 			}
1714 			/* Freeblks is waiting on a inode write. */
1715 			if ((freeblks->fb_state & COMPLETE) == 0) {
1716 				FREE_LOCK(ump);
1717 				ffs_update(vp, 1);
1718 				ACQUIRE_LOCK(ump);
1719 				break;
1720 			}
1721 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1722 			    (ALLCOMPLETE | ONWORKLIST)) {
1723 				remove_from_worklist(&freeblks->fb_list);
1724 				freeblks->fb_state |= INPROGRESS;
1725 				FREE_LOCK(ump);
1726 				if (vn_start_secondary_write(NULL, &mp,
1727 				    V_NOWAIT))
1728 					panic("process_truncates: "
1729 					    "suspended filesystem");
1730 				handle_workitem_freeblocks(freeblks, 0);
1731 				vn_finished_secondary_write(mp);
1732 				ACQUIRE_LOCK(ump);
1733 				break;
1734 			}
1735 			if (freeblks->fb_cgwait)
1736 				cgwait++;
1737 		}
1738 		if (cgwait) {
1739 			FREE_LOCK(ump);
1740 			sync_cgs(mp, MNT_WAIT);
1741 			ffs_sync_snap(mp, MNT_WAIT);
1742 			ACQUIRE_LOCK(ump);
1743 			continue;
1744 		}
1745 		if (freeblks == NULL)
1746 			break;
1747 	}
1748 	return;
1749 }
1750 
1751 /*
1752  * Process one item on the worklist.
1753  */
1754 static int
1755 process_worklist_item(mp, target, flags)
1756 	struct mount *mp;
1757 	int target;
1758 	int flags;
1759 {
1760 	struct worklist sentinel;
1761 	struct worklist *wk;
1762 	struct ufsmount *ump;
1763 	int matchcnt;
1764 	int error;
1765 
1766 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1767 	/*
1768 	 * If we are being called because of a process doing a
1769 	 * copy-on-write, then it is not safe to write as we may
1770 	 * recurse into the copy-on-write routine.
1771 	 */
1772 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1773 		return (-1);
1774 	PHOLD(curproc);	/* Don't let the stack go away. */
1775 	ump = VFSTOUFS(mp);
1776 	LOCK_OWNED(ump);
1777 	matchcnt = 0;
1778 	sentinel.wk_mp = NULL;
1779 	sentinel.wk_type = D_SENTINEL;
1780 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1781 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1782 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1783 		if (wk->wk_type == D_SENTINEL) {
1784 			LIST_REMOVE(&sentinel, wk_list);
1785 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1786 			continue;
1787 		}
1788 		if (wk->wk_state & INPROGRESS)
1789 			panic("process_worklist_item: %p already in progress.",
1790 			    wk);
1791 		wk->wk_state |= INPROGRESS;
1792 		remove_from_worklist(wk);
1793 		FREE_LOCK(ump);
1794 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1795 			panic("process_worklist_item: suspended filesystem");
1796 		switch (wk->wk_type) {
1797 		case D_DIRREM:
1798 			/* removal of a directory entry */
1799 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1800 			break;
1801 
1802 		case D_FREEBLKS:
1803 			/* releasing blocks and/or fragments from a file */
1804 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1805 			    flags);
1806 			break;
1807 
1808 		case D_FREEFRAG:
1809 			/* releasing a fragment when replaced as a file grows */
1810 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1811 			error = 0;
1812 			break;
1813 
1814 		case D_FREEFILE:
1815 			/* releasing an inode when its link count drops to 0 */
1816 			handle_workitem_freefile(WK_FREEFILE(wk));
1817 			error = 0;
1818 			break;
1819 
1820 		default:
1821 			panic("%s_process_worklist: Unknown type %s",
1822 			    "softdep", TYPENAME(wk->wk_type));
1823 			/* NOTREACHED */
1824 		}
1825 		vn_finished_secondary_write(mp);
1826 		ACQUIRE_LOCK(ump);
1827 		if (error == 0) {
1828 			if (++matchcnt == target)
1829 				break;
1830 			continue;
1831 		}
1832 		/*
1833 		 * We have to retry the worklist item later.  Wake up any
1834 		 * waiters who may be able to complete it immediately and
1835 		 * add the item back to the head so we don't try to execute
1836 		 * it again.
1837 		 */
1838 		wk->wk_state &= ~INPROGRESS;
1839 		wake_worklist(wk);
1840 		add_to_worklist(wk, WK_HEAD);
1841 	}
1842 	/* Sentinal could've become the tail from remove_from_worklist. */
1843 	if (ump->softdep_worklist_tail == &sentinel)
1844 		ump->softdep_worklist_tail =
1845 		    (struct worklist *)sentinel.wk_list.le_prev;
1846 	LIST_REMOVE(&sentinel, wk_list);
1847 	PRELE(curproc);
1848 	return (matchcnt);
1849 }
1850 
1851 /*
1852  * Move dependencies from one buffer to another.
1853  */
1854 int
1855 softdep_move_dependencies(oldbp, newbp)
1856 	struct buf *oldbp;
1857 	struct buf *newbp;
1858 {
1859 	struct worklist *wk, *wktail;
1860 	struct ufsmount *ump;
1861 	int dirty;
1862 
1863 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1864 		return (0);
1865 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1866 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1867 	dirty = 0;
1868 	wktail = NULL;
1869 	ump = VFSTOUFS(wk->wk_mp);
1870 	ACQUIRE_LOCK(ump);
1871 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1872 		LIST_REMOVE(wk, wk_list);
1873 		if (wk->wk_type == D_BMSAFEMAP &&
1874 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1875 			dirty = 1;
1876 		if (wktail == NULL)
1877 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1878 		else
1879 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1880 		wktail = wk;
1881 	}
1882 	FREE_LOCK(ump);
1883 
1884 	return (dirty);
1885 }
1886 
1887 /*
1888  * Purge the work list of all items associated with a particular mount point.
1889  */
1890 int
1891 softdep_flushworklist(oldmnt, countp, td)
1892 	struct mount *oldmnt;
1893 	int *countp;
1894 	struct thread *td;
1895 {
1896 	struct vnode *devvp;
1897 	struct ufsmount *ump;
1898 	int count, error;
1899 
1900 	/*
1901 	 * Alternately flush the block device associated with the mount
1902 	 * point and process any dependencies that the flushing
1903 	 * creates. We continue until no more worklist dependencies
1904 	 * are found.
1905 	 */
1906 	*countp = 0;
1907 	error = 0;
1908 	ump = VFSTOUFS(oldmnt);
1909 	devvp = ump->um_devvp;
1910 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1911 		*countp += count;
1912 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1913 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1914 		VOP_UNLOCK(devvp, 0);
1915 		if (error != 0)
1916 			break;
1917 	}
1918 	return (error);
1919 }
1920 
1921 #define	SU_WAITIDLE_RETRIES	20
1922 static int
1923 softdep_waitidle(struct mount *mp, int flags __unused)
1924 {
1925 	struct ufsmount *ump;
1926 	struct vnode *devvp;
1927 	struct thread *td;
1928 	int error, i;
1929 
1930 	ump = VFSTOUFS(mp);
1931 	devvp = ump->um_devvp;
1932 	td = curthread;
1933 	error = 0;
1934 	ACQUIRE_LOCK(ump);
1935 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1936 		ump->softdep_req = 1;
1937 		KASSERT((flags & FORCECLOSE) == 0 ||
1938 		    ump->softdep_on_worklist == 0,
1939 		    ("softdep_waitidle: work added after flush"));
1940 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1941 		    "softdeps", 10 * hz);
1942 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1943 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1944 		VOP_UNLOCK(devvp, 0);
1945 		ACQUIRE_LOCK(ump);
1946 		if (error != 0)
1947 			break;
1948 	}
1949 	ump->softdep_req = 0;
1950 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1951 		error = EBUSY;
1952 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1953 		    mp);
1954 	}
1955 	FREE_LOCK(ump);
1956 	return (error);
1957 }
1958 
1959 /*
1960  * Flush all vnodes and worklist items associated with a specified mount point.
1961  */
1962 int
1963 softdep_flushfiles(oldmnt, flags, td)
1964 	struct mount *oldmnt;
1965 	int flags;
1966 	struct thread *td;
1967 {
1968 #ifdef QUOTA
1969 	struct ufsmount *ump;
1970 	int i;
1971 #endif
1972 	int error, early, depcount, loopcnt, retry_flush_count, retry;
1973 	int morework;
1974 
1975 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1976 	    ("softdep_flushfiles called on non-softdep filesystem"));
1977 	loopcnt = 10;
1978 	retry_flush_count = 3;
1979 retry_flush:
1980 	error = 0;
1981 
1982 	/*
1983 	 * Alternately flush the vnodes associated with the mount
1984 	 * point and process any dependencies that the flushing
1985 	 * creates. In theory, this loop can happen at most twice,
1986 	 * but we give it a few extra just to be sure.
1987 	 */
1988 	for (; loopcnt > 0; loopcnt--) {
1989 		/*
1990 		 * Do another flush in case any vnodes were brought in
1991 		 * as part of the cleanup operations.
1992 		 */
1993 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
1994 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
1995 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
1996 			break;
1997 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1998 		    depcount == 0)
1999 			break;
2000 	}
2001 	/*
2002 	 * If we are unmounting then it is an error to fail. If we
2003 	 * are simply trying to downgrade to read-only, then filesystem
2004 	 * activity can keep us busy forever, so we just fail with EBUSY.
2005 	 */
2006 	if (loopcnt == 0) {
2007 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2008 			panic("softdep_flushfiles: looping");
2009 		error = EBUSY;
2010 	}
2011 	if (!error)
2012 		error = softdep_waitidle(oldmnt, flags);
2013 	if (!error) {
2014 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2015 			retry = 0;
2016 			MNT_ILOCK(oldmnt);
2017 			KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
2018 			    ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
2019 			morework = oldmnt->mnt_nvnodelistsize > 0;
2020 #ifdef QUOTA
2021 			ump = VFSTOUFS(oldmnt);
2022 			UFS_LOCK(ump);
2023 			for (i = 0; i < MAXQUOTAS; i++) {
2024 				if (ump->um_quotas[i] != NULLVP)
2025 					morework = 1;
2026 			}
2027 			UFS_UNLOCK(ump);
2028 #endif
2029 			if (morework) {
2030 				if (--retry_flush_count > 0) {
2031 					retry = 1;
2032 					loopcnt = 3;
2033 				} else
2034 					error = EBUSY;
2035 			}
2036 			MNT_IUNLOCK(oldmnt);
2037 			if (retry)
2038 				goto retry_flush;
2039 		}
2040 	}
2041 	return (error);
2042 }
2043 
2044 /*
2045  * Structure hashing.
2046  *
2047  * There are four types of structures that can be looked up:
2048  *	1) pagedep structures identified by mount point, inode number,
2049  *	   and logical block.
2050  *	2) inodedep structures identified by mount point and inode number.
2051  *	3) newblk structures identified by mount point and
2052  *	   physical block number.
2053  *	4) bmsafemap structures identified by mount point and
2054  *	   cylinder group number.
2055  *
2056  * The "pagedep" and "inodedep" dependency structures are hashed
2057  * separately from the file blocks and inodes to which they correspond.
2058  * This separation helps when the in-memory copy of an inode or
2059  * file block must be replaced. It also obviates the need to access
2060  * an inode or file page when simply updating (or de-allocating)
2061  * dependency structures. Lookup of newblk structures is needed to
2062  * find newly allocated blocks when trying to associate them with
2063  * their allocdirect or allocindir structure.
2064  *
2065  * The lookup routines optionally create and hash a new instance when
2066  * an existing entry is not found. The bmsafemap lookup routine always
2067  * allocates a new structure if an existing one is not found.
2068  */
2069 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2070 
2071 /*
2072  * Structures and routines associated with pagedep caching.
2073  */
2074 #define	PAGEDEP_HASH(ump, inum, lbn) \
2075 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2076 
2077 static int
2078 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2079 	struct pagedep_hashhead *pagedephd;
2080 	ino_t ino;
2081 	ufs_lbn_t lbn;
2082 	struct pagedep **pagedeppp;
2083 {
2084 	struct pagedep *pagedep;
2085 
2086 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2087 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2088 			*pagedeppp = pagedep;
2089 			return (1);
2090 		}
2091 	}
2092 	*pagedeppp = NULL;
2093 	return (0);
2094 }
2095 /*
2096  * Look up a pagedep. Return 1 if found, 0 otherwise.
2097  * If not found, allocate if DEPALLOC flag is passed.
2098  * Found or allocated entry is returned in pagedeppp.
2099  * This routine must be called with splbio interrupts blocked.
2100  */
2101 static int
2102 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2103 	struct mount *mp;
2104 	struct buf *bp;
2105 	ino_t ino;
2106 	ufs_lbn_t lbn;
2107 	int flags;
2108 	struct pagedep **pagedeppp;
2109 {
2110 	struct pagedep *pagedep;
2111 	struct pagedep_hashhead *pagedephd;
2112 	struct worklist *wk;
2113 	struct ufsmount *ump;
2114 	int ret;
2115 	int i;
2116 
2117 	ump = VFSTOUFS(mp);
2118 	LOCK_OWNED(ump);
2119 	if (bp) {
2120 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2121 			if (wk->wk_type == D_PAGEDEP) {
2122 				*pagedeppp = WK_PAGEDEP(wk);
2123 				return (1);
2124 			}
2125 		}
2126 	}
2127 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2128 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2129 	if (ret) {
2130 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2131 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2132 		return (1);
2133 	}
2134 	if ((flags & DEPALLOC) == 0)
2135 		return (0);
2136 	FREE_LOCK(ump);
2137 	pagedep = malloc(sizeof(struct pagedep),
2138 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2139 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2140 	ACQUIRE_LOCK(ump);
2141 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2142 	if (*pagedeppp) {
2143 		/*
2144 		 * This should never happen since we only create pagedeps
2145 		 * with the vnode lock held.  Could be an assert.
2146 		 */
2147 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2148 		return (ret);
2149 	}
2150 	pagedep->pd_ino = ino;
2151 	pagedep->pd_lbn = lbn;
2152 	LIST_INIT(&pagedep->pd_dirremhd);
2153 	LIST_INIT(&pagedep->pd_pendinghd);
2154 	for (i = 0; i < DAHASHSZ; i++)
2155 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2156 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2157 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2158 	*pagedeppp = pagedep;
2159 	return (0);
2160 }
2161 
2162 /*
2163  * Structures and routines associated with inodedep caching.
2164  */
2165 #define	INODEDEP_HASH(ump, inum) \
2166       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2167 
2168 static int
2169 inodedep_find(inodedephd, inum, inodedeppp)
2170 	struct inodedep_hashhead *inodedephd;
2171 	ino_t inum;
2172 	struct inodedep **inodedeppp;
2173 {
2174 	struct inodedep *inodedep;
2175 
2176 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2177 		if (inum == inodedep->id_ino)
2178 			break;
2179 	if (inodedep) {
2180 		*inodedeppp = inodedep;
2181 		return (1);
2182 	}
2183 	*inodedeppp = NULL;
2184 
2185 	return (0);
2186 }
2187 /*
2188  * Look up an inodedep. Return 1 if found, 0 if not found.
2189  * If not found, allocate if DEPALLOC flag is passed.
2190  * Found or allocated entry is returned in inodedeppp.
2191  * This routine must be called with splbio interrupts blocked.
2192  */
2193 static int
2194 inodedep_lookup(mp, inum, flags, inodedeppp)
2195 	struct mount *mp;
2196 	ino_t inum;
2197 	int flags;
2198 	struct inodedep **inodedeppp;
2199 {
2200 	struct inodedep *inodedep;
2201 	struct inodedep_hashhead *inodedephd;
2202 	struct ufsmount *ump;
2203 	struct fs *fs;
2204 
2205 	ump = VFSTOUFS(mp);
2206 	LOCK_OWNED(ump);
2207 	fs = ump->um_fs;
2208 	inodedephd = INODEDEP_HASH(ump, inum);
2209 
2210 	if (inodedep_find(inodedephd, inum, inodedeppp))
2211 		return (1);
2212 	if ((flags & DEPALLOC) == 0)
2213 		return (0);
2214 	/*
2215 	 * If the system is over its limit and our filesystem is
2216 	 * responsible for more than our share of that usage and
2217 	 * we are not in a rush, request some inodedep cleanup.
2218 	 */
2219 	if (softdep_excess_items(ump, D_INODEDEP))
2220 		schedule_cleanup(mp);
2221 	else
2222 		FREE_LOCK(ump);
2223 	inodedep = malloc(sizeof(struct inodedep),
2224 		M_INODEDEP, M_SOFTDEP_FLAGS);
2225 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2226 	ACQUIRE_LOCK(ump);
2227 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2228 		WORKITEM_FREE(inodedep, D_INODEDEP);
2229 		return (1);
2230 	}
2231 	inodedep->id_fs = fs;
2232 	inodedep->id_ino = inum;
2233 	inodedep->id_state = ALLCOMPLETE;
2234 	inodedep->id_nlinkdelta = 0;
2235 	inodedep->id_savedino1 = NULL;
2236 	inodedep->id_savedsize = -1;
2237 	inodedep->id_savedextsize = -1;
2238 	inodedep->id_savednlink = -1;
2239 	inodedep->id_bmsafemap = NULL;
2240 	inodedep->id_mkdiradd = NULL;
2241 	LIST_INIT(&inodedep->id_dirremhd);
2242 	LIST_INIT(&inodedep->id_pendinghd);
2243 	LIST_INIT(&inodedep->id_inowait);
2244 	LIST_INIT(&inodedep->id_bufwait);
2245 	TAILQ_INIT(&inodedep->id_inoreflst);
2246 	TAILQ_INIT(&inodedep->id_inoupdt);
2247 	TAILQ_INIT(&inodedep->id_newinoupdt);
2248 	TAILQ_INIT(&inodedep->id_extupdt);
2249 	TAILQ_INIT(&inodedep->id_newextupdt);
2250 	TAILQ_INIT(&inodedep->id_freeblklst);
2251 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2252 	*inodedeppp = inodedep;
2253 	return (0);
2254 }
2255 
2256 /*
2257  * Structures and routines associated with newblk caching.
2258  */
2259 #define	NEWBLK_HASH(ump, inum) \
2260 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2261 
2262 static int
2263 newblk_find(newblkhd, newblkno, flags, newblkpp)
2264 	struct newblk_hashhead *newblkhd;
2265 	ufs2_daddr_t newblkno;
2266 	int flags;
2267 	struct newblk **newblkpp;
2268 {
2269 	struct newblk *newblk;
2270 
2271 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2272 		if (newblkno != newblk->nb_newblkno)
2273 			continue;
2274 		/*
2275 		 * If we're creating a new dependency don't match those that
2276 		 * have already been converted to allocdirects.  This is for
2277 		 * a frag extend.
2278 		 */
2279 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2280 			continue;
2281 		break;
2282 	}
2283 	if (newblk) {
2284 		*newblkpp = newblk;
2285 		return (1);
2286 	}
2287 	*newblkpp = NULL;
2288 	return (0);
2289 }
2290 
2291 /*
2292  * Look up a newblk. Return 1 if found, 0 if not found.
2293  * If not found, allocate if DEPALLOC flag is passed.
2294  * Found or allocated entry is returned in newblkpp.
2295  */
2296 static int
2297 newblk_lookup(mp, newblkno, flags, newblkpp)
2298 	struct mount *mp;
2299 	ufs2_daddr_t newblkno;
2300 	int flags;
2301 	struct newblk **newblkpp;
2302 {
2303 	struct newblk *newblk;
2304 	struct newblk_hashhead *newblkhd;
2305 	struct ufsmount *ump;
2306 
2307 	ump = VFSTOUFS(mp);
2308 	LOCK_OWNED(ump);
2309 	newblkhd = NEWBLK_HASH(ump, newblkno);
2310 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2311 		return (1);
2312 	if ((flags & DEPALLOC) == 0)
2313 		return (0);
2314 	if (softdep_excess_items(ump, D_NEWBLK) ||
2315 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2316 	    softdep_excess_items(ump, D_ALLOCINDIR))
2317 		schedule_cleanup(mp);
2318 	else
2319 		FREE_LOCK(ump);
2320 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2321 	    M_SOFTDEP_FLAGS | M_ZERO);
2322 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2323 	ACQUIRE_LOCK(ump);
2324 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2325 		WORKITEM_FREE(newblk, D_NEWBLK);
2326 		return (1);
2327 	}
2328 	newblk->nb_freefrag = NULL;
2329 	LIST_INIT(&newblk->nb_indirdeps);
2330 	LIST_INIT(&newblk->nb_newdirblk);
2331 	LIST_INIT(&newblk->nb_jwork);
2332 	newblk->nb_state = ATTACHED;
2333 	newblk->nb_newblkno = newblkno;
2334 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2335 	*newblkpp = newblk;
2336 	return (0);
2337 }
2338 
2339 /*
2340  * Structures and routines associated with freed indirect block caching.
2341  */
2342 #define	INDIR_HASH(ump, blkno) \
2343 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2344 
2345 /*
2346  * Lookup an indirect block in the indir hash table.  The freework is
2347  * removed and potentially freed.  The caller must do a blocking journal
2348  * write before writing to the blkno.
2349  */
2350 static int
2351 indirblk_lookup(mp, blkno)
2352 	struct mount *mp;
2353 	ufs2_daddr_t blkno;
2354 {
2355 	struct freework *freework;
2356 	struct indir_hashhead *wkhd;
2357 	struct ufsmount *ump;
2358 
2359 	ump = VFSTOUFS(mp);
2360 	wkhd = INDIR_HASH(ump, blkno);
2361 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2362 		if (freework->fw_blkno != blkno)
2363 			continue;
2364 		indirblk_remove(freework);
2365 		return (1);
2366 	}
2367 	return (0);
2368 }
2369 
2370 /*
2371  * Insert an indirect block represented by freework into the indirblk
2372  * hash table so that it may prevent the block from being re-used prior
2373  * to the journal being written.
2374  */
2375 static void
2376 indirblk_insert(freework)
2377 	struct freework *freework;
2378 {
2379 	struct jblocks *jblocks;
2380 	struct jseg *jseg;
2381 	struct ufsmount *ump;
2382 
2383 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2384 	jblocks = ump->softdep_jblocks;
2385 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2386 	if (jseg == NULL)
2387 		return;
2388 
2389 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2390 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2391 	    fw_next);
2392 	freework->fw_state &= ~DEPCOMPLETE;
2393 }
2394 
2395 static void
2396 indirblk_remove(freework)
2397 	struct freework *freework;
2398 {
2399 	struct ufsmount *ump;
2400 
2401 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2402 	LIST_REMOVE(freework, fw_segs);
2403 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2404 	freework->fw_state |= DEPCOMPLETE;
2405 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2406 		WORKITEM_FREE(freework, D_FREEWORK);
2407 }
2408 
2409 /*
2410  * Executed during filesystem system initialization before
2411  * mounting any filesystems.
2412  */
2413 void
2414 softdep_initialize()
2415 {
2416 
2417 	TAILQ_INIT(&softdepmounts);
2418 #ifdef __LP64__
2419 	max_softdeps = desiredvnodes * 4;
2420 #else
2421 	max_softdeps = desiredvnodes * 2;
2422 #endif
2423 
2424 	/* initialise bioops hack */
2425 	bioops.io_start = softdep_disk_io_initiation;
2426 	bioops.io_complete = softdep_disk_write_complete;
2427 	bioops.io_deallocate = softdep_deallocate_dependencies;
2428 	bioops.io_countdeps = softdep_count_dependencies;
2429 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2430 
2431 	/* Initialize the callout with an mtx. */
2432 	callout_init_mtx(&softdep_callout, &lk, 0);
2433 }
2434 
2435 /*
2436  * Executed after all filesystems have been unmounted during
2437  * filesystem module unload.
2438  */
2439 void
2440 softdep_uninitialize()
2441 {
2442 
2443 	/* clear bioops hack */
2444 	bioops.io_start = NULL;
2445 	bioops.io_complete = NULL;
2446 	bioops.io_deallocate = NULL;
2447 	bioops.io_countdeps = NULL;
2448 	softdep_ast_cleanup = NULL;
2449 
2450 	callout_drain(&softdep_callout);
2451 }
2452 
2453 /*
2454  * Called at mount time to notify the dependency code that a
2455  * filesystem wishes to use it.
2456  */
2457 int
2458 softdep_mount(devvp, mp, fs, cred)
2459 	struct vnode *devvp;
2460 	struct mount *mp;
2461 	struct fs *fs;
2462 	struct ucred *cred;
2463 {
2464 	struct csum_total cstotal;
2465 	struct mount_softdeps *sdp;
2466 	struct ufsmount *ump;
2467 	struct cg *cgp;
2468 	struct buf *bp;
2469 	u_int cyl, i;
2470 	int error;
2471 
2472 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2473 	    M_WAITOK | M_ZERO);
2474 	MNT_ILOCK(mp);
2475 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2476 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2477 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2478 			MNTK_SOFTDEP | MNTK_NOASYNC;
2479 	}
2480 	ump = VFSTOUFS(mp);
2481 	ump->um_softdep = sdp;
2482 	MNT_IUNLOCK(mp);
2483 	rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2484 	sdp->sd_ump = ump;
2485 	LIST_INIT(&ump->softdep_workitem_pending);
2486 	LIST_INIT(&ump->softdep_journal_pending);
2487 	TAILQ_INIT(&ump->softdep_unlinked);
2488 	LIST_INIT(&ump->softdep_dirtycg);
2489 	ump->softdep_worklist_tail = NULL;
2490 	ump->softdep_on_worklist = 0;
2491 	ump->softdep_deps = 0;
2492 	LIST_INIT(&ump->softdep_mkdirlisthd);
2493 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2494 	    &ump->pagedep_hash_size);
2495 	ump->pagedep_nextclean = 0;
2496 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2497 	    &ump->inodedep_hash_size);
2498 	ump->inodedep_nextclean = 0;
2499 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2500 	    &ump->newblk_hash_size);
2501 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2502 	    &ump->bmsafemap_hash_size);
2503 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2504 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2505 	    M_FREEWORK, M_WAITOK);
2506 	ump->indir_hash_size = i - 1;
2507 	for (i = 0; i <= ump->indir_hash_size; i++)
2508 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2509 	ACQUIRE_GBLLOCK(&lk);
2510 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2511 	FREE_GBLLOCK(&lk);
2512 	if ((fs->fs_flags & FS_SUJ) &&
2513 	    (error = journal_mount(mp, fs, cred)) != 0) {
2514 		printf("Failed to start journal: %d\n", error);
2515 		softdep_unmount(mp);
2516 		return (error);
2517 	}
2518 	/*
2519 	 * Start our flushing thread in the bufdaemon process.
2520 	 */
2521 	ACQUIRE_LOCK(ump);
2522 	ump->softdep_flags |= FLUSH_STARTING;
2523 	FREE_LOCK(ump);
2524 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2525 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2526 	    mp->mnt_stat.f_mntonname);
2527 	ACQUIRE_LOCK(ump);
2528 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2529 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2530 		    hz / 2);
2531 	}
2532 	FREE_LOCK(ump);
2533 	/*
2534 	 * When doing soft updates, the counters in the
2535 	 * superblock may have gotten out of sync. Recomputation
2536 	 * can take a long time and can be deferred for background
2537 	 * fsck.  However, the old behavior of scanning the cylinder
2538 	 * groups and recalculating them at mount time is available
2539 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2540 	 */
2541 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2542 		return (0);
2543 	bzero(&cstotal, sizeof cstotal);
2544 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2545 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2546 		    fs->fs_cgsize, cred, &bp)) != 0) {
2547 			brelse(bp);
2548 			softdep_unmount(mp);
2549 			return (error);
2550 		}
2551 		cgp = (struct cg *)bp->b_data;
2552 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2553 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2554 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2555 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2556 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2557 		brelse(bp);
2558 	}
2559 #ifdef DEBUG
2560 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2561 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2562 #endif
2563 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2564 	return (0);
2565 }
2566 
2567 void
2568 softdep_unmount(mp)
2569 	struct mount *mp;
2570 {
2571 	struct ufsmount *ump;
2572 #ifdef INVARIANTS
2573 	int i;
2574 #endif
2575 
2576 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2577 	    ("softdep_unmount called on non-softdep filesystem"));
2578 	ump = VFSTOUFS(mp);
2579 	MNT_ILOCK(mp);
2580 	mp->mnt_flag &= ~MNT_SOFTDEP;
2581 	if (MOUNTEDSUJ(mp) == 0) {
2582 		MNT_IUNLOCK(mp);
2583 	} else {
2584 		mp->mnt_flag &= ~MNT_SUJ;
2585 		MNT_IUNLOCK(mp);
2586 		journal_unmount(ump);
2587 	}
2588 	/*
2589 	 * Shut down our flushing thread. Check for NULL is if
2590 	 * softdep_mount errors out before the thread has been created.
2591 	 */
2592 	if (ump->softdep_flushtd != NULL) {
2593 		ACQUIRE_LOCK(ump);
2594 		ump->softdep_flags |= FLUSH_EXIT;
2595 		wakeup(&ump->softdep_flushtd);
2596 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2597 		    "sdwait", 0);
2598 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2599 		    ("Thread shutdown failed"));
2600 	}
2601 	/*
2602 	 * Free up our resources.
2603 	 */
2604 	ACQUIRE_GBLLOCK(&lk);
2605 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2606 	FREE_GBLLOCK(&lk);
2607 	rw_destroy(LOCK_PTR(ump));
2608 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2609 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2610 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2611 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2612 	    ump->bmsafemap_hash_size);
2613 	free(ump->indir_hashtbl, M_FREEWORK);
2614 #ifdef INVARIANTS
2615 	for (i = 0; i <= D_LAST; i++)
2616 		KASSERT(ump->softdep_curdeps[i] == 0,
2617 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2618 		    TYPENAME(i), ump->softdep_curdeps[i]));
2619 #endif
2620 	free(ump->um_softdep, M_MOUNTDATA);
2621 }
2622 
2623 static struct jblocks *
2624 jblocks_create(void)
2625 {
2626 	struct jblocks *jblocks;
2627 
2628 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2629 	TAILQ_INIT(&jblocks->jb_segs);
2630 	jblocks->jb_avail = 10;
2631 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2632 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2633 
2634 	return (jblocks);
2635 }
2636 
2637 static ufs2_daddr_t
2638 jblocks_alloc(jblocks, bytes, actual)
2639 	struct jblocks *jblocks;
2640 	int bytes;
2641 	int *actual;
2642 {
2643 	ufs2_daddr_t daddr;
2644 	struct jextent *jext;
2645 	int freecnt;
2646 	int blocks;
2647 
2648 	blocks = bytes / DEV_BSIZE;
2649 	jext = &jblocks->jb_extent[jblocks->jb_head];
2650 	freecnt = jext->je_blocks - jblocks->jb_off;
2651 	if (freecnt == 0) {
2652 		jblocks->jb_off = 0;
2653 		if (++jblocks->jb_head > jblocks->jb_used)
2654 			jblocks->jb_head = 0;
2655 		jext = &jblocks->jb_extent[jblocks->jb_head];
2656 		freecnt = jext->je_blocks;
2657 	}
2658 	if (freecnt > blocks)
2659 		freecnt = blocks;
2660 	*actual = freecnt * DEV_BSIZE;
2661 	daddr = jext->je_daddr + jblocks->jb_off;
2662 	jblocks->jb_off += freecnt;
2663 	jblocks->jb_free -= freecnt;
2664 
2665 	return (daddr);
2666 }
2667 
2668 static void
2669 jblocks_free(jblocks, mp, bytes)
2670 	struct jblocks *jblocks;
2671 	struct mount *mp;
2672 	int bytes;
2673 {
2674 
2675 	LOCK_OWNED(VFSTOUFS(mp));
2676 	jblocks->jb_free += bytes / DEV_BSIZE;
2677 	if (jblocks->jb_suspended)
2678 		worklist_speedup(mp);
2679 	wakeup(jblocks);
2680 }
2681 
2682 static void
2683 jblocks_destroy(jblocks)
2684 	struct jblocks *jblocks;
2685 {
2686 
2687 	if (jblocks->jb_extent)
2688 		free(jblocks->jb_extent, M_JBLOCKS);
2689 	free(jblocks, M_JBLOCKS);
2690 }
2691 
2692 static void
2693 jblocks_add(jblocks, daddr, blocks)
2694 	struct jblocks *jblocks;
2695 	ufs2_daddr_t daddr;
2696 	int blocks;
2697 {
2698 	struct jextent *jext;
2699 
2700 	jblocks->jb_blocks += blocks;
2701 	jblocks->jb_free += blocks;
2702 	jext = &jblocks->jb_extent[jblocks->jb_used];
2703 	/* Adding the first block. */
2704 	if (jext->je_daddr == 0) {
2705 		jext->je_daddr = daddr;
2706 		jext->je_blocks = blocks;
2707 		return;
2708 	}
2709 	/* Extending the last extent. */
2710 	if (jext->je_daddr + jext->je_blocks == daddr) {
2711 		jext->je_blocks += blocks;
2712 		return;
2713 	}
2714 	/* Adding a new extent. */
2715 	if (++jblocks->jb_used == jblocks->jb_avail) {
2716 		jblocks->jb_avail *= 2;
2717 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2718 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2719 		memcpy(jext, jblocks->jb_extent,
2720 		    sizeof(struct jextent) * jblocks->jb_used);
2721 		free(jblocks->jb_extent, M_JBLOCKS);
2722 		jblocks->jb_extent = jext;
2723 	}
2724 	jext = &jblocks->jb_extent[jblocks->jb_used];
2725 	jext->je_daddr = daddr;
2726 	jext->je_blocks = blocks;
2727 	return;
2728 }
2729 
2730 int
2731 softdep_journal_lookup(mp, vpp)
2732 	struct mount *mp;
2733 	struct vnode **vpp;
2734 {
2735 	struct componentname cnp;
2736 	struct vnode *dvp;
2737 	ino_t sujournal;
2738 	int error;
2739 
2740 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2741 	if (error)
2742 		return (error);
2743 	bzero(&cnp, sizeof(cnp));
2744 	cnp.cn_nameiop = LOOKUP;
2745 	cnp.cn_flags = ISLASTCN;
2746 	cnp.cn_thread = curthread;
2747 	cnp.cn_cred = curthread->td_ucred;
2748 	cnp.cn_pnbuf = SUJ_FILE;
2749 	cnp.cn_nameptr = SUJ_FILE;
2750 	cnp.cn_namelen = strlen(SUJ_FILE);
2751 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2752 	vput(dvp);
2753 	if (error != 0)
2754 		return (error);
2755 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2756 	return (error);
2757 }
2758 
2759 /*
2760  * Open and verify the journal file.
2761  */
2762 static int
2763 journal_mount(mp, fs, cred)
2764 	struct mount *mp;
2765 	struct fs *fs;
2766 	struct ucred *cred;
2767 {
2768 	struct jblocks *jblocks;
2769 	struct ufsmount *ump;
2770 	struct vnode *vp;
2771 	struct inode *ip;
2772 	ufs2_daddr_t blkno;
2773 	int bcount;
2774 	int error;
2775 	int i;
2776 
2777 	ump = VFSTOUFS(mp);
2778 	ump->softdep_journal_tail = NULL;
2779 	ump->softdep_on_journal = 0;
2780 	ump->softdep_accdeps = 0;
2781 	ump->softdep_req = 0;
2782 	ump->softdep_jblocks = NULL;
2783 	error = softdep_journal_lookup(mp, &vp);
2784 	if (error != 0) {
2785 		printf("Failed to find journal.  Use tunefs to create one\n");
2786 		return (error);
2787 	}
2788 	ip = VTOI(vp);
2789 	if (ip->i_size < SUJ_MIN) {
2790 		error = ENOSPC;
2791 		goto out;
2792 	}
2793 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2794 	jblocks = jblocks_create();
2795 	for (i = 0; i < bcount; i++) {
2796 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2797 		if (error)
2798 			break;
2799 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2800 	}
2801 	if (error) {
2802 		jblocks_destroy(jblocks);
2803 		goto out;
2804 	}
2805 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2806 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2807 	ump->softdep_jblocks = jblocks;
2808 out:
2809 	if (error == 0) {
2810 		MNT_ILOCK(mp);
2811 		mp->mnt_flag |= MNT_SUJ;
2812 		mp->mnt_flag &= ~MNT_SOFTDEP;
2813 		MNT_IUNLOCK(mp);
2814 		/*
2815 		 * Only validate the journal contents if the
2816 		 * filesystem is clean, otherwise we write the logs
2817 		 * but they'll never be used.  If the filesystem was
2818 		 * still dirty when we mounted it the journal is
2819 		 * invalid and a new journal can only be valid if it
2820 		 * starts from a clean mount.
2821 		 */
2822 		if (fs->fs_clean) {
2823 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2824 			ip->i_flags |= IN_MODIFIED;
2825 			ffs_update(vp, 1);
2826 		}
2827 	}
2828 	vput(vp);
2829 	return (error);
2830 }
2831 
2832 static void
2833 journal_unmount(ump)
2834 	struct ufsmount *ump;
2835 {
2836 
2837 	if (ump->softdep_jblocks)
2838 		jblocks_destroy(ump->softdep_jblocks);
2839 	ump->softdep_jblocks = NULL;
2840 }
2841 
2842 /*
2843  * Called when a journal record is ready to be written.  Space is allocated
2844  * and the journal entry is created when the journal is flushed to stable
2845  * store.
2846  */
2847 static void
2848 add_to_journal(wk)
2849 	struct worklist *wk;
2850 {
2851 	struct ufsmount *ump;
2852 
2853 	ump = VFSTOUFS(wk->wk_mp);
2854 	LOCK_OWNED(ump);
2855 	if (wk->wk_state & ONWORKLIST)
2856 		panic("add_to_journal: %s(0x%X) already on list",
2857 		    TYPENAME(wk->wk_type), wk->wk_state);
2858 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2859 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2860 		ump->softdep_jblocks->jb_age = ticks;
2861 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2862 	} else
2863 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2864 	ump->softdep_journal_tail = wk;
2865 	ump->softdep_on_journal += 1;
2866 }
2867 
2868 /*
2869  * Remove an arbitrary item for the journal worklist maintain the tail
2870  * pointer.  This happens when a new operation obviates the need to
2871  * journal an old operation.
2872  */
2873 static void
2874 remove_from_journal(wk)
2875 	struct worklist *wk;
2876 {
2877 	struct ufsmount *ump;
2878 
2879 	ump = VFSTOUFS(wk->wk_mp);
2880 	LOCK_OWNED(ump);
2881 #ifdef SUJ_DEBUG
2882 	{
2883 		struct worklist *wkn;
2884 
2885 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2886 			if (wkn == wk)
2887 				break;
2888 		if (wkn == NULL)
2889 			panic("remove_from_journal: %p is not in journal", wk);
2890 	}
2891 #endif
2892 	/*
2893 	 * We emulate a TAILQ to save space in most structures which do not
2894 	 * require TAILQ semantics.  Here we must update the tail position
2895 	 * when removing the tail which is not the final entry. This works
2896 	 * only if the worklist linkage are at the beginning of the structure.
2897 	 */
2898 	if (ump->softdep_journal_tail == wk)
2899 		ump->softdep_journal_tail =
2900 		    (struct worklist *)wk->wk_list.le_prev;
2901 	WORKLIST_REMOVE(wk);
2902 	ump->softdep_on_journal -= 1;
2903 }
2904 
2905 /*
2906  * Check for journal space as well as dependency limits so the prelink
2907  * code can throttle both journaled and non-journaled filesystems.
2908  * Threshold is 0 for low and 1 for min.
2909  */
2910 static int
2911 journal_space(ump, thresh)
2912 	struct ufsmount *ump;
2913 	int thresh;
2914 {
2915 	struct jblocks *jblocks;
2916 	int limit, avail;
2917 
2918 	jblocks = ump->softdep_jblocks;
2919 	if (jblocks == NULL)
2920 		return (1);
2921 	/*
2922 	 * We use a tighter restriction here to prevent request_cleanup()
2923 	 * running in threads from running into locks we currently hold.
2924 	 * We have to be over the limit and our filesystem has to be
2925 	 * responsible for more than our share of that usage.
2926 	 */
2927 	limit = (max_softdeps / 10) * 9;
2928 	if (dep_current[D_INODEDEP] > limit &&
2929 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2930 		return (0);
2931 	if (thresh)
2932 		thresh = jblocks->jb_min;
2933 	else
2934 		thresh = jblocks->jb_low;
2935 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2936 	avail = jblocks->jb_free - avail;
2937 
2938 	return (avail > thresh);
2939 }
2940 
2941 static void
2942 journal_suspend(ump)
2943 	struct ufsmount *ump;
2944 {
2945 	struct jblocks *jblocks;
2946 	struct mount *mp;
2947 
2948 	mp = UFSTOVFS(ump);
2949 	jblocks = ump->softdep_jblocks;
2950 	MNT_ILOCK(mp);
2951 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2952 		stat_journal_min++;
2953 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2954 		mp->mnt_susp_owner = ump->softdep_flushtd;
2955 	}
2956 	jblocks->jb_suspended = 1;
2957 	MNT_IUNLOCK(mp);
2958 }
2959 
2960 static int
2961 journal_unsuspend(struct ufsmount *ump)
2962 {
2963 	struct jblocks *jblocks;
2964 	struct mount *mp;
2965 
2966 	mp = UFSTOVFS(ump);
2967 	jblocks = ump->softdep_jblocks;
2968 
2969 	if (jblocks != NULL && jblocks->jb_suspended &&
2970 	    journal_space(ump, jblocks->jb_min)) {
2971 		jblocks->jb_suspended = 0;
2972 		FREE_LOCK(ump);
2973 		mp->mnt_susp_owner = curthread;
2974 		vfs_write_resume(mp, 0);
2975 		ACQUIRE_LOCK(ump);
2976 		return (1);
2977 	}
2978 	return (0);
2979 }
2980 
2981 /*
2982  * Called before any allocation function to be certain that there is
2983  * sufficient space in the journal prior to creating any new records.
2984  * Since in the case of block allocation we may have multiple locked
2985  * buffers at the time of the actual allocation we can not block
2986  * when the journal records are created.  Doing so would create a deadlock
2987  * if any of these buffers needed to be flushed to reclaim space.  Instead
2988  * we require a sufficiently large amount of available space such that
2989  * each thread in the system could have passed this allocation check and
2990  * still have sufficient free space.  With 20% of a minimum journal size
2991  * of 1MB we have 6553 records available.
2992  */
2993 int
2994 softdep_prealloc(vp, waitok)
2995 	struct vnode *vp;
2996 	int waitok;
2997 {
2998 	struct ufsmount *ump;
2999 
3000 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3001 	    ("softdep_prealloc called on non-softdep filesystem"));
3002 	/*
3003 	 * Nothing to do if we are not running journaled soft updates.
3004 	 * If we currently hold the snapshot lock, we must avoid
3005 	 * handling other resources that could cause deadlock.  Do not
3006 	 * touch quotas vnode since it is typically recursed with
3007 	 * other vnode locks held.
3008 	 */
3009 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3010 	    (vp->v_vflag & VV_SYSTEM) != 0)
3011 		return (0);
3012 	ump = VFSTOUFS(vp->v_mount);
3013 	ACQUIRE_LOCK(ump);
3014 	if (journal_space(ump, 0)) {
3015 		FREE_LOCK(ump);
3016 		return (0);
3017 	}
3018 	stat_journal_low++;
3019 	FREE_LOCK(ump);
3020 	if (waitok == MNT_NOWAIT)
3021 		return (ENOSPC);
3022 	/*
3023 	 * Attempt to sync this vnode once to flush any journal
3024 	 * work attached to it.
3025 	 */
3026 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3027 		ffs_syncvnode(vp, waitok, 0);
3028 	ACQUIRE_LOCK(ump);
3029 	process_removes(vp);
3030 	process_truncates(vp);
3031 	if (journal_space(ump, 0) == 0) {
3032 		softdep_speedup(ump);
3033 		if (journal_space(ump, 1) == 0)
3034 			journal_suspend(ump);
3035 	}
3036 	FREE_LOCK(ump);
3037 
3038 	return (0);
3039 }
3040 
3041 /*
3042  * Before adjusting a link count on a vnode verify that we have sufficient
3043  * journal space.  If not, process operations that depend on the currently
3044  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3045  * and softdep flush threads can not acquire these locks to reclaim space.
3046  */
3047 static void
3048 softdep_prelink(dvp, vp)
3049 	struct vnode *dvp;
3050 	struct vnode *vp;
3051 {
3052 	struct ufsmount *ump;
3053 
3054 	ump = VFSTOUFS(dvp->v_mount);
3055 	LOCK_OWNED(ump);
3056 	/*
3057 	 * Nothing to do if we have sufficient journal space.
3058 	 * If we currently hold the snapshot lock, we must avoid
3059 	 * handling other resources that could cause deadlock.
3060 	 */
3061 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3062 		return;
3063 	stat_journal_low++;
3064 	FREE_LOCK(ump);
3065 	if (vp)
3066 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3067 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3068 	ACQUIRE_LOCK(ump);
3069 	/* Process vp before dvp as it may create .. removes. */
3070 	if (vp) {
3071 		process_removes(vp);
3072 		process_truncates(vp);
3073 	}
3074 	process_removes(dvp);
3075 	process_truncates(dvp);
3076 	softdep_speedup(ump);
3077 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3078 	if (journal_space(ump, 0) == 0) {
3079 		softdep_speedup(ump);
3080 		if (journal_space(ump, 1) == 0)
3081 			journal_suspend(ump);
3082 	}
3083 }
3084 
3085 static void
3086 jseg_write(ump, jseg, data)
3087 	struct ufsmount *ump;
3088 	struct jseg *jseg;
3089 	uint8_t *data;
3090 {
3091 	struct jsegrec *rec;
3092 
3093 	rec = (struct jsegrec *)data;
3094 	rec->jsr_seq = jseg->js_seq;
3095 	rec->jsr_oldest = jseg->js_oldseq;
3096 	rec->jsr_cnt = jseg->js_cnt;
3097 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3098 	rec->jsr_crc = 0;
3099 	rec->jsr_time = ump->um_fs->fs_mtime;
3100 }
3101 
3102 static inline void
3103 inoref_write(inoref, jseg, rec)
3104 	struct inoref *inoref;
3105 	struct jseg *jseg;
3106 	struct jrefrec *rec;
3107 {
3108 
3109 	inoref->if_jsegdep->jd_seg = jseg;
3110 	rec->jr_ino = inoref->if_ino;
3111 	rec->jr_parent = inoref->if_parent;
3112 	rec->jr_nlink = inoref->if_nlink;
3113 	rec->jr_mode = inoref->if_mode;
3114 	rec->jr_diroff = inoref->if_diroff;
3115 }
3116 
3117 static void
3118 jaddref_write(jaddref, jseg, data)
3119 	struct jaddref *jaddref;
3120 	struct jseg *jseg;
3121 	uint8_t *data;
3122 {
3123 	struct jrefrec *rec;
3124 
3125 	rec = (struct jrefrec *)data;
3126 	rec->jr_op = JOP_ADDREF;
3127 	inoref_write(&jaddref->ja_ref, jseg, rec);
3128 }
3129 
3130 static void
3131 jremref_write(jremref, jseg, data)
3132 	struct jremref *jremref;
3133 	struct jseg *jseg;
3134 	uint8_t *data;
3135 {
3136 	struct jrefrec *rec;
3137 
3138 	rec = (struct jrefrec *)data;
3139 	rec->jr_op = JOP_REMREF;
3140 	inoref_write(&jremref->jr_ref, jseg, rec);
3141 }
3142 
3143 static void
3144 jmvref_write(jmvref, jseg, data)
3145 	struct jmvref *jmvref;
3146 	struct jseg *jseg;
3147 	uint8_t *data;
3148 {
3149 	struct jmvrec *rec;
3150 
3151 	rec = (struct jmvrec *)data;
3152 	rec->jm_op = JOP_MVREF;
3153 	rec->jm_ino = jmvref->jm_ino;
3154 	rec->jm_parent = jmvref->jm_parent;
3155 	rec->jm_oldoff = jmvref->jm_oldoff;
3156 	rec->jm_newoff = jmvref->jm_newoff;
3157 }
3158 
3159 static void
3160 jnewblk_write(jnewblk, jseg, data)
3161 	struct jnewblk *jnewblk;
3162 	struct jseg *jseg;
3163 	uint8_t *data;
3164 {
3165 	struct jblkrec *rec;
3166 
3167 	jnewblk->jn_jsegdep->jd_seg = jseg;
3168 	rec = (struct jblkrec *)data;
3169 	rec->jb_op = JOP_NEWBLK;
3170 	rec->jb_ino = jnewblk->jn_ino;
3171 	rec->jb_blkno = jnewblk->jn_blkno;
3172 	rec->jb_lbn = jnewblk->jn_lbn;
3173 	rec->jb_frags = jnewblk->jn_frags;
3174 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3175 }
3176 
3177 static void
3178 jfreeblk_write(jfreeblk, jseg, data)
3179 	struct jfreeblk *jfreeblk;
3180 	struct jseg *jseg;
3181 	uint8_t *data;
3182 {
3183 	struct jblkrec *rec;
3184 
3185 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3186 	rec = (struct jblkrec *)data;
3187 	rec->jb_op = JOP_FREEBLK;
3188 	rec->jb_ino = jfreeblk->jf_ino;
3189 	rec->jb_blkno = jfreeblk->jf_blkno;
3190 	rec->jb_lbn = jfreeblk->jf_lbn;
3191 	rec->jb_frags = jfreeblk->jf_frags;
3192 	rec->jb_oldfrags = 0;
3193 }
3194 
3195 static void
3196 jfreefrag_write(jfreefrag, jseg, data)
3197 	struct jfreefrag *jfreefrag;
3198 	struct jseg *jseg;
3199 	uint8_t *data;
3200 {
3201 	struct jblkrec *rec;
3202 
3203 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3204 	rec = (struct jblkrec *)data;
3205 	rec->jb_op = JOP_FREEBLK;
3206 	rec->jb_ino = jfreefrag->fr_ino;
3207 	rec->jb_blkno = jfreefrag->fr_blkno;
3208 	rec->jb_lbn = jfreefrag->fr_lbn;
3209 	rec->jb_frags = jfreefrag->fr_frags;
3210 	rec->jb_oldfrags = 0;
3211 }
3212 
3213 static void
3214 jtrunc_write(jtrunc, jseg, data)
3215 	struct jtrunc *jtrunc;
3216 	struct jseg *jseg;
3217 	uint8_t *data;
3218 {
3219 	struct jtrncrec *rec;
3220 
3221 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3222 	rec = (struct jtrncrec *)data;
3223 	rec->jt_op = JOP_TRUNC;
3224 	rec->jt_ino = jtrunc->jt_ino;
3225 	rec->jt_size = jtrunc->jt_size;
3226 	rec->jt_extsize = jtrunc->jt_extsize;
3227 }
3228 
3229 static void
3230 jfsync_write(jfsync, jseg, data)
3231 	struct jfsync *jfsync;
3232 	struct jseg *jseg;
3233 	uint8_t *data;
3234 {
3235 	struct jtrncrec *rec;
3236 
3237 	rec = (struct jtrncrec *)data;
3238 	rec->jt_op = JOP_SYNC;
3239 	rec->jt_ino = jfsync->jfs_ino;
3240 	rec->jt_size = jfsync->jfs_size;
3241 	rec->jt_extsize = jfsync->jfs_extsize;
3242 }
3243 
3244 static void
3245 softdep_flushjournal(mp)
3246 	struct mount *mp;
3247 {
3248 	struct jblocks *jblocks;
3249 	struct ufsmount *ump;
3250 
3251 	if (MOUNTEDSUJ(mp) == 0)
3252 		return;
3253 	ump = VFSTOUFS(mp);
3254 	jblocks = ump->softdep_jblocks;
3255 	ACQUIRE_LOCK(ump);
3256 	while (ump->softdep_on_journal) {
3257 		jblocks->jb_needseg = 1;
3258 		softdep_process_journal(mp, NULL, MNT_WAIT);
3259 	}
3260 	FREE_LOCK(ump);
3261 }
3262 
3263 static void softdep_synchronize_completed(struct bio *);
3264 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3265 
3266 static void
3267 softdep_synchronize_completed(bp)
3268         struct bio *bp;
3269 {
3270 	struct jseg *oldest;
3271 	struct jseg *jseg;
3272 	struct ufsmount *ump;
3273 
3274 	/*
3275 	 * caller1 marks the last segment written before we issued the
3276 	 * synchronize cache.
3277 	 */
3278 	jseg = bp->bio_caller1;
3279 	if (jseg == NULL) {
3280 		g_destroy_bio(bp);
3281 		return;
3282 	}
3283 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3284 	ACQUIRE_LOCK(ump);
3285 	oldest = NULL;
3286 	/*
3287 	 * Mark all the journal entries waiting on the synchronize cache
3288 	 * as completed so they may continue on.
3289 	 */
3290 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3291 		jseg->js_state |= COMPLETE;
3292 		oldest = jseg;
3293 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3294 	}
3295 	/*
3296 	 * Restart deferred journal entry processing from the oldest
3297 	 * completed jseg.
3298 	 */
3299 	if (oldest)
3300 		complete_jsegs(oldest);
3301 
3302 	FREE_LOCK(ump);
3303 	g_destroy_bio(bp);
3304 }
3305 
3306 /*
3307  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3308  * barriers.  The journal must be written prior to any blocks that depend
3309  * on it and the journal can not be released until the blocks have be
3310  * written.  This code handles both barriers simultaneously.
3311  */
3312 static void
3313 softdep_synchronize(bp, ump, caller1)
3314 	struct bio *bp;
3315 	struct ufsmount *ump;
3316 	void *caller1;
3317 {
3318 
3319 	bp->bio_cmd = BIO_FLUSH;
3320 	bp->bio_flags |= BIO_ORDERED;
3321 	bp->bio_data = NULL;
3322 	bp->bio_offset = ump->um_cp->provider->mediasize;
3323 	bp->bio_length = 0;
3324 	bp->bio_done = softdep_synchronize_completed;
3325 	bp->bio_caller1 = caller1;
3326 	g_io_request(bp,
3327 	    (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3328 }
3329 
3330 /*
3331  * Flush some journal records to disk.
3332  */
3333 static void
3334 softdep_process_journal(mp, needwk, flags)
3335 	struct mount *mp;
3336 	struct worklist *needwk;
3337 	int flags;
3338 {
3339 	struct jblocks *jblocks;
3340 	struct ufsmount *ump;
3341 	struct worklist *wk;
3342 	struct jseg *jseg;
3343 	struct buf *bp;
3344 	struct bio *bio;
3345 	uint8_t *data;
3346 	struct fs *fs;
3347 	int shouldflush;
3348 	int segwritten;
3349 	int jrecmin;	/* Minimum records per block. */
3350 	int jrecmax;	/* Maximum records per block. */
3351 	int size;
3352 	int cnt;
3353 	int off;
3354 	int devbsize;
3355 
3356 	if (MOUNTEDSUJ(mp) == 0)
3357 		return;
3358 	shouldflush = softdep_flushcache;
3359 	bio = NULL;
3360 	jseg = NULL;
3361 	ump = VFSTOUFS(mp);
3362 	LOCK_OWNED(ump);
3363 	fs = ump->um_fs;
3364 	jblocks = ump->softdep_jblocks;
3365 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3366 	/*
3367 	 * We write anywhere between a disk block and fs block.  The upper
3368 	 * bound is picked to prevent buffer cache fragmentation and limit
3369 	 * processing time per I/O.
3370 	 */
3371 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3372 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3373 	segwritten = 0;
3374 	for (;;) {
3375 		cnt = ump->softdep_on_journal;
3376 		/*
3377 		 * Criteria for writing a segment:
3378 		 * 1) We have a full block.
3379 		 * 2) We're called from jwait() and haven't found the
3380 		 *    journal item yet.
3381 		 * 3) Always write if needseg is set.
3382 		 * 4) If we are called from process_worklist and have
3383 		 *    not yet written anything we write a partial block
3384 		 *    to enforce a 1 second maximum latency on journal
3385 		 *    entries.
3386 		 */
3387 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3388 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3389 			break;
3390 		cnt++;
3391 		/*
3392 		 * Verify some free journal space.  softdep_prealloc() should
3393 		 * guarantee that we don't run out so this is indicative of
3394 		 * a problem with the flow control.  Try to recover
3395 		 * gracefully in any event.
3396 		 */
3397 		while (jblocks->jb_free == 0) {
3398 			if (flags != MNT_WAIT)
3399 				break;
3400 			printf("softdep: Out of journal space!\n");
3401 			softdep_speedup(ump);
3402 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3403 		}
3404 		FREE_LOCK(ump);
3405 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3406 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3407 		LIST_INIT(&jseg->js_entries);
3408 		LIST_INIT(&jseg->js_indirs);
3409 		jseg->js_state = ATTACHED;
3410 		if (shouldflush == 0)
3411 			jseg->js_state |= COMPLETE;
3412 		else if (bio == NULL)
3413 			bio = g_alloc_bio();
3414 		jseg->js_jblocks = jblocks;
3415 		bp = geteblk(fs->fs_bsize, 0);
3416 		ACQUIRE_LOCK(ump);
3417 		/*
3418 		 * If there was a race while we were allocating the block
3419 		 * and jseg the entry we care about was likely written.
3420 		 * We bail out in both the WAIT and NOWAIT case and assume
3421 		 * the caller will loop if the entry it cares about is
3422 		 * not written.
3423 		 */
3424 		cnt = ump->softdep_on_journal;
3425 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3426 			bp->b_flags |= B_INVAL | B_NOCACHE;
3427 			WORKITEM_FREE(jseg, D_JSEG);
3428 			FREE_LOCK(ump);
3429 			brelse(bp);
3430 			ACQUIRE_LOCK(ump);
3431 			break;
3432 		}
3433 		/*
3434 		 * Calculate the disk block size required for the available
3435 		 * records rounded to the min size.
3436 		 */
3437 		if (cnt == 0)
3438 			size = devbsize;
3439 		else if (cnt < jrecmax)
3440 			size = howmany(cnt, jrecmin) * devbsize;
3441 		else
3442 			size = fs->fs_bsize;
3443 		/*
3444 		 * Allocate a disk block for this journal data and account
3445 		 * for truncation of the requested size if enough contiguous
3446 		 * space was not available.
3447 		 */
3448 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3449 		bp->b_lblkno = bp->b_blkno;
3450 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3451 		bp->b_bcount = size;
3452 		bp->b_flags &= ~B_INVAL;
3453 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3454 		/*
3455 		 * Initialize our jseg with cnt records.  Assign the next
3456 		 * sequence number to it and link it in-order.
3457 		 */
3458 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3459 		jseg->js_buf = bp;
3460 		jseg->js_cnt = cnt;
3461 		jseg->js_refs = cnt + 1;	/* Self ref. */
3462 		jseg->js_size = size;
3463 		jseg->js_seq = jblocks->jb_nextseq++;
3464 		if (jblocks->jb_oldestseg == NULL)
3465 			jblocks->jb_oldestseg = jseg;
3466 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3467 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3468 		if (jblocks->jb_writeseg == NULL)
3469 			jblocks->jb_writeseg = jseg;
3470 		/*
3471 		 * Start filling in records from the pending list.
3472 		 */
3473 		data = bp->b_data;
3474 		off = 0;
3475 
3476 		/*
3477 		 * Always put a header on the first block.
3478 		 * XXX As with below, there might not be a chance to get
3479 		 * into the loop.  Ensure that something valid is written.
3480 		 */
3481 		jseg_write(ump, jseg, data);
3482 		off += JREC_SIZE;
3483 		data = bp->b_data + off;
3484 
3485 		/*
3486 		 * XXX Something is wrong here.  There's no work to do,
3487 		 * but we need to perform and I/O and allow it to complete
3488 		 * anyways.
3489 		 */
3490 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3491 			stat_emptyjblocks++;
3492 
3493 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3494 		    != NULL) {
3495 			if (cnt == 0)
3496 				break;
3497 			/* Place a segment header on every device block. */
3498 			if ((off % devbsize) == 0) {
3499 				jseg_write(ump, jseg, data);
3500 				off += JREC_SIZE;
3501 				data = bp->b_data + off;
3502 			}
3503 			if (wk == needwk)
3504 				needwk = NULL;
3505 			remove_from_journal(wk);
3506 			wk->wk_state |= INPROGRESS;
3507 			WORKLIST_INSERT(&jseg->js_entries, wk);
3508 			switch (wk->wk_type) {
3509 			case D_JADDREF:
3510 				jaddref_write(WK_JADDREF(wk), jseg, data);
3511 				break;
3512 			case D_JREMREF:
3513 				jremref_write(WK_JREMREF(wk), jseg, data);
3514 				break;
3515 			case D_JMVREF:
3516 				jmvref_write(WK_JMVREF(wk), jseg, data);
3517 				break;
3518 			case D_JNEWBLK:
3519 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3520 				break;
3521 			case D_JFREEBLK:
3522 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3523 				break;
3524 			case D_JFREEFRAG:
3525 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3526 				break;
3527 			case D_JTRUNC:
3528 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3529 				break;
3530 			case D_JFSYNC:
3531 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3532 				break;
3533 			default:
3534 				panic("process_journal: Unknown type %s",
3535 				    TYPENAME(wk->wk_type));
3536 				/* NOTREACHED */
3537 			}
3538 			off += JREC_SIZE;
3539 			data = bp->b_data + off;
3540 			cnt--;
3541 		}
3542 
3543 		/* Clear any remaining space so we don't leak kernel data */
3544 		if (size > off)
3545 			bzero(data, size - off);
3546 
3547 		/*
3548 		 * Write this one buffer and continue.
3549 		 */
3550 		segwritten = 1;
3551 		jblocks->jb_needseg = 0;
3552 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3553 		FREE_LOCK(ump);
3554 		pbgetvp(ump->um_devvp, bp);
3555 		/*
3556 		 * We only do the blocking wait once we find the journal
3557 		 * entry we're looking for.
3558 		 */
3559 		if (needwk == NULL && flags == MNT_WAIT)
3560 			bwrite(bp);
3561 		else
3562 			bawrite(bp);
3563 		ACQUIRE_LOCK(ump);
3564 	}
3565 	/*
3566 	 * If we wrote a segment issue a synchronize cache so the journal
3567 	 * is reflected on disk before the data is written.  Since reclaiming
3568 	 * journal space also requires writing a journal record this
3569 	 * process also enforces a barrier before reclamation.
3570 	 */
3571 	if (segwritten && shouldflush) {
3572 		softdep_synchronize(bio, ump,
3573 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3574 	} else if (bio)
3575 		g_destroy_bio(bio);
3576 	/*
3577 	 * If we've suspended the filesystem because we ran out of journal
3578 	 * space either try to sync it here to make some progress or
3579 	 * unsuspend it if we already have.
3580 	 */
3581 	if (flags == 0 && jblocks->jb_suspended) {
3582 		if (journal_unsuspend(ump))
3583 			return;
3584 		FREE_LOCK(ump);
3585 		VFS_SYNC(mp, MNT_NOWAIT);
3586 		ffs_sbupdate(ump, MNT_WAIT, 0);
3587 		ACQUIRE_LOCK(ump);
3588 	}
3589 }
3590 
3591 /*
3592  * Complete a jseg, allowing all dependencies awaiting journal writes
3593  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3594  * structures so that the journal segment can be freed to reclaim space.
3595  */
3596 static void
3597 complete_jseg(jseg)
3598 	struct jseg *jseg;
3599 {
3600 	struct worklist *wk;
3601 	struct jmvref *jmvref;
3602 #ifdef INVARIANTS
3603 	int i = 0;
3604 #endif
3605 
3606 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3607 		WORKLIST_REMOVE(wk);
3608 		wk->wk_state &= ~INPROGRESS;
3609 		wk->wk_state |= COMPLETE;
3610 		KASSERT(i++ < jseg->js_cnt,
3611 		    ("handle_written_jseg: overflow %d >= %d",
3612 		    i - 1, jseg->js_cnt));
3613 		switch (wk->wk_type) {
3614 		case D_JADDREF:
3615 			handle_written_jaddref(WK_JADDREF(wk));
3616 			break;
3617 		case D_JREMREF:
3618 			handle_written_jremref(WK_JREMREF(wk));
3619 			break;
3620 		case D_JMVREF:
3621 			rele_jseg(jseg);	/* No jsegdep. */
3622 			jmvref = WK_JMVREF(wk);
3623 			LIST_REMOVE(jmvref, jm_deps);
3624 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3625 				free_pagedep(jmvref->jm_pagedep);
3626 			WORKITEM_FREE(jmvref, D_JMVREF);
3627 			break;
3628 		case D_JNEWBLK:
3629 			handle_written_jnewblk(WK_JNEWBLK(wk));
3630 			break;
3631 		case D_JFREEBLK:
3632 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3633 			break;
3634 		case D_JTRUNC:
3635 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3636 			break;
3637 		case D_JFSYNC:
3638 			rele_jseg(jseg);	/* No jsegdep. */
3639 			WORKITEM_FREE(wk, D_JFSYNC);
3640 			break;
3641 		case D_JFREEFRAG:
3642 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3643 			break;
3644 		default:
3645 			panic("handle_written_jseg: Unknown type %s",
3646 			    TYPENAME(wk->wk_type));
3647 			/* NOTREACHED */
3648 		}
3649 	}
3650 	/* Release the self reference so the structure may be freed. */
3651 	rele_jseg(jseg);
3652 }
3653 
3654 /*
3655  * Determine which jsegs are ready for completion processing.  Waits for
3656  * synchronize cache to complete as well as forcing in-order completion
3657  * of journal entries.
3658  */
3659 static void
3660 complete_jsegs(jseg)
3661 	struct jseg *jseg;
3662 {
3663 	struct jblocks *jblocks;
3664 	struct jseg *jsegn;
3665 
3666 	jblocks = jseg->js_jblocks;
3667 	/*
3668 	 * Don't allow out of order completions.  If this isn't the first
3669 	 * block wait for it to write before we're done.
3670 	 */
3671 	if (jseg != jblocks->jb_writeseg)
3672 		return;
3673 	/* Iterate through available jsegs processing their entries. */
3674 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3675 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3676 		jsegn = TAILQ_NEXT(jseg, js_next);
3677 		complete_jseg(jseg);
3678 		jseg = jsegn;
3679 	}
3680 	jblocks->jb_writeseg = jseg;
3681 	/*
3682 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3683 	 */
3684 	free_jsegs(jblocks);
3685 }
3686 
3687 /*
3688  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3689  * the final completions.
3690  */
3691 static void
3692 handle_written_jseg(jseg, bp)
3693 	struct jseg *jseg;
3694 	struct buf *bp;
3695 {
3696 
3697 	if (jseg->js_refs == 0)
3698 		panic("handle_written_jseg: No self-reference on %p", jseg);
3699 	jseg->js_state |= DEPCOMPLETE;
3700 	/*
3701 	 * We'll never need this buffer again, set flags so it will be
3702 	 * discarded.
3703 	 */
3704 	bp->b_flags |= B_INVAL | B_NOCACHE;
3705 	pbrelvp(bp);
3706 	complete_jsegs(jseg);
3707 }
3708 
3709 static inline struct jsegdep *
3710 inoref_jseg(inoref)
3711 	struct inoref *inoref;
3712 {
3713 	struct jsegdep *jsegdep;
3714 
3715 	jsegdep = inoref->if_jsegdep;
3716 	inoref->if_jsegdep = NULL;
3717 
3718 	return (jsegdep);
3719 }
3720 
3721 /*
3722  * Called once a jremref has made it to stable store.  The jremref is marked
3723  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3724  * for the jremref to complete will be awoken by free_jremref.
3725  */
3726 static void
3727 handle_written_jremref(jremref)
3728 	struct jremref *jremref;
3729 {
3730 	struct inodedep *inodedep;
3731 	struct jsegdep *jsegdep;
3732 	struct dirrem *dirrem;
3733 
3734 	/* Grab the jsegdep. */
3735 	jsegdep = inoref_jseg(&jremref->jr_ref);
3736 	/*
3737 	 * Remove us from the inoref list.
3738 	 */
3739 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3740 	    0, &inodedep) == 0)
3741 		panic("handle_written_jremref: Lost inodedep");
3742 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3743 	/*
3744 	 * Complete the dirrem.
3745 	 */
3746 	dirrem = jremref->jr_dirrem;
3747 	jremref->jr_dirrem = NULL;
3748 	LIST_REMOVE(jremref, jr_deps);
3749 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3750 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3751 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3752 	    (dirrem->dm_state & COMPLETE) != 0)
3753 		add_to_worklist(&dirrem->dm_list, 0);
3754 	free_jremref(jremref);
3755 }
3756 
3757 /*
3758  * Called once a jaddref has made it to stable store.  The dependency is
3759  * marked complete and any dependent structures are added to the inode
3760  * bufwait list to be completed as soon as it is written.  If a bitmap write
3761  * depends on this entry we move the inode into the inodedephd of the
3762  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3763  */
3764 static void
3765 handle_written_jaddref(jaddref)
3766 	struct jaddref *jaddref;
3767 {
3768 	struct jsegdep *jsegdep;
3769 	struct inodedep *inodedep;
3770 	struct diradd *diradd;
3771 	struct mkdir *mkdir;
3772 
3773 	/* Grab the jsegdep. */
3774 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3775 	mkdir = NULL;
3776 	diradd = NULL;
3777 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3778 	    0, &inodedep) == 0)
3779 		panic("handle_written_jaddref: Lost inodedep.");
3780 	if (jaddref->ja_diradd == NULL)
3781 		panic("handle_written_jaddref: No dependency");
3782 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3783 		diradd = jaddref->ja_diradd;
3784 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3785 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3786 		mkdir = jaddref->ja_mkdir;
3787 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3788 	} else if (jaddref->ja_state & MKDIR_BODY)
3789 		mkdir = jaddref->ja_mkdir;
3790 	else
3791 		panic("handle_written_jaddref: Unknown dependency %p",
3792 		    jaddref->ja_diradd);
3793 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3794 	/*
3795 	 * Remove us from the inode list.
3796 	 */
3797 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3798 	/*
3799 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3800 	 */
3801 	if (mkdir) {
3802 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3803 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3804 		    TYPENAME(mkdir->md_list.wk_type)));
3805 		mkdir->md_jaddref = NULL;
3806 		diradd = mkdir->md_diradd;
3807 		mkdir->md_state |= DEPCOMPLETE;
3808 		complete_mkdir(mkdir);
3809 	}
3810 	jwork_insert(&diradd->da_jwork, jsegdep);
3811 	if (jaddref->ja_state & NEWBLOCK) {
3812 		inodedep->id_state |= ONDEPLIST;
3813 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3814 		    inodedep, id_deps);
3815 	}
3816 	free_jaddref(jaddref);
3817 }
3818 
3819 /*
3820  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3821  * is placed in the bmsafemap to await notification of a written bitmap.  If
3822  * the operation was canceled we add the segdep to the appropriate
3823  * dependency to free the journal space once the canceling operation
3824  * completes.
3825  */
3826 static void
3827 handle_written_jnewblk(jnewblk)
3828 	struct jnewblk *jnewblk;
3829 {
3830 	struct bmsafemap *bmsafemap;
3831 	struct freefrag *freefrag;
3832 	struct freework *freework;
3833 	struct jsegdep *jsegdep;
3834 	struct newblk *newblk;
3835 
3836 	/* Grab the jsegdep. */
3837 	jsegdep = jnewblk->jn_jsegdep;
3838 	jnewblk->jn_jsegdep = NULL;
3839 	if (jnewblk->jn_dep == NULL)
3840 		panic("handle_written_jnewblk: No dependency for the segdep.");
3841 	switch (jnewblk->jn_dep->wk_type) {
3842 	case D_NEWBLK:
3843 	case D_ALLOCDIRECT:
3844 	case D_ALLOCINDIR:
3845 		/*
3846 		 * Add the written block to the bmsafemap so it can
3847 		 * be notified when the bitmap is on disk.
3848 		 */
3849 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3850 		newblk->nb_jnewblk = NULL;
3851 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3852 			bmsafemap = newblk->nb_bmsafemap;
3853 			newblk->nb_state |= ONDEPLIST;
3854 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3855 			    nb_deps);
3856 		}
3857 		jwork_insert(&newblk->nb_jwork, jsegdep);
3858 		break;
3859 	case D_FREEFRAG:
3860 		/*
3861 		 * A newblock being removed by a freefrag when replaced by
3862 		 * frag extension.
3863 		 */
3864 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3865 		freefrag->ff_jdep = NULL;
3866 		jwork_insert(&freefrag->ff_jwork, jsegdep);
3867 		break;
3868 	case D_FREEWORK:
3869 		/*
3870 		 * A direct block was removed by truncate.
3871 		 */
3872 		freework = WK_FREEWORK(jnewblk->jn_dep);
3873 		freework->fw_jnewblk = NULL;
3874 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3875 		break;
3876 	default:
3877 		panic("handle_written_jnewblk: Unknown type %d.",
3878 		    jnewblk->jn_dep->wk_type);
3879 	}
3880 	jnewblk->jn_dep = NULL;
3881 	free_jnewblk(jnewblk);
3882 }
3883 
3884 /*
3885  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3886  * an in-flight allocation that has not yet been committed.  Divorce us
3887  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3888  * to the worklist.
3889  */
3890 static void
3891 cancel_jfreefrag(jfreefrag)
3892 	struct jfreefrag *jfreefrag;
3893 {
3894 	struct freefrag *freefrag;
3895 
3896 	if (jfreefrag->fr_jsegdep) {
3897 		free_jsegdep(jfreefrag->fr_jsegdep);
3898 		jfreefrag->fr_jsegdep = NULL;
3899 	}
3900 	freefrag = jfreefrag->fr_freefrag;
3901 	jfreefrag->fr_freefrag = NULL;
3902 	free_jfreefrag(jfreefrag);
3903 	freefrag->ff_state |= DEPCOMPLETE;
3904 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3905 }
3906 
3907 /*
3908  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3909  */
3910 static void
3911 free_jfreefrag(jfreefrag)
3912 	struct jfreefrag *jfreefrag;
3913 {
3914 
3915 	if (jfreefrag->fr_state & INPROGRESS)
3916 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3917 	else if (jfreefrag->fr_state & ONWORKLIST)
3918 		remove_from_journal(&jfreefrag->fr_list);
3919 	if (jfreefrag->fr_freefrag != NULL)
3920 		panic("free_jfreefrag:  Still attached to a freefrag.");
3921 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3922 }
3923 
3924 /*
3925  * Called when the journal write for a jfreefrag completes.  The parent
3926  * freefrag is added to the worklist if this completes its dependencies.
3927  */
3928 static void
3929 handle_written_jfreefrag(jfreefrag)
3930 	struct jfreefrag *jfreefrag;
3931 {
3932 	struct jsegdep *jsegdep;
3933 	struct freefrag *freefrag;
3934 
3935 	/* Grab the jsegdep. */
3936 	jsegdep = jfreefrag->fr_jsegdep;
3937 	jfreefrag->fr_jsegdep = NULL;
3938 	freefrag = jfreefrag->fr_freefrag;
3939 	if (freefrag == NULL)
3940 		panic("handle_written_jfreefrag: No freefrag.");
3941 	freefrag->ff_state |= DEPCOMPLETE;
3942 	freefrag->ff_jdep = NULL;
3943 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3944 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3945 		add_to_worklist(&freefrag->ff_list, 0);
3946 	jfreefrag->fr_freefrag = NULL;
3947 	free_jfreefrag(jfreefrag);
3948 }
3949 
3950 /*
3951  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3952  * is removed from the freeblks list of pending journal writes and the
3953  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3954  * have been reclaimed.
3955  */
3956 static void
3957 handle_written_jblkdep(jblkdep)
3958 	struct jblkdep *jblkdep;
3959 {
3960 	struct freeblks *freeblks;
3961 	struct jsegdep *jsegdep;
3962 
3963 	/* Grab the jsegdep. */
3964 	jsegdep = jblkdep->jb_jsegdep;
3965 	jblkdep->jb_jsegdep = NULL;
3966 	freeblks = jblkdep->jb_freeblks;
3967 	LIST_REMOVE(jblkdep, jb_deps);
3968 	jwork_insert(&freeblks->fb_jwork, jsegdep);
3969 	/*
3970 	 * If the freeblks is all journaled, we can add it to the worklist.
3971 	 */
3972 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3973 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3974 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3975 
3976 	free_jblkdep(jblkdep);
3977 }
3978 
3979 static struct jsegdep *
3980 newjsegdep(struct worklist *wk)
3981 {
3982 	struct jsegdep *jsegdep;
3983 
3984 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3985 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3986 	jsegdep->jd_seg = NULL;
3987 
3988 	return (jsegdep);
3989 }
3990 
3991 static struct jmvref *
3992 newjmvref(dp, ino, oldoff, newoff)
3993 	struct inode *dp;
3994 	ino_t ino;
3995 	off_t oldoff;
3996 	off_t newoff;
3997 {
3998 	struct jmvref *jmvref;
3999 
4000 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4001 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4002 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4003 	jmvref->jm_parent = dp->i_number;
4004 	jmvref->jm_ino = ino;
4005 	jmvref->jm_oldoff = oldoff;
4006 	jmvref->jm_newoff = newoff;
4007 
4008 	return (jmvref);
4009 }
4010 
4011 /*
4012  * Allocate a new jremref that tracks the removal of ip from dp with the
4013  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4014  * DEPCOMPLETE as we have all the information required for the journal write
4015  * and the directory has already been removed from the buffer.  The caller
4016  * is responsible for linking the jremref into the pagedep and adding it
4017  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4018  * a DOTDOT addition so handle_workitem_remove() can properly assign
4019  * the jsegdep when we're done.
4020  */
4021 static struct jremref *
4022 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4023     off_t diroff, nlink_t nlink)
4024 {
4025 	struct jremref *jremref;
4026 
4027 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4028 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4029 	jremref->jr_state = ATTACHED;
4030 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4031 	   nlink, ip->i_mode);
4032 	jremref->jr_dirrem = dirrem;
4033 
4034 	return (jremref);
4035 }
4036 
4037 static inline void
4038 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4039     nlink_t nlink, uint16_t mode)
4040 {
4041 
4042 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4043 	inoref->if_diroff = diroff;
4044 	inoref->if_ino = ino;
4045 	inoref->if_parent = parent;
4046 	inoref->if_nlink = nlink;
4047 	inoref->if_mode = mode;
4048 }
4049 
4050 /*
4051  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4052  * directory offset may not be known until later.  The caller is responsible
4053  * adding the entry to the journal when this information is available.  nlink
4054  * should be the link count prior to the addition and mode is only required
4055  * to have the correct FMT.
4056  */
4057 static struct jaddref *
4058 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4059     uint16_t mode)
4060 {
4061 	struct jaddref *jaddref;
4062 
4063 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4064 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4065 	jaddref->ja_state = ATTACHED;
4066 	jaddref->ja_mkdir = NULL;
4067 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4068 
4069 	return (jaddref);
4070 }
4071 
4072 /*
4073  * Create a new free dependency for a freework.  The caller is responsible
4074  * for adjusting the reference count when it has the lock held.  The freedep
4075  * will track an outstanding bitmap write that will ultimately clear the
4076  * freework to continue.
4077  */
4078 static struct freedep *
4079 newfreedep(struct freework *freework)
4080 {
4081 	struct freedep *freedep;
4082 
4083 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4084 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4085 	freedep->fd_freework = freework;
4086 
4087 	return (freedep);
4088 }
4089 
4090 /*
4091  * Free a freedep structure once the buffer it is linked to is written.  If
4092  * this is the last reference to the freework schedule it for completion.
4093  */
4094 static void
4095 free_freedep(freedep)
4096 	struct freedep *freedep;
4097 {
4098 	struct freework *freework;
4099 
4100 	freework = freedep->fd_freework;
4101 	freework->fw_freeblks->fb_cgwait--;
4102 	if (--freework->fw_ref == 0)
4103 		freework_enqueue(freework);
4104 	WORKITEM_FREE(freedep, D_FREEDEP);
4105 }
4106 
4107 /*
4108  * Allocate a new freework structure that may be a level in an indirect
4109  * when parent is not NULL or a top level block when it is.  The top level
4110  * freework structures are allocated without the per-filesystem lock held
4111  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4112  */
4113 static struct freework *
4114 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4115 	struct ufsmount *ump;
4116 	struct freeblks *freeblks;
4117 	struct freework *parent;
4118 	ufs_lbn_t lbn;
4119 	ufs2_daddr_t nb;
4120 	int frags;
4121 	int off;
4122 	int journal;
4123 {
4124 	struct freework *freework;
4125 
4126 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4127 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4128 	freework->fw_state = ATTACHED;
4129 	freework->fw_jnewblk = NULL;
4130 	freework->fw_freeblks = freeblks;
4131 	freework->fw_parent = parent;
4132 	freework->fw_lbn = lbn;
4133 	freework->fw_blkno = nb;
4134 	freework->fw_frags = frags;
4135 	freework->fw_indir = NULL;
4136 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4137 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4138 	freework->fw_start = freework->fw_off = off;
4139 	if (journal)
4140 		newjfreeblk(freeblks, lbn, nb, frags);
4141 	if (parent == NULL) {
4142 		ACQUIRE_LOCK(ump);
4143 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4144 		freeblks->fb_ref++;
4145 		FREE_LOCK(ump);
4146 	}
4147 
4148 	return (freework);
4149 }
4150 
4151 /*
4152  * Eliminate a jfreeblk for a block that does not need journaling.
4153  */
4154 static void
4155 cancel_jfreeblk(freeblks, blkno)
4156 	struct freeblks *freeblks;
4157 	ufs2_daddr_t blkno;
4158 {
4159 	struct jfreeblk *jfreeblk;
4160 	struct jblkdep *jblkdep;
4161 
4162 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4163 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4164 			continue;
4165 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4166 		if (jfreeblk->jf_blkno == blkno)
4167 			break;
4168 	}
4169 	if (jblkdep == NULL)
4170 		return;
4171 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4172 	free_jsegdep(jblkdep->jb_jsegdep);
4173 	LIST_REMOVE(jblkdep, jb_deps);
4174 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4175 }
4176 
4177 /*
4178  * Allocate a new jfreeblk to journal top level block pointer when truncating
4179  * a file.  The caller must add this to the worklist when the per-filesystem
4180  * lock is held.
4181  */
4182 static struct jfreeblk *
4183 newjfreeblk(freeblks, lbn, blkno, frags)
4184 	struct freeblks *freeblks;
4185 	ufs_lbn_t lbn;
4186 	ufs2_daddr_t blkno;
4187 	int frags;
4188 {
4189 	struct jfreeblk *jfreeblk;
4190 
4191 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4192 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4193 	    freeblks->fb_list.wk_mp);
4194 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4195 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4196 	jfreeblk->jf_ino = freeblks->fb_inum;
4197 	jfreeblk->jf_lbn = lbn;
4198 	jfreeblk->jf_blkno = blkno;
4199 	jfreeblk->jf_frags = frags;
4200 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4201 
4202 	return (jfreeblk);
4203 }
4204 
4205 /*
4206  * The journal is only prepared to handle full-size block numbers, so we
4207  * have to adjust the record to reflect the change to a full-size block.
4208  * For example, suppose we have a block made up of fragments 8-15 and
4209  * want to free its last two fragments. We are given a request that says:
4210  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4211  * where frags are the number of fragments to free and oldfrags are the
4212  * number of fragments to keep. To block align it, we have to change it to
4213  * have a valid full-size blkno, so it becomes:
4214  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4215  */
4216 static void
4217 adjust_newfreework(freeblks, frag_offset)
4218 	struct freeblks *freeblks;
4219 	int frag_offset;
4220 {
4221 	struct jfreeblk *jfreeblk;
4222 
4223 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4224 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4225 	    ("adjust_newfreework: Missing freeblks dependency"));
4226 
4227 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4228 	jfreeblk->jf_blkno -= frag_offset;
4229 	jfreeblk->jf_frags += frag_offset;
4230 }
4231 
4232 /*
4233  * Allocate a new jtrunc to track a partial truncation.
4234  */
4235 static struct jtrunc *
4236 newjtrunc(freeblks, size, extsize)
4237 	struct freeblks *freeblks;
4238 	off_t size;
4239 	int extsize;
4240 {
4241 	struct jtrunc *jtrunc;
4242 
4243 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4244 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4245 	    freeblks->fb_list.wk_mp);
4246 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4247 	jtrunc->jt_dep.jb_freeblks = freeblks;
4248 	jtrunc->jt_ino = freeblks->fb_inum;
4249 	jtrunc->jt_size = size;
4250 	jtrunc->jt_extsize = extsize;
4251 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4252 
4253 	return (jtrunc);
4254 }
4255 
4256 /*
4257  * If we're canceling a new bitmap we have to search for another ref
4258  * to move into the bmsafemap dep.  This might be better expressed
4259  * with another structure.
4260  */
4261 static void
4262 move_newblock_dep(jaddref, inodedep)
4263 	struct jaddref *jaddref;
4264 	struct inodedep *inodedep;
4265 {
4266 	struct inoref *inoref;
4267 	struct jaddref *jaddrefn;
4268 
4269 	jaddrefn = NULL;
4270 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4271 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4272 		if ((jaddref->ja_state & NEWBLOCK) &&
4273 		    inoref->if_list.wk_type == D_JADDREF) {
4274 			jaddrefn = (struct jaddref *)inoref;
4275 			break;
4276 		}
4277 	}
4278 	if (jaddrefn == NULL)
4279 		return;
4280 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4281 	jaddrefn->ja_state |= jaddref->ja_state &
4282 	    (ATTACHED | UNDONE | NEWBLOCK);
4283 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4284 	jaddref->ja_state |= ATTACHED;
4285 	LIST_REMOVE(jaddref, ja_bmdeps);
4286 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4287 	    ja_bmdeps);
4288 }
4289 
4290 /*
4291  * Cancel a jaddref either before it has been written or while it is being
4292  * written.  This happens when a link is removed before the add reaches
4293  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4294  * and inode to prevent the link count or bitmap from reaching the disk
4295  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4296  * required.
4297  *
4298  * Returns 1 if the canceled addref requires journaling of the remove and
4299  * 0 otherwise.
4300  */
4301 static int
4302 cancel_jaddref(jaddref, inodedep, wkhd)
4303 	struct jaddref *jaddref;
4304 	struct inodedep *inodedep;
4305 	struct workhead *wkhd;
4306 {
4307 	struct inoref *inoref;
4308 	struct jsegdep *jsegdep;
4309 	int needsj;
4310 
4311 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4312 	    ("cancel_jaddref: Canceling complete jaddref"));
4313 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4314 		needsj = 1;
4315 	else
4316 		needsj = 0;
4317 	if (inodedep == NULL)
4318 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4319 		    0, &inodedep) == 0)
4320 			panic("cancel_jaddref: Lost inodedep");
4321 	/*
4322 	 * We must adjust the nlink of any reference operation that follows
4323 	 * us so that it is consistent with the in-memory reference.  This
4324 	 * ensures that inode nlink rollbacks always have the correct link.
4325 	 */
4326 	if (needsj == 0) {
4327 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4328 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4329 			if (inoref->if_state & GOINGAWAY)
4330 				break;
4331 			inoref->if_nlink--;
4332 		}
4333 	}
4334 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4335 	if (jaddref->ja_state & NEWBLOCK)
4336 		move_newblock_dep(jaddref, inodedep);
4337 	wake_worklist(&jaddref->ja_list);
4338 	jaddref->ja_mkdir = NULL;
4339 	if (jaddref->ja_state & INPROGRESS) {
4340 		jaddref->ja_state &= ~INPROGRESS;
4341 		WORKLIST_REMOVE(&jaddref->ja_list);
4342 		jwork_insert(wkhd, jsegdep);
4343 	} else {
4344 		free_jsegdep(jsegdep);
4345 		if (jaddref->ja_state & DEPCOMPLETE)
4346 			remove_from_journal(&jaddref->ja_list);
4347 	}
4348 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4349 	/*
4350 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4351 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4352 	 * no longer need this addref attached to the inoreflst and it
4353 	 * will incorrectly adjust nlink if we leave it.
4354 	 */
4355 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4356 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4357 		    if_deps);
4358 		jaddref->ja_state |= COMPLETE;
4359 		free_jaddref(jaddref);
4360 		return (needsj);
4361 	}
4362 	/*
4363 	 * Leave the head of the list for jsegdeps for fast merging.
4364 	 */
4365 	if (LIST_FIRST(wkhd) != NULL) {
4366 		jaddref->ja_state |= ONWORKLIST;
4367 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4368 	} else
4369 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4370 
4371 	return (needsj);
4372 }
4373 
4374 /*
4375  * Attempt to free a jaddref structure when some work completes.  This
4376  * should only succeed once the entry is written and all dependencies have
4377  * been notified.
4378  */
4379 static void
4380 free_jaddref(jaddref)
4381 	struct jaddref *jaddref;
4382 {
4383 
4384 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4385 		return;
4386 	if (jaddref->ja_ref.if_jsegdep)
4387 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4388 		    jaddref, jaddref->ja_state);
4389 	if (jaddref->ja_state & NEWBLOCK)
4390 		LIST_REMOVE(jaddref, ja_bmdeps);
4391 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4392 		panic("free_jaddref: Bad state %p(0x%X)",
4393 		    jaddref, jaddref->ja_state);
4394 	if (jaddref->ja_mkdir != NULL)
4395 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4396 	WORKITEM_FREE(jaddref, D_JADDREF);
4397 }
4398 
4399 /*
4400  * Free a jremref structure once it has been written or discarded.
4401  */
4402 static void
4403 free_jremref(jremref)
4404 	struct jremref *jremref;
4405 {
4406 
4407 	if (jremref->jr_ref.if_jsegdep)
4408 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4409 	if (jremref->jr_state & INPROGRESS)
4410 		panic("free_jremref: IO still pending");
4411 	WORKITEM_FREE(jremref, D_JREMREF);
4412 }
4413 
4414 /*
4415  * Free a jnewblk structure.
4416  */
4417 static void
4418 free_jnewblk(jnewblk)
4419 	struct jnewblk *jnewblk;
4420 {
4421 
4422 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4423 		return;
4424 	LIST_REMOVE(jnewblk, jn_deps);
4425 	if (jnewblk->jn_dep != NULL)
4426 		panic("free_jnewblk: Dependency still attached.");
4427 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4428 }
4429 
4430 /*
4431  * Cancel a jnewblk which has been been made redundant by frag extension.
4432  */
4433 static void
4434 cancel_jnewblk(jnewblk, wkhd)
4435 	struct jnewblk *jnewblk;
4436 	struct workhead *wkhd;
4437 {
4438 	struct jsegdep *jsegdep;
4439 
4440 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4441 	jsegdep = jnewblk->jn_jsegdep;
4442 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4443 		panic("cancel_jnewblk: Invalid state");
4444 	jnewblk->jn_jsegdep  = NULL;
4445 	jnewblk->jn_dep = NULL;
4446 	jnewblk->jn_state |= GOINGAWAY;
4447 	if (jnewblk->jn_state & INPROGRESS) {
4448 		jnewblk->jn_state &= ~INPROGRESS;
4449 		WORKLIST_REMOVE(&jnewblk->jn_list);
4450 		jwork_insert(wkhd, jsegdep);
4451 	} else {
4452 		free_jsegdep(jsegdep);
4453 		remove_from_journal(&jnewblk->jn_list);
4454 	}
4455 	wake_worklist(&jnewblk->jn_list);
4456 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4457 }
4458 
4459 static void
4460 free_jblkdep(jblkdep)
4461 	struct jblkdep *jblkdep;
4462 {
4463 
4464 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4465 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4466 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4467 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4468 	else
4469 		panic("free_jblkdep: Unexpected type %s",
4470 		    TYPENAME(jblkdep->jb_list.wk_type));
4471 }
4472 
4473 /*
4474  * Free a single jseg once it is no longer referenced in memory or on
4475  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4476  * to disappear.
4477  */
4478 static void
4479 free_jseg(jseg, jblocks)
4480 	struct jseg *jseg;
4481 	struct jblocks *jblocks;
4482 {
4483 	struct freework *freework;
4484 
4485 	/*
4486 	 * Free freework structures that were lingering to indicate freed
4487 	 * indirect blocks that forced journal write ordering on reallocate.
4488 	 */
4489 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4490 		indirblk_remove(freework);
4491 	if (jblocks->jb_oldestseg == jseg)
4492 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4493 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4494 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4495 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4496 	    ("free_jseg: Freed jseg has valid entries."));
4497 	WORKITEM_FREE(jseg, D_JSEG);
4498 }
4499 
4500 /*
4501  * Free all jsegs that meet the criteria for being reclaimed and update
4502  * oldestseg.
4503  */
4504 static void
4505 free_jsegs(jblocks)
4506 	struct jblocks *jblocks;
4507 {
4508 	struct jseg *jseg;
4509 
4510 	/*
4511 	 * Free only those jsegs which have none allocated before them to
4512 	 * preserve the journal space ordering.
4513 	 */
4514 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4515 		/*
4516 		 * Only reclaim space when nothing depends on this journal
4517 		 * set and another set has written that it is no longer
4518 		 * valid.
4519 		 */
4520 		if (jseg->js_refs != 0) {
4521 			jblocks->jb_oldestseg = jseg;
4522 			return;
4523 		}
4524 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4525 			break;
4526 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4527 			break;
4528 		/*
4529 		 * We can free jsegs that didn't write entries when
4530 		 * oldestwrseq == js_seq.
4531 		 */
4532 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4533 		    jseg->js_cnt != 0)
4534 			break;
4535 		free_jseg(jseg, jblocks);
4536 	}
4537 	/*
4538 	 * If we exited the loop above we still must discover the
4539 	 * oldest valid segment.
4540 	 */
4541 	if (jseg)
4542 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4543 		     jseg = TAILQ_NEXT(jseg, js_next))
4544 			if (jseg->js_refs != 0)
4545 				break;
4546 	jblocks->jb_oldestseg = jseg;
4547 	/*
4548 	 * The journal has no valid records but some jsegs may still be
4549 	 * waiting on oldestwrseq to advance.  We force a small record
4550 	 * out to permit these lingering records to be reclaimed.
4551 	 */
4552 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4553 		jblocks->jb_needseg = 1;
4554 }
4555 
4556 /*
4557  * Release one reference to a jseg and free it if the count reaches 0.  This
4558  * should eventually reclaim journal space as well.
4559  */
4560 static void
4561 rele_jseg(jseg)
4562 	struct jseg *jseg;
4563 {
4564 
4565 	KASSERT(jseg->js_refs > 0,
4566 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4567 	if (--jseg->js_refs != 0)
4568 		return;
4569 	free_jsegs(jseg->js_jblocks);
4570 }
4571 
4572 /*
4573  * Release a jsegdep and decrement the jseg count.
4574  */
4575 static void
4576 free_jsegdep(jsegdep)
4577 	struct jsegdep *jsegdep;
4578 {
4579 
4580 	if (jsegdep->jd_seg)
4581 		rele_jseg(jsegdep->jd_seg);
4582 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4583 }
4584 
4585 /*
4586  * Wait for a journal item to make it to disk.  Initiate journal processing
4587  * if required.
4588  */
4589 static int
4590 jwait(wk, waitfor)
4591 	struct worklist *wk;
4592 	int waitfor;
4593 {
4594 
4595 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4596 	/*
4597 	 * Blocking journal waits cause slow synchronous behavior.  Record
4598 	 * stats on the frequency of these blocking operations.
4599 	 */
4600 	if (waitfor == MNT_WAIT) {
4601 		stat_journal_wait++;
4602 		switch (wk->wk_type) {
4603 		case D_JREMREF:
4604 		case D_JMVREF:
4605 			stat_jwait_filepage++;
4606 			break;
4607 		case D_JTRUNC:
4608 		case D_JFREEBLK:
4609 			stat_jwait_freeblks++;
4610 			break;
4611 		case D_JNEWBLK:
4612 			stat_jwait_newblk++;
4613 			break;
4614 		case D_JADDREF:
4615 			stat_jwait_inode++;
4616 			break;
4617 		default:
4618 			break;
4619 		}
4620 	}
4621 	/*
4622 	 * If IO has not started we process the journal.  We can't mark the
4623 	 * worklist item as IOWAITING because we drop the lock while
4624 	 * processing the journal and the worklist entry may be freed after
4625 	 * this point.  The caller may call back in and re-issue the request.
4626 	 */
4627 	if ((wk->wk_state & INPROGRESS) == 0) {
4628 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4629 		if (waitfor != MNT_WAIT)
4630 			return (EBUSY);
4631 		return (0);
4632 	}
4633 	if (waitfor != MNT_WAIT)
4634 		return (EBUSY);
4635 	wait_worklist(wk, "jwait");
4636 	return (0);
4637 }
4638 
4639 /*
4640  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4641  * appropriate.  This is a convenience function to reduce duplicate code
4642  * for the setup and revert functions below.
4643  */
4644 static struct inodedep *
4645 inodedep_lookup_ip(ip)
4646 	struct inode *ip;
4647 {
4648 	struct inodedep *inodedep;
4649 
4650 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4651 	    ("inodedep_lookup_ip: bad delta"));
4652 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4653 	    &inodedep);
4654 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4655 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4656 
4657 	return (inodedep);
4658 }
4659 
4660 /*
4661  * Called prior to creating a new inode and linking it to a directory.  The
4662  * jaddref structure must already be allocated by softdep_setup_inomapdep
4663  * and it is discovered here so we can initialize the mode and update
4664  * nlinkdelta.
4665  */
4666 void
4667 softdep_setup_create(dp, ip)
4668 	struct inode *dp;
4669 	struct inode *ip;
4670 {
4671 	struct inodedep *inodedep;
4672 	struct jaddref *jaddref;
4673 	struct vnode *dvp;
4674 
4675 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4676 	    ("softdep_setup_create called on non-softdep filesystem"));
4677 	KASSERT(ip->i_nlink == 1,
4678 	    ("softdep_setup_create: Invalid link count."));
4679 	dvp = ITOV(dp);
4680 	ACQUIRE_LOCK(ITOUMP(dp));
4681 	inodedep = inodedep_lookup_ip(ip);
4682 	if (DOINGSUJ(dvp)) {
4683 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4684 		    inoreflst);
4685 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4686 		    ("softdep_setup_create: No addref structure present."));
4687 	}
4688 	softdep_prelink(dvp, NULL);
4689 	FREE_LOCK(ITOUMP(dp));
4690 }
4691 
4692 /*
4693  * Create a jaddref structure to track the addition of a DOTDOT link when
4694  * we are reparenting an inode as part of a rename.  This jaddref will be
4695  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4696  * non-journaling softdep.
4697  */
4698 void
4699 softdep_setup_dotdot_link(dp, ip)
4700 	struct inode *dp;
4701 	struct inode *ip;
4702 {
4703 	struct inodedep *inodedep;
4704 	struct jaddref *jaddref;
4705 	struct vnode *dvp;
4706 
4707 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4708 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4709 	dvp = ITOV(dp);
4710 	jaddref = NULL;
4711 	/*
4712 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4713 	 * is used as a normal link would be.
4714 	 */
4715 	if (DOINGSUJ(dvp))
4716 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4717 		    dp->i_effnlink - 1, dp->i_mode);
4718 	ACQUIRE_LOCK(ITOUMP(dp));
4719 	inodedep = inodedep_lookup_ip(dp);
4720 	if (jaddref)
4721 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4722 		    if_deps);
4723 	softdep_prelink(dvp, ITOV(ip));
4724 	FREE_LOCK(ITOUMP(dp));
4725 }
4726 
4727 /*
4728  * Create a jaddref structure to track a new link to an inode.  The directory
4729  * offset is not known until softdep_setup_directory_add or
4730  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4731  * softdep.
4732  */
4733 void
4734 softdep_setup_link(dp, ip)
4735 	struct inode *dp;
4736 	struct inode *ip;
4737 {
4738 	struct inodedep *inodedep;
4739 	struct jaddref *jaddref;
4740 	struct vnode *dvp;
4741 
4742 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4743 	    ("softdep_setup_link called on non-softdep filesystem"));
4744 	dvp = ITOV(dp);
4745 	jaddref = NULL;
4746 	if (DOINGSUJ(dvp))
4747 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4748 		    ip->i_mode);
4749 	ACQUIRE_LOCK(ITOUMP(dp));
4750 	inodedep = inodedep_lookup_ip(ip);
4751 	if (jaddref)
4752 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4753 		    if_deps);
4754 	softdep_prelink(dvp, ITOV(ip));
4755 	FREE_LOCK(ITOUMP(dp));
4756 }
4757 
4758 /*
4759  * Called to create the jaddref structures to track . and .. references as
4760  * well as lookup and further initialize the incomplete jaddref created
4761  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4762  * nlinkdelta for non-journaling softdep.
4763  */
4764 void
4765 softdep_setup_mkdir(dp, ip)
4766 	struct inode *dp;
4767 	struct inode *ip;
4768 {
4769 	struct inodedep *inodedep;
4770 	struct jaddref *dotdotaddref;
4771 	struct jaddref *dotaddref;
4772 	struct jaddref *jaddref;
4773 	struct vnode *dvp;
4774 
4775 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4776 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
4777 	dvp = ITOV(dp);
4778 	dotaddref = dotdotaddref = NULL;
4779 	if (DOINGSUJ(dvp)) {
4780 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4781 		    ip->i_mode);
4782 		dotaddref->ja_state |= MKDIR_BODY;
4783 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4784 		    dp->i_effnlink - 1, dp->i_mode);
4785 		dotdotaddref->ja_state |= MKDIR_PARENT;
4786 	}
4787 	ACQUIRE_LOCK(ITOUMP(dp));
4788 	inodedep = inodedep_lookup_ip(ip);
4789 	if (DOINGSUJ(dvp)) {
4790 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4791 		    inoreflst);
4792 		KASSERT(jaddref != NULL,
4793 		    ("softdep_setup_mkdir: No addref structure present."));
4794 		KASSERT(jaddref->ja_parent == dp->i_number,
4795 		    ("softdep_setup_mkdir: bad parent %ju",
4796 		    (uintmax_t)jaddref->ja_parent));
4797 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4798 		    if_deps);
4799 	}
4800 	inodedep = inodedep_lookup_ip(dp);
4801 	if (DOINGSUJ(dvp))
4802 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4803 		    &dotdotaddref->ja_ref, if_deps);
4804 	softdep_prelink(ITOV(dp), NULL);
4805 	FREE_LOCK(ITOUMP(dp));
4806 }
4807 
4808 /*
4809  * Called to track nlinkdelta of the inode and parent directories prior to
4810  * unlinking a directory.
4811  */
4812 void
4813 softdep_setup_rmdir(dp, ip)
4814 	struct inode *dp;
4815 	struct inode *ip;
4816 {
4817 	struct vnode *dvp;
4818 
4819 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4820 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4821 	dvp = ITOV(dp);
4822 	ACQUIRE_LOCK(ITOUMP(dp));
4823 	(void) inodedep_lookup_ip(ip);
4824 	(void) inodedep_lookup_ip(dp);
4825 	softdep_prelink(dvp, ITOV(ip));
4826 	FREE_LOCK(ITOUMP(dp));
4827 }
4828 
4829 /*
4830  * Called to track nlinkdelta of the inode and parent directories prior to
4831  * unlink.
4832  */
4833 void
4834 softdep_setup_unlink(dp, ip)
4835 	struct inode *dp;
4836 	struct inode *ip;
4837 {
4838 	struct vnode *dvp;
4839 
4840 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4841 	    ("softdep_setup_unlink called on non-softdep filesystem"));
4842 	dvp = ITOV(dp);
4843 	ACQUIRE_LOCK(ITOUMP(dp));
4844 	(void) inodedep_lookup_ip(ip);
4845 	(void) inodedep_lookup_ip(dp);
4846 	softdep_prelink(dvp, ITOV(ip));
4847 	FREE_LOCK(ITOUMP(dp));
4848 }
4849 
4850 /*
4851  * Called to release the journal structures created by a failed non-directory
4852  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4853  */
4854 void
4855 softdep_revert_create(dp, ip)
4856 	struct inode *dp;
4857 	struct inode *ip;
4858 {
4859 	struct inodedep *inodedep;
4860 	struct jaddref *jaddref;
4861 	struct vnode *dvp;
4862 
4863 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4864 	    ("softdep_revert_create called on non-softdep filesystem"));
4865 	dvp = ITOV(dp);
4866 	ACQUIRE_LOCK(ITOUMP(dp));
4867 	inodedep = inodedep_lookup_ip(ip);
4868 	if (DOINGSUJ(dvp)) {
4869 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4870 		    inoreflst);
4871 		KASSERT(jaddref->ja_parent == dp->i_number,
4872 		    ("softdep_revert_create: addref parent mismatch"));
4873 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4874 	}
4875 	FREE_LOCK(ITOUMP(dp));
4876 }
4877 
4878 /*
4879  * Called to release the journal structures created by a failed link
4880  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4881  */
4882 void
4883 softdep_revert_link(dp, ip)
4884 	struct inode *dp;
4885 	struct inode *ip;
4886 {
4887 	struct inodedep *inodedep;
4888 	struct jaddref *jaddref;
4889 	struct vnode *dvp;
4890 
4891 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4892 	    ("softdep_revert_link called on non-softdep filesystem"));
4893 	dvp = ITOV(dp);
4894 	ACQUIRE_LOCK(ITOUMP(dp));
4895 	inodedep = inodedep_lookup_ip(ip);
4896 	if (DOINGSUJ(dvp)) {
4897 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4898 		    inoreflst);
4899 		KASSERT(jaddref->ja_parent == dp->i_number,
4900 		    ("softdep_revert_link: addref parent mismatch"));
4901 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4902 	}
4903 	FREE_LOCK(ITOUMP(dp));
4904 }
4905 
4906 /*
4907  * Called to release the journal structures created by a failed mkdir
4908  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4909  */
4910 void
4911 softdep_revert_mkdir(dp, ip)
4912 	struct inode *dp;
4913 	struct inode *ip;
4914 {
4915 	struct inodedep *inodedep;
4916 	struct jaddref *jaddref;
4917 	struct jaddref *dotaddref;
4918 	struct vnode *dvp;
4919 
4920 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4921 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4922 	dvp = ITOV(dp);
4923 
4924 	ACQUIRE_LOCK(ITOUMP(dp));
4925 	inodedep = inodedep_lookup_ip(dp);
4926 	if (DOINGSUJ(dvp)) {
4927 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4928 		    inoreflst);
4929 		KASSERT(jaddref->ja_parent == ip->i_number,
4930 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4931 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4932 	}
4933 	inodedep = inodedep_lookup_ip(ip);
4934 	if (DOINGSUJ(dvp)) {
4935 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4936 		    inoreflst);
4937 		KASSERT(jaddref->ja_parent == dp->i_number,
4938 		    ("softdep_revert_mkdir: addref parent mismatch"));
4939 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4940 		    inoreflst, if_deps);
4941 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4942 		KASSERT(dotaddref->ja_parent == ip->i_number,
4943 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4944 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4945 	}
4946 	FREE_LOCK(ITOUMP(dp));
4947 }
4948 
4949 /*
4950  * Called to correct nlinkdelta after a failed rmdir.
4951  */
4952 void
4953 softdep_revert_rmdir(dp, ip)
4954 	struct inode *dp;
4955 	struct inode *ip;
4956 {
4957 
4958 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4959 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
4960 	ACQUIRE_LOCK(ITOUMP(dp));
4961 	(void) inodedep_lookup_ip(ip);
4962 	(void) inodedep_lookup_ip(dp);
4963 	FREE_LOCK(ITOUMP(dp));
4964 }
4965 
4966 /*
4967  * Protecting the freemaps (or bitmaps).
4968  *
4969  * To eliminate the need to execute fsck before mounting a filesystem
4970  * after a power failure, one must (conservatively) guarantee that the
4971  * on-disk copy of the bitmaps never indicate that a live inode or block is
4972  * free.  So, when a block or inode is allocated, the bitmap should be
4973  * updated (on disk) before any new pointers.  When a block or inode is
4974  * freed, the bitmap should not be updated until all pointers have been
4975  * reset.  The latter dependency is handled by the delayed de-allocation
4976  * approach described below for block and inode de-allocation.  The former
4977  * dependency is handled by calling the following procedure when a block or
4978  * inode is allocated. When an inode is allocated an "inodedep" is created
4979  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4980  * Each "inodedep" is also inserted into the hash indexing structure so
4981  * that any additional link additions can be made dependent on the inode
4982  * allocation.
4983  *
4984  * The ufs filesystem maintains a number of free block counts (e.g., per
4985  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4986  * in addition to the bitmaps.  These counts are used to improve efficiency
4987  * during allocation and therefore must be consistent with the bitmaps.
4988  * There is no convenient way to guarantee post-crash consistency of these
4989  * counts with simple update ordering, for two main reasons: (1) The counts
4990  * and bitmaps for a single cylinder group block are not in the same disk
4991  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4992  * be written and the other not.  (2) Some of the counts are located in the
4993  * superblock rather than the cylinder group block. So, we focus our soft
4994  * updates implementation on protecting the bitmaps. When mounting a
4995  * filesystem, we recompute the auxiliary counts from the bitmaps.
4996  */
4997 
4998 /*
4999  * Called just after updating the cylinder group block to allocate an inode.
5000  */
5001 void
5002 softdep_setup_inomapdep(bp, ip, newinum, mode)
5003 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5004 	struct inode *ip;	/* inode related to allocation */
5005 	ino_t newinum;		/* new inode number being allocated */
5006 	int mode;
5007 {
5008 	struct inodedep *inodedep;
5009 	struct bmsafemap *bmsafemap;
5010 	struct jaddref *jaddref;
5011 	struct mount *mp;
5012 	struct fs *fs;
5013 
5014 	mp = ITOVFS(ip);
5015 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5016 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5017 	fs = VFSTOUFS(mp)->um_fs;
5018 	jaddref = NULL;
5019 
5020 	/*
5021 	 * Allocate the journal reference add structure so that the bitmap
5022 	 * can be dependent on it.
5023 	 */
5024 	if (MOUNTEDSUJ(mp)) {
5025 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5026 		jaddref->ja_state |= NEWBLOCK;
5027 	}
5028 
5029 	/*
5030 	 * Create a dependency for the newly allocated inode.
5031 	 * Panic if it already exists as something is seriously wrong.
5032 	 * Otherwise add it to the dependency list for the buffer holding
5033 	 * the cylinder group map from which it was allocated.
5034 	 *
5035 	 * We have to preallocate a bmsafemap entry in case it is needed
5036 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5037 	 * have to finish initializing it before we can FREE_LOCK().
5038 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5039 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5040 	 * creating the inodedep as it can be freed during the time
5041 	 * that we FREE_LOCK() while allocating the inodedep. We must
5042 	 * call workitem_alloc() before entering the locked section as
5043 	 * it also acquires the lock and we must avoid trying doing so
5044 	 * recursively.
5045 	 */
5046 	bmsafemap = malloc(sizeof(struct bmsafemap),
5047 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5048 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5049 	ACQUIRE_LOCK(ITOUMP(ip));
5050 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5051 		panic("softdep_setup_inomapdep: dependency %p for new"
5052 		    "inode already exists", inodedep);
5053 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5054 	if (jaddref) {
5055 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5056 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5057 		    if_deps);
5058 	} else {
5059 		inodedep->id_state |= ONDEPLIST;
5060 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5061 	}
5062 	inodedep->id_bmsafemap = bmsafemap;
5063 	inodedep->id_state &= ~DEPCOMPLETE;
5064 	FREE_LOCK(ITOUMP(ip));
5065 }
5066 
5067 /*
5068  * Called just after updating the cylinder group block to
5069  * allocate block or fragment.
5070  */
5071 void
5072 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5073 	struct buf *bp;		/* buffer for cylgroup block with block map */
5074 	struct mount *mp;	/* filesystem doing allocation */
5075 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5076 	int frags;		/* Number of fragments. */
5077 	int oldfrags;		/* Previous number of fragments for extend. */
5078 {
5079 	struct newblk *newblk;
5080 	struct bmsafemap *bmsafemap;
5081 	struct jnewblk *jnewblk;
5082 	struct ufsmount *ump;
5083 	struct fs *fs;
5084 
5085 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5086 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5087 	ump = VFSTOUFS(mp);
5088 	fs = ump->um_fs;
5089 	jnewblk = NULL;
5090 	/*
5091 	 * Create a dependency for the newly allocated block.
5092 	 * Add it to the dependency list for the buffer holding
5093 	 * the cylinder group map from which it was allocated.
5094 	 */
5095 	if (MOUNTEDSUJ(mp)) {
5096 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5097 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5098 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5099 		jnewblk->jn_state = ATTACHED;
5100 		jnewblk->jn_blkno = newblkno;
5101 		jnewblk->jn_frags = frags;
5102 		jnewblk->jn_oldfrags = oldfrags;
5103 #ifdef SUJ_DEBUG
5104 		{
5105 			struct cg *cgp;
5106 			uint8_t *blksfree;
5107 			long bno;
5108 			int i;
5109 
5110 			cgp = (struct cg *)bp->b_data;
5111 			blksfree = cg_blksfree(cgp);
5112 			bno = dtogd(fs, jnewblk->jn_blkno);
5113 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5114 			    i++) {
5115 				if (isset(blksfree, bno + i))
5116 					panic("softdep_setup_blkmapdep: "
5117 					    "free fragment %d from %d-%d "
5118 					    "state 0x%X dep %p", i,
5119 					    jnewblk->jn_oldfrags,
5120 					    jnewblk->jn_frags,
5121 					    jnewblk->jn_state,
5122 					    jnewblk->jn_dep);
5123 			}
5124 		}
5125 #endif
5126 	}
5127 
5128 	CTR3(KTR_SUJ,
5129 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5130 	    newblkno, frags, oldfrags);
5131 	ACQUIRE_LOCK(ump);
5132 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5133 		panic("softdep_setup_blkmapdep: found block");
5134 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5135 	    dtog(fs, newblkno), NULL);
5136 	if (jnewblk) {
5137 		jnewblk->jn_dep = (struct worklist *)newblk;
5138 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5139 	} else {
5140 		newblk->nb_state |= ONDEPLIST;
5141 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5142 	}
5143 	newblk->nb_bmsafemap = bmsafemap;
5144 	newblk->nb_jnewblk = jnewblk;
5145 	FREE_LOCK(ump);
5146 }
5147 
5148 #define	BMSAFEMAP_HASH(ump, cg) \
5149       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5150 
5151 static int
5152 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5153 	struct bmsafemap_hashhead *bmsafemaphd;
5154 	int cg;
5155 	struct bmsafemap **bmsafemapp;
5156 {
5157 	struct bmsafemap *bmsafemap;
5158 
5159 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5160 		if (bmsafemap->sm_cg == cg)
5161 			break;
5162 	if (bmsafemap) {
5163 		*bmsafemapp = bmsafemap;
5164 		return (1);
5165 	}
5166 	*bmsafemapp = NULL;
5167 
5168 	return (0);
5169 }
5170 
5171 /*
5172  * Find the bmsafemap associated with a cylinder group buffer.
5173  * If none exists, create one. The buffer must be locked when
5174  * this routine is called and this routine must be called with
5175  * the softdep lock held. To avoid giving up the lock while
5176  * allocating a new bmsafemap, a preallocated bmsafemap may be
5177  * provided. If it is provided but not needed, it is freed.
5178  */
5179 static struct bmsafemap *
5180 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5181 	struct mount *mp;
5182 	struct buf *bp;
5183 	int cg;
5184 	struct bmsafemap *newbmsafemap;
5185 {
5186 	struct bmsafemap_hashhead *bmsafemaphd;
5187 	struct bmsafemap *bmsafemap, *collision;
5188 	struct worklist *wk;
5189 	struct ufsmount *ump;
5190 
5191 	ump = VFSTOUFS(mp);
5192 	LOCK_OWNED(ump);
5193 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5194 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5195 		if (wk->wk_type == D_BMSAFEMAP) {
5196 			if (newbmsafemap)
5197 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5198 			return (WK_BMSAFEMAP(wk));
5199 		}
5200 	}
5201 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5202 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5203 		if (newbmsafemap)
5204 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5205 		return (bmsafemap);
5206 	}
5207 	if (newbmsafemap) {
5208 		bmsafemap = newbmsafemap;
5209 	} else {
5210 		FREE_LOCK(ump);
5211 		bmsafemap = malloc(sizeof(struct bmsafemap),
5212 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5213 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5214 		ACQUIRE_LOCK(ump);
5215 	}
5216 	bmsafemap->sm_buf = bp;
5217 	LIST_INIT(&bmsafemap->sm_inodedephd);
5218 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5219 	LIST_INIT(&bmsafemap->sm_newblkhd);
5220 	LIST_INIT(&bmsafemap->sm_newblkwr);
5221 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5222 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5223 	LIST_INIT(&bmsafemap->sm_freehd);
5224 	LIST_INIT(&bmsafemap->sm_freewr);
5225 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5226 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5227 		return (collision);
5228 	}
5229 	bmsafemap->sm_cg = cg;
5230 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5231 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5232 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5233 	return (bmsafemap);
5234 }
5235 
5236 /*
5237  * Direct block allocation dependencies.
5238  *
5239  * When a new block is allocated, the corresponding disk locations must be
5240  * initialized (with zeros or new data) before the on-disk inode points to
5241  * them.  Also, the freemap from which the block was allocated must be
5242  * updated (on disk) before the inode's pointer. These two dependencies are
5243  * independent of each other and are needed for all file blocks and indirect
5244  * blocks that are pointed to directly by the inode.  Just before the
5245  * "in-core" version of the inode is updated with a newly allocated block
5246  * number, a procedure (below) is called to setup allocation dependency
5247  * structures.  These structures are removed when the corresponding
5248  * dependencies are satisfied or when the block allocation becomes obsolete
5249  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5250  * fragment that gets upgraded).  All of these cases are handled in
5251  * procedures described later.
5252  *
5253  * When a file extension causes a fragment to be upgraded, either to a larger
5254  * fragment or to a full block, the on-disk location may change (if the
5255  * previous fragment could not simply be extended). In this case, the old
5256  * fragment must be de-allocated, but not until after the inode's pointer has
5257  * been updated. In most cases, this is handled by later procedures, which
5258  * will construct a "freefrag" structure to be added to the workitem queue
5259  * when the inode update is complete (or obsolete).  The main exception to
5260  * this is when an allocation occurs while a pending allocation dependency
5261  * (for the same block pointer) remains.  This case is handled in the main
5262  * allocation dependency setup procedure by immediately freeing the
5263  * unreferenced fragments.
5264  */
5265 void
5266 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5267 	struct inode *ip;	/* inode to which block is being added */
5268 	ufs_lbn_t off;		/* block pointer within inode */
5269 	ufs2_daddr_t newblkno;	/* disk block number being added */
5270 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5271 	long newsize;		/* size of new block */
5272 	long oldsize;		/* size of new block */
5273 	struct buf *bp;		/* bp for allocated block */
5274 {
5275 	struct allocdirect *adp, *oldadp;
5276 	struct allocdirectlst *adphead;
5277 	struct freefrag *freefrag;
5278 	struct inodedep *inodedep;
5279 	struct pagedep *pagedep;
5280 	struct jnewblk *jnewblk;
5281 	struct newblk *newblk;
5282 	struct mount *mp;
5283 	ufs_lbn_t lbn;
5284 
5285 	lbn = bp->b_lblkno;
5286 	mp = ITOVFS(ip);
5287 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5288 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5289 	if (oldblkno && oldblkno != newblkno)
5290 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5291 	else
5292 		freefrag = NULL;
5293 
5294 	CTR6(KTR_SUJ,
5295 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5296 	    "off %jd newsize %ld oldsize %d",
5297 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5298 	ACQUIRE_LOCK(ITOUMP(ip));
5299 	if (off >= UFS_NDADDR) {
5300 		if (lbn > 0)
5301 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5302 			    lbn, off);
5303 		/* allocating an indirect block */
5304 		if (oldblkno != 0)
5305 			panic("softdep_setup_allocdirect: non-zero indir");
5306 	} else {
5307 		if (off != lbn)
5308 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5309 			    lbn, off);
5310 		/*
5311 		 * Allocating a direct block.
5312 		 *
5313 		 * If we are allocating a directory block, then we must
5314 		 * allocate an associated pagedep to track additions and
5315 		 * deletions.
5316 		 */
5317 		if ((ip->i_mode & IFMT) == IFDIR)
5318 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5319 			    &pagedep);
5320 	}
5321 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5322 		panic("softdep_setup_allocdirect: lost block");
5323 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5324 	    ("softdep_setup_allocdirect: newblk already initialized"));
5325 	/*
5326 	 * Convert the newblk to an allocdirect.
5327 	 */
5328 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5329 	adp = (struct allocdirect *)newblk;
5330 	newblk->nb_freefrag = freefrag;
5331 	adp->ad_offset = off;
5332 	adp->ad_oldblkno = oldblkno;
5333 	adp->ad_newsize = newsize;
5334 	adp->ad_oldsize = oldsize;
5335 
5336 	/*
5337 	 * Finish initializing the journal.
5338 	 */
5339 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5340 		jnewblk->jn_ino = ip->i_number;
5341 		jnewblk->jn_lbn = lbn;
5342 		add_to_journal(&jnewblk->jn_list);
5343 	}
5344 	if (freefrag && freefrag->ff_jdep != NULL &&
5345 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5346 		add_to_journal(freefrag->ff_jdep);
5347 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5348 	adp->ad_inodedep = inodedep;
5349 
5350 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5351 	/*
5352 	 * The list of allocdirects must be kept in sorted and ascending
5353 	 * order so that the rollback routines can quickly determine the
5354 	 * first uncommitted block (the size of the file stored on disk
5355 	 * ends at the end of the lowest committed fragment, or if there
5356 	 * are no fragments, at the end of the highest committed block).
5357 	 * Since files generally grow, the typical case is that the new
5358 	 * block is to be added at the end of the list. We speed this
5359 	 * special case by checking against the last allocdirect in the
5360 	 * list before laboriously traversing the list looking for the
5361 	 * insertion point.
5362 	 */
5363 	adphead = &inodedep->id_newinoupdt;
5364 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5365 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5366 		/* insert at end of list */
5367 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5368 		if (oldadp != NULL && oldadp->ad_offset == off)
5369 			allocdirect_merge(adphead, adp, oldadp);
5370 		FREE_LOCK(ITOUMP(ip));
5371 		return;
5372 	}
5373 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5374 		if (oldadp->ad_offset >= off)
5375 			break;
5376 	}
5377 	if (oldadp == NULL)
5378 		panic("softdep_setup_allocdirect: lost entry");
5379 	/* insert in middle of list */
5380 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5381 	if (oldadp->ad_offset == off)
5382 		allocdirect_merge(adphead, adp, oldadp);
5383 
5384 	FREE_LOCK(ITOUMP(ip));
5385 }
5386 
5387 /*
5388  * Merge a newer and older journal record to be stored either in a
5389  * newblock or freefrag.  This handles aggregating journal records for
5390  * fragment allocation into a second record as well as replacing a
5391  * journal free with an aborted journal allocation.  A segment for the
5392  * oldest record will be placed on wkhd if it has been written.  If not
5393  * the segment for the newer record will suffice.
5394  */
5395 static struct worklist *
5396 jnewblk_merge(new, old, wkhd)
5397 	struct worklist *new;
5398 	struct worklist *old;
5399 	struct workhead *wkhd;
5400 {
5401 	struct jnewblk *njnewblk;
5402 	struct jnewblk *jnewblk;
5403 
5404 	/* Handle NULLs to simplify callers. */
5405 	if (new == NULL)
5406 		return (old);
5407 	if (old == NULL)
5408 		return (new);
5409 	/* Replace a jfreefrag with a jnewblk. */
5410 	if (new->wk_type == D_JFREEFRAG) {
5411 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5412 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5413 			    old, new);
5414 		cancel_jfreefrag(WK_JFREEFRAG(new));
5415 		return (old);
5416 	}
5417 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5418 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5419 		    old->wk_type, new->wk_type);
5420 	/*
5421 	 * Handle merging of two jnewblk records that describe
5422 	 * different sets of fragments in the same block.
5423 	 */
5424 	jnewblk = WK_JNEWBLK(old);
5425 	njnewblk = WK_JNEWBLK(new);
5426 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5427 		panic("jnewblk_merge: Merging disparate blocks.");
5428 	/*
5429 	 * The record may be rolled back in the cg.
5430 	 */
5431 	if (jnewblk->jn_state & UNDONE) {
5432 		jnewblk->jn_state &= ~UNDONE;
5433 		njnewblk->jn_state |= UNDONE;
5434 		njnewblk->jn_state &= ~ATTACHED;
5435 	}
5436 	/*
5437 	 * We modify the newer addref and free the older so that if neither
5438 	 * has been written the most up-to-date copy will be on disk.  If
5439 	 * both have been written but rolled back we only temporarily need
5440 	 * one of them to fix the bits when the cg write completes.
5441 	 */
5442 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5443 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5444 	cancel_jnewblk(jnewblk, wkhd);
5445 	WORKLIST_REMOVE(&jnewblk->jn_list);
5446 	free_jnewblk(jnewblk);
5447 	return (new);
5448 }
5449 
5450 /*
5451  * Replace an old allocdirect dependency with a newer one.
5452  * This routine must be called with splbio interrupts blocked.
5453  */
5454 static void
5455 allocdirect_merge(adphead, newadp, oldadp)
5456 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5457 	struct allocdirect *newadp;	/* allocdirect being added */
5458 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5459 {
5460 	struct worklist *wk;
5461 	struct freefrag *freefrag;
5462 
5463 	freefrag = NULL;
5464 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5465 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5466 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5467 	    newadp->ad_offset >= UFS_NDADDR)
5468 		panic("%s %jd != new %jd || old size %ld != new %ld",
5469 		    "allocdirect_merge: old blkno",
5470 		    (intmax_t)newadp->ad_oldblkno,
5471 		    (intmax_t)oldadp->ad_newblkno,
5472 		    newadp->ad_oldsize, oldadp->ad_newsize);
5473 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5474 	newadp->ad_oldsize = oldadp->ad_oldsize;
5475 	/*
5476 	 * If the old dependency had a fragment to free or had never
5477 	 * previously had a block allocated, then the new dependency
5478 	 * can immediately post its freefrag and adopt the old freefrag.
5479 	 * This action is done by swapping the freefrag dependencies.
5480 	 * The new dependency gains the old one's freefrag, and the
5481 	 * old one gets the new one and then immediately puts it on
5482 	 * the worklist when it is freed by free_newblk. It is
5483 	 * not possible to do this swap when the old dependency had a
5484 	 * non-zero size but no previous fragment to free. This condition
5485 	 * arises when the new block is an extension of the old block.
5486 	 * Here, the first part of the fragment allocated to the new
5487 	 * dependency is part of the block currently claimed on disk by
5488 	 * the old dependency, so cannot legitimately be freed until the
5489 	 * conditions for the new dependency are fulfilled.
5490 	 */
5491 	freefrag = newadp->ad_freefrag;
5492 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5493 		newadp->ad_freefrag = oldadp->ad_freefrag;
5494 		oldadp->ad_freefrag = freefrag;
5495 	}
5496 	/*
5497 	 * If we are tracking a new directory-block allocation,
5498 	 * move it from the old allocdirect to the new allocdirect.
5499 	 */
5500 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5501 		WORKLIST_REMOVE(wk);
5502 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5503 			panic("allocdirect_merge: extra newdirblk");
5504 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5505 	}
5506 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5507 	/*
5508 	 * We need to move any journal dependencies over to the freefrag
5509 	 * that releases this block if it exists.  Otherwise we are
5510 	 * extending an existing block and we'll wait until that is
5511 	 * complete to release the journal space and extend the
5512 	 * new journal to cover this old space as well.
5513 	 */
5514 	if (freefrag == NULL) {
5515 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5516 			panic("allocdirect_merge: %jd != %jd",
5517 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5518 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5519 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5520 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5521 		    &newadp->ad_block.nb_jwork);
5522 		oldadp->ad_block.nb_jnewblk = NULL;
5523 		cancel_newblk(&oldadp->ad_block, NULL,
5524 		    &newadp->ad_block.nb_jwork);
5525 	} else {
5526 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5527 		    &freefrag->ff_list, &freefrag->ff_jwork);
5528 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5529 		    &freefrag->ff_jwork);
5530 	}
5531 	free_newblk(&oldadp->ad_block);
5532 }
5533 
5534 /*
5535  * Allocate a jfreefrag structure to journal a single block free.
5536  */
5537 static struct jfreefrag *
5538 newjfreefrag(freefrag, ip, blkno, size, lbn)
5539 	struct freefrag *freefrag;
5540 	struct inode *ip;
5541 	ufs2_daddr_t blkno;
5542 	long size;
5543 	ufs_lbn_t lbn;
5544 {
5545 	struct jfreefrag *jfreefrag;
5546 	struct fs *fs;
5547 
5548 	fs = ITOFS(ip);
5549 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5550 	    M_SOFTDEP_FLAGS);
5551 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5552 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5553 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5554 	jfreefrag->fr_ino = ip->i_number;
5555 	jfreefrag->fr_lbn = lbn;
5556 	jfreefrag->fr_blkno = blkno;
5557 	jfreefrag->fr_frags = numfrags(fs, size);
5558 	jfreefrag->fr_freefrag = freefrag;
5559 
5560 	return (jfreefrag);
5561 }
5562 
5563 /*
5564  * Allocate a new freefrag structure.
5565  */
5566 static struct freefrag *
5567 newfreefrag(ip, blkno, size, lbn)
5568 	struct inode *ip;
5569 	ufs2_daddr_t blkno;
5570 	long size;
5571 	ufs_lbn_t lbn;
5572 {
5573 	struct freefrag *freefrag;
5574 	struct ufsmount *ump;
5575 	struct fs *fs;
5576 
5577 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5578 	    ip->i_number, blkno, size, lbn);
5579 	ump = ITOUMP(ip);
5580 	fs = ump->um_fs;
5581 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5582 		panic("newfreefrag: frag size");
5583 	freefrag = malloc(sizeof(struct freefrag),
5584 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5585 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5586 	freefrag->ff_state = ATTACHED;
5587 	LIST_INIT(&freefrag->ff_jwork);
5588 	freefrag->ff_inum = ip->i_number;
5589 	freefrag->ff_vtype = ITOV(ip)->v_type;
5590 	freefrag->ff_blkno = blkno;
5591 	freefrag->ff_fragsize = size;
5592 
5593 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5594 		freefrag->ff_jdep = (struct worklist *)
5595 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5596 	} else {
5597 		freefrag->ff_state |= DEPCOMPLETE;
5598 		freefrag->ff_jdep = NULL;
5599 	}
5600 
5601 	return (freefrag);
5602 }
5603 
5604 /*
5605  * This workitem de-allocates fragments that were replaced during
5606  * file block allocation.
5607  */
5608 static void
5609 handle_workitem_freefrag(freefrag)
5610 	struct freefrag *freefrag;
5611 {
5612 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5613 	struct workhead wkhd;
5614 
5615 	CTR3(KTR_SUJ,
5616 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5617 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5618 	/*
5619 	 * It would be illegal to add new completion items to the
5620 	 * freefrag after it was schedule to be done so it must be
5621 	 * safe to modify the list head here.
5622 	 */
5623 	LIST_INIT(&wkhd);
5624 	ACQUIRE_LOCK(ump);
5625 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5626 	/*
5627 	 * If the journal has not been written we must cancel it here.
5628 	 */
5629 	if (freefrag->ff_jdep) {
5630 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5631 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5632 			    freefrag->ff_jdep->wk_type);
5633 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5634 	}
5635 	FREE_LOCK(ump);
5636 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5637 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5638 	ACQUIRE_LOCK(ump);
5639 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5640 	FREE_LOCK(ump);
5641 }
5642 
5643 /*
5644  * Set up a dependency structure for an external attributes data block.
5645  * This routine follows much of the structure of softdep_setup_allocdirect.
5646  * See the description of softdep_setup_allocdirect above for details.
5647  */
5648 void
5649 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5650 	struct inode *ip;
5651 	ufs_lbn_t off;
5652 	ufs2_daddr_t newblkno;
5653 	ufs2_daddr_t oldblkno;
5654 	long newsize;
5655 	long oldsize;
5656 	struct buf *bp;
5657 {
5658 	struct allocdirect *adp, *oldadp;
5659 	struct allocdirectlst *adphead;
5660 	struct freefrag *freefrag;
5661 	struct inodedep *inodedep;
5662 	struct jnewblk *jnewblk;
5663 	struct newblk *newblk;
5664 	struct mount *mp;
5665 	struct ufsmount *ump;
5666 	ufs_lbn_t lbn;
5667 
5668 	mp = ITOVFS(ip);
5669 	ump = VFSTOUFS(mp);
5670 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5671 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5672 	KASSERT(off < UFS_NXADDR,
5673 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5674 
5675 	lbn = bp->b_lblkno;
5676 	if (oldblkno && oldblkno != newblkno)
5677 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5678 	else
5679 		freefrag = NULL;
5680 
5681 	ACQUIRE_LOCK(ump);
5682 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5683 		panic("softdep_setup_allocext: lost block");
5684 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5685 	    ("softdep_setup_allocext: newblk already initialized"));
5686 	/*
5687 	 * Convert the newblk to an allocdirect.
5688 	 */
5689 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5690 	adp = (struct allocdirect *)newblk;
5691 	newblk->nb_freefrag = freefrag;
5692 	adp->ad_offset = off;
5693 	adp->ad_oldblkno = oldblkno;
5694 	adp->ad_newsize = newsize;
5695 	adp->ad_oldsize = oldsize;
5696 	adp->ad_state |=  EXTDATA;
5697 
5698 	/*
5699 	 * Finish initializing the journal.
5700 	 */
5701 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5702 		jnewblk->jn_ino = ip->i_number;
5703 		jnewblk->jn_lbn = lbn;
5704 		add_to_journal(&jnewblk->jn_list);
5705 	}
5706 	if (freefrag && freefrag->ff_jdep != NULL &&
5707 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5708 		add_to_journal(freefrag->ff_jdep);
5709 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5710 	adp->ad_inodedep = inodedep;
5711 
5712 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5713 	/*
5714 	 * The list of allocdirects must be kept in sorted and ascending
5715 	 * order so that the rollback routines can quickly determine the
5716 	 * first uncommitted block (the size of the file stored on disk
5717 	 * ends at the end of the lowest committed fragment, or if there
5718 	 * are no fragments, at the end of the highest committed block).
5719 	 * Since files generally grow, the typical case is that the new
5720 	 * block is to be added at the end of the list. We speed this
5721 	 * special case by checking against the last allocdirect in the
5722 	 * list before laboriously traversing the list looking for the
5723 	 * insertion point.
5724 	 */
5725 	adphead = &inodedep->id_newextupdt;
5726 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5727 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5728 		/* insert at end of list */
5729 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5730 		if (oldadp != NULL && oldadp->ad_offset == off)
5731 			allocdirect_merge(adphead, adp, oldadp);
5732 		FREE_LOCK(ump);
5733 		return;
5734 	}
5735 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5736 		if (oldadp->ad_offset >= off)
5737 			break;
5738 	}
5739 	if (oldadp == NULL)
5740 		panic("softdep_setup_allocext: lost entry");
5741 	/* insert in middle of list */
5742 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5743 	if (oldadp->ad_offset == off)
5744 		allocdirect_merge(adphead, adp, oldadp);
5745 	FREE_LOCK(ump);
5746 }
5747 
5748 /*
5749  * Indirect block allocation dependencies.
5750  *
5751  * The same dependencies that exist for a direct block also exist when
5752  * a new block is allocated and pointed to by an entry in a block of
5753  * indirect pointers. The undo/redo states described above are also
5754  * used here. Because an indirect block contains many pointers that
5755  * may have dependencies, a second copy of the entire in-memory indirect
5756  * block is kept. The buffer cache copy is always completely up-to-date.
5757  * The second copy, which is used only as a source for disk writes,
5758  * contains only the safe pointers (i.e., those that have no remaining
5759  * update dependencies). The second copy is freed when all pointers
5760  * are safe. The cache is not allowed to replace indirect blocks with
5761  * pending update dependencies. If a buffer containing an indirect
5762  * block with dependencies is written, these routines will mark it
5763  * dirty again. It can only be successfully written once all the
5764  * dependencies are removed. The ffs_fsync routine in conjunction with
5765  * softdep_sync_metadata work together to get all the dependencies
5766  * removed so that a file can be successfully written to disk. Three
5767  * procedures are used when setting up indirect block pointer
5768  * dependencies. The division is necessary because of the organization
5769  * of the "balloc" routine and because of the distinction between file
5770  * pages and file metadata blocks.
5771  */
5772 
5773 /*
5774  * Allocate a new allocindir structure.
5775  */
5776 static struct allocindir *
5777 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5778 	struct inode *ip;	/* inode for file being extended */
5779 	int ptrno;		/* offset of pointer in indirect block */
5780 	ufs2_daddr_t newblkno;	/* disk block number being added */
5781 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5782 	ufs_lbn_t lbn;
5783 {
5784 	struct newblk *newblk;
5785 	struct allocindir *aip;
5786 	struct freefrag *freefrag;
5787 	struct jnewblk *jnewblk;
5788 
5789 	if (oldblkno)
5790 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn);
5791 	else
5792 		freefrag = NULL;
5793 	ACQUIRE_LOCK(ITOUMP(ip));
5794 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5795 		panic("new_allocindir: lost block");
5796 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5797 	    ("newallocindir: newblk already initialized"));
5798 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5799 	newblk->nb_freefrag = freefrag;
5800 	aip = (struct allocindir *)newblk;
5801 	aip->ai_offset = ptrno;
5802 	aip->ai_oldblkno = oldblkno;
5803 	aip->ai_lbn = lbn;
5804 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5805 		jnewblk->jn_ino = ip->i_number;
5806 		jnewblk->jn_lbn = lbn;
5807 		add_to_journal(&jnewblk->jn_list);
5808 	}
5809 	if (freefrag && freefrag->ff_jdep != NULL &&
5810 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5811 		add_to_journal(freefrag->ff_jdep);
5812 	return (aip);
5813 }
5814 
5815 /*
5816  * Called just before setting an indirect block pointer
5817  * to a newly allocated file page.
5818  */
5819 void
5820 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5821 	struct inode *ip;	/* inode for file being extended */
5822 	ufs_lbn_t lbn;		/* allocated block number within file */
5823 	struct buf *bp;		/* buffer with indirect blk referencing page */
5824 	int ptrno;		/* offset of pointer in indirect block */
5825 	ufs2_daddr_t newblkno;	/* disk block number being added */
5826 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5827 	struct buf *nbp;	/* buffer holding allocated page */
5828 {
5829 	struct inodedep *inodedep;
5830 	struct freefrag *freefrag;
5831 	struct allocindir *aip;
5832 	struct pagedep *pagedep;
5833 	struct mount *mp;
5834 	struct ufsmount *ump;
5835 
5836 	mp = ITOVFS(ip);
5837 	ump = VFSTOUFS(mp);
5838 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5839 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5840 	KASSERT(lbn == nbp->b_lblkno,
5841 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5842 	    lbn, bp->b_lblkno));
5843 	CTR4(KTR_SUJ,
5844 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5845 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5846 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5847 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5848 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5849 	/*
5850 	 * If we are allocating a directory page, then we must
5851 	 * allocate an associated pagedep to track additions and
5852 	 * deletions.
5853 	 */
5854 	if ((ip->i_mode & IFMT) == IFDIR)
5855 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5856 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5857 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5858 	FREE_LOCK(ump);
5859 	if (freefrag)
5860 		handle_workitem_freefrag(freefrag);
5861 }
5862 
5863 /*
5864  * Called just before setting an indirect block pointer to a
5865  * newly allocated indirect block.
5866  */
5867 void
5868 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5869 	struct buf *nbp;	/* newly allocated indirect block */
5870 	struct inode *ip;	/* inode for file being extended */
5871 	struct buf *bp;		/* indirect block referencing allocated block */
5872 	int ptrno;		/* offset of pointer in indirect block */
5873 	ufs2_daddr_t newblkno;	/* disk block number being added */
5874 {
5875 	struct inodedep *inodedep;
5876 	struct allocindir *aip;
5877 	struct ufsmount *ump;
5878 	ufs_lbn_t lbn;
5879 
5880 	ump = ITOUMP(ip);
5881 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5882 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5883 	CTR3(KTR_SUJ,
5884 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5885 	    ip->i_number, newblkno, ptrno);
5886 	lbn = nbp->b_lblkno;
5887 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5888 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5889 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5890 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5891 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5892 		panic("softdep_setup_allocindir_meta: Block already existed");
5893 	FREE_LOCK(ump);
5894 }
5895 
5896 static void
5897 indirdep_complete(indirdep)
5898 	struct indirdep *indirdep;
5899 {
5900 	struct allocindir *aip;
5901 
5902 	LIST_REMOVE(indirdep, ir_next);
5903 	indirdep->ir_state |= DEPCOMPLETE;
5904 
5905 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5906 		LIST_REMOVE(aip, ai_next);
5907 		free_newblk(&aip->ai_block);
5908 	}
5909 	/*
5910 	 * If this indirdep is not attached to a buf it was simply waiting
5911 	 * on completion to clear completehd.  free_indirdep() asserts
5912 	 * that nothing is dangling.
5913 	 */
5914 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5915 		free_indirdep(indirdep);
5916 }
5917 
5918 static struct indirdep *
5919 indirdep_lookup(mp, ip, bp)
5920 	struct mount *mp;
5921 	struct inode *ip;
5922 	struct buf *bp;
5923 {
5924 	struct indirdep *indirdep, *newindirdep;
5925 	struct newblk *newblk;
5926 	struct ufsmount *ump;
5927 	struct worklist *wk;
5928 	struct fs *fs;
5929 	ufs2_daddr_t blkno;
5930 
5931 	ump = VFSTOUFS(mp);
5932 	LOCK_OWNED(ump);
5933 	indirdep = NULL;
5934 	newindirdep = NULL;
5935 	fs = ump->um_fs;
5936 	for (;;) {
5937 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5938 			if (wk->wk_type != D_INDIRDEP)
5939 				continue;
5940 			indirdep = WK_INDIRDEP(wk);
5941 			break;
5942 		}
5943 		/* Found on the buffer worklist, no new structure to free. */
5944 		if (indirdep != NULL && newindirdep == NULL)
5945 			return (indirdep);
5946 		if (indirdep != NULL && newindirdep != NULL)
5947 			panic("indirdep_lookup: simultaneous create");
5948 		/* None found on the buffer and a new structure is ready. */
5949 		if (indirdep == NULL && newindirdep != NULL)
5950 			break;
5951 		/* None found and no new structure available. */
5952 		FREE_LOCK(ump);
5953 		newindirdep = malloc(sizeof(struct indirdep),
5954 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
5955 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5956 		newindirdep->ir_state = ATTACHED;
5957 		if (I_IS_UFS1(ip))
5958 			newindirdep->ir_state |= UFS1FMT;
5959 		TAILQ_INIT(&newindirdep->ir_trunc);
5960 		newindirdep->ir_saveddata = NULL;
5961 		LIST_INIT(&newindirdep->ir_deplisthd);
5962 		LIST_INIT(&newindirdep->ir_donehd);
5963 		LIST_INIT(&newindirdep->ir_writehd);
5964 		LIST_INIT(&newindirdep->ir_completehd);
5965 		if (bp->b_blkno == bp->b_lblkno) {
5966 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5967 			    NULL, NULL);
5968 			bp->b_blkno = blkno;
5969 		}
5970 		newindirdep->ir_freeblks = NULL;
5971 		newindirdep->ir_savebp =
5972 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5973 		newindirdep->ir_bp = bp;
5974 		BUF_KERNPROC(newindirdep->ir_savebp);
5975 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5976 		ACQUIRE_LOCK(ump);
5977 	}
5978 	indirdep = newindirdep;
5979 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5980 	/*
5981 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
5982 	 * that we don't free dependencies until the pointers are valid.
5983 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5984 	 * than using the hash.
5985 	 */
5986 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5987 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5988 	else
5989 		indirdep->ir_state |= DEPCOMPLETE;
5990 	return (indirdep);
5991 }
5992 
5993 /*
5994  * Called to finish the allocation of the "aip" allocated
5995  * by one of the two routines above.
5996  */
5997 static struct freefrag *
5998 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
5999 	struct buf *bp;		/* in-memory copy of the indirect block */
6000 	struct inode *ip;	/* inode for file being extended */
6001 	struct inodedep *inodedep; /* Inodedep for ip */
6002 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6003 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6004 {
6005 	struct fs *fs;
6006 	struct indirdep *indirdep;
6007 	struct allocindir *oldaip;
6008 	struct freefrag *freefrag;
6009 	struct mount *mp;
6010 	struct ufsmount *ump;
6011 
6012 	mp = ITOVFS(ip);
6013 	ump = VFSTOUFS(mp);
6014 	LOCK_OWNED(ump);
6015 	fs = ump->um_fs;
6016 	if (bp->b_lblkno >= 0)
6017 		panic("setup_allocindir_phase2: not indir blk");
6018 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6019 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6020 	indirdep = indirdep_lookup(mp, ip, bp);
6021 	KASSERT(indirdep->ir_savebp != NULL,
6022 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6023 	aip->ai_indirdep = indirdep;
6024 	/*
6025 	 * Check for an unwritten dependency for this indirect offset.  If
6026 	 * there is, merge the old dependency into the new one.  This happens
6027 	 * as a result of reallocblk only.
6028 	 */
6029 	freefrag = NULL;
6030 	if (aip->ai_oldblkno != 0) {
6031 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6032 			if (oldaip->ai_offset == aip->ai_offset) {
6033 				freefrag = allocindir_merge(aip, oldaip);
6034 				goto done;
6035 			}
6036 		}
6037 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6038 			if (oldaip->ai_offset == aip->ai_offset) {
6039 				freefrag = allocindir_merge(aip, oldaip);
6040 				goto done;
6041 			}
6042 		}
6043 	}
6044 done:
6045 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6046 	return (freefrag);
6047 }
6048 
6049 /*
6050  * Merge two allocindirs which refer to the same block.  Move newblock
6051  * dependencies and setup the freefrags appropriately.
6052  */
6053 static struct freefrag *
6054 allocindir_merge(aip, oldaip)
6055 	struct allocindir *aip;
6056 	struct allocindir *oldaip;
6057 {
6058 	struct freefrag *freefrag;
6059 	struct worklist *wk;
6060 
6061 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6062 		panic("allocindir_merge: blkno");
6063 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6064 	freefrag = aip->ai_freefrag;
6065 	aip->ai_freefrag = oldaip->ai_freefrag;
6066 	oldaip->ai_freefrag = NULL;
6067 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6068 	/*
6069 	 * If we are tracking a new directory-block allocation,
6070 	 * move it from the old allocindir to the new allocindir.
6071 	 */
6072 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6073 		WORKLIST_REMOVE(wk);
6074 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6075 			panic("allocindir_merge: extra newdirblk");
6076 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6077 	}
6078 	/*
6079 	 * We can skip journaling for this freefrag and just complete
6080 	 * any pending journal work for the allocindir that is being
6081 	 * removed after the freefrag completes.
6082 	 */
6083 	if (freefrag->ff_jdep)
6084 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6085 	LIST_REMOVE(oldaip, ai_next);
6086 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6087 	    &freefrag->ff_list, &freefrag->ff_jwork);
6088 	free_newblk(&oldaip->ai_block);
6089 
6090 	return (freefrag);
6091 }
6092 
6093 static inline void
6094 setup_freedirect(freeblks, ip, i, needj)
6095 	struct freeblks *freeblks;
6096 	struct inode *ip;
6097 	int i;
6098 	int needj;
6099 {
6100 	struct ufsmount *ump;
6101 	ufs2_daddr_t blkno;
6102 	int frags;
6103 
6104 	blkno = DIP(ip, i_db[i]);
6105 	if (blkno == 0)
6106 		return;
6107 	DIP_SET(ip, i_db[i], 0);
6108 	ump = ITOUMP(ip);
6109 	frags = sblksize(ump->um_fs, ip->i_size, i);
6110 	frags = numfrags(ump->um_fs, frags);
6111 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6112 }
6113 
6114 static inline void
6115 setup_freeext(freeblks, ip, i, needj)
6116 	struct freeblks *freeblks;
6117 	struct inode *ip;
6118 	int i;
6119 	int needj;
6120 {
6121 	struct ufsmount *ump;
6122 	ufs2_daddr_t blkno;
6123 	int frags;
6124 
6125 	blkno = ip->i_din2->di_extb[i];
6126 	if (blkno == 0)
6127 		return;
6128 	ip->i_din2->di_extb[i] = 0;
6129 	ump = ITOUMP(ip);
6130 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6131 	frags = numfrags(ump->um_fs, frags);
6132 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6133 }
6134 
6135 static inline void
6136 setup_freeindir(freeblks, ip, i, lbn, needj)
6137 	struct freeblks *freeblks;
6138 	struct inode *ip;
6139 	int i;
6140 	ufs_lbn_t lbn;
6141 	int needj;
6142 {
6143 	struct ufsmount *ump;
6144 	ufs2_daddr_t blkno;
6145 
6146 	blkno = DIP(ip, i_ib[i]);
6147 	if (blkno == 0)
6148 		return;
6149 	DIP_SET(ip, i_ib[i], 0);
6150 	ump = ITOUMP(ip);
6151 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6152 	    0, needj);
6153 }
6154 
6155 static inline struct freeblks *
6156 newfreeblks(mp, ip)
6157 	struct mount *mp;
6158 	struct inode *ip;
6159 {
6160 	struct freeblks *freeblks;
6161 
6162 	freeblks = malloc(sizeof(struct freeblks),
6163 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6164 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6165 	LIST_INIT(&freeblks->fb_jblkdephd);
6166 	LIST_INIT(&freeblks->fb_jwork);
6167 	freeblks->fb_ref = 0;
6168 	freeblks->fb_cgwait = 0;
6169 	freeblks->fb_state = ATTACHED;
6170 	freeblks->fb_uid = ip->i_uid;
6171 	freeblks->fb_inum = ip->i_number;
6172 	freeblks->fb_vtype = ITOV(ip)->v_type;
6173 	freeblks->fb_modrev = DIP(ip, i_modrev);
6174 	freeblks->fb_devvp = ITODEVVP(ip);
6175 	freeblks->fb_chkcnt = 0;
6176 	freeblks->fb_len = 0;
6177 
6178 	return (freeblks);
6179 }
6180 
6181 static void
6182 trunc_indirdep(indirdep, freeblks, bp, off)
6183 	struct indirdep *indirdep;
6184 	struct freeblks *freeblks;
6185 	struct buf *bp;
6186 	int off;
6187 {
6188 	struct allocindir *aip, *aipn;
6189 
6190 	/*
6191 	 * The first set of allocindirs won't be in savedbp.
6192 	 */
6193 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6194 		if (aip->ai_offset > off)
6195 			cancel_allocindir(aip, bp, freeblks, 1);
6196 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6197 		if (aip->ai_offset > off)
6198 			cancel_allocindir(aip, bp, freeblks, 1);
6199 	/*
6200 	 * These will exist in savedbp.
6201 	 */
6202 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6203 		if (aip->ai_offset > off)
6204 			cancel_allocindir(aip, NULL, freeblks, 0);
6205 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6206 		if (aip->ai_offset > off)
6207 			cancel_allocindir(aip, NULL, freeblks, 0);
6208 }
6209 
6210 /*
6211  * Follow the chain of indirects down to lastlbn creating a freework
6212  * structure for each.  This will be used to start indir_trunc() at
6213  * the right offset and create the journal records for the parrtial
6214  * truncation.  A second step will handle the truncated dependencies.
6215  */
6216 static int
6217 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6218 	struct freeblks *freeblks;
6219 	struct inode *ip;
6220 	ufs_lbn_t lbn;
6221 	ufs_lbn_t lastlbn;
6222 	ufs2_daddr_t blkno;
6223 {
6224 	struct indirdep *indirdep;
6225 	struct indirdep *indirn;
6226 	struct freework *freework;
6227 	struct newblk *newblk;
6228 	struct mount *mp;
6229 	struct ufsmount *ump;
6230 	struct buf *bp;
6231 	uint8_t *start;
6232 	uint8_t *end;
6233 	ufs_lbn_t lbnadd;
6234 	int level;
6235 	int error;
6236 	int off;
6237 
6238 
6239 	freework = NULL;
6240 	if (blkno == 0)
6241 		return (0);
6242 	mp = freeblks->fb_list.wk_mp;
6243 	ump = VFSTOUFS(mp);
6244 	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6245 	if ((bp->b_flags & B_CACHE) == 0) {
6246 		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6247 		bp->b_iocmd = BIO_READ;
6248 		bp->b_flags &= ~B_INVAL;
6249 		bp->b_ioflags &= ~BIO_ERROR;
6250 		vfs_busy_pages(bp, 0);
6251 		bp->b_iooffset = dbtob(bp->b_blkno);
6252 		bstrategy(bp);
6253 #ifdef RACCT
6254 		if (racct_enable) {
6255 			PROC_LOCK(curproc);
6256 			racct_add_buf(curproc, bp, 0);
6257 			PROC_UNLOCK(curproc);
6258 		}
6259 #endif /* RACCT */
6260 		curthread->td_ru.ru_inblock++;
6261 		error = bufwait(bp);
6262 		if (error) {
6263 			brelse(bp);
6264 			return (error);
6265 		}
6266 	}
6267 	level = lbn_level(lbn);
6268 	lbnadd = lbn_offset(ump->um_fs, level);
6269 	/*
6270 	 * Compute the offset of the last block we want to keep.  Store
6271 	 * in the freework the first block we want to completely free.
6272 	 */
6273 	off = (lastlbn - -(lbn + level)) / lbnadd;
6274 	if (off + 1 == NINDIR(ump->um_fs))
6275 		goto nowork;
6276 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6277 	/*
6278 	 * Link the freework into the indirdep.  This will prevent any new
6279 	 * allocations from proceeding until we are finished with the
6280 	 * truncate and the block is written.
6281 	 */
6282 	ACQUIRE_LOCK(ump);
6283 	indirdep = indirdep_lookup(mp, ip, bp);
6284 	if (indirdep->ir_freeblks)
6285 		panic("setup_trunc_indir: indirdep already truncated.");
6286 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6287 	freework->fw_indir = indirdep;
6288 	/*
6289 	 * Cancel any allocindirs that will not make it to disk.
6290 	 * We have to do this for all copies of the indirdep that
6291 	 * live on this newblk.
6292 	 */
6293 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6294 		newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0, &newblk);
6295 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6296 			trunc_indirdep(indirn, freeblks, bp, off);
6297 	} else
6298 		trunc_indirdep(indirdep, freeblks, bp, off);
6299 	FREE_LOCK(ump);
6300 	/*
6301 	 * Creation is protected by the buf lock. The saveddata is only
6302 	 * needed if a full truncation follows a partial truncation but it
6303 	 * is difficult to allocate in that case so we fetch it anyway.
6304 	 */
6305 	if (indirdep->ir_saveddata == NULL)
6306 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6307 		    M_SOFTDEP_FLAGS);
6308 nowork:
6309 	/* Fetch the blkno of the child and the zero start offset. */
6310 	if (I_IS_UFS1(ip)) {
6311 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6312 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6313 	} else {
6314 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6315 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6316 	}
6317 	if (freework) {
6318 		/* Zero the truncated pointers. */
6319 		end = bp->b_data + bp->b_bcount;
6320 		bzero(start, end - start);
6321 		bdwrite(bp);
6322 	} else
6323 		bqrelse(bp);
6324 	if (level == 0)
6325 		return (0);
6326 	lbn++; /* adjust level */
6327 	lbn -= (off * lbnadd);
6328 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6329 }
6330 
6331 /*
6332  * Complete the partial truncation of an indirect block setup by
6333  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6334  * copy and writes them to disk before the freeblks is allowed to complete.
6335  */
6336 static void
6337 complete_trunc_indir(freework)
6338 	struct freework *freework;
6339 {
6340 	struct freework *fwn;
6341 	struct indirdep *indirdep;
6342 	struct ufsmount *ump;
6343 	struct buf *bp;
6344 	uintptr_t start;
6345 	int count;
6346 
6347 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6348 	LOCK_OWNED(ump);
6349 	indirdep = freework->fw_indir;
6350 	for (;;) {
6351 		bp = indirdep->ir_bp;
6352 		/* See if the block was discarded. */
6353 		if (bp == NULL)
6354 			break;
6355 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6356 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6357 			break;
6358 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6359 		    LOCK_PTR(ump)) == 0)
6360 			BUF_UNLOCK(bp);
6361 		ACQUIRE_LOCK(ump);
6362 	}
6363 	freework->fw_state |= DEPCOMPLETE;
6364 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6365 	/*
6366 	 * Zero the pointers in the saved copy.
6367 	 */
6368 	if (indirdep->ir_state & UFS1FMT)
6369 		start = sizeof(ufs1_daddr_t);
6370 	else
6371 		start = sizeof(ufs2_daddr_t);
6372 	start *= freework->fw_start;
6373 	count = indirdep->ir_savebp->b_bcount - start;
6374 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6375 	bzero((char *)start, count);
6376 	/*
6377 	 * We need to start the next truncation in the list if it has not
6378 	 * been started yet.
6379 	 */
6380 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6381 	if (fwn != NULL) {
6382 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6383 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6384 		if ((fwn->fw_state & ONWORKLIST) == 0)
6385 			freework_enqueue(fwn);
6386 	}
6387 	/*
6388 	 * If bp is NULL the block was fully truncated, restore
6389 	 * the saved block list otherwise free it if it is no
6390 	 * longer needed.
6391 	 */
6392 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6393 		if (bp == NULL)
6394 			bcopy(indirdep->ir_saveddata,
6395 			    indirdep->ir_savebp->b_data,
6396 			    indirdep->ir_savebp->b_bcount);
6397 		free(indirdep->ir_saveddata, M_INDIRDEP);
6398 		indirdep->ir_saveddata = NULL;
6399 	}
6400 	/*
6401 	 * When bp is NULL there is a full truncation pending.  We
6402 	 * must wait for this full truncation to be journaled before
6403 	 * we can release this freework because the disk pointers will
6404 	 * never be written as zero.
6405 	 */
6406 	if (bp == NULL)  {
6407 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6408 			handle_written_freework(freework);
6409 		else
6410 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6411 			   &freework->fw_list);
6412 	} else {
6413 		/* Complete when the real copy is written. */
6414 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6415 		BUF_UNLOCK(bp);
6416 	}
6417 }
6418 
6419 /*
6420  * Calculate the number of blocks we are going to release where datablocks
6421  * is the current total and length is the new file size.
6422  */
6423 static ufs2_daddr_t
6424 blkcount(fs, datablocks, length)
6425 	struct fs *fs;
6426 	ufs2_daddr_t datablocks;
6427 	off_t length;
6428 {
6429 	off_t totblks, numblks;
6430 
6431 	totblks = 0;
6432 	numblks = howmany(length, fs->fs_bsize);
6433 	if (numblks <= UFS_NDADDR) {
6434 		totblks = howmany(length, fs->fs_fsize);
6435 		goto out;
6436 	}
6437         totblks = blkstofrags(fs, numblks);
6438 	numblks -= UFS_NDADDR;
6439 	/*
6440 	 * Count all single, then double, then triple indirects required.
6441 	 * Subtracting one indirects worth of blocks for each pass
6442 	 * acknowledges one of each pointed to by the inode.
6443 	 */
6444 	for (;;) {
6445 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6446 		numblks -= NINDIR(fs);
6447 		if (numblks <= 0)
6448 			break;
6449 		numblks = howmany(numblks, NINDIR(fs));
6450 	}
6451 out:
6452 	totblks = fsbtodb(fs, totblks);
6453 	/*
6454 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6455 	 * references.  We will correct it later in handle_complete_freeblks()
6456 	 * when we know the real count.
6457 	 */
6458 	if (totblks > datablocks)
6459 		return (0);
6460 	return (datablocks - totblks);
6461 }
6462 
6463 /*
6464  * Handle freeblocks for journaled softupdate filesystems.
6465  *
6466  * Contrary to normal softupdates, we must preserve the block pointers in
6467  * indirects until their subordinates are free.  This is to avoid journaling
6468  * every block that is freed which may consume more space than the journal
6469  * itself.  The recovery program will see the free block journals at the
6470  * base of the truncated area and traverse them to reclaim space.  The
6471  * pointers in the inode may be cleared immediately after the journal
6472  * records are written because each direct and indirect pointer in the
6473  * inode is recorded in a journal.  This permits full truncation to proceed
6474  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6475  *
6476  * The algorithm is as follows:
6477  * 1) Traverse the in-memory state and create journal entries to release
6478  *    the relevant blocks and full indirect trees.
6479  * 2) Traverse the indirect block chain adding partial truncation freework
6480  *    records to indirects in the path to lastlbn.  The freework will
6481  *    prevent new allocation dependencies from being satisfied in this
6482  *    indirect until the truncation completes.
6483  * 3) Read and lock the inode block, performing an update with the new size
6484  *    and pointers.  This prevents truncated data from becoming valid on
6485  *    disk through step 4.
6486  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6487  *    eliminate journal work for those records that do not require it.
6488  * 5) Schedule the journal records to be written followed by the inode block.
6489  * 6) Allocate any necessary frags for the end of file.
6490  * 7) Zero any partially truncated blocks.
6491  *
6492  * From this truncation proceeds asynchronously using the freework and
6493  * indir_trunc machinery.  The file will not be extended again into a
6494  * partially truncated indirect block until all work is completed but
6495  * the normal dependency mechanism ensures that it is rolled back/forward
6496  * as appropriate.  Further truncation may occur without delay and is
6497  * serialized in indir_trunc().
6498  */
6499 void
6500 softdep_journal_freeblocks(ip, cred, length, flags)
6501 	struct inode *ip;	/* The inode whose length is to be reduced */
6502 	struct ucred *cred;
6503 	off_t length;		/* The new length for the file */
6504 	int flags;		/* IO_EXT and/or IO_NORMAL */
6505 {
6506 	struct freeblks *freeblks, *fbn;
6507 	struct worklist *wk, *wkn;
6508 	struct inodedep *inodedep;
6509 	struct jblkdep *jblkdep;
6510 	struct allocdirect *adp, *adpn;
6511 	struct ufsmount *ump;
6512 	struct fs *fs;
6513 	struct buf *bp;
6514 	struct vnode *vp;
6515 	struct mount *mp;
6516 	ufs2_daddr_t extblocks, datablocks;
6517 	ufs_lbn_t tmpval, lbn, lastlbn;
6518 	int frags, lastoff, iboff, allocblock, needj, error, i;
6519 
6520 	ump = ITOUMP(ip);
6521 	mp = UFSTOVFS(ump);
6522 	fs = ump->um_fs;
6523 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6524 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6525 	vp = ITOV(ip);
6526 	needj = 1;
6527 	iboff = -1;
6528 	allocblock = 0;
6529 	extblocks = 0;
6530 	datablocks = 0;
6531 	frags = 0;
6532 	freeblks = newfreeblks(mp, ip);
6533 	ACQUIRE_LOCK(ump);
6534 	/*
6535 	 * If we're truncating a removed file that will never be written
6536 	 * we don't need to journal the block frees.  The canceled journals
6537 	 * for the allocations will suffice.
6538 	 */
6539 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6540 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6541 	    length == 0)
6542 		needj = 0;
6543 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6544 	    ip->i_number, length, needj);
6545 	FREE_LOCK(ump);
6546 	/*
6547 	 * Calculate the lbn that we are truncating to.  This results in -1
6548 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6549 	 * to keep, not the first lbn we want to truncate.
6550 	 */
6551 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6552 	lastoff = blkoff(fs, length);
6553 	/*
6554 	 * Compute frags we are keeping in lastlbn.  0 means all.
6555 	 */
6556 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6557 		frags = fragroundup(fs, lastoff);
6558 		/* adp offset of last valid allocdirect. */
6559 		iboff = lastlbn;
6560 	} else if (lastlbn > 0)
6561 		iboff = UFS_NDADDR;
6562 	if (fs->fs_magic == FS_UFS2_MAGIC)
6563 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6564 	/*
6565 	 * Handle normal data blocks and indirects.  This section saves
6566 	 * values used after the inode update to complete frag and indirect
6567 	 * truncation.
6568 	 */
6569 	if ((flags & IO_NORMAL) != 0) {
6570 		/*
6571 		 * Handle truncation of whole direct and indirect blocks.
6572 		 */
6573 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6574 			setup_freedirect(freeblks, ip, i, needj);
6575 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6576 		    i < UFS_NIADDR;
6577 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6578 			/* Release a whole indirect tree. */
6579 			if (lbn > lastlbn) {
6580 				setup_freeindir(freeblks, ip, i, -lbn -i,
6581 				    needj);
6582 				continue;
6583 			}
6584 			iboff = i + UFS_NDADDR;
6585 			/*
6586 			 * Traverse partially truncated indirect tree.
6587 			 */
6588 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6589 				setup_trunc_indir(freeblks, ip, -lbn - i,
6590 				    lastlbn, DIP(ip, i_ib[i]));
6591 		}
6592 		/*
6593 		 * Handle partial truncation to a frag boundary.
6594 		 */
6595 		if (frags) {
6596 			ufs2_daddr_t blkno;
6597 			long oldfrags;
6598 
6599 			oldfrags = blksize(fs, ip, lastlbn);
6600 			blkno = DIP(ip, i_db[lastlbn]);
6601 			if (blkno && oldfrags != frags) {
6602 				oldfrags -= frags;
6603 				oldfrags = numfrags(fs, oldfrags);
6604 				blkno += numfrags(fs, frags);
6605 				newfreework(ump, freeblks, NULL, lastlbn,
6606 				    blkno, oldfrags, 0, needj);
6607 				if (needj)
6608 					adjust_newfreework(freeblks,
6609 					    numfrags(fs, frags));
6610 			} else if (blkno == 0)
6611 				allocblock = 1;
6612 		}
6613 		/*
6614 		 * Add a journal record for partial truncate if we are
6615 		 * handling indirect blocks.  Non-indirects need no extra
6616 		 * journaling.
6617 		 */
6618 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6619 			ip->i_flag |= IN_TRUNCATED;
6620 			newjtrunc(freeblks, length, 0);
6621 		}
6622 		ip->i_size = length;
6623 		DIP_SET(ip, i_size, ip->i_size);
6624 		datablocks = DIP(ip, i_blocks) - extblocks;
6625 		if (length != 0)
6626 			datablocks = blkcount(fs, datablocks, length);
6627 		freeblks->fb_len = length;
6628 	}
6629 	if ((flags & IO_EXT) != 0) {
6630 		for (i = 0; i < UFS_NXADDR; i++)
6631 			setup_freeext(freeblks, ip, i, needj);
6632 		ip->i_din2->di_extsize = 0;
6633 		datablocks += extblocks;
6634 	}
6635 #ifdef QUOTA
6636 	/* Reference the quotas in case the block count is wrong in the end. */
6637 	quotaref(vp, freeblks->fb_quota);
6638 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6639 #endif
6640 	freeblks->fb_chkcnt = -datablocks;
6641 	UFS_LOCK(ump);
6642 	fs->fs_pendingblocks += datablocks;
6643 	UFS_UNLOCK(ump);
6644 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6645 	/*
6646 	 * Handle truncation of incomplete alloc direct dependencies.  We
6647 	 * hold the inode block locked to prevent incomplete dependencies
6648 	 * from reaching the disk while we are eliminating those that
6649 	 * have been truncated.  This is a partially inlined ffs_update().
6650 	 */
6651 	ufs_itimes(vp);
6652 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6653 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6654 	    (int)fs->fs_bsize, cred, &bp);
6655 	if (error) {
6656 		brelse(bp);
6657 		softdep_error("softdep_journal_freeblocks", error);
6658 		return;
6659 	}
6660 	if (bp->b_bufsize == fs->fs_bsize)
6661 		bp->b_flags |= B_CLUSTEROK;
6662 	softdep_update_inodeblock(ip, bp, 0);
6663 	if (ump->um_fstype == UFS1)
6664 		*((struct ufs1_dinode *)bp->b_data +
6665 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6666 	else
6667 		*((struct ufs2_dinode *)bp->b_data +
6668 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6669 	ACQUIRE_LOCK(ump);
6670 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6671 	if ((inodedep->id_state & IOSTARTED) != 0)
6672 		panic("softdep_setup_freeblocks: inode busy");
6673 	/*
6674 	 * Add the freeblks structure to the list of operations that
6675 	 * must await the zero'ed inode being written to disk. If we
6676 	 * still have a bitmap dependency (needj), then the inode
6677 	 * has never been written to disk, so we can process the
6678 	 * freeblks below once we have deleted the dependencies.
6679 	 */
6680 	if (needj)
6681 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6682 	else
6683 		freeblks->fb_state |= COMPLETE;
6684 	if ((flags & IO_NORMAL) != 0) {
6685 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6686 			if (adp->ad_offset > iboff)
6687 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6688 				    freeblks);
6689 			/*
6690 			 * Truncate the allocdirect.  We could eliminate
6691 			 * or modify journal records as well.
6692 			 */
6693 			else if (adp->ad_offset == iboff && frags)
6694 				adp->ad_newsize = frags;
6695 		}
6696 	}
6697 	if ((flags & IO_EXT) != 0)
6698 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6699 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6700 			    freeblks);
6701 	/*
6702 	 * Scan the bufwait list for newblock dependencies that will never
6703 	 * make it to disk.
6704 	 */
6705 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6706 		if (wk->wk_type != D_ALLOCDIRECT)
6707 			continue;
6708 		adp = WK_ALLOCDIRECT(wk);
6709 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6710 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6711 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6712 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6713 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6714 		}
6715 	}
6716 	/*
6717 	 * Add journal work.
6718 	 */
6719 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6720 		add_to_journal(&jblkdep->jb_list);
6721 	FREE_LOCK(ump);
6722 	bdwrite(bp);
6723 	/*
6724 	 * Truncate dependency structures beyond length.
6725 	 */
6726 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6727 	/*
6728 	 * This is only set when we need to allocate a fragment because
6729 	 * none existed at the end of a frag-sized file.  It handles only
6730 	 * allocating a new, zero filled block.
6731 	 */
6732 	if (allocblock) {
6733 		ip->i_size = length - lastoff;
6734 		DIP_SET(ip, i_size, ip->i_size);
6735 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6736 		if (error != 0) {
6737 			softdep_error("softdep_journal_freeblks", error);
6738 			return;
6739 		}
6740 		ip->i_size = length;
6741 		DIP_SET(ip, i_size, length);
6742 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6743 		allocbuf(bp, frags);
6744 		ffs_update(vp, 0);
6745 		bawrite(bp);
6746 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6747 		int size;
6748 
6749 		/*
6750 		 * Zero the end of a truncated frag or block.
6751 		 */
6752 		size = sblksize(fs, length, lastlbn);
6753 		error = bread(vp, lastlbn, size, cred, &bp);
6754 		if (error) {
6755 			softdep_error("softdep_journal_freeblks", error);
6756 			return;
6757 		}
6758 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6759 		bawrite(bp);
6760 
6761 	}
6762 	ACQUIRE_LOCK(ump);
6763 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6764 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6765 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6766 	/*
6767 	 * We zero earlier truncations so they don't erroneously
6768 	 * update i_blocks.
6769 	 */
6770 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6771 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6772 			fbn->fb_len = 0;
6773 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6774 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6775 		freeblks->fb_state |= INPROGRESS;
6776 	else
6777 		freeblks = NULL;
6778 	FREE_LOCK(ump);
6779 	if (freeblks)
6780 		handle_workitem_freeblocks(freeblks, 0);
6781 	trunc_pages(ip, length, extblocks, flags);
6782 
6783 }
6784 
6785 /*
6786  * Flush a JOP_SYNC to the journal.
6787  */
6788 void
6789 softdep_journal_fsync(ip)
6790 	struct inode *ip;
6791 {
6792 	struct jfsync *jfsync;
6793 	struct ufsmount *ump;
6794 
6795 	ump = ITOUMP(ip);
6796 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6797 	    ("softdep_journal_fsync called on non-softdep filesystem"));
6798 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6799 		return;
6800 	ip->i_flag &= ~IN_TRUNCATED;
6801 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6802 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6803 	jfsync->jfs_size = ip->i_size;
6804 	jfsync->jfs_ino = ip->i_number;
6805 	ACQUIRE_LOCK(ump);
6806 	add_to_journal(&jfsync->jfs_list);
6807 	jwait(&jfsync->jfs_list, MNT_WAIT);
6808 	FREE_LOCK(ump);
6809 }
6810 
6811 /*
6812  * Block de-allocation dependencies.
6813  *
6814  * When blocks are de-allocated, the on-disk pointers must be nullified before
6815  * the blocks are made available for use by other files.  (The true
6816  * requirement is that old pointers must be nullified before new on-disk
6817  * pointers are set.  We chose this slightly more stringent requirement to
6818  * reduce complexity.) Our implementation handles this dependency by updating
6819  * the inode (or indirect block) appropriately but delaying the actual block
6820  * de-allocation (i.e., freemap and free space count manipulation) until
6821  * after the updated versions reach stable storage.  After the disk is
6822  * updated, the blocks can be safely de-allocated whenever it is convenient.
6823  * This implementation handles only the common case of reducing a file's
6824  * length to zero. Other cases are handled by the conventional synchronous
6825  * write approach.
6826  *
6827  * The ffs implementation with which we worked double-checks
6828  * the state of the block pointers and file size as it reduces
6829  * a file's length.  Some of this code is replicated here in our
6830  * soft updates implementation.  The freeblks->fb_chkcnt field is
6831  * used to transfer a part of this information to the procedure
6832  * that eventually de-allocates the blocks.
6833  *
6834  * This routine should be called from the routine that shortens
6835  * a file's length, before the inode's size or block pointers
6836  * are modified. It will save the block pointer information for
6837  * later release and zero the inode so that the calling routine
6838  * can release it.
6839  */
6840 void
6841 softdep_setup_freeblocks(ip, length, flags)
6842 	struct inode *ip;	/* The inode whose length is to be reduced */
6843 	off_t length;		/* The new length for the file */
6844 	int flags;		/* IO_EXT and/or IO_NORMAL */
6845 {
6846 	struct ufs1_dinode *dp1;
6847 	struct ufs2_dinode *dp2;
6848 	struct freeblks *freeblks;
6849 	struct inodedep *inodedep;
6850 	struct allocdirect *adp;
6851 	struct ufsmount *ump;
6852 	struct buf *bp;
6853 	struct fs *fs;
6854 	ufs2_daddr_t extblocks, datablocks;
6855 	struct mount *mp;
6856 	int i, delay, error;
6857 	ufs_lbn_t tmpval;
6858 	ufs_lbn_t lbn;
6859 
6860 	ump = ITOUMP(ip);
6861 	mp = UFSTOVFS(ump);
6862 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6863 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6864 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6865 	    ip->i_number, length);
6866 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6867 	fs = ump->um_fs;
6868 	if ((error = bread(ump->um_devvp,
6869 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6870 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6871 		brelse(bp);
6872 		softdep_error("softdep_setup_freeblocks", error);
6873 		return;
6874 	}
6875 	freeblks = newfreeblks(mp, ip);
6876 	extblocks = 0;
6877 	datablocks = 0;
6878 	if (fs->fs_magic == FS_UFS2_MAGIC)
6879 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6880 	if ((flags & IO_NORMAL) != 0) {
6881 		for (i = 0; i < UFS_NDADDR; i++)
6882 			setup_freedirect(freeblks, ip, i, 0);
6883 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6884 		    i < UFS_NIADDR;
6885 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6886 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6887 		ip->i_size = 0;
6888 		DIP_SET(ip, i_size, 0);
6889 		datablocks = DIP(ip, i_blocks) - extblocks;
6890 	}
6891 	if ((flags & IO_EXT) != 0) {
6892 		for (i = 0; i < UFS_NXADDR; i++)
6893 			setup_freeext(freeblks, ip, i, 0);
6894 		ip->i_din2->di_extsize = 0;
6895 		datablocks += extblocks;
6896 	}
6897 #ifdef QUOTA
6898 	/* Reference the quotas in case the block count is wrong in the end. */
6899 	quotaref(ITOV(ip), freeblks->fb_quota);
6900 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6901 #endif
6902 	freeblks->fb_chkcnt = -datablocks;
6903 	UFS_LOCK(ump);
6904 	fs->fs_pendingblocks += datablocks;
6905 	UFS_UNLOCK(ump);
6906 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6907 	/*
6908 	 * Push the zero'ed inode to its disk buffer so that we are free
6909 	 * to delete its dependencies below. Once the dependencies are gone
6910 	 * the buffer can be safely released.
6911 	 */
6912 	if (ump->um_fstype == UFS1) {
6913 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6914 		    ino_to_fsbo(fs, ip->i_number));
6915 		ip->i_din1->di_freelink = dp1->di_freelink;
6916 		*dp1 = *ip->i_din1;
6917 	} else {
6918 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6919 		    ino_to_fsbo(fs, ip->i_number));
6920 		ip->i_din2->di_freelink = dp2->di_freelink;
6921 		*dp2 = *ip->i_din2;
6922 	}
6923 	/*
6924 	 * Find and eliminate any inode dependencies.
6925 	 */
6926 	ACQUIRE_LOCK(ump);
6927 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6928 	if ((inodedep->id_state & IOSTARTED) != 0)
6929 		panic("softdep_setup_freeblocks: inode busy");
6930 	/*
6931 	 * Add the freeblks structure to the list of operations that
6932 	 * must await the zero'ed inode being written to disk. If we
6933 	 * still have a bitmap dependency (delay == 0), then the inode
6934 	 * has never been written to disk, so we can process the
6935 	 * freeblks below once we have deleted the dependencies.
6936 	 */
6937 	delay = (inodedep->id_state & DEPCOMPLETE);
6938 	if (delay)
6939 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6940 	else
6941 		freeblks->fb_state |= COMPLETE;
6942 	/*
6943 	 * Because the file length has been truncated to zero, any
6944 	 * pending block allocation dependency structures associated
6945 	 * with this inode are obsolete and can simply be de-allocated.
6946 	 * We must first merge the two dependency lists to get rid of
6947 	 * any duplicate freefrag structures, then purge the merged list.
6948 	 * If we still have a bitmap dependency, then the inode has never
6949 	 * been written to disk, so we can free any fragments without delay.
6950 	 */
6951 	if (flags & IO_NORMAL) {
6952 		merge_inode_lists(&inodedep->id_newinoupdt,
6953 		    &inodedep->id_inoupdt);
6954 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
6955 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
6956 			    freeblks);
6957 	}
6958 	if (flags & IO_EXT) {
6959 		merge_inode_lists(&inodedep->id_newextupdt,
6960 		    &inodedep->id_extupdt);
6961 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6962 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6963 			    freeblks);
6964 	}
6965 	FREE_LOCK(ump);
6966 	bdwrite(bp);
6967 	trunc_dependencies(ip, freeblks, -1, 0, flags);
6968 	ACQUIRE_LOCK(ump);
6969 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6970 		(void) free_inodedep(inodedep);
6971 	freeblks->fb_state |= DEPCOMPLETE;
6972 	/*
6973 	 * If the inode with zeroed block pointers is now on disk
6974 	 * we can start freeing blocks.
6975 	 */
6976 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6977 		freeblks->fb_state |= INPROGRESS;
6978 	else
6979 		freeblks = NULL;
6980 	FREE_LOCK(ump);
6981 	if (freeblks)
6982 		handle_workitem_freeblocks(freeblks, 0);
6983 	trunc_pages(ip, length, extblocks, flags);
6984 }
6985 
6986 /*
6987  * Eliminate pages from the page cache that back parts of this inode and
6988  * adjust the vnode pager's idea of our size.  This prevents stale data
6989  * from hanging around in the page cache.
6990  */
6991 static void
6992 trunc_pages(ip, length, extblocks, flags)
6993 	struct inode *ip;
6994 	off_t length;
6995 	ufs2_daddr_t extblocks;
6996 	int flags;
6997 {
6998 	struct vnode *vp;
6999 	struct fs *fs;
7000 	ufs_lbn_t lbn;
7001 	off_t end, extend;
7002 
7003 	vp = ITOV(ip);
7004 	fs = ITOFS(ip);
7005 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7006 	if ((flags & IO_EXT) != 0)
7007 		vn_pages_remove(vp, extend, 0);
7008 	if ((flags & IO_NORMAL) == 0)
7009 		return;
7010 	BO_LOCK(&vp->v_bufobj);
7011 	drain_output(vp);
7012 	BO_UNLOCK(&vp->v_bufobj);
7013 	/*
7014 	 * The vnode pager eliminates file pages we eliminate indirects
7015 	 * below.
7016 	 */
7017 	vnode_pager_setsize(vp, length);
7018 	/*
7019 	 * Calculate the end based on the last indirect we want to keep.  If
7020 	 * the block extends into indirects we can just use the negative of
7021 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7022 	 * be careful not to remove those, if they exist.  double and triple
7023 	 * indirect lbns do not overlap with others so it is not important
7024 	 * to verify how many levels are required.
7025 	 */
7026 	lbn = lblkno(fs, length);
7027 	if (lbn >= UFS_NDADDR) {
7028 		/* Calculate the virtual lbn of the triple indirect. */
7029 		lbn = -lbn - (UFS_NIADDR - 1);
7030 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7031 	} else
7032 		end = extend;
7033 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7034 }
7035 
7036 /*
7037  * See if the buf bp is in the range eliminated by truncation.
7038  */
7039 static int
7040 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7041 	struct buf *bp;
7042 	int *blkoffp;
7043 	ufs_lbn_t lastlbn;
7044 	int lastoff;
7045 	int flags;
7046 {
7047 	ufs_lbn_t lbn;
7048 
7049 	*blkoffp = 0;
7050 	/* Only match ext/normal blocks as appropriate. */
7051 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7052 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7053 		return (0);
7054 	/* ALTDATA is always a full truncation. */
7055 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7056 		return (1);
7057 	/* -1 is full truncation. */
7058 	if (lastlbn == -1)
7059 		return (1);
7060 	/*
7061 	 * If this is a partial truncate we only want those
7062 	 * blocks and indirect blocks that cover the range
7063 	 * we're after.
7064 	 */
7065 	lbn = bp->b_lblkno;
7066 	if (lbn < 0)
7067 		lbn = -(lbn + lbn_level(lbn));
7068 	if (lbn < lastlbn)
7069 		return (0);
7070 	/* Here we only truncate lblkno if it's partial. */
7071 	if (lbn == lastlbn) {
7072 		if (lastoff == 0)
7073 			return (0);
7074 		*blkoffp = lastoff;
7075 	}
7076 	return (1);
7077 }
7078 
7079 /*
7080  * Eliminate any dependencies that exist in memory beyond lblkno:off
7081  */
7082 static void
7083 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7084 	struct inode *ip;
7085 	struct freeblks *freeblks;
7086 	ufs_lbn_t lastlbn;
7087 	int lastoff;
7088 	int flags;
7089 {
7090 	struct bufobj *bo;
7091 	struct vnode *vp;
7092 	struct buf *bp;
7093 	int blkoff;
7094 
7095 	/*
7096 	 * We must wait for any I/O in progress to finish so that
7097 	 * all potential buffers on the dirty list will be visible.
7098 	 * Once they are all there, walk the list and get rid of
7099 	 * any dependencies.
7100 	 */
7101 	vp = ITOV(ip);
7102 	bo = &vp->v_bufobj;
7103 	BO_LOCK(bo);
7104 	drain_output(vp);
7105 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7106 		bp->b_vflags &= ~BV_SCANNED;
7107 restart:
7108 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7109 		if (bp->b_vflags & BV_SCANNED)
7110 			continue;
7111 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7112 			bp->b_vflags |= BV_SCANNED;
7113 			continue;
7114 		}
7115 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7116 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7117 			goto restart;
7118 		BO_UNLOCK(bo);
7119 		if (deallocate_dependencies(bp, freeblks, blkoff))
7120 			bqrelse(bp);
7121 		else
7122 			brelse(bp);
7123 		BO_LOCK(bo);
7124 		goto restart;
7125 	}
7126 	/*
7127 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7128 	 */
7129 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7130 		bp->b_vflags &= ~BV_SCANNED;
7131 cleanrestart:
7132 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7133 		if (bp->b_vflags & BV_SCANNED)
7134 			continue;
7135 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7136 			bp->b_vflags |= BV_SCANNED;
7137 			continue;
7138 		}
7139 		if (BUF_LOCK(bp,
7140 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7141 		    BO_LOCKPTR(bo)) == ENOLCK) {
7142 			BO_LOCK(bo);
7143 			goto cleanrestart;
7144 		}
7145 		bp->b_vflags |= BV_SCANNED;
7146 		bremfree(bp);
7147 		if (blkoff != 0) {
7148 			allocbuf(bp, blkoff);
7149 			bqrelse(bp);
7150 		} else {
7151 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7152 			brelse(bp);
7153 		}
7154 		BO_LOCK(bo);
7155 		goto cleanrestart;
7156 	}
7157 	drain_output(vp);
7158 	BO_UNLOCK(bo);
7159 }
7160 
7161 static int
7162 cancel_pagedep(pagedep, freeblks, blkoff)
7163 	struct pagedep *pagedep;
7164 	struct freeblks *freeblks;
7165 	int blkoff;
7166 {
7167 	struct jremref *jremref;
7168 	struct jmvref *jmvref;
7169 	struct dirrem *dirrem, *tmp;
7170 	int i;
7171 
7172 	/*
7173 	 * Copy any directory remove dependencies to the list
7174 	 * to be processed after the freeblks proceeds.  If
7175 	 * directory entry never made it to disk they
7176 	 * can be dumped directly onto the work list.
7177 	 */
7178 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7179 		/* Skip this directory removal if it is intended to remain. */
7180 		if (dirrem->dm_offset < blkoff)
7181 			continue;
7182 		/*
7183 		 * If there are any dirrems we wait for the journal write
7184 		 * to complete and then restart the buf scan as the lock
7185 		 * has been dropped.
7186 		 */
7187 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7188 			jwait(&jremref->jr_list, MNT_WAIT);
7189 			return (ERESTART);
7190 		}
7191 		LIST_REMOVE(dirrem, dm_next);
7192 		dirrem->dm_dirinum = pagedep->pd_ino;
7193 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7194 	}
7195 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7196 		jwait(&jmvref->jm_list, MNT_WAIT);
7197 		return (ERESTART);
7198 	}
7199 	/*
7200 	 * When we're partially truncating a pagedep we just want to flush
7201 	 * journal entries and return.  There can not be any adds in the
7202 	 * truncated portion of the directory and newblk must remain if
7203 	 * part of the block remains.
7204 	 */
7205 	if (blkoff != 0) {
7206 		struct diradd *dap;
7207 
7208 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7209 			if (dap->da_offset > blkoff)
7210 				panic("cancel_pagedep: diradd %p off %d > %d",
7211 				    dap, dap->da_offset, blkoff);
7212 		for (i = 0; i < DAHASHSZ; i++)
7213 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7214 				if (dap->da_offset > blkoff)
7215 					panic("cancel_pagedep: diradd %p off %d > %d",
7216 					    dap, dap->da_offset, blkoff);
7217 		return (0);
7218 	}
7219 	/*
7220 	 * There should be no directory add dependencies present
7221 	 * as the directory could not be truncated until all
7222 	 * children were removed.
7223 	 */
7224 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7225 	    ("deallocate_dependencies: pendinghd != NULL"));
7226 	for (i = 0; i < DAHASHSZ; i++)
7227 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7228 		    ("deallocate_dependencies: diraddhd != NULL"));
7229 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7230 		free_newdirblk(pagedep->pd_newdirblk);
7231 	if (free_pagedep(pagedep) == 0)
7232 		panic("Failed to free pagedep %p", pagedep);
7233 	return (0);
7234 }
7235 
7236 /*
7237  * Reclaim any dependency structures from a buffer that is about to
7238  * be reallocated to a new vnode. The buffer must be locked, thus,
7239  * no I/O completion operations can occur while we are manipulating
7240  * its associated dependencies. The mutex is held so that other I/O's
7241  * associated with related dependencies do not occur.
7242  */
7243 static int
7244 deallocate_dependencies(bp, freeblks, off)
7245 	struct buf *bp;
7246 	struct freeblks *freeblks;
7247 	int off;
7248 {
7249 	struct indirdep *indirdep;
7250 	struct pagedep *pagedep;
7251 	struct worklist *wk, *wkn;
7252 	struct ufsmount *ump;
7253 
7254 	ump = softdep_bp_to_mp(bp);
7255 	if (ump == NULL)
7256 		goto done;
7257 	ACQUIRE_LOCK(ump);
7258 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7259 		switch (wk->wk_type) {
7260 		case D_INDIRDEP:
7261 			indirdep = WK_INDIRDEP(wk);
7262 			if (bp->b_lblkno >= 0 ||
7263 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7264 				panic("deallocate_dependencies: not indir");
7265 			cancel_indirdep(indirdep, bp, freeblks);
7266 			continue;
7267 
7268 		case D_PAGEDEP:
7269 			pagedep = WK_PAGEDEP(wk);
7270 			if (cancel_pagedep(pagedep, freeblks, off)) {
7271 				FREE_LOCK(ump);
7272 				return (ERESTART);
7273 			}
7274 			continue;
7275 
7276 		case D_ALLOCINDIR:
7277 			/*
7278 			 * Simply remove the allocindir, we'll find it via
7279 			 * the indirdep where we can clear pointers if
7280 			 * needed.
7281 			 */
7282 			WORKLIST_REMOVE(wk);
7283 			continue;
7284 
7285 		case D_FREEWORK:
7286 			/*
7287 			 * A truncation is waiting for the zero'd pointers
7288 			 * to be written.  It can be freed when the freeblks
7289 			 * is journaled.
7290 			 */
7291 			WORKLIST_REMOVE(wk);
7292 			wk->wk_state |= ONDEPLIST;
7293 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7294 			break;
7295 
7296 		case D_ALLOCDIRECT:
7297 			if (off != 0)
7298 				continue;
7299 			/* FALLTHROUGH */
7300 		default:
7301 			panic("deallocate_dependencies: Unexpected type %s",
7302 			    TYPENAME(wk->wk_type));
7303 			/* NOTREACHED */
7304 		}
7305 	}
7306 	FREE_LOCK(ump);
7307 done:
7308 	/*
7309 	 * Don't throw away this buf, we were partially truncating and
7310 	 * some deps may always remain.
7311 	 */
7312 	if (off) {
7313 		allocbuf(bp, off);
7314 		bp->b_vflags |= BV_SCANNED;
7315 		return (EBUSY);
7316 	}
7317 	bp->b_flags |= B_INVAL | B_NOCACHE;
7318 
7319 	return (0);
7320 }
7321 
7322 /*
7323  * An allocdirect is being canceled due to a truncate.  We must make sure
7324  * the journal entry is released in concert with the blkfree that releases
7325  * the storage.  Completed journal entries must not be released until the
7326  * space is no longer pointed to by the inode or in the bitmap.
7327  */
7328 static void
7329 cancel_allocdirect(adphead, adp, freeblks)
7330 	struct allocdirectlst *adphead;
7331 	struct allocdirect *adp;
7332 	struct freeblks *freeblks;
7333 {
7334 	struct freework *freework;
7335 	struct newblk *newblk;
7336 	struct worklist *wk;
7337 
7338 	TAILQ_REMOVE(adphead, adp, ad_next);
7339 	newblk = (struct newblk *)adp;
7340 	freework = NULL;
7341 	/*
7342 	 * Find the correct freework structure.
7343 	 */
7344 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7345 		if (wk->wk_type != D_FREEWORK)
7346 			continue;
7347 		freework = WK_FREEWORK(wk);
7348 		if (freework->fw_blkno == newblk->nb_newblkno)
7349 			break;
7350 	}
7351 	if (freework == NULL)
7352 		panic("cancel_allocdirect: Freework not found");
7353 	/*
7354 	 * If a newblk exists at all we still have the journal entry that
7355 	 * initiated the allocation so we do not need to journal the free.
7356 	 */
7357 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7358 	/*
7359 	 * If the journal hasn't been written the jnewblk must be passed
7360 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7361 	 * this by linking the journal dependency into the freework to be
7362 	 * freed when freework_freeblock() is called.  If the journal has
7363 	 * been written we can simply reclaim the journal space when the
7364 	 * freeblks work is complete.
7365 	 */
7366 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7367 	    &freeblks->fb_jwork);
7368 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7369 }
7370 
7371 
7372 /*
7373  * Cancel a new block allocation.  May be an indirect or direct block.  We
7374  * remove it from various lists and return any journal record that needs to
7375  * be resolved by the caller.
7376  *
7377  * A special consideration is made for indirects which were never pointed
7378  * at on disk and will never be found once this block is released.
7379  */
7380 static struct jnewblk *
7381 cancel_newblk(newblk, wk, wkhd)
7382 	struct newblk *newblk;
7383 	struct worklist *wk;
7384 	struct workhead *wkhd;
7385 {
7386 	struct jnewblk *jnewblk;
7387 
7388 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7389 
7390 	newblk->nb_state |= GOINGAWAY;
7391 	/*
7392 	 * Previously we traversed the completedhd on each indirdep
7393 	 * attached to this newblk to cancel them and gather journal
7394 	 * work.  Since we need only the oldest journal segment and
7395 	 * the lowest point on the tree will always have the oldest
7396 	 * journal segment we are free to release the segments
7397 	 * of any subordinates and may leave the indirdep list to
7398 	 * indirdep_complete() when this newblk is freed.
7399 	 */
7400 	if (newblk->nb_state & ONDEPLIST) {
7401 		newblk->nb_state &= ~ONDEPLIST;
7402 		LIST_REMOVE(newblk, nb_deps);
7403 	}
7404 	if (newblk->nb_state & ONWORKLIST)
7405 		WORKLIST_REMOVE(&newblk->nb_list);
7406 	/*
7407 	 * If the journal entry hasn't been written we save a pointer to
7408 	 * the dependency that frees it until it is written or the
7409 	 * superseding operation completes.
7410 	 */
7411 	jnewblk = newblk->nb_jnewblk;
7412 	if (jnewblk != NULL && wk != NULL) {
7413 		newblk->nb_jnewblk = NULL;
7414 		jnewblk->jn_dep = wk;
7415 	}
7416 	if (!LIST_EMPTY(&newblk->nb_jwork))
7417 		jwork_move(wkhd, &newblk->nb_jwork);
7418 	/*
7419 	 * When truncating we must free the newdirblk early to remove
7420 	 * the pagedep from the hash before returning.
7421 	 */
7422 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7423 		free_newdirblk(WK_NEWDIRBLK(wk));
7424 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7425 		panic("cancel_newblk: extra newdirblk");
7426 
7427 	return (jnewblk);
7428 }
7429 
7430 /*
7431  * Schedule the freefrag associated with a newblk to be released once
7432  * the pointers are written and the previous block is no longer needed.
7433  */
7434 static void
7435 newblk_freefrag(newblk)
7436 	struct newblk *newblk;
7437 {
7438 	struct freefrag *freefrag;
7439 
7440 	if (newblk->nb_freefrag == NULL)
7441 		return;
7442 	freefrag = newblk->nb_freefrag;
7443 	newblk->nb_freefrag = NULL;
7444 	freefrag->ff_state |= COMPLETE;
7445 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7446 		add_to_worklist(&freefrag->ff_list, 0);
7447 }
7448 
7449 /*
7450  * Free a newblk. Generate a new freefrag work request if appropriate.
7451  * This must be called after the inode pointer and any direct block pointers
7452  * are valid or fully removed via truncate or frag extension.
7453  */
7454 static void
7455 free_newblk(newblk)
7456 	struct newblk *newblk;
7457 {
7458 	struct indirdep *indirdep;
7459 	struct worklist *wk;
7460 
7461 	KASSERT(newblk->nb_jnewblk == NULL,
7462 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7463 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7464 	    ("free_newblk: unclaimed newblk"));
7465 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7466 	newblk_freefrag(newblk);
7467 	if (newblk->nb_state & ONDEPLIST)
7468 		LIST_REMOVE(newblk, nb_deps);
7469 	if (newblk->nb_state & ONWORKLIST)
7470 		WORKLIST_REMOVE(&newblk->nb_list);
7471 	LIST_REMOVE(newblk, nb_hash);
7472 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7473 		free_newdirblk(WK_NEWDIRBLK(wk));
7474 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7475 		panic("free_newblk: extra newdirblk");
7476 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7477 		indirdep_complete(indirdep);
7478 	handle_jwork(&newblk->nb_jwork);
7479 	WORKITEM_FREE(newblk, D_NEWBLK);
7480 }
7481 
7482 /*
7483  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7484  * This routine must be called with splbio interrupts blocked.
7485  */
7486 static void
7487 free_newdirblk(newdirblk)
7488 	struct newdirblk *newdirblk;
7489 {
7490 	struct pagedep *pagedep;
7491 	struct diradd *dap;
7492 	struct worklist *wk;
7493 
7494 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7495 	WORKLIST_REMOVE(&newdirblk->db_list);
7496 	/*
7497 	 * If the pagedep is still linked onto the directory buffer
7498 	 * dependency chain, then some of the entries on the
7499 	 * pd_pendinghd list may not be committed to disk yet. In
7500 	 * this case, we will simply clear the NEWBLOCK flag and
7501 	 * let the pd_pendinghd list be processed when the pagedep
7502 	 * is next written. If the pagedep is no longer on the buffer
7503 	 * dependency chain, then all the entries on the pd_pending
7504 	 * list are committed to disk and we can free them here.
7505 	 */
7506 	pagedep = newdirblk->db_pagedep;
7507 	pagedep->pd_state &= ~NEWBLOCK;
7508 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7509 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7510 			free_diradd(dap, NULL);
7511 		/*
7512 		 * If no dependencies remain, the pagedep will be freed.
7513 		 */
7514 		free_pagedep(pagedep);
7515 	}
7516 	/* Should only ever be one item in the list. */
7517 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7518 		WORKLIST_REMOVE(wk);
7519 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7520 	}
7521 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7522 }
7523 
7524 /*
7525  * Prepare an inode to be freed. The actual free operation is not
7526  * done until the zero'ed inode has been written to disk.
7527  */
7528 void
7529 softdep_freefile(pvp, ino, mode)
7530 	struct vnode *pvp;
7531 	ino_t ino;
7532 	int mode;
7533 {
7534 	struct inode *ip = VTOI(pvp);
7535 	struct inodedep *inodedep;
7536 	struct freefile *freefile;
7537 	struct freeblks *freeblks;
7538 	struct ufsmount *ump;
7539 
7540 	ump = ITOUMP(ip);
7541 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7542 	    ("softdep_freefile called on non-softdep filesystem"));
7543 	/*
7544 	 * This sets up the inode de-allocation dependency.
7545 	 */
7546 	freefile = malloc(sizeof(struct freefile),
7547 		M_FREEFILE, M_SOFTDEP_FLAGS);
7548 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7549 	freefile->fx_mode = mode;
7550 	freefile->fx_oldinum = ino;
7551 	freefile->fx_devvp = ump->um_devvp;
7552 	LIST_INIT(&freefile->fx_jwork);
7553 	UFS_LOCK(ump);
7554 	ump->um_fs->fs_pendinginodes += 1;
7555 	UFS_UNLOCK(ump);
7556 
7557 	/*
7558 	 * If the inodedep does not exist, then the zero'ed inode has
7559 	 * been written to disk. If the allocated inode has never been
7560 	 * written to disk, then the on-disk inode is zero'ed. In either
7561 	 * case we can free the file immediately.  If the journal was
7562 	 * canceled before being written the inode will never make it to
7563 	 * disk and we must send the canceled journal entrys to
7564 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7565 	 * Any blocks waiting on the inode to write can be safely freed
7566 	 * here as it will never been written.
7567 	 */
7568 	ACQUIRE_LOCK(ump);
7569 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7570 	if (inodedep) {
7571 		/*
7572 		 * Clear out freeblks that no longer need to reference
7573 		 * this inode.
7574 		 */
7575 		while ((freeblks =
7576 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7577 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7578 			    fb_next);
7579 			freeblks->fb_state &= ~ONDEPLIST;
7580 		}
7581 		/*
7582 		 * Remove this inode from the unlinked list.
7583 		 */
7584 		if (inodedep->id_state & UNLINKED) {
7585 			/*
7586 			 * Save the journal work to be freed with the bitmap
7587 			 * before we clear UNLINKED.  Otherwise it can be lost
7588 			 * if the inode block is written.
7589 			 */
7590 			handle_bufwait(inodedep, &freefile->fx_jwork);
7591 			clear_unlinked_inodedep(inodedep);
7592 			/*
7593 			 * Re-acquire inodedep as we've dropped the
7594 			 * per-filesystem lock in clear_unlinked_inodedep().
7595 			 */
7596 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7597 		}
7598 	}
7599 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7600 		FREE_LOCK(ump);
7601 		handle_workitem_freefile(freefile);
7602 		return;
7603 	}
7604 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7605 		inodedep->id_state |= GOINGAWAY;
7606 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7607 	FREE_LOCK(ump);
7608 	if (ip->i_number == ino)
7609 		ip->i_flag |= IN_MODIFIED;
7610 }
7611 
7612 /*
7613  * Check to see if an inode has never been written to disk. If
7614  * so free the inodedep and return success, otherwise return failure.
7615  * This routine must be called with splbio interrupts blocked.
7616  *
7617  * If we still have a bitmap dependency, then the inode has never
7618  * been written to disk. Drop the dependency as it is no longer
7619  * necessary since the inode is being deallocated. We set the
7620  * ALLCOMPLETE flags since the bitmap now properly shows that the
7621  * inode is not allocated. Even if the inode is actively being
7622  * written, it has been rolled back to its zero'ed state, so we
7623  * are ensured that a zero inode is what is on the disk. For short
7624  * lived files, this change will usually result in removing all the
7625  * dependencies from the inode so that it can be freed immediately.
7626  */
7627 static int
7628 check_inode_unwritten(inodedep)
7629 	struct inodedep *inodedep;
7630 {
7631 
7632 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7633 
7634 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7635 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7636 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7637 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7638 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7639 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7640 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7641 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7642 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7643 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7644 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7645 	    inodedep->id_mkdiradd != NULL ||
7646 	    inodedep->id_nlinkdelta != 0)
7647 		return (0);
7648 	/*
7649 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7650 	 * trying to allocate memory without holding "Softdep Lock".
7651 	 */
7652 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7653 	    inodedep->id_savedino1 == NULL)
7654 		return (0);
7655 
7656 	if (inodedep->id_state & ONDEPLIST)
7657 		LIST_REMOVE(inodedep, id_deps);
7658 	inodedep->id_state &= ~ONDEPLIST;
7659 	inodedep->id_state |= ALLCOMPLETE;
7660 	inodedep->id_bmsafemap = NULL;
7661 	if (inodedep->id_state & ONWORKLIST)
7662 		WORKLIST_REMOVE(&inodedep->id_list);
7663 	if (inodedep->id_savedino1 != NULL) {
7664 		free(inodedep->id_savedino1, M_SAVEDINO);
7665 		inodedep->id_savedino1 = NULL;
7666 	}
7667 	if (free_inodedep(inodedep) == 0)
7668 		panic("check_inode_unwritten: busy inode");
7669 	return (1);
7670 }
7671 
7672 static int
7673 check_inodedep_free(inodedep)
7674 	struct inodedep *inodedep;
7675 {
7676 
7677 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7678 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7679 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7680 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7681 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7682 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7683 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7684 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7685 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7686 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7687 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7688 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7689 	    inodedep->id_mkdiradd != NULL ||
7690 	    inodedep->id_nlinkdelta != 0 ||
7691 	    inodedep->id_savedino1 != NULL)
7692 		return (0);
7693 	return (1);
7694 }
7695 
7696 /*
7697  * Try to free an inodedep structure. Return 1 if it could be freed.
7698  */
7699 static int
7700 free_inodedep(inodedep)
7701 	struct inodedep *inodedep;
7702 {
7703 
7704 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7705 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7706 	    !check_inodedep_free(inodedep))
7707 		return (0);
7708 	if (inodedep->id_state & ONDEPLIST)
7709 		LIST_REMOVE(inodedep, id_deps);
7710 	LIST_REMOVE(inodedep, id_hash);
7711 	WORKITEM_FREE(inodedep, D_INODEDEP);
7712 	return (1);
7713 }
7714 
7715 /*
7716  * Free the block referenced by a freework structure.  The parent freeblks
7717  * structure is released and completed when the final cg bitmap reaches
7718  * the disk.  This routine may be freeing a jnewblk which never made it to
7719  * disk in which case we do not have to wait as the operation is undone
7720  * in memory immediately.
7721  */
7722 static void
7723 freework_freeblock(freework)
7724 	struct freework *freework;
7725 {
7726 	struct freeblks *freeblks;
7727 	struct jnewblk *jnewblk;
7728 	struct ufsmount *ump;
7729 	struct workhead wkhd;
7730 	struct fs *fs;
7731 	int bsize;
7732 	int needj;
7733 
7734 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7735 	LOCK_OWNED(ump);
7736 	/*
7737 	 * Handle partial truncate separately.
7738 	 */
7739 	if (freework->fw_indir) {
7740 		complete_trunc_indir(freework);
7741 		return;
7742 	}
7743 	freeblks = freework->fw_freeblks;
7744 	fs = ump->um_fs;
7745 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7746 	bsize = lfragtosize(fs, freework->fw_frags);
7747 	LIST_INIT(&wkhd);
7748 	/*
7749 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7750 	 * on the indirblk hashtable and prevents premature freeing.
7751 	 */
7752 	freework->fw_state |= DEPCOMPLETE;
7753 	/*
7754 	 * SUJ needs to wait for the segment referencing freed indirect
7755 	 * blocks to expire so that we know the checker will not confuse
7756 	 * a re-allocated indirect block with its old contents.
7757 	 */
7758 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7759 		indirblk_insert(freework);
7760 	/*
7761 	 * If we are canceling an existing jnewblk pass it to the free
7762 	 * routine, otherwise pass the freeblk which will ultimately
7763 	 * release the freeblks.  If we're not journaling, we can just
7764 	 * free the freeblks immediately.
7765 	 */
7766 	jnewblk = freework->fw_jnewblk;
7767 	if (jnewblk != NULL) {
7768 		cancel_jnewblk(jnewblk, &wkhd);
7769 		needj = 0;
7770 	} else if (needj) {
7771 		freework->fw_state |= DELAYEDFREE;
7772 		freeblks->fb_cgwait++;
7773 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7774 	}
7775 	FREE_LOCK(ump);
7776 	freeblks_free(ump, freeblks, btodb(bsize));
7777 	CTR4(KTR_SUJ,
7778 	    "freework_freeblock: ino %d blkno %jd lbn %jd size %ld",
7779 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7780 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7781 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7782 	ACQUIRE_LOCK(ump);
7783 	/*
7784 	 * The jnewblk will be discarded and the bits in the map never
7785 	 * made it to disk.  We can immediately free the freeblk.
7786 	 */
7787 	if (needj == 0)
7788 		handle_written_freework(freework);
7789 }
7790 
7791 /*
7792  * We enqueue freework items that need processing back on the freeblks and
7793  * add the freeblks to the worklist.  This makes it easier to find all work
7794  * required to flush a truncation in process_truncates().
7795  */
7796 static void
7797 freework_enqueue(freework)
7798 	struct freework *freework;
7799 {
7800 	struct freeblks *freeblks;
7801 
7802 	freeblks = freework->fw_freeblks;
7803 	if ((freework->fw_state & INPROGRESS) == 0)
7804 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7805 	if ((freeblks->fb_state &
7806 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7807 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7808 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7809 }
7810 
7811 /*
7812  * Start, continue, or finish the process of freeing an indirect block tree.
7813  * The free operation may be paused at any point with fw_off containing the
7814  * offset to restart from.  This enables us to implement some flow control
7815  * for large truncates which may fan out and generate a huge number of
7816  * dependencies.
7817  */
7818 static void
7819 handle_workitem_indirblk(freework)
7820 	struct freework *freework;
7821 {
7822 	struct freeblks *freeblks;
7823 	struct ufsmount *ump;
7824 	struct fs *fs;
7825 
7826 	freeblks = freework->fw_freeblks;
7827 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7828 	fs = ump->um_fs;
7829 	if (freework->fw_state & DEPCOMPLETE) {
7830 		handle_written_freework(freework);
7831 		return;
7832 	}
7833 	if (freework->fw_off == NINDIR(fs)) {
7834 		freework_freeblock(freework);
7835 		return;
7836 	}
7837 	freework->fw_state |= INPROGRESS;
7838 	FREE_LOCK(ump);
7839 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7840 	    freework->fw_lbn);
7841 	ACQUIRE_LOCK(ump);
7842 }
7843 
7844 /*
7845  * Called when a freework structure attached to a cg buf is written.  The
7846  * ref on either the parent or the freeblks structure is released and
7847  * the freeblks is added back to the worklist if there is more work to do.
7848  */
7849 static void
7850 handle_written_freework(freework)
7851 	struct freework *freework;
7852 {
7853 	struct freeblks *freeblks;
7854 	struct freework *parent;
7855 
7856 	freeblks = freework->fw_freeblks;
7857 	parent = freework->fw_parent;
7858 	if (freework->fw_state & DELAYEDFREE)
7859 		freeblks->fb_cgwait--;
7860 	freework->fw_state |= COMPLETE;
7861 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7862 		WORKITEM_FREE(freework, D_FREEWORK);
7863 	if (parent) {
7864 		if (--parent->fw_ref == 0)
7865 			freework_enqueue(parent);
7866 		return;
7867 	}
7868 	if (--freeblks->fb_ref != 0)
7869 		return;
7870 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7871 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7872 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7873 }
7874 
7875 /*
7876  * This workitem routine performs the block de-allocation.
7877  * The workitem is added to the pending list after the updated
7878  * inode block has been written to disk.  As mentioned above,
7879  * checks regarding the number of blocks de-allocated (compared
7880  * to the number of blocks allocated for the file) are also
7881  * performed in this function.
7882  */
7883 static int
7884 handle_workitem_freeblocks(freeblks, flags)
7885 	struct freeblks *freeblks;
7886 	int flags;
7887 {
7888 	struct freework *freework;
7889 	struct newblk *newblk;
7890 	struct allocindir *aip;
7891 	struct ufsmount *ump;
7892 	struct worklist *wk;
7893 
7894 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7895 	    ("handle_workitem_freeblocks: Journal entries not written."));
7896 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7897 	ACQUIRE_LOCK(ump);
7898 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7899 		WORKLIST_REMOVE(wk);
7900 		switch (wk->wk_type) {
7901 		case D_DIRREM:
7902 			wk->wk_state |= COMPLETE;
7903 			add_to_worklist(wk, 0);
7904 			continue;
7905 
7906 		case D_ALLOCDIRECT:
7907 			free_newblk(WK_NEWBLK(wk));
7908 			continue;
7909 
7910 		case D_ALLOCINDIR:
7911 			aip = WK_ALLOCINDIR(wk);
7912 			freework = NULL;
7913 			if (aip->ai_state & DELAYEDFREE) {
7914 				FREE_LOCK(ump);
7915 				freework = newfreework(ump, freeblks, NULL,
7916 				    aip->ai_lbn, aip->ai_newblkno,
7917 				    ump->um_fs->fs_frag, 0, 0);
7918 				ACQUIRE_LOCK(ump);
7919 			}
7920 			newblk = WK_NEWBLK(wk);
7921 			if (newblk->nb_jnewblk) {
7922 				freework->fw_jnewblk = newblk->nb_jnewblk;
7923 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7924 				newblk->nb_jnewblk = NULL;
7925 			}
7926 			free_newblk(newblk);
7927 			continue;
7928 
7929 		case D_FREEWORK:
7930 			freework = WK_FREEWORK(wk);
7931 			if (freework->fw_lbn <= -UFS_NDADDR)
7932 				handle_workitem_indirblk(freework);
7933 			else
7934 				freework_freeblock(freework);
7935 			continue;
7936 		default:
7937 			panic("handle_workitem_freeblocks: Unknown type %s",
7938 			    TYPENAME(wk->wk_type));
7939 		}
7940 	}
7941 	if (freeblks->fb_ref != 0) {
7942 		freeblks->fb_state &= ~INPROGRESS;
7943 		wake_worklist(&freeblks->fb_list);
7944 		freeblks = NULL;
7945 	}
7946 	FREE_LOCK(ump);
7947 	if (freeblks)
7948 		return handle_complete_freeblocks(freeblks, flags);
7949 	return (0);
7950 }
7951 
7952 /*
7953  * Handle completion of block free via truncate.  This allows fs_pending
7954  * to track the actual free block count more closely than if we only updated
7955  * it at the end.  We must be careful to handle cases where the block count
7956  * on free was incorrect.
7957  */
7958 static void
7959 freeblks_free(ump, freeblks, blocks)
7960 	struct ufsmount *ump;
7961 	struct freeblks *freeblks;
7962 	int blocks;
7963 {
7964 	struct fs *fs;
7965 	ufs2_daddr_t remain;
7966 
7967 	UFS_LOCK(ump);
7968 	remain = -freeblks->fb_chkcnt;
7969 	freeblks->fb_chkcnt += blocks;
7970 	if (remain > 0) {
7971 		if (remain < blocks)
7972 			blocks = remain;
7973 		fs = ump->um_fs;
7974 		fs->fs_pendingblocks -= blocks;
7975 	}
7976 	UFS_UNLOCK(ump);
7977 }
7978 
7979 /*
7980  * Once all of the freework workitems are complete we can retire the
7981  * freeblocks dependency and any journal work awaiting completion.  This
7982  * can not be called until all other dependencies are stable on disk.
7983  */
7984 static int
7985 handle_complete_freeblocks(freeblks, flags)
7986 	struct freeblks *freeblks;
7987 	int flags;
7988 {
7989 	struct inodedep *inodedep;
7990 	struct inode *ip;
7991 	struct vnode *vp;
7992 	struct fs *fs;
7993 	struct ufsmount *ump;
7994 	ufs2_daddr_t spare;
7995 
7996 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7997 	fs = ump->um_fs;
7998 	flags = LK_EXCLUSIVE | flags;
7999 	spare = freeblks->fb_chkcnt;
8000 
8001 	/*
8002 	 * If we did not release the expected number of blocks we may have
8003 	 * to adjust the inode block count here.  Only do so if it wasn't
8004 	 * a truncation to zero and the modrev still matches.
8005 	 */
8006 	if (spare && freeblks->fb_len != 0) {
8007 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8008 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8009 			return (EBUSY);
8010 		ip = VTOI(vp);
8011 		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8012 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8013 			ip->i_flag |= IN_CHANGE;
8014 			/*
8015 			 * We must wait so this happens before the
8016 			 * journal is reclaimed.
8017 			 */
8018 			ffs_update(vp, 1);
8019 		}
8020 		vput(vp);
8021 	}
8022 	if (spare < 0) {
8023 		UFS_LOCK(ump);
8024 		fs->fs_pendingblocks += spare;
8025 		UFS_UNLOCK(ump);
8026 	}
8027 #ifdef QUOTA
8028 	/* Handle spare. */
8029 	if (spare)
8030 		quotaadj(freeblks->fb_quota, ump, -spare);
8031 	quotarele(freeblks->fb_quota);
8032 #endif
8033 	ACQUIRE_LOCK(ump);
8034 	if (freeblks->fb_state & ONDEPLIST) {
8035 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8036 		    0, &inodedep);
8037 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8038 		freeblks->fb_state &= ~ONDEPLIST;
8039 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8040 			free_inodedep(inodedep);
8041 	}
8042 	/*
8043 	 * All of the freeblock deps must be complete prior to this call
8044 	 * so it's now safe to complete earlier outstanding journal entries.
8045 	 */
8046 	handle_jwork(&freeblks->fb_jwork);
8047 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8048 	FREE_LOCK(ump);
8049 	return (0);
8050 }
8051 
8052 /*
8053  * Release blocks associated with the freeblks and stored in the indirect
8054  * block dbn. If level is greater than SINGLE, the block is an indirect block
8055  * and recursive calls to indirtrunc must be used to cleanse other indirect
8056  * blocks.
8057  *
8058  * This handles partial and complete truncation of blocks.  Partial is noted
8059  * with goingaway == 0.  In this case the freework is completed after the
8060  * zero'd indirects are written to disk.  For full truncation the freework
8061  * is completed after the block is freed.
8062  */
8063 static void
8064 indir_trunc(freework, dbn, lbn)
8065 	struct freework *freework;
8066 	ufs2_daddr_t dbn;
8067 	ufs_lbn_t lbn;
8068 {
8069 	struct freework *nfreework;
8070 	struct workhead wkhd;
8071 	struct freeblks *freeblks;
8072 	struct buf *bp;
8073 	struct fs *fs;
8074 	struct indirdep *indirdep;
8075 	struct ufsmount *ump;
8076 	ufs1_daddr_t *bap1;
8077 	ufs2_daddr_t nb, nnb, *bap2;
8078 	ufs_lbn_t lbnadd, nlbn;
8079 	int i, nblocks, ufs1fmt;
8080 	int freedblocks;
8081 	int goingaway;
8082 	int freedeps;
8083 	int needj;
8084 	int level;
8085 	int cnt;
8086 
8087 	freeblks = freework->fw_freeblks;
8088 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8089 	fs = ump->um_fs;
8090 	/*
8091 	 * Get buffer of block pointers to be freed.  There are three cases:
8092 	 *
8093 	 * 1) Partial truncate caches the indirdep pointer in the freework
8094 	 *    which provides us a back copy to the save bp which holds the
8095 	 *    pointers we want to clear.  When this completes the zero
8096 	 *    pointers are written to the real copy.
8097 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8098 	 *    eliminated the real copy and placed the indirdep on the saved
8099 	 *    copy.  The indirdep and buf are discarded when this completes.
8100 	 * 3) The indirect was not in memory, we read a copy off of the disk
8101 	 *    using the devvp and drop and invalidate the buffer when we're
8102 	 *    done.
8103 	 */
8104 	goingaway = 1;
8105 	indirdep = NULL;
8106 	if (freework->fw_indir != NULL) {
8107 		goingaway = 0;
8108 		indirdep = freework->fw_indir;
8109 		bp = indirdep->ir_savebp;
8110 		if (bp == NULL || bp->b_blkno != dbn)
8111 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8112 			    bp, (intmax_t)dbn);
8113 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8114 		/*
8115 		 * The lock prevents the buf dep list from changing and
8116 	 	 * indirects on devvp should only ever have one dependency.
8117 		 */
8118 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8119 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8120 			panic("indir_trunc: Bad indirdep %p from buf %p",
8121 			    indirdep, bp);
8122 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8123 	    NOCRED, &bp) != 0) {
8124 		brelse(bp);
8125 		return;
8126 	}
8127 	ACQUIRE_LOCK(ump);
8128 	/* Protects against a race with complete_trunc_indir(). */
8129 	freework->fw_state &= ~INPROGRESS;
8130 	/*
8131 	 * If we have an indirdep we need to enforce the truncation order
8132 	 * and discard it when it is complete.
8133 	 */
8134 	if (indirdep) {
8135 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8136 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8137 			/*
8138 			 * Add the complete truncate to the list on the
8139 			 * indirdep to enforce in-order processing.
8140 			 */
8141 			if (freework->fw_indir == NULL)
8142 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8143 				    freework, fw_next);
8144 			FREE_LOCK(ump);
8145 			return;
8146 		}
8147 		/*
8148 		 * If we're goingaway, free the indirdep.  Otherwise it will
8149 		 * linger until the write completes.
8150 		 */
8151 		if (goingaway)
8152 			free_indirdep(indirdep);
8153 	}
8154 	FREE_LOCK(ump);
8155 	/* Initialize pointers depending on block size. */
8156 	if (ump->um_fstype == UFS1) {
8157 		bap1 = (ufs1_daddr_t *)bp->b_data;
8158 		nb = bap1[freework->fw_off];
8159 		ufs1fmt = 1;
8160 		bap2 = NULL;
8161 	} else {
8162 		bap2 = (ufs2_daddr_t *)bp->b_data;
8163 		nb = bap2[freework->fw_off];
8164 		ufs1fmt = 0;
8165 		bap1 = NULL;
8166 	}
8167 	level = lbn_level(lbn);
8168 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8169 	lbnadd = lbn_offset(fs, level);
8170 	nblocks = btodb(fs->fs_bsize);
8171 	nfreework = freework;
8172 	freedeps = 0;
8173 	cnt = 0;
8174 	/*
8175 	 * Reclaim blocks.  Traverses into nested indirect levels and
8176 	 * arranges for the current level to be freed when subordinates
8177 	 * are free when journaling.
8178 	 */
8179 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8180 		if (i != NINDIR(fs) - 1) {
8181 			if (ufs1fmt)
8182 				nnb = bap1[i+1];
8183 			else
8184 				nnb = bap2[i+1];
8185 		} else
8186 			nnb = 0;
8187 		if (nb == 0)
8188 			continue;
8189 		cnt++;
8190 		if (level != 0) {
8191 			nlbn = (lbn + 1) - (i * lbnadd);
8192 			if (needj != 0) {
8193 				nfreework = newfreework(ump, freeblks, freework,
8194 				    nlbn, nb, fs->fs_frag, 0, 0);
8195 				freedeps++;
8196 			}
8197 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8198 		} else {
8199 			struct freedep *freedep;
8200 
8201 			/*
8202 			 * Attempt to aggregate freedep dependencies for
8203 			 * all blocks being released to the same CG.
8204 			 */
8205 			LIST_INIT(&wkhd);
8206 			if (needj != 0 &&
8207 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8208 				freedep = newfreedep(freework);
8209 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8210 				    &freedep->fd_list);
8211 				freedeps++;
8212 			}
8213 			CTR3(KTR_SUJ,
8214 			    "indir_trunc: ino %d blkno %jd size %ld",
8215 			    freeblks->fb_inum, nb, fs->fs_bsize);
8216 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8217 			    fs->fs_bsize, freeblks->fb_inum,
8218 			    freeblks->fb_vtype, &wkhd);
8219 		}
8220 	}
8221 	if (goingaway) {
8222 		bp->b_flags |= B_INVAL | B_NOCACHE;
8223 		brelse(bp);
8224 	}
8225 	freedblocks = 0;
8226 	if (level == 0)
8227 		freedblocks = (nblocks * cnt);
8228 	if (needj == 0)
8229 		freedblocks += nblocks;
8230 	freeblks_free(ump, freeblks, freedblocks);
8231 	/*
8232 	 * If we are journaling set up the ref counts and offset so this
8233 	 * indirect can be completed when its children are free.
8234 	 */
8235 	if (needj) {
8236 		ACQUIRE_LOCK(ump);
8237 		freework->fw_off = i;
8238 		freework->fw_ref += freedeps;
8239 		freework->fw_ref -= NINDIR(fs) + 1;
8240 		if (level == 0)
8241 			freeblks->fb_cgwait += freedeps;
8242 		if (freework->fw_ref == 0)
8243 			freework_freeblock(freework);
8244 		FREE_LOCK(ump);
8245 		return;
8246 	}
8247 	/*
8248 	 * If we're not journaling we can free the indirect now.
8249 	 */
8250 	dbn = dbtofsb(fs, dbn);
8251 	CTR3(KTR_SUJ,
8252 	    "indir_trunc 2: ino %d blkno %jd size %ld",
8253 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8254 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8255 	    freeblks->fb_inum, freeblks->fb_vtype, NULL);
8256 	/* Non SUJ softdep does single-threaded truncations. */
8257 	if (freework->fw_blkno == dbn) {
8258 		freework->fw_state |= ALLCOMPLETE;
8259 		ACQUIRE_LOCK(ump);
8260 		handle_written_freework(freework);
8261 		FREE_LOCK(ump);
8262 	}
8263 	return;
8264 }
8265 
8266 /*
8267  * Cancel an allocindir when it is removed via truncation.  When bp is not
8268  * NULL the indirect never appeared on disk and is scheduled to be freed
8269  * independently of the indir so we can more easily track journal work.
8270  */
8271 static void
8272 cancel_allocindir(aip, bp, freeblks, trunc)
8273 	struct allocindir *aip;
8274 	struct buf *bp;
8275 	struct freeblks *freeblks;
8276 	int trunc;
8277 {
8278 	struct indirdep *indirdep;
8279 	struct freefrag *freefrag;
8280 	struct newblk *newblk;
8281 
8282 	newblk = (struct newblk *)aip;
8283 	LIST_REMOVE(aip, ai_next);
8284 	/*
8285 	 * We must eliminate the pointer in bp if it must be freed on its
8286 	 * own due to partial truncate or pending journal work.
8287 	 */
8288 	if (bp && (trunc || newblk->nb_jnewblk)) {
8289 		/*
8290 		 * Clear the pointer and mark the aip to be freed
8291 		 * directly if it never existed on disk.
8292 		 */
8293 		aip->ai_state |= DELAYEDFREE;
8294 		indirdep = aip->ai_indirdep;
8295 		if (indirdep->ir_state & UFS1FMT)
8296 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8297 		else
8298 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8299 	}
8300 	/*
8301 	 * When truncating the previous pointer will be freed via
8302 	 * savedbp.  Eliminate the freefrag which would dup free.
8303 	 */
8304 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8305 		newblk->nb_freefrag = NULL;
8306 		if (freefrag->ff_jdep)
8307 			cancel_jfreefrag(
8308 			    WK_JFREEFRAG(freefrag->ff_jdep));
8309 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8310 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8311 	}
8312 	/*
8313 	 * If the journal hasn't been written the jnewblk must be passed
8314 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8315 	 * this by leaving the journal dependency on the newblk to be freed
8316 	 * when a freework is created in handle_workitem_freeblocks().
8317 	 */
8318 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8319 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8320 }
8321 
8322 /*
8323  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8324  * in to a newdirblk so any subsequent additions are tracked properly.  The
8325  * caller is responsible for adding the mkdir1 dependency to the journal
8326  * and updating id_mkdiradd.  This function returns with the per-filesystem
8327  * lock held.
8328  */
8329 static struct mkdir *
8330 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8331 	struct diradd *dap;
8332 	ino_t newinum;
8333 	ino_t dinum;
8334 	struct buf *newdirbp;
8335 	struct mkdir **mkdirp;
8336 {
8337 	struct newblk *newblk;
8338 	struct pagedep *pagedep;
8339 	struct inodedep *inodedep;
8340 	struct newdirblk *newdirblk;
8341 	struct mkdir *mkdir1, *mkdir2;
8342 	struct worklist *wk;
8343 	struct jaddref *jaddref;
8344 	struct ufsmount *ump;
8345 	struct mount *mp;
8346 
8347 	mp = dap->da_list.wk_mp;
8348 	ump = VFSTOUFS(mp);
8349 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8350 	    M_SOFTDEP_FLAGS);
8351 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8352 	LIST_INIT(&newdirblk->db_mkdir);
8353 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8354 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8355 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8356 	mkdir1->md_diradd = dap;
8357 	mkdir1->md_jaddref = NULL;
8358 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8359 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8360 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8361 	mkdir2->md_diradd = dap;
8362 	mkdir2->md_jaddref = NULL;
8363 	if (MOUNTEDSUJ(mp) == 0) {
8364 		mkdir1->md_state |= DEPCOMPLETE;
8365 		mkdir2->md_state |= DEPCOMPLETE;
8366 	}
8367 	/*
8368 	 * Dependency on "." and ".." being written to disk.
8369 	 */
8370 	mkdir1->md_buf = newdirbp;
8371 	ACQUIRE_LOCK(VFSTOUFS(mp));
8372 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8373 	/*
8374 	 * We must link the pagedep, allocdirect, and newdirblk for
8375 	 * the initial file page so the pointer to the new directory
8376 	 * is not written until the directory contents are live and
8377 	 * any subsequent additions are not marked live until the
8378 	 * block is reachable via the inode.
8379 	 */
8380 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8381 		panic("setup_newdir: lost pagedep");
8382 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8383 		if (wk->wk_type == D_ALLOCDIRECT)
8384 			break;
8385 	if (wk == NULL)
8386 		panic("setup_newdir: lost allocdirect");
8387 	if (pagedep->pd_state & NEWBLOCK)
8388 		panic("setup_newdir: NEWBLOCK already set");
8389 	newblk = WK_NEWBLK(wk);
8390 	pagedep->pd_state |= NEWBLOCK;
8391 	pagedep->pd_newdirblk = newdirblk;
8392 	newdirblk->db_pagedep = pagedep;
8393 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8394 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8395 	/*
8396 	 * Look up the inodedep for the parent directory so that we
8397 	 * can link mkdir2 into the pending dotdot jaddref or
8398 	 * the inode write if there is none.  If the inode is
8399 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8400 	 * been satisfied and mkdir2 can be freed.
8401 	 */
8402 	inodedep_lookup(mp, dinum, 0, &inodedep);
8403 	if (MOUNTEDSUJ(mp)) {
8404 		if (inodedep == NULL)
8405 			panic("setup_newdir: Lost parent.");
8406 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8407 		    inoreflst);
8408 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8409 		    (jaddref->ja_state & MKDIR_PARENT),
8410 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8411 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8412 		mkdir2->md_jaddref = jaddref;
8413 		jaddref->ja_mkdir = mkdir2;
8414 	} else if (inodedep == NULL ||
8415 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8416 		dap->da_state &= ~MKDIR_PARENT;
8417 		WORKITEM_FREE(mkdir2, D_MKDIR);
8418 		mkdir2 = NULL;
8419 	} else {
8420 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8421 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8422 	}
8423 	*mkdirp = mkdir2;
8424 
8425 	return (mkdir1);
8426 }
8427 
8428 /*
8429  * Directory entry addition dependencies.
8430  *
8431  * When adding a new directory entry, the inode (with its incremented link
8432  * count) must be written to disk before the directory entry's pointer to it.
8433  * Also, if the inode is newly allocated, the corresponding freemap must be
8434  * updated (on disk) before the directory entry's pointer. These requirements
8435  * are met via undo/redo on the directory entry's pointer, which consists
8436  * simply of the inode number.
8437  *
8438  * As directory entries are added and deleted, the free space within a
8439  * directory block can become fragmented.  The ufs filesystem will compact
8440  * a fragmented directory block to make space for a new entry. When this
8441  * occurs, the offsets of previously added entries change. Any "diradd"
8442  * dependency structures corresponding to these entries must be updated with
8443  * the new offsets.
8444  */
8445 
8446 /*
8447  * This routine is called after the in-memory inode's link
8448  * count has been incremented, but before the directory entry's
8449  * pointer to the inode has been set.
8450  */
8451 int
8452 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8453 	struct buf *bp;		/* buffer containing directory block */
8454 	struct inode *dp;	/* inode for directory */
8455 	off_t diroffset;	/* offset of new entry in directory */
8456 	ino_t newinum;		/* inode referenced by new directory entry */
8457 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8458 	int isnewblk;		/* entry is in a newly allocated block */
8459 {
8460 	int offset;		/* offset of new entry within directory block */
8461 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8462 	struct fs *fs;
8463 	struct diradd *dap;
8464 	struct newblk *newblk;
8465 	struct pagedep *pagedep;
8466 	struct inodedep *inodedep;
8467 	struct newdirblk *newdirblk;
8468 	struct mkdir *mkdir1, *mkdir2;
8469 	struct jaddref *jaddref;
8470 	struct ufsmount *ump;
8471 	struct mount *mp;
8472 	int isindir;
8473 
8474 	mp = ITOVFS(dp);
8475 	ump = VFSTOUFS(mp);
8476 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8477 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8478 	/*
8479 	 * Whiteouts have no dependencies.
8480 	 */
8481 	if (newinum == UFS_WINO) {
8482 		if (newdirbp != NULL)
8483 			bdwrite(newdirbp);
8484 		return (0);
8485 	}
8486 	jaddref = NULL;
8487 	mkdir1 = mkdir2 = NULL;
8488 	fs = ump->um_fs;
8489 	lbn = lblkno(fs, diroffset);
8490 	offset = blkoff(fs, diroffset);
8491 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8492 		M_SOFTDEP_FLAGS|M_ZERO);
8493 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8494 	dap->da_offset = offset;
8495 	dap->da_newinum = newinum;
8496 	dap->da_state = ATTACHED;
8497 	LIST_INIT(&dap->da_jwork);
8498 	isindir = bp->b_lblkno >= UFS_NDADDR;
8499 	newdirblk = NULL;
8500 	if (isnewblk &&
8501 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8502 		newdirblk = malloc(sizeof(struct newdirblk),
8503 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8504 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8505 		LIST_INIT(&newdirblk->db_mkdir);
8506 	}
8507 	/*
8508 	 * If we're creating a new directory setup the dependencies and set
8509 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8510 	 * we can move on.
8511 	 */
8512 	if (newdirbp == NULL) {
8513 		dap->da_state |= DEPCOMPLETE;
8514 		ACQUIRE_LOCK(ump);
8515 	} else {
8516 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8517 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8518 		    &mkdir2);
8519 	}
8520 	/*
8521 	 * Link into parent directory pagedep to await its being written.
8522 	 */
8523 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8524 #ifdef DEBUG
8525 	if (diradd_lookup(pagedep, offset) != NULL)
8526 		panic("softdep_setup_directory_add: %p already at off %d\n",
8527 		    diradd_lookup(pagedep, offset), offset);
8528 #endif
8529 	dap->da_pagedep = pagedep;
8530 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8531 	    da_pdlist);
8532 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8533 	/*
8534 	 * If we're journaling, link the diradd into the jaddref so it
8535 	 * may be completed after the journal entry is written.  Otherwise,
8536 	 * link the diradd into its inodedep.  If the inode is not yet
8537 	 * written place it on the bufwait list, otherwise do the post-inode
8538 	 * write processing to put it on the id_pendinghd list.
8539 	 */
8540 	if (MOUNTEDSUJ(mp)) {
8541 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8542 		    inoreflst);
8543 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8544 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8545 		jaddref->ja_diroff = diroffset;
8546 		jaddref->ja_diradd = dap;
8547 		add_to_journal(&jaddref->ja_list);
8548 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8549 		diradd_inode_written(dap, inodedep);
8550 	else
8551 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8552 	/*
8553 	 * Add the journal entries for . and .. links now that the primary
8554 	 * link is written.
8555 	 */
8556 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8557 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8558 		    inoreflst, if_deps);
8559 		KASSERT(jaddref != NULL &&
8560 		    jaddref->ja_ino == jaddref->ja_parent &&
8561 		    (jaddref->ja_state & MKDIR_BODY),
8562 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8563 		    jaddref));
8564 		mkdir1->md_jaddref = jaddref;
8565 		jaddref->ja_mkdir = mkdir1;
8566 		/*
8567 		 * It is important that the dotdot journal entry
8568 		 * is added prior to the dot entry since dot writes
8569 		 * both the dot and dotdot links.  These both must
8570 		 * be added after the primary link for the journal
8571 		 * to remain consistent.
8572 		 */
8573 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8574 		add_to_journal(&jaddref->ja_list);
8575 	}
8576 	/*
8577 	 * If we are adding a new directory remember this diradd so that if
8578 	 * we rename it we can keep the dot and dotdot dependencies.  If
8579 	 * we are adding a new name for an inode that has a mkdiradd we
8580 	 * must be in rename and we have to move the dot and dotdot
8581 	 * dependencies to this new name.  The old name is being orphaned
8582 	 * soon.
8583 	 */
8584 	if (mkdir1 != NULL) {
8585 		if (inodedep->id_mkdiradd != NULL)
8586 			panic("softdep_setup_directory_add: Existing mkdir");
8587 		inodedep->id_mkdiradd = dap;
8588 	} else if (inodedep->id_mkdiradd)
8589 		merge_diradd(inodedep, dap);
8590 	if (newdirblk != NULL) {
8591 		/*
8592 		 * There is nothing to do if we are already tracking
8593 		 * this block.
8594 		 */
8595 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8596 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8597 			FREE_LOCK(ump);
8598 			return (0);
8599 		}
8600 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8601 		    == 0)
8602 			panic("softdep_setup_directory_add: lost entry");
8603 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8604 		pagedep->pd_state |= NEWBLOCK;
8605 		pagedep->pd_newdirblk = newdirblk;
8606 		newdirblk->db_pagedep = pagedep;
8607 		FREE_LOCK(ump);
8608 		/*
8609 		 * If we extended into an indirect signal direnter to sync.
8610 		 */
8611 		if (isindir)
8612 			return (1);
8613 		return (0);
8614 	}
8615 	FREE_LOCK(ump);
8616 	return (0);
8617 }
8618 
8619 /*
8620  * This procedure is called to change the offset of a directory
8621  * entry when compacting a directory block which must be owned
8622  * exclusively by the caller. Note that the actual entry movement
8623  * must be done in this procedure to ensure that no I/O completions
8624  * occur while the move is in progress.
8625  */
8626 void
8627 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8628 	struct buf *bp;		/* Buffer holding directory block. */
8629 	struct inode *dp;	/* inode for directory */
8630 	caddr_t base;		/* address of dp->i_offset */
8631 	caddr_t oldloc;		/* address of old directory location */
8632 	caddr_t newloc;		/* address of new directory location */
8633 	int entrysize;		/* size of directory entry */
8634 {
8635 	int offset, oldoffset, newoffset;
8636 	struct pagedep *pagedep;
8637 	struct jmvref *jmvref;
8638 	struct diradd *dap;
8639 	struct direct *de;
8640 	struct mount *mp;
8641 	struct ufsmount *ump;
8642 	ufs_lbn_t lbn;
8643 	int flags;
8644 
8645 	mp = ITOVFS(dp);
8646 	ump = VFSTOUFS(mp);
8647 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8648 	    ("softdep_change_directoryentry_offset called on "
8649 	     "non-softdep filesystem"));
8650 	de = (struct direct *)oldloc;
8651 	jmvref = NULL;
8652 	flags = 0;
8653 	/*
8654 	 * Moves are always journaled as it would be too complex to
8655 	 * determine if any affected adds or removes are present in the
8656 	 * journal.
8657 	 */
8658 	if (MOUNTEDSUJ(mp)) {
8659 		flags = DEPALLOC;
8660 		jmvref = newjmvref(dp, de->d_ino,
8661 		    dp->i_offset + (oldloc - base),
8662 		    dp->i_offset + (newloc - base));
8663 	}
8664 	lbn = lblkno(ump->um_fs, dp->i_offset);
8665 	offset = blkoff(ump->um_fs, dp->i_offset);
8666 	oldoffset = offset + (oldloc - base);
8667 	newoffset = offset + (newloc - base);
8668 	ACQUIRE_LOCK(ump);
8669 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8670 		goto done;
8671 	dap = diradd_lookup(pagedep, oldoffset);
8672 	if (dap) {
8673 		dap->da_offset = newoffset;
8674 		newoffset = DIRADDHASH(newoffset);
8675 		oldoffset = DIRADDHASH(oldoffset);
8676 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8677 		    newoffset != oldoffset) {
8678 			LIST_REMOVE(dap, da_pdlist);
8679 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8680 			    dap, da_pdlist);
8681 		}
8682 	}
8683 done:
8684 	if (jmvref) {
8685 		jmvref->jm_pagedep = pagedep;
8686 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8687 		add_to_journal(&jmvref->jm_list);
8688 	}
8689 	bcopy(oldloc, newloc, entrysize);
8690 	FREE_LOCK(ump);
8691 }
8692 
8693 /*
8694  * Move the mkdir dependencies and journal work from one diradd to another
8695  * when renaming a directory.  The new name must depend on the mkdir deps
8696  * completing as the old name did.  Directories can only have one valid link
8697  * at a time so one must be canonical.
8698  */
8699 static void
8700 merge_diradd(inodedep, newdap)
8701 	struct inodedep *inodedep;
8702 	struct diradd *newdap;
8703 {
8704 	struct diradd *olddap;
8705 	struct mkdir *mkdir, *nextmd;
8706 	struct ufsmount *ump;
8707 	short state;
8708 
8709 	olddap = inodedep->id_mkdiradd;
8710 	inodedep->id_mkdiradd = newdap;
8711 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8712 		newdap->da_state &= ~DEPCOMPLETE;
8713 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8714 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8715 		     mkdir = nextmd) {
8716 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8717 			if (mkdir->md_diradd != olddap)
8718 				continue;
8719 			mkdir->md_diradd = newdap;
8720 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8721 			newdap->da_state |= state;
8722 			olddap->da_state &= ~state;
8723 			if ((olddap->da_state &
8724 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8725 				break;
8726 		}
8727 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8728 			panic("merge_diradd: unfound ref");
8729 	}
8730 	/*
8731 	 * Any mkdir related journal items are not safe to be freed until
8732 	 * the new name is stable.
8733 	 */
8734 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8735 	olddap->da_state |= DEPCOMPLETE;
8736 	complete_diradd(olddap);
8737 }
8738 
8739 /*
8740  * Move the diradd to the pending list when all diradd dependencies are
8741  * complete.
8742  */
8743 static void
8744 complete_diradd(dap)
8745 	struct diradd *dap;
8746 {
8747 	struct pagedep *pagedep;
8748 
8749 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8750 		if (dap->da_state & DIRCHG)
8751 			pagedep = dap->da_previous->dm_pagedep;
8752 		else
8753 			pagedep = dap->da_pagedep;
8754 		LIST_REMOVE(dap, da_pdlist);
8755 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8756 	}
8757 }
8758 
8759 /*
8760  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8761  * add entries and conditonally journal the remove.
8762  */
8763 static void
8764 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8765 	struct diradd *dap;
8766 	struct dirrem *dirrem;
8767 	struct jremref *jremref;
8768 	struct jremref *dotremref;
8769 	struct jremref *dotdotremref;
8770 {
8771 	struct inodedep *inodedep;
8772 	struct jaddref *jaddref;
8773 	struct inoref *inoref;
8774 	struct ufsmount *ump;
8775 	struct mkdir *mkdir;
8776 
8777 	/*
8778 	 * If no remove references were allocated we're on a non-journaled
8779 	 * filesystem and can skip the cancel step.
8780 	 */
8781 	if (jremref == NULL) {
8782 		free_diradd(dap, NULL);
8783 		return;
8784 	}
8785 	/*
8786 	 * Cancel the primary name an free it if it does not require
8787 	 * journaling.
8788 	 */
8789 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8790 	    0, &inodedep) != 0) {
8791 		/* Abort the addref that reference this diradd.  */
8792 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8793 			if (inoref->if_list.wk_type != D_JADDREF)
8794 				continue;
8795 			jaddref = (struct jaddref *)inoref;
8796 			if (jaddref->ja_diradd != dap)
8797 				continue;
8798 			if (cancel_jaddref(jaddref, inodedep,
8799 			    &dirrem->dm_jwork) == 0) {
8800 				free_jremref(jremref);
8801 				jremref = NULL;
8802 			}
8803 			break;
8804 		}
8805 	}
8806 	/*
8807 	 * Cancel subordinate names and free them if they do not require
8808 	 * journaling.
8809 	 */
8810 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8811 		ump = VFSTOUFS(dap->da_list.wk_mp);
8812 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8813 			if (mkdir->md_diradd != dap)
8814 				continue;
8815 			if ((jaddref = mkdir->md_jaddref) == NULL)
8816 				continue;
8817 			mkdir->md_jaddref = NULL;
8818 			if (mkdir->md_state & MKDIR_PARENT) {
8819 				if (cancel_jaddref(jaddref, NULL,
8820 				    &dirrem->dm_jwork) == 0) {
8821 					free_jremref(dotdotremref);
8822 					dotdotremref = NULL;
8823 				}
8824 			} else {
8825 				if (cancel_jaddref(jaddref, inodedep,
8826 				    &dirrem->dm_jwork) == 0) {
8827 					free_jremref(dotremref);
8828 					dotremref = NULL;
8829 				}
8830 			}
8831 		}
8832 	}
8833 
8834 	if (jremref)
8835 		journal_jremref(dirrem, jremref, inodedep);
8836 	if (dotremref)
8837 		journal_jremref(dirrem, dotremref, inodedep);
8838 	if (dotdotremref)
8839 		journal_jremref(dirrem, dotdotremref, NULL);
8840 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8841 	free_diradd(dap, &dirrem->dm_jwork);
8842 }
8843 
8844 /*
8845  * Free a diradd dependency structure. This routine must be called
8846  * with splbio interrupts blocked.
8847  */
8848 static void
8849 free_diradd(dap, wkhd)
8850 	struct diradd *dap;
8851 	struct workhead *wkhd;
8852 {
8853 	struct dirrem *dirrem;
8854 	struct pagedep *pagedep;
8855 	struct inodedep *inodedep;
8856 	struct mkdir *mkdir, *nextmd;
8857 	struct ufsmount *ump;
8858 
8859 	ump = VFSTOUFS(dap->da_list.wk_mp);
8860 	LOCK_OWNED(ump);
8861 	LIST_REMOVE(dap, da_pdlist);
8862 	if (dap->da_state & ONWORKLIST)
8863 		WORKLIST_REMOVE(&dap->da_list);
8864 	if ((dap->da_state & DIRCHG) == 0) {
8865 		pagedep = dap->da_pagedep;
8866 	} else {
8867 		dirrem = dap->da_previous;
8868 		pagedep = dirrem->dm_pagedep;
8869 		dirrem->dm_dirinum = pagedep->pd_ino;
8870 		dirrem->dm_state |= COMPLETE;
8871 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8872 			add_to_worklist(&dirrem->dm_list, 0);
8873 	}
8874 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8875 	    0, &inodedep) != 0)
8876 		if (inodedep->id_mkdiradd == dap)
8877 			inodedep->id_mkdiradd = NULL;
8878 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8879 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8880 		     mkdir = nextmd) {
8881 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8882 			if (mkdir->md_diradd != dap)
8883 				continue;
8884 			dap->da_state &=
8885 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8886 			LIST_REMOVE(mkdir, md_mkdirs);
8887 			if (mkdir->md_state & ONWORKLIST)
8888 				WORKLIST_REMOVE(&mkdir->md_list);
8889 			if (mkdir->md_jaddref != NULL)
8890 				panic("free_diradd: Unexpected jaddref");
8891 			WORKITEM_FREE(mkdir, D_MKDIR);
8892 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8893 				break;
8894 		}
8895 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8896 			panic("free_diradd: unfound ref");
8897 	}
8898 	if (inodedep)
8899 		free_inodedep(inodedep);
8900 	/*
8901 	 * Free any journal segments waiting for the directory write.
8902 	 */
8903 	handle_jwork(&dap->da_jwork);
8904 	WORKITEM_FREE(dap, D_DIRADD);
8905 }
8906 
8907 /*
8908  * Directory entry removal dependencies.
8909  *
8910  * When removing a directory entry, the entry's inode pointer must be
8911  * zero'ed on disk before the corresponding inode's link count is decremented
8912  * (possibly freeing the inode for re-use). This dependency is handled by
8913  * updating the directory entry but delaying the inode count reduction until
8914  * after the directory block has been written to disk. After this point, the
8915  * inode count can be decremented whenever it is convenient.
8916  */
8917 
8918 /*
8919  * This routine should be called immediately after removing
8920  * a directory entry.  The inode's link count should not be
8921  * decremented by the calling procedure -- the soft updates
8922  * code will do this task when it is safe.
8923  */
8924 void
8925 softdep_setup_remove(bp, dp, ip, isrmdir)
8926 	struct buf *bp;		/* buffer containing directory block */
8927 	struct inode *dp;	/* inode for the directory being modified */
8928 	struct inode *ip;	/* inode for directory entry being removed */
8929 	int isrmdir;		/* indicates if doing RMDIR */
8930 {
8931 	struct dirrem *dirrem, *prevdirrem;
8932 	struct inodedep *inodedep;
8933 	struct ufsmount *ump;
8934 	int direct;
8935 
8936 	ump = ITOUMP(ip);
8937 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8938 	    ("softdep_setup_remove called on non-softdep filesystem"));
8939 	/*
8940 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8941 	 * newdirrem() to setup the full directory remove which requires
8942 	 * isrmdir > 1.
8943 	 */
8944 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8945 	/*
8946 	 * Add the dirrem to the inodedep's pending remove list for quick
8947 	 * discovery later.
8948 	 */
8949 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
8950 		panic("softdep_setup_remove: Lost inodedep.");
8951 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8952 	dirrem->dm_state |= ONDEPLIST;
8953 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8954 
8955 	/*
8956 	 * If the COMPLETE flag is clear, then there were no active
8957 	 * entries and we want to roll back to a zeroed entry until
8958 	 * the new inode is committed to disk. If the COMPLETE flag is
8959 	 * set then we have deleted an entry that never made it to
8960 	 * disk. If the entry we deleted resulted from a name change,
8961 	 * then the old name still resides on disk. We cannot delete
8962 	 * its inode (returned to us in prevdirrem) until the zeroed
8963 	 * directory entry gets to disk. The new inode has never been
8964 	 * referenced on the disk, so can be deleted immediately.
8965 	 */
8966 	if ((dirrem->dm_state & COMPLETE) == 0) {
8967 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8968 		    dm_next);
8969 		FREE_LOCK(ump);
8970 	} else {
8971 		if (prevdirrem != NULL)
8972 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8973 			    prevdirrem, dm_next);
8974 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8975 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8976 		FREE_LOCK(ump);
8977 		if (direct)
8978 			handle_workitem_remove(dirrem, 0);
8979 	}
8980 }
8981 
8982 /*
8983  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8984  * pd_pendinghd list of a pagedep.
8985  */
8986 static struct diradd *
8987 diradd_lookup(pagedep, offset)
8988 	struct pagedep *pagedep;
8989 	int offset;
8990 {
8991 	struct diradd *dap;
8992 
8993 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8994 		if (dap->da_offset == offset)
8995 			return (dap);
8996 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8997 		if (dap->da_offset == offset)
8998 			return (dap);
8999 	return (NULL);
9000 }
9001 
9002 /*
9003  * Search for a .. diradd dependency in a directory that is being removed.
9004  * If the directory was renamed to a new parent we have a diradd rather
9005  * than a mkdir for the .. entry.  We need to cancel it now before
9006  * it is found in truncate().
9007  */
9008 static struct jremref *
9009 cancel_diradd_dotdot(ip, dirrem, jremref)
9010 	struct inode *ip;
9011 	struct dirrem *dirrem;
9012 	struct jremref *jremref;
9013 {
9014 	struct pagedep *pagedep;
9015 	struct diradd *dap;
9016 	struct worklist *wk;
9017 
9018 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9019 		return (jremref);
9020 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9021 	if (dap == NULL)
9022 		return (jremref);
9023 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9024 	/*
9025 	 * Mark any journal work as belonging to the parent so it is freed
9026 	 * with the .. reference.
9027 	 */
9028 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9029 		wk->wk_state |= MKDIR_PARENT;
9030 	return (NULL);
9031 }
9032 
9033 /*
9034  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9035  * replace it with a dirrem/diradd pair as a result of re-parenting a
9036  * directory.  This ensures that we don't simultaneously have a mkdir and
9037  * a diradd for the same .. entry.
9038  */
9039 static struct jremref *
9040 cancel_mkdir_dotdot(ip, dirrem, jremref)
9041 	struct inode *ip;
9042 	struct dirrem *dirrem;
9043 	struct jremref *jremref;
9044 {
9045 	struct inodedep *inodedep;
9046 	struct jaddref *jaddref;
9047 	struct ufsmount *ump;
9048 	struct mkdir *mkdir;
9049 	struct diradd *dap;
9050 	struct mount *mp;
9051 
9052 	mp = ITOVFS(ip);
9053 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9054 		return (jremref);
9055 	dap = inodedep->id_mkdiradd;
9056 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9057 		return (jremref);
9058 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9059 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9060 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9061 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9062 			break;
9063 	if (mkdir == NULL)
9064 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9065 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9066 		mkdir->md_jaddref = NULL;
9067 		jaddref->ja_state &= ~MKDIR_PARENT;
9068 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9069 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9070 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9071 			journal_jremref(dirrem, jremref, inodedep);
9072 			jremref = NULL;
9073 		}
9074 	}
9075 	if (mkdir->md_state & ONWORKLIST)
9076 		WORKLIST_REMOVE(&mkdir->md_list);
9077 	mkdir->md_state |= ALLCOMPLETE;
9078 	complete_mkdir(mkdir);
9079 	return (jremref);
9080 }
9081 
9082 static void
9083 journal_jremref(dirrem, jremref, inodedep)
9084 	struct dirrem *dirrem;
9085 	struct jremref *jremref;
9086 	struct inodedep *inodedep;
9087 {
9088 
9089 	if (inodedep == NULL)
9090 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9091 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9092 			panic("journal_jremref: Lost inodedep");
9093 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9094 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9095 	add_to_journal(&jremref->jr_list);
9096 }
9097 
9098 static void
9099 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9100 	struct dirrem *dirrem;
9101 	struct jremref *jremref;
9102 	struct jremref *dotremref;
9103 	struct jremref *dotdotremref;
9104 {
9105 	struct inodedep *inodedep;
9106 
9107 
9108 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9109 	    &inodedep) == 0)
9110 		panic("dirrem_journal: Lost inodedep");
9111 	journal_jremref(dirrem, jremref, inodedep);
9112 	if (dotremref)
9113 		journal_jremref(dirrem, dotremref, inodedep);
9114 	if (dotdotremref)
9115 		journal_jremref(dirrem, dotdotremref, NULL);
9116 }
9117 
9118 /*
9119  * Allocate a new dirrem if appropriate and return it along with
9120  * its associated pagedep. Called without a lock, returns with lock.
9121  */
9122 static struct dirrem *
9123 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9124 	struct buf *bp;		/* buffer containing directory block */
9125 	struct inode *dp;	/* inode for the directory being modified */
9126 	struct inode *ip;	/* inode for directory entry being removed */
9127 	int isrmdir;		/* indicates if doing RMDIR */
9128 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9129 {
9130 	int offset;
9131 	ufs_lbn_t lbn;
9132 	struct diradd *dap;
9133 	struct dirrem *dirrem;
9134 	struct pagedep *pagedep;
9135 	struct jremref *jremref;
9136 	struct jremref *dotremref;
9137 	struct jremref *dotdotremref;
9138 	struct vnode *dvp;
9139 	struct ufsmount *ump;
9140 
9141 	/*
9142 	 * Whiteouts have no deletion dependencies.
9143 	 */
9144 	if (ip == NULL)
9145 		panic("newdirrem: whiteout");
9146 	dvp = ITOV(dp);
9147 	ump = ITOUMP(dp);
9148 
9149 	/*
9150 	 * If the system is over its limit and our filesystem is
9151 	 * responsible for more than our share of that usage and
9152 	 * we are not a snapshot, request some inodedep cleanup.
9153 	 * Limiting the number of dirrem structures will also limit
9154 	 * the number of freefile and freeblks structures.
9155 	 */
9156 	ACQUIRE_LOCK(ump);
9157 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9158 		schedule_cleanup(UFSTOVFS(ump));
9159 	else
9160 		FREE_LOCK(ump);
9161 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9162 	    M_ZERO);
9163 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9164 	LIST_INIT(&dirrem->dm_jremrefhd);
9165 	LIST_INIT(&dirrem->dm_jwork);
9166 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9167 	dirrem->dm_oldinum = ip->i_number;
9168 	*prevdirremp = NULL;
9169 	/*
9170 	 * Allocate remove reference structures to track journal write
9171 	 * dependencies.  We will always have one for the link and
9172 	 * when doing directories we will always have one more for dot.
9173 	 * When renaming a directory we skip the dotdot link change so
9174 	 * this is not needed.
9175 	 */
9176 	jremref = dotremref = dotdotremref = NULL;
9177 	if (DOINGSUJ(dvp)) {
9178 		if (isrmdir) {
9179 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9180 			    ip->i_effnlink + 2);
9181 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9182 			    ip->i_effnlink + 1);
9183 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9184 			    dp->i_effnlink + 1);
9185 			dotdotremref->jr_state |= MKDIR_PARENT;
9186 		} else
9187 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9188 			    ip->i_effnlink + 1);
9189 	}
9190 	ACQUIRE_LOCK(ump);
9191 	lbn = lblkno(ump->um_fs, dp->i_offset);
9192 	offset = blkoff(ump->um_fs, dp->i_offset);
9193 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9194 	    &pagedep);
9195 	dirrem->dm_pagedep = pagedep;
9196 	dirrem->dm_offset = offset;
9197 	/*
9198 	 * If we're renaming a .. link to a new directory, cancel any
9199 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9200 	 * the jremref is preserved for any potential diradd in this
9201 	 * location.  This can not coincide with a rmdir.
9202 	 */
9203 	if (dp->i_offset == DOTDOT_OFFSET) {
9204 		if (isrmdir)
9205 			panic("newdirrem: .. directory change during remove?");
9206 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9207 	}
9208 	/*
9209 	 * If we're removing a directory search for the .. dependency now and
9210 	 * cancel it.  Any pending journal work will be added to the dirrem
9211 	 * to be completed when the workitem remove completes.
9212 	 */
9213 	if (isrmdir)
9214 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9215 	/*
9216 	 * Check for a diradd dependency for the same directory entry.
9217 	 * If present, then both dependencies become obsolete and can
9218 	 * be de-allocated.
9219 	 */
9220 	dap = diradd_lookup(pagedep, offset);
9221 	if (dap == NULL) {
9222 		/*
9223 		 * Link the jremref structures into the dirrem so they are
9224 		 * written prior to the pagedep.
9225 		 */
9226 		if (jremref)
9227 			dirrem_journal(dirrem, jremref, dotremref,
9228 			    dotdotremref);
9229 		return (dirrem);
9230 	}
9231 	/*
9232 	 * Must be ATTACHED at this point.
9233 	 */
9234 	if ((dap->da_state & ATTACHED) == 0)
9235 		panic("newdirrem: not ATTACHED");
9236 	if (dap->da_newinum != ip->i_number)
9237 		panic("newdirrem: inum %ju should be %ju",
9238 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9239 	/*
9240 	 * If we are deleting a changed name that never made it to disk,
9241 	 * then return the dirrem describing the previous inode (which
9242 	 * represents the inode currently referenced from this entry on disk).
9243 	 */
9244 	if ((dap->da_state & DIRCHG) != 0) {
9245 		*prevdirremp = dap->da_previous;
9246 		dap->da_state &= ~DIRCHG;
9247 		dap->da_pagedep = pagedep;
9248 	}
9249 	/*
9250 	 * We are deleting an entry that never made it to disk.
9251 	 * Mark it COMPLETE so we can delete its inode immediately.
9252 	 */
9253 	dirrem->dm_state |= COMPLETE;
9254 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9255 #ifdef SUJ_DEBUG
9256 	if (isrmdir == 0) {
9257 		struct worklist *wk;
9258 
9259 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9260 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9261 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9262 	}
9263 #endif
9264 
9265 	return (dirrem);
9266 }
9267 
9268 /*
9269  * Directory entry change dependencies.
9270  *
9271  * Changing an existing directory entry requires that an add operation
9272  * be completed first followed by a deletion. The semantics for the addition
9273  * are identical to the description of adding a new entry above except
9274  * that the rollback is to the old inode number rather than zero. Once
9275  * the addition dependency is completed, the removal is done as described
9276  * in the removal routine above.
9277  */
9278 
9279 /*
9280  * This routine should be called immediately after changing
9281  * a directory entry.  The inode's link count should not be
9282  * decremented by the calling procedure -- the soft updates
9283  * code will perform this task when it is safe.
9284  */
9285 void
9286 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9287 	struct buf *bp;		/* buffer containing directory block */
9288 	struct inode *dp;	/* inode for the directory being modified */
9289 	struct inode *ip;	/* inode for directory entry being removed */
9290 	ino_t newinum;		/* new inode number for changed entry */
9291 	int isrmdir;		/* indicates if doing RMDIR */
9292 {
9293 	int offset;
9294 	struct diradd *dap = NULL;
9295 	struct dirrem *dirrem, *prevdirrem;
9296 	struct pagedep *pagedep;
9297 	struct inodedep *inodedep;
9298 	struct jaddref *jaddref;
9299 	struct mount *mp;
9300 	struct ufsmount *ump;
9301 
9302 	mp = ITOVFS(dp);
9303 	ump = VFSTOUFS(mp);
9304 	offset = blkoff(ump->um_fs, dp->i_offset);
9305 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9306 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9307 
9308 	/*
9309 	 * Whiteouts do not need diradd dependencies.
9310 	 */
9311 	if (newinum != UFS_WINO) {
9312 		dap = malloc(sizeof(struct diradd),
9313 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9314 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9315 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9316 		dap->da_offset = offset;
9317 		dap->da_newinum = newinum;
9318 		LIST_INIT(&dap->da_jwork);
9319 	}
9320 
9321 	/*
9322 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9323 	 */
9324 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9325 	pagedep = dirrem->dm_pagedep;
9326 	/*
9327 	 * The possible values for isrmdir:
9328 	 *	0 - non-directory file rename
9329 	 *	1 - directory rename within same directory
9330 	 *   inum - directory rename to new directory of given inode number
9331 	 * When renaming to a new directory, we are both deleting and
9332 	 * creating a new directory entry, so the link count on the new
9333 	 * directory should not change. Thus we do not need the followup
9334 	 * dirrem which is usually done in handle_workitem_remove. We set
9335 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9336 	 * followup dirrem.
9337 	 */
9338 	if (isrmdir > 1)
9339 		dirrem->dm_state |= DIRCHG;
9340 
9341 	/*
9342 	 * Whiteouts have no additional dependencies,
9343 	 * so just put the dirrem on the correct list.
9344 	 */
9345 	if (newinum == UFS_WINO) {
9346 		if ((dirrem->dm_state & COMPLETE) == 0) {
9347 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9348 			    dm_next);
9349 		} else {
9350 			dirrem->dm_dirinum = pagedep->pd_ino;
9351 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9352 				add_to_worklist(&dirrem->dm_list, 0);
9353 		}
9354 		FREE_LOCK(ump);
9355 		return;
9356 	}
9357 	/*
9358 	 * Add the dirrem to the inodedep's pending remove list for quick
9359 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9360 	 * will not fail.
9361 	 */
9362 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9363 		panic("softdep_setup_directory_change: Lost inodedep.");
9364 	dirrem->dm_state |= ONDEPLIST;
9365 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9366 
9367 	/*
9368 	 * If the COMPLETE flag is clear, then there were no active
9369 	 * entries and we want to roll back to the previous inode until
9370 	 * the new inode is committed to disk. If the COMPLETE flag is
9371 	 * set, then we have deleted an entry that never made it to disk.
9372 	 * If the entry we deleted resulted from a name change, then the old
9373 	 * inode reference still resides on disk. Any rollback that we do
9374 	 * needs to be to that old inode (returned to us in prevdirrem). If
9375 	 * the entry we deleted resulted from a create, then there is
9376 	 * no entry on the disk, so we want to roll back to zero rather
9377 	 * than the uncommitted inode. In either of the COMPLETE cases we
9378 	 * want to immediately free the unwritten and unreferenced inode.
9379 	 */
9380 	if ((dirrem->dm_state & COMPLETE) == 0) {
9381 		dap->da_previous = dirrem;
9382 	} else {
9383 		if (prevdirrem != NULL) {
9384 			dap->da_previous = prevdirrem;
9385 		} else {
9386 			dap->da_state &= ~DIRCHG;
9387 			dap->da_pagedep = pagedep;
9388 		}
9389 		dirrem->dm_dirinum = pagedep->pd_ino;
9390 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9391 			add_to_worklist(&dirrem->dm_list, 0);
9392 	}
9393 	/*
9394 	 * Lookup the jaddref for this journal entry.  We must finish
9395 	 * initializing it and make the diradd write dependent on it.
9396 	 * If we're not journaling, put it on the id_bufwait list if the
9397 	 * inode is not yet written. If it is written, do the post-inode
9398 	 * write processing to put it on the id_pendinghd list.
9399 	 */
9400 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9401 	if (MOUNTEDSUJ(mp)) {
9402 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9403 		    inoreflst);
9404 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9405 		    ("softdep_setup_directory_change: bad jaddref %p",
9406 		    jaddref));
9407 		jaddref->ja_diroff = dp->i_offset;
9408 		jaddref->ja_diradd = dap;
9409 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9410 		    dap, da_pdlist);
9411 		add_to_journal(&jaddref->ja_list);
9412 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9413 		dap->da_state |= COMPLETE;
9414 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9415 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9416 	} else {
9417 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9418 		    dap, da_pdlist);
9419 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9420 	}
9421 	/*
9422 	 * If we're making a new name for a directory that has not been
9423 	 * committed when need to move the dot and dotdot references to
9424 	 * this new name.
9425 	 */
9426 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9427 		merge_diradd(inodedep, dap);
9428 	FREE_LOCK(ump);
9429 }
9430 
9431 /*
9432  * Called whenever the link count on an inode is changed.
9433  * It creates an inode dependency so that the new reference(s)
9434  * to the inode cannot be committed to disk until the updated
9435  * inode has been written.
9436  */
9437 void
9438 softdep_change_linkcnt(ip)
9439 	struct inode *ip;	/* the inode with the increased link count */
9440 {
9441 	struct inodedep *inodedep;
9442 	struct ufsmount *ump;
9443 
9444 	ump = ITOUMP(ip);
9445 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9446 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9447 	ACQUIRE_LOCK(ump);
9448 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9449 	if (ip->i_nlink < ip->i_effnlink)
9450 		panic("softdep_change_linkcnt: bad delta");
9451 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9452 	FREE_LOCK(ump);
9453 }
9454 
9455 /*
9456  * Attach a sbdep dependency to the superblock buf so that we can keep
9457  * track of the head of the linked list of referenced but unlinked inodes.
9458  */
9459 void
9460 softdep_setup_sbupdate(ump, fs, bp)
9461 	struct ufsmount *ump;
9462 	struct fs *fs;
9463 	struct buf *bp;
9464 {
9465 	struct sbdep *sbdep;
9466 	struct worklist *wk;
9467 
9468 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9469 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9470 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9471 		if (wk->wk_type == D_SBDEP)
9472 			break;
9473 	if (wk != NULL)
9474 		return;
9475 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9476 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9477 	sbdep->sb_fs = fs;
9478 	sbdep->sb_ump = ump;
9479 	ACQUIRE_LOCK(ump);
9480 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9481 	FREE_LOCK(ump);
9482 }
9483 
9484 /*
9485  * Return the first unlinked inodedep which is ready to be the head of the
9486  * list.  The inodedep and all those after it must have valid next pointers.
9487  */
9488 static struct inodedep *
9489 first_unlinked_inodedep(ump)
9490 	struct ufsmount *ump;
9491 {
9492 	struct inodedep *inodedep;
9493 	struct inodedep *idp;
9494 
9495 	LOCK_OWNED(ump);
9496 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9497 	    inodedep; inodedep = idp) {
9498 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9499 			return (NULL);
9500 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9501 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9502 			break;
9503 		if ((inodedep->id_state & UNLINKPREV) == 0)
9504 			break;
9505 	}
9506 	return (inodedep);
9507 }
9508 
9509 /*
9510  * Set the sujfree unlinked head pointer prior to writing a superblock.
9511  */
9512 static void
9513 initiate_write_sbdep(sbdep)
9514 	struct sbdep *sbdep;
9515 {
9516 	struct inodedep *inodedep;
9517 	struct fs *bpfs;
9518 	struct fs *fs;
9519 
9520 	bpfs = sbdep->sb_fs;
9521 	fs = sbdep->sb_ump->um_fs;
9522 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9523 	if (inodedep) {
9524 		fs->fs_sujfree = inodedep->id_ino;
9525 		inodedep->id_state |= UNLINKPREV;
9526 	} else
9527 		fs->fs_sujfree = 0;
9528 	bpfs->fs_sujfree = fs->fs_sujfree;
9529 }
9530 
9531 /*
9532  * After a superblock is written determine whether it must be written again
9533  * due to a changing unlinked list head.
9534  */
9535 static int
9536 handle_written_sbdep(sbdep, bp)
9537 	struct sbdep *sbdep;
9538 	struct buf *bp;
9539 {
9540 	struct inodedep *inodedep;
9541 	struct fs *fs;
9542 
9543 	LOCK_OWNED(sbdep->sb_ump);
9544 	fs = sbdep->sb_fs;
9545 	/*
9546 	 * If the superblock doesn't match the in-memory list start over.
9547 	 */
9548 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9549 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9550 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9551 		bdirty(bp);
9552 		return (1);
9553 	}
9554 	WORKITEM_FREE(sbdep, D_SBDEP);
9555 	if (fs->fs_sujfree == 0)
9556 		return (0);
9557 	/*
9558 	 * Now that we have a record of this inode in stable store allow it
9559 	 * to be written to free up pending work.  Inodes may see a lot of
9560 	 * write activity after they are unlinked which we must not hold up.
9561 	 */
9562 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9563 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9564 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9565 			    inodedep, inodedep->id_state);
9566 		if (inodedep->id_state & UNLINKONLIST)
9567 			break;
9568 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9569 	}
9570 
9571 	return (0);
9572 }
9573 
9574 /*
9575  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9576  */
9577 static void
9578 unlinked_inodedep(mp, inodedep)
9579 	struct mount *mp;
9580 	struct inodedep *inodedep;
9581 {
9582 	struct ufsmount *ump;
9583 
9584 	ump = VFSTOUFS(mp);
9585 	LOCK_OWNED(ump);
9586 	if (MOUNTEDSUJ(mp) == 0)
9587 		return;
9588 	ump->um_fs->fs_fmod = 1;
9589 	if (inodedep->id_state & UNLINKED)
9590 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9591 	inodedep->id_state |= UNLINKED;
9592 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9593 }
9594 
9595 /*
9596  * Remove an inodedep from the unlinked inodedep list.  This may require
9597  * disk writes if the inode has made it that far.
9598  */
9599 static void
9600 clear_unlinked_inodedep(inodedep)
9601 	struct inodedep *inodedep;
9602 {
9603 	struct ufsmount *ump;
9604 	struct inodedep *idp;
9605 	struct inodedep *idn;
9606 	struct fs *fs;
9607 	struct buf *bp;
9608 	ino_t ino;
9609 	ino_t nino;
9610 	ino_t pino;
9611 	int error;
9612 
9613 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9614 	fs = ump->um_fs;
9615 	ino = inodedep->id_ino;
9616 	error = 0;
9617 	for (;;) {
9618 		LOCK_OWNED(ump);
9619 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9620 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9621 		    inodedep));
9622 		/*
9623 		 * If nothing has yet been written simply remove us from
9624 		 * the in memory list and return.  This is the most common
9625 		 * case where handle_workitem_remove() loses the final
9626 		 * reference.
9627 		 */
9628 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9629 			break;
9630 		/*
9631 		 * If we have a NEXT pointer and no PREV pointer we can simply
9632 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9633 		 * careful not to clear PREV if the superblock points at
9634 		 * next as well.
9635 		 */
9636 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9637 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9638 			if (idn && fs->fs_sujfree != idn->id_ino)
9639 				idn->id_state &= ~UNLINKPREV;
9640 			break;
9641 		}
9642 		/*
9643 		 * Here we have an inodedep which is actually linked into
9644 		 * the list.  We must remove it by forcing a write to the
9645 		 * link before us, whether it be the superblock or an inode.
9646 		 * Unfortunately the list may change while we're waiting
9647 		 * on the buf lock for either resource so we must loop until
9648 		 * we lock the right one.  If both the superblock and an
9649 		 * inode point to this inode we must clear the inode first
9650 		 * followed by the superblock.
9651 		 */
9652 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9653 		pino = 0;
9654 		if (idp && (idp->id_state & UNLINKNEXT))
9655 			pino = idp->id_ino;
9656 		FREE_LOCK(ump);
9657 		if (pino == 0) {
9658 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9659 			    (int)fs->fs_sbsize, 0, 0, 0);
9660 		} else {
9661 			error = bread(ump->um_devvp,
9662 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9663 			    (int)fs->fs_bsize, NOCRED, &bp);
9664 			if (error)
9665 				brelse(bp);
9666 		}
9667 		ACQUIRE_LOCK(ump);
9668 		if (error)
9669 			break;
9670 		/* If the list has changed restart the loop. */
9671 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9672 		nino = 0;
9673 		if (idp && (idp->id_state & UNLINKNEXT))
9674 			nino = idp->id_ino;
9675 		if (nino != pino ||
9676 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9677 			FREE_LOCK(ump);
9678 			brelse(bp);
9679 			ACQUIRE_LOCK(ump);
9680 			continue;
9681 		}
9682 		nino = 0;
9683 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9684 		if (idn)
9685 			nino = idn->id_ino;
9686 		/*
9687 		 * Remove us from the in memory list.  After this we cannot
9688 		 * access the inodedep.
9689 		 */
9690 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9691 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9692 		    inodedep));
9693 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9694 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9695 		FREE_LOCK(ump);
9696 		/*
9697 		 * The predecessor's next pointer is manually updated here
9698 		 * so that the NEXT flag is never cleared for an element
9699 		 * that is in the list.
9700 		 */
9701 		if (pino == 0) {
9702 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9703 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9704 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9705 			    bp);
9706 		} else if (fs->fs_magic == FS_UFS1_MAGIC)
9707 			((struct ufs1_dinode *)bp->b_data +
9708 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9709 		else
9710 			((struct ufs2_dinode *)bp->b_data +
9711 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9712 		/*
9713 		 * If the bwrite fails we have no recourse to recover.  The
9714 		 * filesystem is corrupted already.
9715 		 */
9716 		bwrite(bp);
9717 		ACQUIRE_LOCK(ump);
9718 		/*
9719 		 * If the superblock pointer still needs to be cleared force
9720 		 * a write here.
9721 		 */
9722 		if (fs->fs_sujfree == ino) {
9723 			FREE_LOCK(ump);
9724 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9725 			    (int)fs->fs_sbsize, 0, 0, 0);
9726 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9727 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9728 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9729 			    bp);
9730 			bwrite(bp);
9731 			ACQUIRE_LOCK(ump);
9732 		}
9733 
9734 		if (fs->fs_sujfree != ino)
9735 			return;
9736 		panic("clear_unlinked_inodedep: Failed to clear free head");
9737 	}
9738 	if (inodedep->id_ino == fs->fs_sujfree)
9739 		panic("clear_unlinked_inodedep: Freeing head of free list");
9740 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9741 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9742 	return;
9743 }
9744 
9745 /*
9746  * This workitem decrements the inode's link count.
9747  * If the link count reaches zero, the file is removed.
9748  */
9749 static int
9750 handle_workitem_remove(dirrem, flags)
9751 	struct dirrem *dirrem;
9752 	int flags;
9753 {
9754 	struct inodedep *inodedep;
9755 	struct workhead dotdotwk;
9756 	struct worklist *wk;
9757 	struct ufsmount *ump;
9758 	struct mount *mp;
9759 	struct vnode *vp;
9760 	struct inode *ip;
9761 	ino_t oldinum;
9762 
9763 	if (dirrem->dm_state & ONWORKLIST)
9764 		panic("handle_workitem_remove: dirrem %p still on worklist",
9765 		    dirrem);
9766 	oldinum = dirrem->dm_oldinum;
9767 	mp = dirrem->dm_list.wk_mp;
9768 	ump = VFSTOUFS(mp);
9769 	flags |= LK_EXCLUSIVE;
9770 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9771 		return (EBUSY);
9772 	ip = VTOI(vp);
9773 	ACQUIRE_LOCK(ump);
9774 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9775 		panic("handle_workitem_remove: lost inodedep");
9776 	if (dirrem->dm_state & ONDEPLIST)
9777 		LIST_REMOVE(dirrem, dm_inonext);
9778 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9779 	    ("handle_workitem_remove:  Journal entries not written."));
9780 
9781 	/*
9782 	 * Move all dependencies waiting on the remove to complete
9783 	 * from the dirrem to the inode inowait list to be completed
9784 	 * after the inode has been updated and written to disk.  Any
9785 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9786 	 * is removed.
9787 	 */
9788 	LIST_INIT(&dotdotwk);
9789 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9790 		WORKLIST_REMOVE(wk);
9791 		if (wk->wk_state & MKDIR_PARENT) {
9792 			wk->wk_state &= ~MKDIR_PARENT;
9793 			WORKLIST_INSERT(&dotdotwk, wk);
9794 			continue;
9795 		}
9796 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9797 	}
9798 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9799 	/*
9800 	 * Normal file deletion.
9801 	 */
9802 	if ((dirrem->dm_state & RMDIR) == 0) {
9803 		ip->i_nlink--;
9804 		DIP_SET(ip, i_nlink, ip->i_nlink);
9805 		ip->i_flag |= IN_CHANGE;
9806 		if (ip->i_nlink < ip->i_effnlink)
9807 			panic("handle_workitem_remove: bad file delta");
9808 		if (ip->i_nlink == 0)
9809 			unlinked_inodedep(mp, inodedep);
9810 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9811 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9812 		    ("handle_workitem_remove: worklist not empty. %s",
9813 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9814 		WORKITEM_FREE(dirrem, D_DIRREM);
9815 		FREE_LOCK(ump);
9816 		goto out;
9817 	}
9818 	/*
9819 	 * Directory deletion. Decrement reference count for both the
9820 	 * just deleted parent directory entry and the reference for ".".
9821 	 * Arrange to have the reference count on the parent decremented
9822 	 * to account for the loss of "..".
9823 	 */
9824 	ip->i_nlink -= 2;
9825 	DIP_SET(ip, i_nlink, ip->i_nlink);
9826 	ip->i_flag |= IN_CHANGE;
9827 	if (ip->i_nlink < ip->i_effnlink)
9828 		panic("handle_workitem_remove: bad dir delta");
9829 	if (ip->i_nlink == 0)
9830 		unlinked_inodedep(mp, inodedep);
9831 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9832 	/*
9833 	 * Rename a directory to a new parent. Since, we are both deleting
9834 	 * and creating a new directory entry, the link count on the new
9835 	 * directory should not change. Thus we skip the followup dirrem.
9836 	 */
9837 	if (dirrem->dm_state & DIRCHG) {
9838 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9839 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9840 		WORKITEM_FREE(dirrem, D_DIRREM);
9841 		FREE_LOCK(ump);
9842 		goto out;
9843 	}
9844 	dirrem->dm_state = ONDEPLIST;
9845 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9846 	/*
9847 	 * Place the dirrem on the parent's diremhd list.
9848 	 */
9849 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9850 		panic("handle_workitem_remove: lost dir inodedep");
9851 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9852 	/*
9853 	 * If the allocated inode has never been written to disk, then
9854 	 * the on-disk inode is zero'ed and we can remove the file
9855 	 * immediately.  When journaling if the inode has been marked
9856 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9857 	 */
9858 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9859 	if (inodedep == NULL ||
9860 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9861 	    check_inode_unwritten(inodedep)) {
9862 		FREE_LOCK(ump);
9863 		vput(vp);
9864 		return handle_workitem_remove(dirrem, flags);
9865 	}
9866 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9867 	FREE_LOCK(ump);
9868 	ip->i_flag |= IN_CHANGE;
9869 out:
9870 	ffs_update(vp, 0);
9871 	vput(vp);
9872 	return (0);
9873 }
9874 
9875 /*
9876  * Inode de-allocation dependencies.
9877  *
9878  * When an inode's link count is reduced to zero, it can be de-allocated. We
9879  * found it convenient to postpone de-allocation until after the inode is
9880  * written to disk with its new link count (zero).  At this point, all of the
9881  * on-disk inode's block pointers are nullified and, with careful dependency
9882  * list ordering, all dependencies related to the inode will be satisfied and
9883  * the corresponding dependency structures de-allocated.  So, if/when the
9884  * inode is reused, there will be no mixing of old dependencies with new
9885  * ones.  This artificial dependency is set up by the block de-allocation
9886  * procedure above (softdep_setup_freeblocks) and completed by the
9887  * following procedure.
9888  */
9889 static void
9890 handle_workitem_freefile(freefile)
9891 	struct freefile *freefile;
9892 {
9893 	struct workhead wkhd;
9894 	struct fs *fs;
9895 	struct inodedep *idp;
9896 	struct ufsmount *ump;
9897 	int error;
9898 
9899 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9900 	fs = ump->um_fs;
9901 #ifdef DEBUG
9902 	ACQUIRE_LOCK(ump);
9903 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9904 	FREE_LOCK(ump);
9905 	if (error)
9906 		panic("handle_workitem_freefile: inodedep %p survived", idp);
9907 #endif
9908 	UFS_LOCK(ump);
9909 	fs->fs_pendinginodes -= 1;
9910 	UFS_UNLOCK(ump);
9911 	LIST_INIT(&wkhd);
9912 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9913 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9914 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9915 		softdep_error("handle_workitem_freefile", error);
9916 	ACQUIRE_LOCK(ump);
9917 	WORKITEM_FREE(freefile, D_FREEFILE);
9918 	FREE_LOCK(ump);
9919 }
9920 
9921 
9922 /*
9923  * Helper function which unlinks marker element from work list and returns
9924  * the next element on the list.
9925  */
9926 static __inline struct worklist *
9927 markernext(struct worklist *marker)
9928 {
9929 	struct worklist *next;
9930 
9931 	next = LIST_NEXT(marker, wk_list);
9932 	LIST_REMOVE(marker, wk_list);
9933 	return next;
9934 }
9935 
9936 /*
9937  * Disk writes.
9938  *
9939  * The dependency structures constructed above are most actively used when file
9940  * system blocks are written to disk.  No constraints are placed on when a
9941  * block can be written, but unsatisfied update dependencies are made safe by
9942  * modifying (or replacing) the source memory for the duration of the disk
9943  * write.  When the disk write completes, the memory block is again brought
9944  * up-to-date.
9945  *
9946  * In-core inode structure reclamation.
9947  *
9948  * Because there are a finite number of "in-core" inode structures, they are
9949  * reused regularly.  By transferring all inode-related dependencies to the
9950  * in-memory inode block and indexing them separately (via "inodedep"s), we
9951  * can allow "in-core" inode structures to be reused at any time and avoid
9952  * any increase in contention.
9953  *
9954  * Called just before entering the device driver to initiate a new disk I/O.
9955  * The buffer must be locked, thus, no I/O completion operations can occur
9956  * while we are manipulating its associated dependencies.
9957  */
9958 static void
9959 softdep_disk_io_initiation(bp)
9960 	struct buf *bp;		/* structure describing disk write to occur */
9961 {
9962 	struct worklist *wk;
9963 	struct worklist marker;
9964 	struct inodedep *inodedep;
9965 	struct freeblks *freeblks;
9966 	struct jblkdep *jblkdep;
9967 	struct newblk *newblk;
9968 	struct ufsmount *ump;
9969 
9970 	/*
9971 	 * We only care about write operations. There should never
9972 	 * be dependencies for reads.
9973 	 */
9974 	if (bp->b_iocmd != BIO_WRITE)
9975 		panic("softdep_disk_io_initiation: not write");
9976 
9977 	if (bp->b_vflags & BV_BKGRDINPROG)
9978 		panic("softdep_disk_io_initiation: Writing buffer with "
9979 		    "background write in progress: %p", bp);
9980 
9981 	ump = softdep_bp_to_mp(bp);
9982 	if (ump == NULL)
9983 		return;
9984 
9985 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
9986 	PHOLD(curproc);			/* Don't swap out kernel stack */
9987 	ACQUIRE_LOCK(ump);
9988 	/*
9989 	 * Do any necessary pre-I/O processing.
9990 	 */
9991 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9992 	     wk = markernext(&marker)) {
9993 		LIST_INSERT_AFTER(wk, &marker, wk_list);
9994 		switch (wk->wk_type) {
9995 
9996 		case D_PAGEDEP:
9997 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
9998 			continue;
9999 
10000 		case D_INODEDEP:
10001 			inodedep = WK_INODEDEP(wk);
10002 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10003 				initiate_write_inodeblock_ufs1(inodedep, bp);
10004 			else
10005 				initiate_write_inodeblock_ufs2(inodedep, bp);
10006 			continue;
10007 
10008 		case D_INDIRDEP:
10009 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10010 			continue;
10011 
10012 		case D_BMSAFEMAP:
10013 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10014 			continue;
10015 
10016 		case D_JSEG:
10017 			WK_JSEG(wk)->js_buf = NULL;
10018 			continue;
10019 
10020 		case D_FREEBLKS:
10021 			freeblks = WK_FREEBLKS(wk);
10022 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10023 			/*
10024 			 * We have to wait for the freeblks to be journaled
10025 			 * before we can write an inodeblock with updated
10026 			 * pointers.  Be careful to arrange the marker so
10027 			 * we revisit the freeblks if it's not removed by
10028 			 * the first jwait().
10029 			 */
10030 			if (jblkdep != NULL) {
10031 				LIST_REMOVE(&marker, wk_list);
10032 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10033 				jwait(&jblkdep->jb_list, MNT_WAIT);
10034 			}
10035 			continue;
10036 		case D_ALLOCDIRECT:
10037 		case D_ALLOCINDIR:
10038 			/*
10039 			 * We have to wait for the jnewblk to be journaled
10040 			 * before we can write to a block if the contents
10041 			 * may be confused with an earlier file's indirect
10042 			 * at recovery time.  Handle the marker as described
10043 			 * above.
10044 			 */
10045 			newblk = WK_NEWBLK(wk);
10046 			if (newblk->nb_jnewblk != NULL &&
10047 			    indirblk_lookup(newblk->nb_list.wk_mp,
10048 			    newblk->nb_newblkno)) {
10049 				LIST_REMOVE(&marker, wk_list);
10050 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10051 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10052 			}
10053 			continue;
10054 
10055 		case D_SBDEP:
10056 			initiate_write_sbdep(WK_SBDEP(wk));
10057 			continue;
10058 
10059 		case D_MKDIR:
10060 		case D_FREEWORK:
10061 		case D_FREEDEP:
10062 		case D_JSEGDEP:
10063 			continue;
10064 
10065 		default:
10066 			panic("handle_disk_io_initiation: Unexpected type %s",
10067 			    TYPENAME(wk->wk_type));
10068 			/* NOTREACHED */
10069 		}
10070 	}
10071 	FREE_LOCK(ump);
10072 	PRELE(curproc);			/* Allow swapout of kernel stack */
10073 }
10074 
10075 /*
10076  * Called from within the procedure above to deal with unsatisfied
10077  * allocation dependencies in a directory. The buffer must be locked,
10078  * thus, no I/O completion operations can occur while we are
10079  * manipulating its associated dependencies.
10080  */
10081 static void
10082 initiate_write_filepage(pagedep, bp)
10083 	struct pagedep *pagedep;
10084 	struct buf *bp;
10085 {
10086 	struct jremref *jremref;
10087 	struct jmvref *jmvref;
10088 	struct dirrem *dirrem;
10089 	struct diradd *dap;
10090 	struct direct *ep;
10091 	int i;
10092 
10093 	if (pagedep->pd_state & IOSTARTED) {
10094 		/*
10095 		 * This can only happen if there is a driver that does not
10096 		 * understand chaining. Here biodone will reissue the call
10097 		 * to strategy for the incomplete buffers.
10098 		 */
10099 		printf("initiate_write_filepage: already started\n");
10100 		return;
10101 	}
10102 	pagedep->pd_state |= IOSTARTED;
10103 	/*
10104 	 * Wait for all journal remove dependencies to hit the disk.
10105 	 * We can not allow any potentially conflicting directory adds
10106 	 * to be visible before removes and rollback is too difficult.
10107 	 * The per-filesystem lock may be dropped and re-acquired, however
10108 	 * we hold the buf locked so the dependency can not go away.
10109 	 */
10110 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10111 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10112 			jwait(&jremref->jr_list, MNT_WAIT);
10113 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10114 		jwait(&jmvref->jm_list, MNT_WAIT);
10115 	for (i = 0; i < DAHASHSZ; i++) {
10116 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10117 			ep = (struct direct *)
10118 			    ((char *)bp->b_data + dap->da_offset);
10119 			if (ep->d_ino != dap->da_newinum)
10120 				panic("%s: dir inum %ju != new %ju",
10121 				    "initiate_write_filepage",
10122 				    (uintmax_t)ep->d_ino,
10123 				    (uintmax_t)dap->da_newinum);
10124 			if (dap->da_state & DIRCHG)
10125 				ep->d_ino = dap->da_previous->dm_oldinum;
10126 			else
10127 				ep->d_ino = 0;
10128 			dap->da_state &= ~ATTACHED;
10129 			dap->da_state |= UNDONE;
10130 		}
10131 	}
10132 }
10133 
10134 /*
10135  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10136  * Note that any bug fixes made to this routine must be done in the
10137  * version found below.
10138  *
10139  * Called from within the procedure above to deal with unsatisfied
10140  * allocation dependencies in an inodeblock. The buffer must be
10141  * locked, thus, no I/O completion operations can occur while we
10142  * are manipulating its associated dependencies.
10143  */
10144 static void
10145 initiate_write_inodeblock_ufs1(inodedep, bp)
10146 	struct inodedep *inodedep;
10147 	struct buf *bp;			/* The inode block */
10148 {
10149 	struct allocdirect *adp, *lastadp;
10150 	struct ufs1_dinode *dp;
10151 	struct ufs1_dinode *sip;
10152 	struct inoref *inoref;
10153 	struct ufsmount *ump;
10154 	struct fs *fs;
10155 	ufs_lbn_t i;
10156 #ifdef INVARIANTS
10157 	ufs_lbn_t prevlbn = 0;
10158 #endif
10159 	int deplist;
10160 
10161 	if (inodedep->id_state & IOSTARTED)
10162 		panic("initiate_write_inodeblock_ufs1: already started");
10163 	inodedep->id_state |= IOSTARTED;
10164 	fs = inodedep->id_fs;
10165 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10166 	LOCK_OWNED(ump);
10167 	dp = (struct ufs1_dinode *)bp->b_data +
10168 	    ino_to_fsbo(fs, inodedep->id_ino);
10169 
10170 	/*
10171 	 * If we're on the unlinked list but have not yet written our
10172 	 * next pointer initialize it here.
10173 	 */
10174 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10175 		struct inodedep *inon;
10176 
10177 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10178 		dp->di_freelink = inon ? inon->id_ino : 0;
10179 	}
10180 	/*
10181 	 * If the bitmap is not yet written, then the allocated
10182 	 * inode cannot be written to disk.
10183 	 */
10184 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10185 		if (inodedep->id_savedino1 != NULL)
10186 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10187 		FREE_LOCK(ump);
10188 		sip = malloc(sizeof(struct ufs1_dinode),
10189 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10190 		ACQUIRE_LOCK(ump);
10191 		inodedep->id_savedino1 = sip;
10192 		*inodedep->id_savedino1 = *dp;
10193 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10194 		dp->di_gen = inodedep->id_savedino1->di_gen;
10195 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10196 		return;
10197 	}
10198 	/*
10199 	 * If no dependencies, then there is nothing to roll back.
10200 	 */
10201 	inodedep->id_savedsize = dp->di_size;
10202 	inodedep->id_savedextsize = 0;
10203 	inodedep->id_savednlink = dp->di_nlink;
10204 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10205 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10206 		return;
10207 	/*
10208 	 * Revert the link count to that of the first unwritten journal entry.
10209 	 */
10210 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10211 	if (inoref)
10212 		dp->di_nlink = inoref->if_nlink;
10213 	/*
10214 	 * Set the dependencies to busy.
10215 	 */
10216 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10217 	     adp = TAILQ_NEXT(adp, ad_next)) {
10218 #ifdef INVARIANTS
10219 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10220 			panic("softdep_write_inodeblock: lbn order");
10221 		prevlbn = adp->ad_offset;
10222 		if (adp->ad_offset < UFS_NDADDR &&
10223 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10224 			panic("%s: direct pointer #%jd mismatch %d != %jd",
10225 			    "softdep_write_inodeblock",
10226 			    (intmax_t)adp->ad_offset,
10227 			    dp->di_db[adp->ad_offset],
10228 			    (intmax_t)adp->ad_newblkno);
10229 		if (adp->ad_offset >= UFS_NDADDR &&
10230 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10231 			panic("%s: indirect pointer #%jd mismatch %d != %jd",
10232 			    "softdep_write_inodeblock",
10233 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10234 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10235 			    (intmax_t)adp->ad_newblkno);
10236 		deplist |= 1 << adp->ad_offset;
10237 		if ((adp->ad_state & ATTACHED) == 0)
10238 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10239 			    adp->ad_state);
10240 #endif /* INVARIANTS */
10241 		adp->ad_state &= ~ATTACHED;
10242 		adp->ad_state |= UNDONE;
10243 	}
10244 	/*
10245 	 * The on-disk inode cannot claim to be any larger than the last
10246 	 * fragment that has been written. Otherwise, the on-disk inode
10247 	 * might have fragments that were not the last block in the file
10248 	 * which would corrupt the filesystem.
10249 	 */
10250 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10251 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10252 		if (adp->ad_offset >= UFS_NDADDR)
10253 			break;
10254 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10255 		/* keep going until hitting a rollback to a frag */
10256 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10257 			continue;
10258 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10259 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10260 #ifdef INVARIANTS
10261 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10262 				panic("softdep_write_inodeblock: lost dep1");
10263 #endif /* INVARIANTS */
10264 			dp->di_db[i] = 0;
10265 		}
10266 		for (i = 0; i < UFS_NIADDR; i++) {
10267 #ifdef INVARIANTS
10268 			if (dp->di_ib[i] != 0 &&
10269 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10270 				panic("softdep_write_inodeblock: lost dep2");
10271 #endif /* INVARIANTS */
10272 			dp->di_ib[i] = 0;
10273 		}
10274 		return;
10275 	}
10276 	/*
10277 	 * If we have zero'ed out the last allocated block of the file,
10278 	 * roll back the size to the last currently allocated block.
10279 	 * We know that this last allocated block is a full-sized as
10280 	 * we already checked for fragments in the loop above.
10281 	 */
10282 	if (lastadp != NULL &&
10283 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10284 		for (i = lastadp->ad_offset; i >= 0; i--)
10285 			if (dp->di_db[i] != 0)
10286 				break;
10287 		dp->di_size = (i + 1) * fs->fs_bsize;
10288 	}
10289 	/*
10290 	 * The only dependencies are for indirect blocks.
10291 	 *
10292 	 * The file size for indirect block additions is not guaranteed.
10293 	 * Such a guarantee would be non-trivial to achieve. The conventional
10294 	 * synchronous write implementation also does not make this guarantee.
10295 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10296 	 * can be over-estimated without destroying integrity when the file
10297 	 * moves into the indirect blocks (i.e., is large). If we want to
10298 	 * postpone fsck, we are stuck with this argument.
10299 	 */
10300 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10301 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10302 }
10303 
10304 /*
10305  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10306  * Note that any bug fixes made to this routine must be done in the
10307  * version found above.
10308  *
10309  * Called from within the procedure above to deal with unsatisfied
10310  * allocation dependencies in an inodeblock. The buffer must be
10311  * locked, thus, no I/O completion operations can occur while we
10312  * are manipulating its associated dependencies.
10313  */
10314 static void
10315 initiate_write_inodeblock_ufs2(inodedep, bp)
10316 	struct inodedep *inodedep;
10317 	struct buf *bp;			/* The inode block */
10318 {
10319 	struct allocdirect *adp, *lastadp;
10320 	struct ufs2_dinode *dp;
10321 	struct ufs2_dinode *sip;
10322 	struct inoref *inoref;
10323 	struct ufsmount *ump;
10324 	struct fs *fs;
10325 	ufs_lbn_t i;
10326 #ifdef INVARIANTS
10327 	ufs_lbn_t prevlbn = 0;
10328 #endif
10329 	int deplist;
10330 
10331 	if (inodedep->id_state & IOSTARTED)
10332 		panic("initiate_write_inodeblock_ufs2: already started");
10333 	inodedep->id_state |= IOSTARTED;
10334 	fs = inodedep->id_fs;
10335 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10336 	LOCK_OWNED(ump);
10337 	dp = (struct ufs2_dinode *)bp->b_data +
10338 	    ino_to_fsbo(fs, inodedep->id_ino);
10339 
10340 	/*
10341 	 * If we're on the unlinked list but have not yet written our
10342 	 * next pointer initialize it here.
10343 	 */
10344 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10345 		struct inodedep *inon;
10346 
10347 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10348 		dp->di_freelink = inon ? inon->id_ino : 0;
10349 	}
10350 	/*
10351 	 * If the bitmap is not yet written, then the allocated
10352 	 * inode cannot be written to disk.
10353 	 */
10354 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10355 		if (inodedep->id_savedino2 != NULL)
10356 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10357 		FREE_LOCK(ump);
10358 		sip = malloc(sizeof(struct ufs2_dinode),
10359 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10360 		ACQUIRE_LOCK(ump);
10361 		inodedep->id_savedino2 = sip;
10362 		*inodedep->id_savedino2 = *dp;
10363 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10364 		dp->di_gen = inodedep->id_savedino2->di_gen;
10365 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10366 		return;
10367 	}
10368 	/*
10369 	 * If no dependencies, then there is nothing to roll back.
10370 	 */
10371 	inodedep->id_savedsize = dp->di_size;
10372 	inodedep->id_savedextsize = dp->di_extsize;
10373 	inodedep->id_savednlink = dp->di_nlink;
10374 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10375 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10376 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10377 		return;
10378 	/*
10379 	 * Revert the link count to that of the first unwritten journal entry.
10380 	 */
10381 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10382 	if (inoref)
10383 		dp->di_nlink = inoref->if_nlink;
10384 
10385 	/*
10386 	 * Set the ext data dependencies to busy.
10387 	 */
10388 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10389 	     adp = TAILQ_NEXT(adp, ad_next)) {
10390 #ifdef INVARIANTS
10391 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10392 			panic("softdep_write_inodeblock: lbn order");
10393 		prevlbn = adp->ad_offset;
10394 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10395 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10396 			    "softdep_write_inodeblock",
10397 			    (intmax_t)adp->ad_offset,
10398 			    (intmax_t)dp->di_extb[adp->ad_offset],
10399 			    (intmax_t)adp->ad_newblkno);
10400 		deplist |= 1 << adp->ad_offset;
10401 		if ((adp->ad_state & ATTACHED) == 0)
10402 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10403 			    adp->ad_state);
10404 #endif /* INVARIANTS */
10405 		adp->ad_state &= ~ATTACHED;
10406 		adp->ad_state |= UNDONE;
10407 	}
10408 	/*
10409 	 * The on-disk inode cannot claim to be any larger than the last
10410 	 * fragment that has been written. Otherwise, the on-disk inode
10411 	 * might have fragments that were not the last block in the ext
10412 	 * data which would corrupt the filesystem.
10413 	 */
10414 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10415 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10416 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10417 		/* keep going until hitting a rollback to a frag */
10418 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10419 			continue;
10420 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10421 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10422 #ifdef INVARIANTS
10423 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10424 				panic("softdep_write_inodeblock: lost dep1");
10425 #endif /* INVARIANTS */
10426 			dp->di_extb[i] = 0;
10427 		}
10428 		lastadp = NULL;
10429 		break;
10430 	}
10431 	/*
10432 	 * If we have zero'ed out the last allocated block of the ext
10433 	 * data, roll back the size to the last currently allocated block.
10434 	 * We know that this last allocated block is a full-sized as
10435 	 * we already checked for fragments in the loop above.
10436 	 */
10437 	if (lastadp != NULL &&
10438 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10439 		for (i = lastadp->ad_offset; i >= 0; i--)
10440 			if (dp->di_extb[i] != 0)
10441 				break;
10442 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10443 	}
10444 	/*
10445 	 * Set the file data dependencies to busy.
10446 	 */
10447 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10448 	     adp = TAILQ_NEXT(adp, ad_next)) {
10449 #ifdef INVARIANTS
10450 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10451 			panic("softdep_write_inodeblock: lbn order");
10452 		if ((adp->ad_state & ATTACHED) == 0)
10453 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10454 		prevlbn = adp->ad_offset;
10455 		if (adp->ad_offset < UFS_NDADDR &&
10456 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10457 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10458 			    "softdep_write_inodeblock",
10459 			    (intmax_t)adp->ad_offset,
10460 			    (intmax_t)dp->di_db[adp->ad_offset],
10461 			    (intmax_t)adp->ad_newblkno);
10462 		if (adp->ad_offset >= UFS_NDADDR &&
10463 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10464 			panic("%s indirect pointer #%jd mismatch %jd != %jd",
10465 			    "softdep_write_inodeblock:",
10466 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10467 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10468 			    (intmax_t)adp->ad_newblkno);
10469 		deplist |= 1 << adp->ad_offset;
10470 		if ((adp->ad_state & ATTACHED) == 0)
10471 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10472 			    adp->ad_state);
10473 #endif /* INVARIANTS */
10474 		adp->ad_state &= ~ATTACHED;
10475 		adp->ad_state |= UNDONE;
10476 	}
10477 	/*
10478 	 * The on-disk inode cannot claim to be any larger than the last
10479 	 * fragment that has been written. Otherwise, the on-disk inode
10480 	 * might have fragments that were not the last block in the file
10481 	 * which would corrupt the filesystem.
10482 	 */
10483 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10484 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10485 		if (adp->ad_offset >= UFS_NDADDR)
10486 			break;
10487 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10488 		/* keep going until hitting a rollback to a frag */
10489 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10490 			continue;
10491 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10492 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10493 #ifdef INVARIANTS
10494 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10495 				panic("softdep_write_inodeblock: lost dep2");
10496 #endif /* INVARIANTS */
10497 			dp->di_db[i] = 0;
10498 		}
10499 		for (i = 0; i < UFS_NIADDR; i++) {
10500 #ifdef INVARIANTS
10501 			if (dp->di_ib[i] != 0 &&
10502 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10503 				panic("softdep_write_inodeblock: lost dep3");
10504 #endif /* INVARIANTS */
10505 			dp->di_ib[i] = 0;
10506 		}
10507 		return;
10508 	}
10509 	/*
10510 	 * If we have zero'ed out the last allocated block of the file,
10511 	 * roll back the size to the last currently allocated block.
10512 	 * We know that this last allocated block is a full-sized as
10513 	 * we already checked for fragments in the loop above.
10514 	 */
10515 	if (lastadp != NULL &&
10516 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10517 		for (i = lastadp->ad_offset; i >= 0; i--)
10518 			if (dp->di_db[i] != 0)
10519 				break;
10520 		dp->di_size = (i + 1) * fs->fs_bsize;
10521 	}
10522 	/*
10523 	 * The only dependencies are for indirect blocks.
10524 	 *
10525 	 * The file size for indirect block additions is not guaranteed.
10526 	 * Such a guarantee would be non-trivial to achieve. The conventional
10527 	 * synchronous write implementation also does not make this guarantee.
10528 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10529 	 * can be over-estimated without destroying integrity when the file
10530 	 * moves into the indirect blocks (i.e., is large). If we want to
10531 	 * postpone fsck, we are stuck with this argument.
10532 	 */
10533 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10534 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10535 }
10536 
10537 /*
10538  * Cancel an indirdep as a result of truncation.  Release all of the
10539  * children allocindirs and place their journal work on the appropriate
10540  * list.
10541  */
10542 static void
10543 cancel_indirdep(indirdep, bp, freeblks)
10544 	struct indirdep *indirdep;
10545 	struct buf *bp;
10546 	struct freeblks *freeblks;
10547 {
10548 	struct allocindir *aip;
10549 
10550 	/*
10551 	 * None of the indirect pointers will ever be visible,
10552 	 * so they can simply be tossed. GOINGAWAY ensures
10553 	 * that allocated pointers will be saved in the buffer
10554 	 * cache until they are freed. Note that they will
10555 	 * only be able to be found by their physical address
10556 	 * since the inode mapping the logical address will
10557 	 * be gone. The save buffer used for the safe copy
10558 	 * was allocated in setup_allocindir_phase2 using
10559 	 * the physical address so it could be used for this
10560 	 * purpose. Hence we swap the safe copy with the real
10561 	 * copy, allowing the safe copy to be freed and holding
10562 	 * on to the real copy for later use in indir_trunc.
10563 	 */
10564 	if (indirdep->ir_state & GOINGAWAY)
10565 		panic("cancel_indirdep: already gone");
10566 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10567 		indirdep->ir_state |= DEPCOMPLETE;
10568 		LIST_REMOVE(indirdep, ir_next);
10569 	}
10570 	indirdep->ir_state |= GOINGAWAY;
10571 	/*
10572 	 * Pass in bp for blocks still have journal writes
10573 	 * pending so we can cancel them on their own.
10574 	 */
10575 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10576 		cancel_allocindir(aip, bp, freeblks, 0);
10577 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10578 		cancel_allocindir(aip, NULL, freeblks, 0);
10579 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10580 		cancel_allocindir(aip, NULL, freeblks, 0);
10581 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10582 		cancel_allocindir(aip, NULL, freeblks, 0);
10583 	/*
10584 	 * If there are pending partial truncations we need to keep the
10585 	 * old block copy around until they complete.  This is because
10586 	 * the current b_data is not a perfect superset of the available
10587 	 * blocks.
10588 	 */
10589 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10590 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10591 	else
10592 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10593 	WORKLIST_REMOVE(&indirdep->ir_list);
10594 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10595 	indirdep->ir_bp = NULL;
10596 	indirdep->ir_freeblks = freeblks;
10597 }
10598 
10599 /*
10600  * Free an indirdep once it no longer has new pointers to track.
10601  */
10602 static void
10603 free_indirdep(indirdep)
10604 	struct indirdep *indirdep;
10605 {
10606 
10607 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10608 	    ("free_indirdep: Indir trunc list not empty."));
10609 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10610 	    ("free_indirdep: Complete head not empty."));
10611 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10612 	    ("free_indirdep: write head not empty."));
10613 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10614 	    ("free_indirdep: done head not empty."));
10615 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10616 	    ("free_indirdep: deplist head not empty."));
10617 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10618 	    ("free_indirdep: %p still on newblk list.", indirdep));
10619 	KASSERT(indirdep->ir_saveddata == NULL,
10620 	    ("free_indirdep: %p still has saved data.", indirdep));
10621 	if (indirdep->ir_state & ONWORKLIST)
10622 		WORKLIST_REMOVE(&indirdep->ir_list);
10623 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10624 }
10625 
10626 /*
10627  * Called before a write to an indirdep.  This routine is responsible for
10628  * rolling back pointers to a safe state which includes only those
10629  * allocindirs which have been completed.
10630  */
10631 static void
10632 initiate_write_indirdep(indirdep, bp)
10633 	struct indirdep *indirdep;
10634 	struct buf *bp;
10635 {
10636 	struct ufsmount *ump;
10637 
10638 	indirdep->ir_state |= IOSTARTED;
10639 	if (indirdep->ir_state & GOINGAWAY)
10640 		panic("disk_io_initiation: indirdep gone");
10641 	/*
10642 	 * If there are no remaining dependencies, this will be writing
10643 	 * the real pointers.
10644 	 */
10645 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10646 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10647 		return;
10648 	/*
10649 	 * Replace up-to-date version with safe version.
10650 	 */
10651 	if (indirdep->ir_saveddata == NULL) {
10652 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10653 		LOCK_OWNED(ump);
10654 		FREE_LOCK(ump);
10655 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10656 		    M_SOFTDEP_FLAGS);
10657 		ACQUIRE_LOCK(ump);
10658 	}
10659 	indirdep->ir_state &= ~ATTACHED;
10660 	indirdep->ir_state |= UNDONE;
10661 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10662 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10663 	    bp->b_bcount);
10664 }
10665 
10666 /*
10667  * Called when an inode has been cleared in a cg bitmap.  This finally
10668  * eliminates any canceled jaddrefs
10669  */
10670 void
10671 softdep_setup_inofree(mp, bp, ino, wkhd)
10672 	struct mount *mp;
10673 	struct buf *bp;
10674 	ino_t ino;
10675 	struct workhead *wkhd;
10676 {
10677 	struct worklist *wk, *wkn;
10678 	struct inodedep *inodedep;
10679 	struct ufsmount *ump;
10680 	uint8_t *inosused;
10681 	struct cg *cgp;
10682 	struct fs *fs;
10683 
10684 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10685 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10686 	ump = VFSTOUFS(mp);
10687 	ACQUIRE_LOCK(ump);
10688 	fs = ump->um_fs;
10689 	cgp = (struct cg *)bp->b_data;
10690 	inosused = cg_inosused(cgp);
10691 	if (isset(inosused, ino % fs->fs_ipg))
10692 		panic("softdep_setup_inofree: inode %ju not freed.",
10693 		    (uintmax_t)ino);
10694 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10695 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10696 		    (uintmax_t)ino, inodedep);
10697 	if (wkhd) {
10698 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10699 			if (wk->wk_type != D_JADDREF)
10700 				continue;
10701 			WORKLIST_REMOVE(wk);
10702 			/*
10703 			 * We can free immediately even if the jaddref
10704 			 * isn't attached in a background write as now
10705 			 * the bitmaps are reconciled.
10706 			 */
10707 			wk->wk_state |= COMPLETE | ATTACHED;
10708 			free_jaddref(WK_JADDREF(wk));
10709 		}
10710 		jwork_move(&bp->b_dep, wkhd);
10711 	}
10712 	FREE_LOCK(ump);
10713 }
10714 
10715 
10716 /*
10717  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10718  * map.  Any dependencies waiting for the write to clear are added to the
10719  * buf's list and any jnewblks that are being canceled are discarded
10720  * immediately.
10721  */
10722 void
10723 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10724 	struct mount *mp;
10725 	struct buf *bp;
10726 	ufs2_daddr_t blkno;
10727 	int frags;
10728 	struct workhead *wkhd;
10729 {
10730 	struct bmsafemap *bmsafemap;
10731 	struct jnewblk *jnewblk;
10732 	struct ufsmount *ump;
10733 	struct worklist *wk;
10734 	struct fs *fs;
10735 #ifdef SUJ_DEBUG
10736 	uint8_t *blksfree;
10737 	struct cg *cgp;
10738 	ufs2_daddr_t jstart;
10739 	ufs2_daddr_t jend;
10740 	ufs2_daddr_t end;
10741 	long bno;
10742 	int i;
10743 #endif
10744 
10745 	CTR3(KTR_SUJ,
10746 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10747 	    blkno, frags, wkhd);
10748 
10749 	ump = VFSTOUFS(mp);
10750 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10751 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10752 	ACQUIRE_LOCK(ump);
10753 	/* Lookup the bmsafemap so we track when it is dirty. */
10754 	fs = ump->um_fs;
10755 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10756 	/*
10757 	 * Detach any jnewblks which have been canceled.  They must linger
10758 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10759 	 * an unjournaled allocation from hitting the disk.
10760 	 */
10761 	if (wkhd) {
10762 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10763 			CTR2(KTR_SUJ,
10764 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10765 			    blkno, wk->wk_type);
10766 			WORKLIST_REMOVE(wk);
10767 			if (wk->wk_type != D_JNEWBLK) {
10768 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10769 				continue;
10770 			}
10771 			jnewblk = WK_JNEWBLK(wk);
10772 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10773 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10774 #ifdef SUJ_DEBUG
10775 			/*
10776 			 * Assert that this block is free in the bitmap
10777 			 * before we discard the jnewblk.
10778 			 */
10779 			cgp = (struct cg *)bp->b_data;
10780 			blksfree = cg_blksfree(cgp);
10781 			bno = dtogd(fs, jnewblk->jn_blkno);
10782 			for (i = jnewblk->jn_oldfrags;
10783 			    i < jnewblk->jn_frags; i++) {
10784 				if (isset(blksfree, bno + i))
10785 					continue;
10786 				panic("softdep_setup_blkfree: not free");
10787 			}
10788 #endif
10789 			/*
10790 			 * Even if it's not attached we can free immediately
10791 			 * as the new bitmap is correct.
10792 			 */
10793 			wk->wk_state |= COMPLETE | ATTACHED;
10794 			free_jnewblk(jnewblk);
10795 		}
10796 	}
10797 
10798 #ifdef SUJ_DEBUG
10799 	/*
10800 	 * Assert that we are not freeing a block which has an outstanding
10801 	 * allocation dependency.
10802 	 */
10803 	fs = VFSTOUFS(mp)->um_fs;
10804 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10805 	end = blkno + frags;
10806 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10807 		/*
10808 		 * Don't match against blocks that will be freed when the
10809 		 * background write is done.
10810 		 */
10811 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10812 		    (COMPLETE | DEPCOMPLETE))
10813 			continue;
10814 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10815 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10816 		if ((blkno >= jstart && blkno < jend) ||
10817 		    (end > jstart && end <= jend)) {
10818 			printf("state 0x%X %jd - %d %d dep %p\n",
10819 			    jnewblk->jn_state, jnewblk->jn_blkno,
10820 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10821 			    jnewblk->jn_dep);
10822 			panic("softdep_setup_blkfree: "
10823 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10824 			    blkno, end, frags, jstart, jend);
10825 		}
10826 	}
10827 #endif
10828 	FREE_LOCK(ump);
10829 }
10830 
10831 /*
10832  * Revert a block allocation when the journal record that describes it
10833  * is not yet written.
10834  */
10835 static int
10836 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10837 	struct jnewblk *jnewblk;
10838 	struct fs *fs;
10839 	struct cg *cgp;
10840 	uint8_t *blksfree;
10841 {
10842 	ufs1_daddr_t fragno;
10843 	long cgbno, bbase;
10844 	int frags, blk;
10845 	int i;
10846 
10847 	frags = 0;
10848 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10849 	/*
10850 	 * We have to test which frags need to be rolled back.  We may
10851 	 * be operating on a stale copy when doing background writes.
10852 	 */
10853 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10854 		if (isclr(blksfree, cgbno + i))
10855 			frags++;
10856 	if (frags == 0)
10857 		return (0);
10858 	/*
10859 	 * This is mostly ffs_blkfree() sans some validation and
10860 	 * superblock updates.
10861 	 */
10862 	if (frags == fs->fs_frag) {
10863 		fragno = fragstoblks(fs, cgbno);
10864 		ffs_setblock(fs, blksfree, fragno);
10865 		ffs_clusteracct(fs, cgp, fragno, 1);
10866 		cgp->cg_cs.cs_nbfree++;
10867 	} else {
10868 		cgbno += jnewblk->jn_oldfrags;
10869 		bbase = cgbno - fragnum(fs, cgbno);
10870 		/* Decrement the old frags.  */
10871 		blk = blkmap(fs, blksfree, bbase);
10872 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10873 		/* Deallocate the fragment */
10874 		for (i = 0; i < frags; i++)
10875 			setbit(blksfree, cgbno + i);
10876 		cgp->cg_cs.cs_nffree += frags;
10877 		/* Add back in counts associated with the new frags */
10878 		blk = blkmap(fs, blksfree, bbase);
10879 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10880 		/* If a complete block has been reassembled, account for it. */
10881 		fragno = fragstoblks(fs, bbase);
10882 		if (ffs_isblock(fs, blksfree, fragno)) {
10883 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10884 			ffs_clusteracct(fs, cgp, fragno, 1);
10885 			cgp->cg_cs.cs_nbfree++;
10886 		}
10887 	}
10888 	stat_jnewblk++;
10889 	jnewblk->jn_state &= ~ATTACHED;
10890 	jnewblk->jn_state |= UNDONE;
10891 
10892 	return (frags);
10893 }
10894 
10895 static void
10896 initiate_write_bmsafemap(bmsafemap, bp)
10897 	struct bmsafemap *bmsafemap;
10898 	struct buf *bp;			/* The cg block. */
10899 {
10900 	struct jaddref *jaddref;
10901 	struct jnewblk *jnewblk;
10902 	uint8_t *inosused;
10903 	uint8_t *blksfree;
10904 	struct cg *cgp;
10905 	struct fs *fs;
10906 	ino_t ino;
10907 
10908 	/*
10909 	 * If this is a background write, we did this at the time that
10910 	 * the copy was made, so do not need to do it again.
10911 	 */
10912 	if (bmsafemap->sm_state & IOSTARTED)
10913 		return;
10914 	bmsafemap->sm_state |= IOSTARTED;
10915 	/*
10916 	 * Clear any inode allocations which are pending journal writes.
10917 	 */
10918 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10919 		cgp = (struct cg *)bp->b_data;
10920 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10921 		inosused = cg_inosused(cgp);
10922 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10923 			ino = jaddref->ja_ino % fs->fs_ipg;
10924 			if (isset(inosused, ino)) {
10925 				if ((jaddref->ja_mode & IFMT) == IFDIR)
10926 					cgp->cg_cs.cs_ndir--;
10927 				cgp->cg_cs.cs_nifree++;
10928 				clrbit(inosused, ino);
10929 				jaddref->ja_state &= ~ATTACHED;
10930 				jaddref->ja_state |= UNDONE;
10931 				stat_jaddref++;
10932 			} else
10933 				panic("initiate_write_bmsafemap: inode %ju "
10934 				    "marked free", (uintmax_t)jaddref->ja_ino);
10935 		}
10936 	}
10937 	/*
10938 	 * Clear any block allocations which are pending journal writes.
10939 	 */
10940 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10941 		cgp = (struct cg *)bp->b_data;
10942 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10943 		blksfree = cg_blksfree(cgp);
10944 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10945 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10946 				continue;
10947 			panic("initiate_write_bmsafemap: block %jd "
10948 			    "marked free", jnewblk->jn_blkno);
10949 		}
10950 	}
10951 	/*
10952 	 * Move allocation lists to the written lists so they can be
10953 	 * cleared once the block write is complete.
10954 	 */
10955 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10956 	    inodedep, id_deps);
10957 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10958 	    newblk, nb_deps);
10959 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10960 	    wk_list);
10961 }
10962 
10963 /*
10964  * This routine is called during the completion interrupt
10965  * service routine for a disk write (from the procedure called
10966  * by the device driver to inform the filesystem caches of
10967  * a request completion).  It should be called early in this
10968  * procedure, before the block is made available to other
10969  * processes or other routines are called.
10970  *
10971  */
10972 static void
10973 softdep_disk_write_complete(bp)
10974 	struct buf *bp;		/* describes the completed disk write */
10975 {
10976 	struct worklist *wk;
10977 	struct worklist *owk;
10978 	struct ufsmount *ump;
10979 	struct workhead reattach;
10980 	struct freeblks *freeblks;
10981 	struct buf *sbp;
10982 
10983 	ump = softdep_bp_to_mp(bp);
10984 	if (ump == NULL)
10985 		return;
10986 
10987 	sbp = NULL;
10988 
10989 	/*
10990 	 * If an error occurred while doing the write, then the data
10991 	 * has not hit the disk and the dependencies cannot be processed.
10992 	 * But we do have to go through and roll forward any dependencies
10993 	 * that were rolled back before the disk write.
10994 	 */
10995 	ACQUIRE_LOCK(ump);
10996 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
10997 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
10998 			switch (wk->wk_type) {
10999 
11000 			case D_PAGEDEP:
11001 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11002 				continue;
11003 
11004 			case D_INODEDEP:
11005 				handle_written_inodeblock(WK_INODEDEP(wk),
11006 				    bp, 0);
11007 				continue;
11008 
11009 			case D_BMSAFEMAP:
11010 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11011 				    bp, 0);
11012 				continue;
11013 
11014 			case D_INDIRDEP:
11015 				handle_written_indirdep(WK_INDIRDEP(wk),
11016 				    bp, &sbp, 0);
11017 				continue;
11018 			default:
11019 				/* nothing to roll forward */
11020 				continue;
11021 			}
11022 		}
11023 		FREE_LOCK(ump);
11024 		return;
11025 	}
11026 	LIST_INIT(&reattach);
11027 
11028 	/*
11029 	 * Ump SU lock must not be released anywhere in this code segment.
11030 	 */
11031 	owk = NULL;
11032 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11033 		WORKLIST_REMOVE(wk);
11034 		atomic_add_long(&dep_write[wk->wk_type], 1);
11035 		if (wk == owk)
11036 			panic("duplicate worklist: %p\n", wk);
11037 		owk = wk;
11038 		switch (wk->wk_type) {
11039 
11040 		case D_PAGEDEP:
11041 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11042 			    WRITESUCCEEDED))
11043 				WORKLIST_INSERT(&reattach, wk);
11044 			continue;
11045 
11046 		case D_INODEDEP:
11047 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11048 			    WRITESUCCEEDED))
11049 				WORKLIST_INSERT(&reattach, wk);
11050 			continue;
11051 
11052 		case D_BMSAFEMAP:
11053 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11054 			    WRITESUCCEEDED))
11055 				WORKLIST_INSERT(&reattach, wk);
11056 			continue;
11057 
11058 		case D_MKDIR:
11059 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11060 			continue;
11061 
11062 		case D_ALLOCDIRECT:
11063 			wk->wk_state |= COMPLETE;
11064 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11065 			continue;
11066 
11067 		case D_ALLOCINDIR:
11068 			wk->wk_state |= COMPLETE;
11069 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11070 			continue;
11071 
11072 		case D_INDIRDEP:
11073 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11074 			    WRITESUCCEEDED))
11075 				WORKLIST_INSERT(&reattach, wk);
11076 			continue;
11077 
11078 		case D_FREEBLKS:
11079 			wk->wk_state |= COMPLETE;
11080 			freeblks = WK_FREEBLKS(wk);
11081 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11082 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11083 				add_to_worklist(wk, WK_NODELAY);
11084 			continue;
11085 
11086 		case D_FREEWORK:
11087 			handle_written_freework(WK_FREEWORK(wk));
11088 			break;
11089 
11090 		case D_JSEGDEP:
11091 			free_jsegdep(WK_JSEGDEP(wk));
11092 			continue;
11093 
11094 		case D_JSEG:
11095 			handle_written_jseg(WK_JSEG(wk), bp);
11096 			continue;
11097 
11098 		case D_SBDEP:
11099 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11100 				WORKLIST_INSERT(&reattach, wk);
11101 			continue;
11102 
11103 		case D_FREEDEP:
11104 			free_freedep(WK_FREEDEP(wk));
11105 			continue;
11106 
11107 		default:
11108 			panic("handle_disk_write_complete: Unknown type %s",
11109 			    TYPENAME(wk->wk_type));
11110 			/* NOTREACHED */
11111 		}
11112 	}
11113 	/*
11114 	 * Reattach any requests that must be redone.
11115 	 */
11116 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11117 		WORKLIST_REMOVE(wk);
11118 		WORKLIST_INSERT(&bp->b_dep, wk);
11119 	}
11120 	FREE_LOCK(ump);
11121 	if (sbp)
11122 		brelse(sbp);
11123 }
11124 
11125 /*
11126  * Called from within softdep_disk_write_complete above. Note that
11127  * this routine is always called from interrupt level with further
11128  * splbio interrupts blocked.
11129  */
11130 static void
11131 handle_allocdirect_partdone(adp, wkhd)
11132 	struct allocdirect *adp;	/* the completed allocdirect */
11133 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11134 {
11135 	struct allocdirectlst *listhead;
11136 	struct allocdirect *listadp;
11137 	struct inodedep *inodedep;
11138 	long bsize;
11139 
11140 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11141 		return;
11142 	/*
11143 	 * The on-disk inode cannot claim to be any larger than the last
11144 	 * fragment that has been written. Otherwise, the on-disk inode
11145 	 * might have fragments that were not the last block in the file
11146 	 * which would corrupt the filesystem. Thus, we cannot free any
11147 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11148 	 * these blocks must be rolled back to zero before writing the inode.
11149 	 * We check the currently active set of allocdirects in id_inoupdt
11150 	 * or id_extupdt as appropriate.
11151 	 */
11152 	inodedep = adp->ad_inodedep;
11153 	bsize = inodedep->id_fs->fs_bsize;
11154 	if (adp->ad_state & EXTDATA)
11155 		listhead = &inodedep->id_extupdt;
11156 	else
11157 		listhead = &inodedep->id_inoupdt;
11158 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11159 		/* found our block */
11160 		if (listadp == adp)
11161 			break;
11162 		/* continue if ad_oldlbn is not a fragment */
11163 		if (listadp->ad_oldsize == 0 ||
11164 		    listadp->ad_oldsize == bsize)
11165 			continue;
11166 		/* hit a fragment */
11167 		return;
11168 	}
11169 	/*
11170 	 * If we have reached the end of the current list without
11171 	 * finding the just finished dependency, then it must be
11172 	 * on the future dependency list. Future dependencies cannot
11173 	 * be freed until they are moved to the current list.
11174 	 */
11175 	if (listadp == NULL) {
11176 #ifdef DEBUG
11177 		if (adp->ad_state & EXTDATA)
11178 			listhead = &inodedep->id_newextupdt;
11179 		else
11180 			listhead = &inodedep->id_newinoupdt;
11181 		TAILQ_FOREACH(listadp, listhead, ad_next)
11182 			/* found our block */
11183 			if (listadp == adp)
11184 				break;
11185 		if (listadp == NULL)
11186 			panic("handle_allocdirect_partdone: lost dep");
11187 #endif /* DEBUG */
11188 		return;
11189 	}
11190 	/*
11191 	 * If we have found the just finished dependency, then queue
11192 	 * it along with anything that follows it that is complete.
11193 	 * Since the pointer has not yet been written in the inode
11194 	 * as the dependency prevents it, place the allocdirect on the
11195 	 * bufwait list where it will be freed once the pointer is
11196 	 * valid.
11197 	 */
11198 	if (wkhd == NULL)
11199 		wkhd = &inodedep->id_bufwait;
11200 	for (; adp; adp = listadp) {
11201 		listadp = TAILQ_NEXT(adp, ad_next);
11202 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11203 			return;
11204 		TAILQ_REMOVE(listhead, adp, ad_next);
11205 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11206 	}
11207 }
11208 
11209 /*
11210  * Called from within softdep_disk_write_complete above.  This routine
11211  * completes successfully written allocindirs.
11212  */
11213 static void
11214 handle_allocindir_partdone(aip)
11215 	struct allocindir *aip;		/* the completed allocindir */
11216 {
11217 	struct indirdep *indirdep;
11218 
11219 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11220 		return;
11221 	indirdep = aip->ai_indirdep;
11222 	LIST_REMOVE(aip, ai_next);
11223 	/*
11224 	 * Don't set a pointer while the buffer is undergoing IO or while
11225 	 * we have active truncations.
11226 	 */
11227 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11228 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11229 		return;
11230 	}
11231 	if (indirdep->ir_state & UFS1FMT)
11232 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11233 		    aip->ai_newblkno;
11234 	else
11235 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11236 		    aip->ai_newblkno;
11237 	/*
11238 	 * Await the pointer write before freeing the allocindir.
11239 	 */
11240 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11241 }
11242 
11243 /*
11244  * Release segments held on a jwork list.
11245  */
11246 static void
11247 handle_jwork(wkhd)
11248 	struct workhead *wkhd;
11249 {
11250 	struct worklist *wk;
11251 
11252 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11253 		WORKLIST_REMOVE(wk);
11254 		switch (wk->wk_type) {
11255 		case D_JSEGDEP:
11256 			free_jsegdep(WK_JSEGDEP(wk));
11257 			continue;
11258 		case D_FREEDEP:
11259 			free_freedep(WK_FREEDEP(wk));
11260 			continue;
11261 		case D_FREEFRAG:
11262 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11263 			WORKITEM_FREE(wk, D_FREEFRAG);
11264 			continue;
11265 		case D_FREEWORK:
11266 			handle_written_freework(WK_FREEWORK(wk));
11267 			continue;
11268 		default:
11269 			panic("handle_jwork: Unknown type %s\n",
11270 			    TYPENAME(wk->wk_type));
11271 		}
11272 	}
11273 }
11274 
11275 /*
11276  * Handle the bufwait list on an inode when it is safe to release items
11277  * held there.  This normally happens after an inode block is written but
11278  * may be delayed and handled later if there are pending journal items that
11279  * are not yet safe to be released.
11280  */
11281 static struct freefile *
11282 handle_bufwait(inodedep, refhd)
11283 	struct inodedep *inodedep;
11284 	struct workhead *refhd;
11285 {
11286 	struct jaddref *jaddref;
11287 	struct freefile *freefile;
11288 	struct worklist *wk;
11289 
11290 	freefile = NULL;
11291 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11292 		WORKLIST_REMOVE(wk);
11293 		switch (wk->wk_type) {
11294 		case D_FREEFILE:
11295 			/*
11296 			 * We defer adding freefile to the worklist
11297 			 * until all other additions have been made to
11298 			 * ensure that it will be done after all the
11299 			 * old blocks have been freed.
11300 			 */
11301 			if (freefile != NULL)
11302 				panic("handle_bufwait: freefile");
11303 			freefile = WK_FREEFILE(wk);
11304 			continue;
11305 
11306 		case D_MKDIR:
11307 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11308 			continue;
11309 
11310 		case D_DIRADD:
11311 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11312 			continue;
11313 
11314 		case D_FREEFRAG:
11315 			wk->wk_state |= COMPLETE;
11316 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11317 				add_to_worklist(wk, 0);
11318 			continue;
11319 
11320 		case D_DIRREM:
11321 			wk->wk_state |= COMPLETE;
11322 			add_to_worklist(wk, 0);
11323 			continue;
11324 
11325 		case D_ALLOCDIRECT:
11326 		case D_ALLOCINDIR:
11327 			free_newblk(WK_NEWBLK(wk));
11328 			continue;
11329 
11330 		case D_JNEWBLK:
11331 			wk->wk_state |= COMPLETE;
11332 			free_jnewblk(WK_JNEWBLK(wk));
11333 			continue;
11334 
11335 		/*
11336 		 * Save freed journal segments and add references on
11337 		 * the supplied list which will delay their release
11338 		 * until the cg bitmap is cleared on disk.
11339 		 */
11340 		case D_JSEGDEP:
11341 			if (refhd == NULL)
11342 				free_jsegdep(WK_JSEGDEP(wk));
11343 			else
11344 				WORKLIST_INSERT(refhd, wk);
11345 			continue;
11346 
11347 		case D_JADDREF:
11348 			jaddref = WK_JADDREF(wk);
11349 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11350 			    if_deps);
11351 			/*
11352 			 * Transfer any jaddrefs to the list to be freed with
11353 			 * the bitmap if we're handling a removed file.
11354 			 */
11355 			if (refhd == NULL) {
11356 				wk->wk_state |= COMPLETE;
11357 				free_jaddref(jaddref);
11358 			} else
11359 				WORKLIST_INSERT(refhd, wk);
11360 			continue;
11361 
11362 		default:
11363 			panic("handle_bufwait: Unknown type %p(%s)",
11364 			    wk, TYPENAME(wk->wk_type));
11365 			/* NOTREACHED */
11366 		}
11367 	}
11368 	return (freefile);
11369 }
11370 /*
11371  * Called from within softdep_disk_write_complete above to restore
11372  * in-memory inode block contents to their most up-to-date state. Note
11373  * that this routine is always called from interrupt level with further
11374  * interrupts from this device blocked.
11375  *
11376  * If the write did not succeed, we will do all the roll-forward
11377  * operations, but we will not take the actions that will allow its
11378  * dependencies to be processed.
11379  */
11380 static int
11381 handle_written_inodeblock(inodedep, bp, flags)
11382 	struct inodedep *inodedep;
11383 	struct buf *bp;		/* buffer containing the inode block */
11384 	int flags;
11385 {
11386 	struct freefile *freefile;
11387 	struct allocdirect *adp, *nextadp;
11388 	struct ufs1_dinode *dp1 = NULL;
11389 	struct ufs2_dinode *dp2 = NULL;
11390 	struct workhead wkhd;
11391 	int hadchanges, fstype;
11392 	ino_t freelink;
11393 
11394 	LIST_INIT(&wkhd);
11395 	hadchanges = 0;
11396 	freefile = NULL;
11397 	if ((inodedep->id_state & IOSTARTED) == 0)
11398 		panic("handle_written_inodeblock: not started");
11399 	inodedep->id_state &= ~IOSTARTED;
11400 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11401 		fstype = UFS1;
11402 		dp1 = (struct ufs1_dinode *)bp->b_data +
11403 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11404 		freelink = dp1->di_freelink;
11405 	} else {
11406 		fstype = UFS2;
11407 		dp2 = (struct ufs2_dinode *)bp->b_data +
11408 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11409 		freelink = dp2->di_freelink;
11410 	}
11411 	/*
11412 	 * Leave this inodeblock dirty until it's in the list.
11413 	 */
11414 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11415 	    (flags & WRITESUCCEEDED)) {
11416 		struct inodedep *inon;
11417 
11418 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11419 		if ((inon == NULL && freelink == 0) ||
11420 		    (inon && inon->id_ino == freelink)) {
11421 			if (inon)
11422 				inon->id_state |= UNLINKPREV;
11423 			inodedep->id_state |= UNLINKNEXT;
11424 		}
11425 		hadchanges = 1;
11426 	}
11427 	/*
11428 	 * If we had to rollback the inode allocation because of
11429 	 * bitmaps being incomplete, then simply restore it.
11430 	 * Keep the block dirty so that it will not be reclaimed until
11431 	 * all associated dependencies have been cleared and the
11432 	 * corresponding updates written to disk.
11433 	 */
11434 	if (inodedep->id_savedino1 != NULL) {
11435 		hadchanges = 1;
11436 		if (fstype == UFS1)
11437 			*dp1 = *inodedep->id_savedino1;
11438 		else
11439 			*dp2 = *inodedep->id_savedino2;
11440 		free(inodedep->id_savedino1, M_SAVEDINO);
11441 		inodedep->id_savedino1 = NULL;
11442 		if ((bp->b_flags & B_DELWRI) == 0)
11443 			stat_inode_bitmap++;
11444 		bdirty(bp);
11445 		/*
11446 		 * If the inode is clear here and GOINGAWAY it will never
11447 		 * be written.  Process the bufwait and clear any pending
11448 		 * work which may include the freefile.
11449 		 */
11450 		if (inodedep->id_state & GOINGAWAY)
11451 			goto bufwait;
11452 		return (1);
11453 	}
11454 	if (flags & WRITESUCCEEDED)
11455 		inodedep->id_state |= COMPLETE;
11456 	/*
11457 	 * Roll forward anything that had to be rolled back before
11458 	 * the inode could be updated.
11459 	 */
11460 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11461 		nextadp = TAILQ_NEXT(adp, ad_next);
11462 		if (adp->ad_state & ATTACHED)
11463 			panic("handle_written_inodeblock: new entry");
11464 		if (fstype == UFS1) {
11465 			if (adp->ad_offset < UFS_NDADDR) {
11466 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11467 					panic("%s %s #%jd mismatch %d != %jd",
11468 					    "handle_written_inodeblock:",
11469 					    "direct pointer",
11470 					    (intmax_t)adp->ad_offset,
11471 					    dp1->di_db[adp->ad_offset],
11472 					    (intmax_t)adp->ad_oldblkno);
11473 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11474 			} else {
11475 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11476 				    0)
11477 					panic("%s: %s #%jd allocated as %d",
11478 					    "handle_written_inodeblock",
11479 					    "indirect pointer",
11480 					    (intmax_t)adp->ad_offset -
11481 					    UFS_NDADDR,
11482 					    dp1->di_ib[adp->ad_offset -
11483 					    UFS_NDADDR]);
11484 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11485 				    adp->ad_newblkno;
11486 			}
11487 		} else {
11488 			if (adp->ad_offset < UFS_NDADDR) {
11489 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11490 					panic("%s: %s #%jd %s %jd != %jd",
11491 					    "handle_written_inodeblock",
11492 					    "direct pointer",
11493 					    (intmax_t)adp->ad_offset, "mismatch",
11494 					    (intmax_t)dp2->di_db[adp->ad_offset],
11495 					    (intmax_t)adp->ad_oldblkno);
11496 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11497 			} else {
11498 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11499 				    0)
11500 					panic("%s: %s #%jd allocated as %jd",
11501 					    "handle_written_inodeblock",
11502 					    "indirect pointer",
11503 					    (intmax_t)adp->ad_offset -
11504 					    UFS_NDADDR,
11505 					    (intmax_t)
11506 					    dp2->di_ib[adp->ad_offset -
11507 					    UFS_NDADDR]);
11508 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11509 				    adp->ad_newblkno;
11510 			}
11511 		}
11512 		adp->ad_state &= ~UNDONE;
11513 		adp->ad_state |= ATTACHED;
11514 		hadchanges = 1;
11515 	}
11516 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11517 		nextadp = TAILQ_NEXT(adp, ad_next);
11518 		if (adp->ad_state & ATTACHED)
11519 			panic("handle_written_inodeblock: new entry");
11520 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11521 			panic("%s: direct pointers #%jd %s %jd != %jd",
11522 			    "handle_written_inodeblock",
11523 			    (intmax_t)adp->ad_offset, "mismatch",
11524 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11525 			    (intmax_t)adp->ad_oldblkno);
11526 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11527 		adp->ad_state &= ~UNDONE;
11528 		adp->ad_state |= ATTACHED;
11529 		hadchanges = 1;
11530 	}
11531 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11532 		stat_direct_blk_ptrs++;
11533 	/*
11534 	 * Reset the file size to its most up-to-date value.
11535 	 */
11536 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11537 		panic("handle_written_inodeblock: bad size");
11538 	if (inodedep->id_savednlink > UFS_LINK_MAX)
11539 		panic("handle_written_inodeblock: Invalid link count "
11540 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11541 		    inodedep);
11542 	if (fstype == UFS1) {
11543 		if (dp1->di_nlink != inodedep->id_savednlink) {
11544 			dp1->di_nlink = inodedep->id_savednlink;
11545 			hadchanges = 1;
11546 		}
11547 		if (dp1->di_size != inodedep->id_savedsize) {
11548 			dp1->di_size = inodedep->id_savedsize;
11549 			hadchanges = 1;
11550 		}
11551 	} else {
11552 		if (dp2->di_nlink != inodedep->id_savednlink) {
11553 			dp2->di_nlink = inodedep->id_savednlink;
11554 			hadchanges = 1;
11555 		}
11556 		if (dp2->di_size != inodedep->id_savedsize) {
11557 			dp2->di_size = inodedep->id_savedsize;
11558 			hadchanges = 1;
11559 		}
11560 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11561 			dp2->di_extsize = inodedep->id_savedextsize;
11562 			hadchanges = 1;
11563 		}
11564 	}
11565 	inodedep->id_savedsize = -1;
11566 	inodedep->id_savedextsize = -1;
11567 	inodedep->id_savednlink = -1;
11568 	/*
11569 	 * If there were any rollbacks in the inode block, then it must be
11570 	 * marked dirty so that its will eventually get written back in
11571 	 * its correct form.
11572 	 */
11573 	if (hadchanges)
11574 		bdirty(bp);
11575 bufwait:
11576 	/*
11577 	 * If the write did not succeed, we have done all the roll-forward
11578 	 * operations, but we cannot take the actions that will allow its
11579 	 * dependencies to be processed.
11580 	 */
11581 	if ((flags & WRITESUCCEEDED) == 0)
11582 		return (hadchanges);
11583 	/*
11584 	 * Process any allocdirects that completed during the update.
11585 	 */
11586 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11587 		handle_allocdirect_partdone(adp, &wkhd);
11588 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11589 		handle_allocdirect_partdone(adp, &wkhd);
11590 	/*
11591 	 * Process deallocations that were held pending until the
11592 	 * inode had been written to disk. Freeing of the inode
11593 	 * is delayed until after all blocks have been freed to
11594 	 * avoid creation of new <vfsid, inum, lbn> triples
11595 	 * before the old ones have been deleted.  Completely
11596 	 * unlinked inodes are not processed until the unlinked
11597 	 * inode list is written or the last reference is removed.
11598 	 */
11599 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11600 		freefile = handle_bufwait(inodedep, NULL);
11601 		if (freefile && !LIST_EMPTY(&wkhd)) {
11602 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11603 			freefile = NULL;
11604 		}
11605 	}
11606 	/*
11607 	 * Move rolled forward dependency completions to the bufwait list
11608 	 * now that those that were already written have been processed.
11609 	 */
11610 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11611 		panic("handle_written_inodeblock: bufwait but no changes");
11612 	jwork_move(&inodedep->id_bufwait, &wkhd);
11613 
11614 	if (freefile != NULL) {
11615 		/*
11616 		 * If the inode is goingaway it was never written.  Fake up
11617 		 * the state here so free_inodedep() can succeed.
11618 		 */
11619 		if (inodedep->id_state & GOINGAWAY)
11620 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11621 		if (free_inodedep(inodedep) == 0)
11622 			panic("handle_written_inodeblock: live inodedep %p",
11623 			    inodedep);
11624 		add_to_worklist(&freefile->fx_list, 0);
11625 		return (0);
11626 	}
11627 
11628 	/*
11629 	 * If no outstanding dependencies, free it.
11630 	 */
11631 	if (free_inodedep(inodedep) ||
11632 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11633 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11634 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11635 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11636 		return (0);
11637 	return (hadchanges);
11638 }
11639 
11640 /*
11641  * Perform needed roll-forwards and kick off any dependencies that
11642  * can now be processed.
11643  *
11644  * If the write did not succeed, we will do all the roll-forward
11645  * operations, but we will not take the actions that will allow its
11646  * dependencies to be processed.
11647  */
11648 static int
11649 handle_written_indirdep(indirdep, bp, bpp, flags)
11650 	struct indirdep *indirdep;
11651 	struct buf *bp;
11652 	struct buf **bpp;
11653 	int flags;
11654 {
11655 	struct allocindir *aip;
11656 	struct buf *sbp;
11657 	int chgs;
11658 
11659 	if (indirdep->ir_state & GOINGAWAY)
11660 		panic("handle_written_indirdep: indirdep gone");
11661 	if ((indirdep->ir_state & IOSTARTED) == 0)
11662 		panic("handle_written_indirdep: IO not started");
11663 	chgs = 0;
11664 	/*
11665 	 * If there were rollbacks revert them here.
11666 	 */
11667 	if (indirdep->ir_saveddata) {
11668 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11669 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11670 			free(indirdep->ir_saveddata, M_INDIRDEP);
11671 			indirdep->ir_saveddata = NULL;
11672 		}
11673 		chgs = 1;
11674 	}
11675 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11676 	indirdep->ir_state |= ATTACHED;
11677 	/*
11678 	 * If the write did not succeed, we have done all the roll-forward
11679 	 * operations, but we cannot take the actions that will allow its
11680 	 * dependencies to be processed.
11681 	 */
11682 	if ((flags & WRITESUCCEEDED) == 0) {
11683 		stat_indir_blk_ptrs++;
11684 		bdirty(bp);
11685 		return (1);
11686 	}
11687 	/*
11688 	 * Move allocindirs with written pointers to the completehd if
11689 	 * the indirdep's pointer is not yet written.  Otherwise
11690 	 * free them here.
11691 	 */
11692 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11693 		LIST_REMOVE(aip, ai_next);
11694 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11695 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11696 			    ai_next);
11697 			newblk_freefrag(&aip->ai_block);
11698 			continue;
11699 		}
11700 		free_newblk(&aip->ai_block);
11701 	}
11702 	/*
11703 	 * Move allocindirs that have finished dependency processing from
11704 	 * the done list to the write list after updating the pointers.
11705 	 */
11706 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11707 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11708 			handle_allocindir_partdone(aip);
11709 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11710 				panic("disk_write_complete: not gone");
11711 			chgs = 1;
11712 		}
11713 	}
11714 	/*
11715 	 * Preserve the indirdep if there were any changes or if it is not
11716 	 * yet valid on disk.
11717 	 */
11718 	if (chgs) {
11719 		stat_indir_blk_ptrs++;
11720 		bdirty(bp);
11721 		return (1);
11722 	}
11723 	/*
11724 	 * If there were no changes we can discard the savedbp and detach
11725 	 * ourselves from the buf.  We are only carrying completed pointers
11726 	 * in this case.
11727 	 */
11728 	sbp = indirdep->ir_savebp;
11729 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11730 	indirdep->ir_savebp = NULL;
11731 	indirdep->ir_bp = NULL;
11732 	if (*bpp != NULL)
11733 		panic("handle_written_indirdep: bp already exists.");
11734 	*bpp = sbp;
11735 	/*
11736 	 * The indirdep may not be freed until its parent points at it.
11737 	 */
11738 	if (indirdep->ir_state & DEPCOMPLETE)
11739 		free_indirdep(indirdep);
11740 
11741 	return (0);
11742 }
11743 
11744 /*
11745  * Process a diradd entry after its dependent inode has been written.
11746  * This routine must be called with splbio interrupts blocked.
11747  */
11748 static void
11749 diradd_inode_written(dap, inodedep)
11750 	struct diradd *dap;
11751 	struct inodedep *inodedep;
11752 {
11753 
11754 	dap->da_state |= COMPLETE;
11755 	complete_diradd(dap);
11756 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11757 }
11758 
11759 /*
11760  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11761  * be called with the per-filesystem lock and the buf lock on the cg held.
11762  */
11763 static int
11764 bmsafemap_backgroundwrite(bmsafemap, bp)
11765 	struct bmsafemap *bmsafemap;
11766 	struct buf *bp;
11767 {
11768 	int dirty;
11769 
11770 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11771 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11772 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11773 	/*
11774 	 * If we're initiating a background write we need to process the
11775 	 * rollbacks as they exist now, not as they exist when IO starts.
11776 	 * No other consumers will look at the contents of the shadowed
11777 	 * buf so this is safe to do here.
11778 	 */
11779 	if (bp->b_xflags & BX_BKGRDMARKER)
11780 		initiate_write_bmsafemap(bmsafemap, bp);
11781 
11782 	return (dirty);
11783 }
11784 
11785 /*
11786  * Re-apply an allocation when a cg write is complete.
11787  */
11788 static int
11789 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11790 	struct jnewblk *jnewblk;
11791 	struct fs *fs;
11792 	struct cg *cgp;
11793 	uint8_t *blksfree;
11794 {
11795 	ufs1_daddr_t fragno;
11796 	ufs2_daddr_t blkno;
11797 	long cgbno, bbase;
11798 	int frags, blk;
11799 	int i;
11800 
11801 	frags = 0;
11802 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11803 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11804 		if (isclr(blksfree, cgbno + i))
11805 			panic("jnewblk_rollforward: re-allocated fragment");
11806 		frags++;
11807 	}
11808 	if (frags == fs->fs_frag) {
11809 		blkno = fragstoblks(fs, cgbno);
11810 		ffs_clrblock(fs, blksfree, (long)blkno);
11811 		ffs_clusteracct(fs, cgp, blkno, -1);
11812 		cgp->cg_cs.cs_nbfree--;
11813 	} else {
11814 		bbase = cgbno - fragnum(fs, cgbno);
11815 		cgbno += jnewblk->jn_oldfrags;
11816                 /* If a complete block had been reassembled, account for it. */
11817 		fragno = fragstoblks(fs, bbase);
11818 		if (ffs_isblock(fs, blksfree, fragno)) {
11819 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11820 			ffs_clusteracct(fs, cgp, fragno, -1);
11821 			cgp->cg_cs.cs_nbfree--;
11822 		}
11823 		/* Decrement the old frags.  */
11824 		blk = blkmap(fs, blksfree, bbase);
11825 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11826 		/* Allocate the fragment */
11827 		for (i = 0; i < frags; i++)
11828 			clrbit(blksfree, cgbno + i);
11829 		cgp->cg_cs.cs_nffree -= frags;
11830 		/* Add back in counts associated with the new frags */
11831 		blk = blkmap(fs, blksfree, bbase);
11832 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11833 	}
11834 	return (frags);
11835 }
11836 
11837 /*
11838  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11839  * changes if it's not a background write.  Set all written dependencies
11840  * to DEPCOMPLETE and free the structure if possible.
11841  *
11842  * If the write did not succeed, we will do all the roll-forward
11843  * operations, but we will not take the actions that will allow its
11844  * dependencies to be processed.
11845  */
11846 static int
11847 handle_written_bmsafemap(bmsafemap, bp, flags)
11848 	struct bmsafemap *bmsafemap;
11849 	struct buf *bp;
11850 	int flags;
11851 {
11852 	struct newblk *newblk;
11853 	struct inodedep *inodedep;
11854 	struct jaddref *jaddref, *jatmp;
11855 	struct jnewblk *jnewblk, *jntmp;
11856 	struct ufsmount *ump;
11857 	uint8_t *inosused;
11858 	uint8_t *blksfree;
11859 	struct cg *cgp;
11860 	struct fs *fs;
11861 	ino_t ino;
11862 	int foreground;
11863 	int chgs;
11864 
11865 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11866 		panic("handle_written_bmsafemap: Not started\n");
11867 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11868 	chgs = 0;
11869 	bmsafemap->sm_state &= ~IOSTARTED;
11870 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11871 	/*
11872 	 * If write was successful, release journal work that was waiting
11873 	 * on the write. Otherwise move the work back.
11874 	 */
11875 	if (flags & WRITESUCCEEDED)
11876 		handle_jwork(&bmsafemap->sm_freewr);
11877 	else
11878 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11879 		    worklist, wk_list);
11880 
11881 	/*
11882 	 * Restore unwritten inode allocation pending jaddref writes.
11883 	 */
11884 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11885 		cgp = (struct cg *)bp->b_data;
11886 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11887 		inosused = cg_inosused(cgp);
11888 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11889 		    ja_bmdeps, jatmp) {
11890 			if ((jaddref->ja_state & UNDONE) == 0)
11891 				continue;
11892 			ino = jaddref->ja_ino % fs->fs_ipg;
11893 			if (isset(inosused, ino))
11894 				panic("handle_written_bmsafemap: "
11895 				    "re-allocated inode");
11896 			/* Do the roll-forward only if it's a real copy. */
11897 			if (foreground) {
11898 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11899 					cgp->cg_cs.cs_ndir++;
11900 				cgp->cg_cs.cs_nifree--;
11901 				setbit(inosused, ino);
11902 				chgs = 1;
11903 			}
11904 			jaddref->ja_state &= ~UNDONE;
11905 			jaddref->ja_state |= ATTACHED;
11906 			free_jaddref(jaddref);
11907 		}
11908 	}
11909 	/*
11910 	 * Restore any block allocations which are pending journal writes.
11911 	 */
11912 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11913 		cgp = (struct cg *)bp->b_data;
11914 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11915 		blksfree = cg_blksfree(cgp);
11916 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11917 		    jntmp) {
11918 			if ((jnewblk->jn_state & UNDONE) == 0)
11919 				continue;
11920 			/* Do the roll-forward only if it's a real copy. */
11921 			if (foreground &&
11922 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11923 				chgs = 1;
11924 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11925 			jnewblk->jn_state |= ATTACHED;
11926 			free_jnewblk(jnewblk);
11927 		}
11928 	}
11929 	/*
11930 	 * If the write did not succeed, we have done all the roll-forward
11931 	 * operations, but we cannot take the actions that will allow its
11932 	 * dependencies to be processed.
11933 	 */
11934 	if ((flags & WRITESUCCEEDED) == 0) {
11935 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11936 		    newblk, nb_deps);
11937 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11938 		    worklist, wk_list);
11939 		if (foreground)
11940 			bdirty(bp);
11941 		return (1);
11942 	}
11943 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11944 		newblk->nb_state |= DEPCOMPLETE;
11945 		newblk->nb_state &= ~ONDEPLIST;
11946 		newblk->nb_bmsafemap = NULL;
11947 		LIST_REMOVE(newblk, nb_deps);
11948 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11949 			handle_allocdirect_partdone(
11950 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11951 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11952 			handle_allocindir_partdone(
11953 			    WK_ALLOCINDIR(&newblk->nb_list));
11954 		else if (newblk->nb_list.wk_type != D_NEWBLK)
11955 			panic("handle_written_bmsafemap: Unexpected type: %s",
11956 			    TYPENAME(newblk->nb_list.wk_type));
11957 	}
11958 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11959 		inodedep->id_state |= DEPCOMPLETE;
11960 		inodedep->id_state &= ~ONDEPLIST;
11961 		LIST_REMOVE(inodedep, id_deps);
11962 		inodedep->id_bmsafemap = NULL;
11963 	}
11964 	LIST_REMOVE(bmsafemap, sm_next);
11965 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11966 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11967 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11968 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11969 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
11970 		LIST_REMOVE(bmsafemap, sm_hash);
11971 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11972 		return (0);
11973 	}
11974 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11975 	if (foreground)
11976 		bdirty(bp);
11977 	return (1);
11978 }
11979 
11980 /*
11981  * Try to free a mkdir dependency.
11982  */
11983 static void
11984 complete_mkdir(mkdir)
11985 	struct mkdir *mkdir;
11986 {
11987 	struct diradd *dap;
11988 
11989 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11990 		return;
11991 	LIST_REMOVE(mkdir, md_mkdirs);
11992 	dap = mkdir->md_diradd;
11993 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11994 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11995 		dap->da_state |= DEPCOMPLETE;
11996 		complete_diradd(dap);
11997 	}
11998 	WORKITEM_FREE(mkdir, D_MKDIR);
11999 }
12000 
12001 /*
12002  * Handle the completion of a mkdir dependency.
12003  */
12004 static void
12005 handle_written_mkdir(mkdir, type)
12006 	struct mkdir *mkdir;
12007 	int type;
12008 {
12009 
12010 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12011 		panic("handle_written_mkdir: bad type");
12012 	mkdir->md_state |= COMPLETE;
12013 	complete_mkdir(mkdir);
12014 }
12015 
12016 static int
12017 free_pagedep(pagedep)
12018 	struct pagedep *pagedep;
12019 {
12020 	int i;
12021 
12022 	if (pagedep->pd_state & NEWBLOCK)
12023 		return (0);
12024 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12025 		return (0);
12026 	for (i = 0; i < DAHASHSZ; i++)
12027 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12028 			return (0);
12029 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12030 		return (0);
12031 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12032 		return (0);
12033 	if (pagedep->pd_state & ONWORKLIST)
12034 		WORKLIST_REMOVE(&pagedep->pd_list);
12035 	LIST_REMOVE(pagedep, pd_hash);
12036 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12037 
12038 	return (1);
12039 }
12040 
12041 /*
12042  * Called from within softdep_disk_write_complete above.
12043  * A write operation was just completed. Removed inodes can
12044  * now be freed and associated block pointers may be committed.
12045  * Note that this routine is always called from interrupt level
12046  * with further interrupts from this device blocked.
12047  *
12048  * If the write did not succeed, we will do all the roll-forward
12049  * operations, but we will not take the actions that will allow its
12050  * dependencies to be processed.
12051  */
12052 static int
12053 handle_written_filepage(pagedep, bp, flags)
12054 	struct pagedep *pagedep;
12055 	struct buf *bp;		/* buffer containing the written page */
12056 	int flags;
12057 {
12058 	struct dirrem *dirrem;
12059 	struct diradd *dap, *nextdap;
12060 	struct direct *ep;
12061 	int i, chgs;
12062 
12063 	if ((pagedep->pd_state & IOSTARTED) == 0)
12064 		panic("handle_written_filepage: not started");
12065 	pagedep->pd_state &= ~IOSTARTED;
12066 	if ((flags & WRITESUCCEEDED) == 0)
12067 		goto rollforward;
12068 	/*
12069 	 * Process any directory removals that have been committed.
12070 	 */
12071 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12072 		LIST_REMOVE(dirrem, dm_next);
12073 		dirrem->dm_state |= COMPLETE;
12074 		dirrem->dm_dirinum = pagedep->pd_ino;
12075 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12076 		    ("handle_written_filepage: Journal entries not written."));
12077 		add_to_worklist(&dirrem->dm_list, 0);
12078 	}
12079 	/*
12080 	 * Free any directory additions that have been committed.
12081 	 * If it is a newly allocated block, we have to wait until
12082 	 * the on-disk directory inode claims the new block.
12083 	 */
12084 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12085 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12086 			free_diradd(dap, NULL);
12087 rollforward:
12088 	/*
12089 	 * Uncommitted directory entries must be restored.
12090 	 */
12091 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12092 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12093 		     dap = nextdap) {
12094 			nextdap = LIST_NEXT(dap, da_pdlist);
12095 			if (dap->da_state & ATTACHED)
12096 				panic("handle_written_filepage: attached");
12097 			ep = (struct direct *)
12098 			    ((char *)bp->b_data + dap->da_offset);
12099 			ep->d_ino = dap->da_newinum;
12100 			dap->da_state &= ~UNDONE;
12101 			dap->da_state |= ATTACHED;
12102 			chgs = 1;
12103 			/*
12104 			 * If the inode referenced by the directory has
12105 			 * been written out, then the dependency can be
12106 			 * moved to the pending list.
12107 			 */
12108 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12109 				LIST_REMOVE(dap, da_pdlist);
12110 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12111 				    da_pdlist);
12112 			}
12113 		}
12114 	}
12115 	/*
12116 	 * If there were any rollbacks in the directory, then it must be
12117 	 * marked dirty so that its will eventually get written back in
12118 	 * its correct form.
12119 	 */
12120 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12121 		if ((bp->b_flags & B_DELWRI) == 0)
12122 			stat_dir_entry++;
12123 		bdirty(bp);
12124 		return (1);
12125 	}
12126 	/*
12127 	 * If we are not waiting for a new directory block to be
12128 	 * claimed by its inode, then the pagedep will be freed.
12129 	 * Otherwise it will remain to track any new entries on
12130 	 * the page in case they are fsync'ed.
12131 	 */
12132 	free_pagedep(pagedep);
12133 	return (0);
12134 }
12135 
12136 /*
12137  * Writing back in-core inode structures.
12138  *
12139  * The filesystem only accesses an inode's contents when it occupies an
12140  * "in-core" inode structure.  These "in-core" structures are separate from
12141  * the page frames used to cache inode blocks.  Only the latter are
12142  * transferred to/from the disk.  So, when the updated contents of the
12143  * "in-core" inode structure are copied to the corresponding in-memory inode
12144  * block, the dependencies are also transferred.  The following procedure is
12145  * called when copying a dirty "in-core" inode to a cached inode block.
12146  */
12147 
12148 /*
12149  * Called when an inode is loaded from disk. If the effective link count
12150  * differed from the actual link count when it was last flushed, then we
12151  * need to ensure that the correct effective link count is put back.
12152  */
12153 void
12154 softdep_load_inodeblock(ip)
12155 	struct inode *ip;	/* the "in_core" copy of the inode */
12156 {
12157 	struct inodedep *inodedep;
12158 	struct ufsmount *ump;
12159 
12160 	ump = ITOUMP(ip);
12161 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12162 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12163 	/*
12164 	 * Check for alternate nlink count.
12165 	 */
12166 	ip->i_effnlink = ip->i_nlink;
12167 	ACQUIRE_LOCK(ump);
12168 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12169 		FREE_LOCK(ump);
12170 		return;
12171 	}
12172 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12173 	FREE_LOCK(ump);
12174 }
12175 
12176 /*
12177  * This routine is called just before the "in-core" inode
12178  * information is to be copied to the in-memory inode block.
12179  * Recall that an inode block contains several inodes. If
12180  * the force flag is set, then the dependencies will be
12181  * cleared so that the update can always be made. Note that
12182  * the buffer is locked when this routine is called, so we
12183  * will never be in the middle of writing the inode block
12184  * to disk.
12185  */
12186 void
12187 softdep_update_inodeblock(ip, bp, waitfor)
12188 	struct inode *ip;	/* the "in_core" copy of the inode */
12189 	struct buf *bp;		/* the buffer containing the inode block */
12190 	int waitfor;		/* nonzero => update must be allowed */
12191 {
12192 	struct inodedep *inodedep;
12193 	struct inoref *inoref;
12194 	struct ufsmount *ump;
12195 	struct worklist *wk;
12196 	struct mount *mp;
12197 	struct buf *ibp;
12198 	struct fs *fs;
12199 	int error;
12200 
12201 	ump = ITOUMP(ip);
12202 	mp = UFSTOVFS(ump);
12203 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12204 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12205 	fs = ump->um_fs;
12206 	/*
12207 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12208 	 * does not have access to the in-core ip so must write directly into
12209 	 * the inode block buffer when setting freelink.
12210 	 */
12211 	if (fs->fs_magic == FS_UFS1_MAGIC)
12212 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12213 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12214 	else
12215 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12216 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12217 	/*
12218 	 * If the effective link count is not equal to the actual link
12219 	 * count, then we must track the difference in an inodedep while
12220 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12221 	 * if there is no existing inodedep, then there are no dependencies
12222 	 * to track.
12223 	 */
12224 	ACQUIRE_LOCK(ump);
12225 again:
12226 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12227 		FREE_LOCK(ump);
12228 		if (ip->i_effnlink != ip->i_nlink)
12229 			panic("softdep_update_inodeblock: bad link count");
12230 		return;
12231 	}
12232 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12233 		panic("softdep_update_inodeblock: bad delta");
12234 	/*
12235 	 * If we're flushing all dependencies we must also move any waiting
12236 	 * for journal writes onto the bufwait list prior to I/O.
12237 	 */
12238 	if (waitfor) {
12239 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12240 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12241 			    == DEPCOMPLETE) {
12242 				jwait(&inoref->if_list, MNT_WAIT);
12243 				goto again;
12244 			}
12245 		}
12246 	}
12247 	/*
12248 	 * Changes have been initiated. Anything depending on these
12249 	 * changes cannot occur until this inode has been written.
12250 	 */
12251 	inodedep->id_state &= ~COMPLETE;
12252 	if ((inodedep->id_state & ONWORKLIST) == 0)
12253 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12254 	/*
12255 	 * Any new dependencies associated with the incore inode must
12256 	 * now be moved to the list associated with the buffer holding
12257 	 * the in-memory copy of the inode. Once merged process any
12258 	 * allocdirects that are completed by the merger.
12259 	 */
12260 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12261 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12262 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12263 		    NULL);
12264 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12265 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12266 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12267 		    NULL);
12268 	/*
12269 	 * Now that the inode has been pushed into the buffer, the
12270 	 * operations dependent on the inode being written to disk
12271 	 * can be moved to the id_bufwait so that they will be
12272 	 * processed when the buffer I/O completes.
12273 	 */
12274 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12275 		WORKLIST_REMOVE(wk);
12276 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12277 	}
12278 	/*
12279 	 * Newly allocated inodes cannot be written until the bitmap
12280 	 * that allocates them have been written (indicated by
12281 	 * DEPCOMPLETE being set in id_state). If we are doing a
12282 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12283 	 * to be written so that the update can be done.
12284 	 */
12285 	if (waitfor == 0) {
12286 		FREE_LOCK(ump);
12287 		return;
12288 	}
12289 retry:
12290 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12291 		FREE_LOCK(ump);
12292 		return;
12293 	}
12294 	ibp = inodedep->id_bmsafemap->sm_buf;
12295 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12296 	if (ibp == NULL) {
12297 		/*
12298 		 * If ibp came back as NULL, the dependency could have been
12299 		 * freed while we slept.  Look it up again, and check to see
12300 		 * that it has completed.
12301 		 */
12302 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12303 			goto retry;
12304 		FREE_LOCK(ump);
12305 		return;
12306 	}
12307 	FREE_LOCK(ump);
12308 	if ((error = bwrite(ibp)) != 0)
12309 		softdep_error("softdep_update_inodeblock: bwrite", error);
12310 }
12311 
12312 /*
12313  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12314  * old inode dependency list (such as id_inoupdt). This routine must be
12315  * called with splbio interrupts blocked.
12316  */
12317 static void
12318 merge_inode_lists(newlisthead, oldlisthead)
12319 	struct allocdirectlst *newlisthead;
12320 	struct allocdirectlst *oldlisthead;
12321 {
12322 	struct allocdirect *listadp, *newadp;
12323 
12324 	newadp = TAILQ_FIRST(newlisthead);
12325 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12326 		if (listadp->ad_offset < newadp->ad_offset) {
12327 			listadp = TAILQ_NEXT(listadp, ad_next);
12328 			continue;
12329 		}
12330 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12331 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12332 		if (listadp->ad_offset == newadp->ad_offset) {
12333 			allocdirect_merge(oldlisthead, newadp,
12334 			    listadp);
12335 			listadp = newadp;
12336 		}
12337 		newadp = TAILQ_FIRST(newlisthead);
12338 	}
12339 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12340 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12341 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12342 	}
12343 }
12344 
12345 /*
12346  * If we are doing an fsync, then we must ensure that any directory
12347  * entries for the inode have been written after the inode gets to disk.
12348  */
12349 int
12350 softdep_fsync(vp)
12351 	struct vnode *vp;	/* the "in_core" copy of the inode */
12352 {
12353 	struct inodedep *inodedep;
12354 	struct pagedep *pagedep;
12355 	struct inoref *inoref;
12356 	struct ufsmount *ump;
12357 	struct worklist *wk;
12358 	struct diradd *dap;
12359 	struct mount *mp;
12360 	struct vnode *pvp;
12361 	struct inode *ip;
12362 	struct buf *bp;
12363 	struct fs *fs;
12364 	struct thread *td = curthread;
12365 	int error, flushparent, pagedep_new_block;
12366 	ino_t parentino;
12367 	ufs_lbn_t lbn;
12368 
12369 	ip = VTOI(vp);
12370 	mp = vp->v_mount;
12371 	ump = VFSTOUFS(mp);
12372 	fs = ump->um_fs;
12373 	if (MOUNTEDSOFTDEP(mp) == 0)
12374 		return (0);
12375 	ACQUIRE_LOCK(ump);
12376 restart:
12377 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12378 		FREE_LOCK(ump);
12379 		return (0);
12380 	}
12381 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12382 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12383 		    == DEPCOMPLETE) {
12384 			jwait(&inoref->if_list, MNT_WAIT);
12385 			goto restart;
12386 		}
12387 	}
12388 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12389 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12390 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12391 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12392 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12393 		panic("softdep_fsync: pending ops %p", inodedep);
12394 	for (error = 0, flushparent = 0; ; ) {
12395 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12396 			break;
12397 		if (wk->wk_type != D_DIRADD)
12398 			panic("softdep_fsync: Unexpected type %s",
12399 			    TYPENAME(wk->wk_type));
12400 		dap = WK_DIRADD(wk);
12401 		/*
12402 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12403 		 * dependency or is contained in a newly allocated block.
12404 		 */
12405 		if (dap->da_state & DIRCHG)
12406 			pagedep = dap->da_previous->dm_pagedep;
12407 		else
12408 			pagedep = dap->da_pagedep;
12409 		parentino = pagedep->pd_ino;
12410 		lbn = pagedep->pd_lbn;
12411 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12412 			panic("softdep_fsync: dirty");
12413 		if ((dap->da_state & MKDIR_PARENT) ||
12414 		    (pagedep->pd_state & NEWBLOCK))
12415 			flushparent = 1;
12416 		else
12417 			flushparent = 0;
12418 		/*
12419 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12420 		 * then we will not be able to release and recover the
12421 		 * vnode below, so we just have to give up on writing its
12422 		 * directory entry out. It will eventually be written, just
12423 		 * not now, but then the user was not asking to have it
12424 		 * written, so we are not breaking any promises.
12425 		 */
12426 		if (vp->v_iflag & VI_DOOMED)
12427 			break;
12428 		/*
12429 		 * We prevent deadlock by always fetching inodes from the
12430 		 * root, moving down the directory tree. Thus, when fetching
12431 		 * our parent directory, we first try to get the lock. If
12432 		 * that fails, we must unlock ourselves before requesting
12433 		 * the lock on our parent. See the comment in ufs_lookup
12434 		 * for details on possible races.
12435 		 */
12436 		FREE_LOCK(ump);
12437 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12438 		    FFSV_FORCEINSMQ)) {
12439 			error = vfs_busy(mp, MBF_NOWAIT);
12440 			if (error != 0) {
12441 				vfs_ref(mp);
12442 				VOP_UNLOCK(vp, 0);
12443 				error = vfs_busy(mp, 0);
12444 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12445 				vfs_rel(mp);
12446 				if (error != 0)
12447 					return (ENOENT);
12448 				if (vp->v_iflag & VI_DOOMED) {
12449 					vfs_unbusy(mp);
12450 					return (ENOENT);
12451 				}
12452 			}
12453 			VOP_UNLOCK(vp, 0);
12454 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12455 			    &pvp, FFSV_FORCEINSMQ);
12456 			vfs_unbusy(mp);
12457 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12458 			if (vp->v_iflag & VI_DOOMED) {
12459 				if (error == 0)
12460 					vput(pvp);
12461 				error = ENOENT;
12462 			}
12463 			if (error != 0)
12464 				return (error);
12465 		}
12466 		/*
12467 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12468 		 * that are contained in direct blocks will be resolved by
12469 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12470 		 * may require a complete sync'ing of the directory. So, we
12471 		 * try the cheap and fast ffs_update first, and if that fails,
12472 		 * then we do the slower ffs_syncvnode of the directory.
12473 		 */
12474 		if (flushparent) {
12475 			int locked;
12476 
12477 			if ((error = ffs_update(pvp, 1)) != 0) {
12478 				vput(pvp);
12479 				return (error);
12480 			}
12481 			ACQUIRE_LOCK(ump);
12482 			locked = 1;
12483 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12484 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12485 					if (wk->wk_type != D_DIRADD)
12486 						panic("softdep_fsync: Unexpected type %s",
12487 						      TYPENAME(wk->wk_type));
12488 					dap = WK_DIRADD(wk);
12489 					if (dap->da_state & DIRCHG)
12490 						pagedep = dap->da_previous->dm_pagedep;
12491 					else
12492 						pagedep = dap->da_pagedep;
12493 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12494 					FREE_LOCK(ump);
12495 					locked = 0;
12496 					if (pagedep_new_block && (error =
12497 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12498 						vput(pvp);
12499 						return (error);
12500 					}
12501 				}
12502 			}
12503 			if (locked)
12504 				FREE_LOCK(ump);
12505 		}
12506 		/*
12507 		 * Flush directory page containing the inode's name.
12508 		 */
12509 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12510 		    &bp);
12511 		if (error == 0)
12512 			error = bwrite(bp);
12513 		else
12514 			brelse(bp);
12515 		vput(pvp);
12516 		if (error != 0)
12517 			return (error);
12518 		ACQUIRE_LOCK(ump);
12519 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12520 			break;
12521 	}
12522 	FREE_LOCK(ump);
12523 	return (0);
12524 }
12525 
12526 /*
12527  * Flush all the dirty bitmaps associated with the block device
12528  * before flushing the rest of the dirty blocks so as to reduce
12529  * the number of dependencies that will have to be rolled back.
12530  *
12531  * XXX Unused?
12532  */
12533 void
12534 softdep_fsync_mountdev(vp)
12535 	struct vnode *vp;
12536 {
12537 	struct buf *bp, *nbp;
12538 	struct worklist *wk;
12539 	struct bufobj *bo;
12540 
12541 	if (!vn_isdisk(vp, NULL))
12542 		panic("softdep_fsync_mountdev: vnode not a disk");
12543 	bo = &vp->v_bufobj;
12544 restart:
12545 	BO_LOCK(bo);
12546 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12547 		/*
12548 		 * If it is already scheduled, skip to the next buffer.
12549 		 */
12550 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12551 			continue;
12552 
12553 		if ((bp->b_flags & B_DELWRI) == 0)
12554 			panic("softdep_fsync_mountdev: not dirty");
12555 		/*
12556 		 * We are only interested in bitmaps with outstanding
12557 		 * dependencies.
12558 		 */
12559 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12560 		    wk->wk_type != D_BMSAFEMAP ||
12561 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12562 			BUF_UNLOCK(bp);
12563 			continue;
12564 		}
12565 		BO_UNLOCK(bo);
12566 		bremfree(bp);
12567 		(void) bawrite(bp);
12568 		goto restart;
12569 	}
12570 	drain_output(vp);
12571 	BO_UNLOCK(bo);
12572 }
12573 
12574 /*
12575  * Sync all cylinder groups that were dirty at the time this function is
12576  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12577  * is used to flush freedep activity that may be holding up writes to a
12578  * indirect block.
12579  */
12580 static int
12581 sync_cgs(mp, waitfor)
12582 	struct mount *mp;
12583 	int waitfor;
12584 {
12585 	struct bmsafemap *bmsafemap;
12586 	struct bmsafemap *sentinel;
12587 	struct ufsmount *ump;
12588 	struct buf *bp;
12589 	int error;
12590 
12591 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12592 	sentinel->sm_cg = -1;
12593 	ump = VFSTOUFS(mp);
12594 	error = 0;
12595 	ACQUIRE_LOCK(ump);
12596 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12597 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12598 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12599 		/* Skip sentinels and cgs with no work to release. */
12600 		if (bmsafemap->sm_cg == -1 ||
12601 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12602 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12603 			LIST_REMOVE(sentinel, sm_next);
12604 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12605 			continue;
12606 		}
12607 		/*
12608 		 * If we don't get the lock and we're waiting try again, if
12609 		 * not move on to the next buf and try to sync it.
12610 		 */
12611 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12612 		if (bp == NULL && waitfor == MNT_WAIT)
12613 			continue;
12614 		LIST_REMOVE(sentinel, sm_next);
12615 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12616 		if (bp == NULL)
12617 			continue;
12618 		FREE_LOCK(ump);
12619 		if (waitfor == MNT_NOWAIT)
12620 			bawrite(bp);
12621 		else
12622 			error = bwrite(bp);
12623 		ACQUIRE_LOCK(ump);
12624 		if (error)
12625 			break;
12626 	}
12627 	LIST_REMOVE(sentinel, sm_next);
12628 	FREE_LOCK(ump);
12629 	free(sentinel, M_BMSAFEMAP);
12630 	return (error);
12631 }
12632 
12633 /*
12634  * This routine is called when we are trying to synchronously flush a
12635  * file. This routine must eliminate any filesystem metadata dependencies
12636  * so that the syncing routine can succeed.
12637  */
12638 int
12639 softdep_sync_metadata(struct vnode *vp)
12640 {
12641 	struct inode *ip;
12642 	int error;
12643 
12644 	ip = VTOI(vp);
12645 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12646 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12647 	/*
12648 	 * Ensure that any direct block dependencies have been cleared,
12649 	 * truncations are started, and inode references are journaled.
12650 	 */
12651 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12652 	/*
12653 	 * Write all journal records to prevent rollbacks on devvp.
12654 	 */
12655 	if (vp->v_type == VCHR)
12656 		softdep_flushjournal(vp->v_mount);
12657 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12658 	/*
12659 	 * Ensure that all truncates are written so we won't find deps on
12660 	 * indirect blocks.
12661 	 */
12662 	process_truncates(vp);
12663 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12664 
12665 	return (error);
12666 }
12667 
12668 /*
12669  * This routine is called when we are attempting to sync a buf with
12670  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12671  * other IO it can but returns EBUSY if the buffer is not yet able to
12672  * be written.  Dependencies which will not cause rollbacks will always
12673  * return 0.
12674  */
12675 int
12676 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12677 {
12678 	struct indirdep *indirdep;
12679 	struct pagedep *pagedep;
12680 	struct allocindir *aip;
12681 	struct newblk *newblk;
12682 	struct ufsmount *ump;
12683 	struct buf *nbp;
12684 	struct worklist *wk;
12685 	int i, error;
12686 
12687 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12688 	    ("softdep_sync_buf called on non-softdep filesystem"));
12689 	/*
12690 	 * For VCHR we just don't want to force flush any dependencies that
12691 	 * will cause rollbacks.
12692 	 */
12693 	if (vp->v_type == VCHR) {
12694 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12695 			return (EBUSY);
12696 		return (0);
12697 	}
12698 	ump = VFSTOUFS(vp->v_mount);
12699 	ACQUIRE_LOCK(ump);
12700 	/*
12701 	 * As we hold the buffer locked, none of its dependencies
12702 	 * will disappear.
12703 	 */
12704 	error = 0;
12705 top:
12706 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12707 		switch (wk->wk_type) {
12708 
12709 		case D_ALLOCDIRECT:
12710 		case D_ALLOCINDIR:
12711 			newblk = WK_NEWBLK(wk);
12712 			if (newblk->nb_jnewblk != NULL) {
12713 				if (waitfor == MNT_NOWAIT) {
12714 					error = EBUSY;
12715 					goto out_unlock;
12716 				}
12717 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12718 				goto top;
12719 			}
12720 			if (newblk->nb_state & DEPCOMPLETE ||
12721 			    waitfor == MNT_NOWAIT)
12722 				continue;
12723 			nbp = newblk->nb_bmsafemap->sm_buf;
12724 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12725 			if (nbp == NULL)
12726 				goto top;
12727 			FREE_LOCK(ump);
12728 			if ((error = bwrite(nbp)) != 0)
12729 				goto out;
12730 			ACQUIRE_LOCK(ump);
12731 			continue;
12732 
12733 		case D_INDIRDEP:
12734 			indirdep = WK_INDIRDEP(wk);
12735 			if (waitfor == MNT_NOWAIT) {
12736 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12737 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12738 					error = EBUSY;
12739 					goto out_unlock;
12740 				}
12741 			}
12742 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12743 				panic("softdep_sync_buf: truncation pending.");
12744 		restart:
12745 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12746 				newblk = (struct newblk *)aip;
12747 				if (newblk->nb_jnewblk != NULL) {
12748 					jwait(&newblk->nb_jnewblk->jn_list,
12749 					    waitfor);
12750 					goto restart;
12751 				}
12752 				if (newblk->nb_state & DEPCOMPLETE)
12753 					continue;
12754 				nbp = newblk->nb_bmsafemap->sm_buf;
12755 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12756 				if (nbp == NULL)
12757 					goto restart;
12758 				FREE_LOCK(ump);
12759 				if ((error = bwrite(nbp)) != 0)
12760 					goto out;
12761 				ACQUIRE_LOCK(ump);
12762 				goto restart;
12763 			}
12764 			continue;
12765 
12766 		case D_PAGEDEP:
12767 			/*
12768 			 * Only flush directory entries in synchronous passes.
12769 			 */
12770 			if (waitfor != MNT_WAIT) {
12771 				error = EBUSY;
12772 				goto out_unlock;
12773 			}
12774 			/*
12775 			 * While syncing snapshots, we must allow recursive
12776 			 * lookups.
12777 			 */
12778 			BUF_AREC(bp);
12779 			/*
12780 			 * We are trying to sync a directory that may
12781 			 * have dependencies on both its own metadata
12782 			 * and/or dependencies on the inodes of any
12783 			 * recently allocated files. We walk its diradd
12784 			 * lists pushing out the associated inode.
12785 			 */
12786 			pagedep = WK_PAGEDEP(wk);
12787 			for (i = 0; i < DAHASHSZ; i++) {
12788 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12789 					continue;
12790 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12791 				    &pagedep->pd_diraddhd[i]))) {
12792 					BUF_NOREC(bp);
12793 					goto out_unlock;
12794 				}
12795 			}
12796 			BUF_NOREC(bp);
12797 			continue;
12798 
12799 		case D_FREEWORK:
12800 		case D_FREEDEP:
12801 		case D_JSEGDEP:
12802 		case D_JNEWBLK:
12803 			continue;
12804 
12805 		default:
12806 			panic("softdep_sync_buf: Unknown type %s",
12807 			    TYPENAME(wk->wk_type));
12808 			/* NOTREACHED */
12809 		}
12810 	}
12811 out_unlock:
12812 	FREE_LOCK(ump);
12813 out:
12814 	return (error);
12815 }
12816 
12817 /*
12818  * Flush the dependencies associated with an inodedep.
12819  * Called with splbio blocked.
12820  */
12821 static int
12822 flush_inodedep_deps(vp, mp, ino)
12823 	struct vnode *vp;
12824 	struct mount *mp;
12825 	ino_t ino;
12826 {
12827 	struct inodedep *inodedep;
12828 	struct inoref *inoref;
12829 	struct ufsmount *ump;
12830 	int error, waitfor;
12831 
12832 	/*
12833 	 * This work is done in two passes. The first pass grabs most
12834 	 * of the buffers and begins asynchronously writing them. The
12835 	 * only way to wait for these asynchronous writes is to sleep
12836 	 * on the filesystem vnode which may stay busy for a long time
12837 	 * if the filesystem is active. So, instead, we make a second
12838 	 * pass over the dependencies blocking on each write. In the
12839 	 * usual case we will be blocking against a write that we
12840 	 * initiated, so when it is done the dependency will have been
12841 	 * resolved. Thus the second pass is expected to end quickly.
12842 	 * We give a brief window at the top of the loop to allow
12843 	 * any pending I/O to complete.
12844 	 */
12845 	ump = VFSTOUFS(mp);
12846 	LOCK_OWNED(ump);
12847 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12848 		if (error)
12849 			return (error);
12850 		FREE_LOCK(ump);
12851 		ACQUIRE_LOCK(ump);
12852 restart:
12853 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12854 			return (0);
12855 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12856 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12857 			    == DEPCOMPLETE) {
12858 				jwait(&inoref->if_list, MNT_WAIT);
12859 				goto restart;
12860 			}
12861 		}
12862 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12863 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12864 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12865 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12866 			continue;
12867 		/*
12868 		 * If pass2, we are done, otherwise do pass 2.
12869 		 */
12870 		if (waitfor == MNT_WAIT)
12871 			break;
12872 		waitfor = MNT_WAIT;
12873 	}
12874 	/*
12875 	 * Try freeing inodedep in case all dependencies have been removed.
12876 	 */
12877 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12878 		(void) free_inodedep(inodedep);
12879 	return (0);
12880 }
12881 
12882 /*
12883  * Flush an inode dependency list.
12884  * Called with splbio blocked.
12885  */
12886 static int
12887 flush_deplist(listhead, waitfor, errorp)
12888 	struct allocdirectlst *listhead;
12889 	int waitfor;
12890 	int *errorp;
12891 {
12892 	struct allocdirect *adp;
12893 	struct newblk *newblk;
12894 	struct ufsmount *ump;
12895 	struct buf *bp;
12896 
12897 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
12898 		return (0);
12899 	ump = VFSTOUFS(adp->ad_list.wk_mp);
12900 	LOCK_OWNED(ump);
12901 	TAILQ_FOREACH(adp, listhead, ad_next) {
12902 		newblk = (struct newblk *)adp;
12903 		if (newblk->nb_jnewblk != NULL) {
12904 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12905 			return (1);
12906 		}
12907 		if (newblk->nb_state & DEPCOMPLETE)
12908 			continue;
12909 		bp = newblk->nb_bmsafemap->sm_buf;
12910 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12911 		if (bp == NULL) {
12912 			if (waitfor == MNT_NOWAIT)
12913 				continue;
12914 			return (1);
12915 		}
12916 		FREE_LOCK(ump);
12917 		if (waitfor == MNT_NOWAIT)
12918 			bawrite(bp);
12919 		else
12920 			*errorp = bwrite(bp);
12921 		ACQUIRE_LOCK(ump);
12922 		return (1);
12923 	}
12924 	return (0);
12925 }
12926 
12927 /*
12928  * Flush dependencies associated with an allocdirect block.
12929  */
12930 static int
12931 flush_newblk_dep(vp, mp, lbn)
12932 	struct vnode *vp;
12933 	struct mount *mp;
12934 	ufs_lbn_t lbn;
12935 {
12936 	struct newblk *newblk;
12937 	struct ufsmount *ump;
12938 	struct bufobj *bo;
12939 	struct inode *ip;
12940 	struct buf *bp;
12941 	ufs2_daddr_t blkno;
12942 	int error;
12943 
12944 	error = 0;
12945 	bo = &vp->v_bufobj;
12946 	ip = VTOI(vp);
12947 	blkno = DIP(ip, i_db[lbn]);
12948 	if (blkno == 0)
12949 		panic("flush_newblk_dep: Missing block");
12950 	ump = VFSTOUFS(mp);
12951 	ACQUIRE_LOCK(ump);
12952 	/*
12953 	 * Loop until all dependencies related to this block are satisfied.
12954 	 * We must be careful to restart after each sleep in case a write
12955 	 * completes some part of this process for us.
12956 	 */
12957 	for (;;) {
12958 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12959 			FREE_LOCK(ump);
12960 			break;
12961 		}
12962 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12963 			panic("flush_newblk_deps: Bad newblk %p", newblk);
12964 		/*
12965 		 * Flush the journal.
12966 		 */
12967 		if (newblk->nb_jnewblk != NULL) {
12968 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12969 			continue;
12970 		}
12971 		/*
12972 		 * Write the bitmap dependency.
12973 		 */
12974 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12975 			bp = newblk->nb_bmsafemap->sm_buf;
12976 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
12977 			if (bp == NULL)
12978 				continue;
12979 			FREE_LOCK(ump);
12980 			error = bwrite(bp);
12981 			if (error)
12982 				break;
12983 			ACQUIRE_LOCK(ump);
12984 			continue;
12985 		}
12986 		/*
12987 		 * Write the buffer.
12988 		 */
12989 		FREE_LOCK(ump);
12990 		BO_LOCK(bo);
12991 		bp = gbincore(bo, lbn);
12992 		if (bp != NULL) {
12993 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12994 			    LK_INTERLOCK, BO_LOCKPTR(bo));
12995 			if (error == ENOLCK) {
12996 				ACQUIRE_LOCK(ump);
12997 				error = 0;
12998 				continue; /* Slept, retry */
12999 			}
13000 			if (error != 0)
13001 				break;	/* Failed */
13002 			if (bp->b_flags & B_DELWRI) {
13003 				bremfree(bp);
13004 				error = bwrite(bp);
13005 				if (error)
13006 					break;
13007 			} else
13008 				BUF_UNLOCK(bp);
13009 		} else
13010 			BO_UNLOCK(bo);
13011 		/*
13012 		 * We have to wait for the direct pointers to
13013 		 * point at the newdirblk before the dependency
13014 		 * will go away.
13015 		 */
13016 		error = ffs_update(vp, 1);
13017 		if (error)
13018 			break;
13019 		ACQUIRE_LOCK(ump);
13020 	}
13021 	return (error);
13022 }
13023 
13024 /*
13025  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13026  * Called with splbio blocked.
13027  */
13028 static int
13029 flush_pagedep_deps(pvp, mp, diraddhdp)
13030 	struct vnode *pvp;
13031 	struct mount *mp;
13032 	struct diraddhd *diraddhdp;
13033 {
13034 	struct inodedep *inodedep;
13035 	struct inoref *inoref;
13036 	struct ufsmount *ump;
13037 	struct diradd *dap;
13038 	struct vnode *vp;
13039 	int error = 0;
13040 	struct buf *bp;
13041 	ino_t inum;
13042 	struct diraddhd unfinished;
13043 
13044 	LIST_INIT(&unfinished);
13045 	ump = VFSTOUFS(mp);
13046 	LOCK_OWNED(ump);
13047 restart:
13048 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13049 		/*
13050 		 * Flush ourselves if this directory entry
13051 		 * has a MKDIR_PARENT dependency.
13052 		 */
13053 		if (dap->da_state & MKDIR_PARENT) {
13054 			FREE_LOCK(ump);
13055 			if ((error = ffs_update(pvp, 1)) != 0)
13056 				break;
13057 			ACQUIRE_LOCK(ump);
13058 			/*
13059 			 * If that cleared dependencies, go on to next.
13060 			 */
13061 			if (dap != LIST_FIRST(diraddhdp))
13062 				continue;
13063 			/*
13064 			 * All MKDIR_PARENT dependencies and all the
13065 			 * NEWBLOCK pagedeps that are contained in direct
13066 			 * blocks were resolved by doing above ffs_update.
13067 			 * Pagedeps contained in indirect blocks may
13068 			 * require a complete sync'ing of the directory.
13069 			 * We are in the midst of doing a complete sync,
13070 			 * so if they are not resolved in this pass we
13071 			 * defer them for now as they will be sync'ed by
13072 			 * our caller shortly.
13073 			 */
13074 			LIST_REMOVE(dap, da_pdlist);
13075 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13076 			continue;
13077 		}
13078 		/*
13079 		 * A newly allocated directory must have its "." and
13080 		 * ".." entries written out before its name can be
13081 		 * committed in its parent.
13082 		 */
13083 		inum = dap->da_newinum;
13084 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13085 			panic("flush_pagedep_deps: lost inode1");
13086 		/*
13087 		 * Wait for any pending journal adds to complete so we don't
13088 		 * cause rollbacks while syncing.
13089 		 */
13090 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13091 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13092 			    == DEPCOMPLETE) {
13093 				jwait(&inoref->if_list, MNT_WAIT);
13094 				goto restart;
13095 			}
13096 		}
13097 		if (dap->da_state & MKDIR_BODY) {
13098 			FREE_LOCK(ump);
13099 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13100 			    FFSV_FORCEINSMQ)))
13101 				break;
13102 			error = flush_newblk_dep(vp, mp, 0);
13103 			/*
13104 			 * If we still have the dependency we might need to
13105 			 * update the vnode to sync the new link count to
13106 			 * disk.
13107 			 */
13108 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13109 				error = ffs_update(vp, 1);
13110 			vput(vp);
13111 			if (error != 0)
13112 				break;
13113 			ACQUIRE_LOCK(ump);
13114 			/*
13115 			 * If that cleared dependencies, go on to next.
13116 			 */
13117 			if (dap != LIST_FIRST(diraddhdp))
13118 				continue;
13119 			if (dap->da_state & MKDIR_BODY) {
13120 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13121 				    &inodedep);
13122 				panic("flush_pagedep_deps: MKDIR_BODY "
13123 				    "inodedep %p dap %p vp %p",
13124 				    inodedep, dap, vp);
13125 			}
13126 		}
13127 		/*
13128 		 * Flush the inode on which the directory entry depends.
13129 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13130 		 * the only remaining dependency is that the updated inode
13131 		 * count must get pushed to disk. The inode has already
13132 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13133 		 * the time of the reference count change. So we need only
13134 		 * locate that buffer, ensure that there will be no rollback
13135 		 * caused by a bitmap dependency, then write the inode buffer.
13136 		 */
13137 retry:
13138 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13139 			panic("flush_pagedep_deps: lost inode");
13140 		/*
13141 		 * If the inode still has bitmap dependencies,
13142 		 * push them to disk.
13143 		 */
13144 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13145 			bp = inodedep->id_bmsafemap->sm_buf;
13146 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13147 			if (bp == NULL)
13148 				goto retry;
13149 			FREE_LOCK(ump);
13150 			if ((error = bwrite(bp)) != 0)
13151 				break;
13152 			ACQUIRE_LOCK(ump);
13153 			if (dap != LIST_FIRST(diraddhdp))
13154 				continue;
13155 		}
13156 		/*
13157 		 * If the inode is still sitting in a buffer waiting
13158 		 * to be written or waiting for the link count to be
13159 		 * adjusted update it here to flush it to disk.
13160 		 */
13161 		if (dap == LIST_FIRST(diraddhdp)) {
13162 			FREE_LOCK(ump);
13163 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13164 			    FFSV_FORCEINSMQ)))
13165 				break;
13166 			error = ffs_update(vp, 1);
13167 			vput(vp);
13168 			if (error)
13169 				break;
13170 			ACQUIRE_LOCK(ump);
13171 		}
13172 		/*
13173 		 * If we have failed to get rid of all the dependencies
13174 		 * then something is seriously wrong.
13175 		 */
13176 		if (dap == LIST_FIRST(diraddhdp)) {
13177 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13178 			panic("flush_pagedep_deps: failed to flush "
13179 			    "inodedep %p ino %ju dap %p",
13180 			    inodedep, (uintmax_t)inum, dap);
13181 		}
13182 	}
13183 	if (error)
13184 		ACQUIRE_LOCK(ump);
13185 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13186 		LIST_REMOVE(dap, da_pdlist);
13187 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13188 	}
13189 	return (error);
13190 }
13191 
13192 /*
13193  * A large burst of file addition or deletion activity can drive the
13194  * memory load excessively high. First attempt to slow things down
13195  * using the techniques below. If that fails, this routine requests
13196  * the offending operations to fall back to running synchronously
13197  * until the memory load returns to a reasonable level.
13198  */
13199 int
13200 softdep_slowdown(vp)
13201 	struct vnode *vp;
13202 {
13203 	struct ufsmount *ump;
13204 	int jlow;
13205 	int max_softdeps_hard;
13206 
13207 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13208 	    ("softdep_slowdown called on non-softdep filesystem"));
13209 	ump = VFSTOUFS(vp->v_mount);
13210 	ACQUIRE_LOCK(ump);
13211 	jlow = 0;
13212 	/*
13213 	 * Check for journal space if needed.
13214 	 */
13215 	if (DOINGSUJ(vp)) {
13216 		if (journal_space(ump, 0) == 0)
13217 			jlow = 1;
13218 	}
13219 	/*
13220 	 * If the system is under its limits and our filesystem is
13221 	 * not responsible for more than our share of the usage and
13222 	 * we are not low on journal space, then no need to slow down.
13223 	 */
13224 	max_softdeps_hard = max_softdeps * 11 / 10;
13225 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13226 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13227 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13228 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13229 	    ump->softdep_curdeps[D_DIRREM] <
13230 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13231 	    ump->softdep_curdeps[D_INODEDEP] <
13232 	    max_softdeps_hard / stat_flush_threads &&
13233 	    ump->softdep_curdeps[D_INDIRDEP] <
13234 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13235 	    ump->softdep_curdeps[D_FREEBLKS] <
13236 	    max_softdeps_hard / stat_flush_threads) {
13237 		FREE_LOCK(ump);
13238   		return (0);
13239 	}
13240 	/*
13241 	 * If the journal is low or our filesystem is over its limit
13242 	 * then speedup the cleanup.
13243 	 */
13244 	if (ump->softdep_curdeps[D_INDIRDEP] <
13245 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13246 		softdep_speedup(ump);
13247 	stat_sync_limit_hit += 1;
13248 	FREE_LOCK(ump);
13249 	/*
13250 	 * We only slow down the rate at which new dependencies are
13251 	 * generated if we are not using journaling. With journaling,
13252 	 * the cleanup should always be sufficient to keep things
13253 	 * under control.
13254 	 */
13255 	if (DOINGSUJ(vp))
13256 		return (0);
13257 	return (1);
13258 }
13259 
13260 /*
13261  * Called by the allocation routines when they are about to fail
13262  * in the hope that we can free up the requested resource (inodes
13263  * or disk space).
13264  *
13265  * First check to see if the work list has anything on it. If it has,
13266  * clean up entries until we successfully free the requested resource.
13267  * Because this process holds inodes locked, we cannot handle any remove
13268  * requests that might block on a locked inode as that could lead to
13269  * deadlock. If the worklist yields none of the requested resource,
13270  * start syncing out vnodes to free up the needed space.
13271  */
13272 int
13273 softdep_request_cleanup(fs, vp, cred, resource)
13274 	struct fs *fs;
13275 	struct vnode *vp;
13276 	struct ucred *cred;
13277 	int resource;
13278 {
13279 	struct ufsmount *ump;
13280 	struct mount *mp;
13281 	long starttime;
13282 	ufs2_daddr_t needed;
13283 	int error, failed_vnode;
13284 
13285 	/*
13286 	 * If we are being called because of a process doing a
13287 	 * copy-on-write, then it is not safe to process any
13288 	 * worklist items as we will recurse into the copyonwrite
13289 	 * routine.  This will result in an incoherent snapshot.
13290 	 * If the vnode that we hold is a snapshot, we must avoid
13291 	 * handling other resources that could cause deadlock.
13292 	 */
13293 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13294 		return (0);
13295 
13296 	if (resource == FLUSH_BLOCKS_WAIT)
13297 		stat_cleanup_blkrequests += 1;
13298 	else
13299 		stat_cleanup_inorequests += 1;
13300 
13301 	mp = vp->v_mount;
13302 	ump = VFSTOUFS(mp);
13303 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13304 	UFS_UNLOCK(ump);
13305 	error = ffs_update(vp, 1);
13306 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13307 		UFS_LOCK(ump);
13308 		return (0);
13309 	}
13310 	/*
13311 	 * If we are in need of resources, start by cleaning up
13312 	 * any block removals associated with our inode.
13313 	 */
13314 	ACQUIRE_LOCK(ump);
13315 	process_removes(vp);
13316 	process_truncates(vp);
13317 	FREE_LOCK(ump);
13318 	/*
13319 	 * Now clean up at least as many resources as we will need.
13320 	 *
13321 	 * When requested to clean up inodes, the number that are needed
13322 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13323 	 * plus a bit of slop (2) in case some more writers show up while
13324 	 * we are cleaning.
13325 	 *
13326 	 * When requested to free up space, the amount of space that
13327 	 * we need is enough blocks to allocate a full-sized segment
13328 	 * (fs_contigsumsize). The number of such segments that will
13329 	 * be needed is set by the number of simultaneous writers
13330 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13331 	 * writers show up while we are cleaning.
13332 	 *
13333 	 * Additionally, if we are unpriviledged and allocating space,
13334 	 * we need to ensure that we clean up enough blocks to get the
13335 	 * needed number of blocks over the threshold of the minimum
13336 	 * number of blocks required to be kept free by the filesystem
13337 	 * (fs_minfree).
13338 	 */
13339 	if (resource == FLUSH_INODES_WAIT) {
13340 		needed = vp->v_mount->mnt_writeopcount + 2;
13341 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13342 		needed = (vp->v_mount->mnt_writeopcount + 2) *
13343 		    fs->fs_contigsumsize;
13344 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
13345 			needed += fragstoblks(fs,
13346 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13347 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13348 	} else {
13349 		UFS_LOCK(ump);
13350 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13351 		    resource);
13352 		return (0);
13353 	}
13354 	starttime = time_second;
13355 retry:
13356 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13357 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13358 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13359 	    fs->fs_cstotal.cs_nifree <= needed)) {
13360 		ACQUIRE_LOCK(ump);
13361 		if (ump->softdep_on_worklist > 0 &&
13362 		    process_worklist_item(UFSTOVFS(ump),
13363 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13364 			stat_worklist_push += 1;
13365 		FREE_LOCK(ump);
13366 	}
13367 	/*
13368 	 * If we still need resources and there are no more worklist
13369 	 * entries to process to obtain them, we have to start flushing
13370 	 * the dirty vnodes to force the release of additional requests
13371 	 * to the worklist that we can then process to reap addition
13372 	 * resources. We walk the vnodes associated with the mount point
13373 	 * until we get the needed worklist requests that we can reap.
13374 	 *
13375 	 * If there are several threads all needing to clean the same
13376 	 * mount point, only one is allowed to walk the mount list.
13377 	 * When several threads all try to walk the same mount list,
13378 	 * they end up competing with each other and often end up in
13379 	 * livelock. This approach ensures that forward progress is
13380 	 * made at the cost of occational ENOSPC errors being returned
13381 	 * that might otherwise have been avoided.
13382 	 */
13383 	error = 1;
13384 	if ((resource == FLUSH_BLOCKS_WAIT &&
13385 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13386 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13387 	     fs->fs_cstotal.cs_nifree <= needed)) {
13388 		ACQUIRE_LOCK(ump);
13389 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13390 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13391 			FREE_LOCK(ump);
13392 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13393 			ACQUIRE_LOCK(ump);
13394 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13395 			FREE_LOCK(ump);
13396 			if (ump->softdep_on_worklist > 0) {
13397 				stat_cleanup_retries += 1;
13398 				if (!failed_vnode)
13399 					goto retry;
13400 			}
13401 		} else {
13402 			FREE_LOCK(ump);
13403 			error = 0;
13404 		}
13405 		stat_cleanup_failures += 1;
13406 	}
13407 	if (time_second - starttime > stat_cleanup_high_delay)
13408 		stat_cleanup_high_delay = time_second - starttime;
13409 	UFS_LOCK(ump);
13410 	return (error);
13411 }
13412 
13413 /*
13414  * Scan the vnodes for the specified mount point flushing out any
13415  * vnodes that can be locked without waiting. Finally, try to flush
13416  * the device associated with the mount point if it can be locked
13417  * without waiting.
13418  *
13419  * We return 0 if we were able to lock every vnode in our scan.
13420  * If we had to skip one or more vnodes, we return 1.
13421  */
13422 static int
13423 softdep_request_cleanup_flush(mp, ump)
13424 	struct mount *mp;
13425 	struct ufsmount *ump;
13426 {
13427 	struct thread *td;
13428 	struct vnode *lvp, *mvp;
13429 	int failed_vnode;
13430 
13431 	failed_vnode = 0;
13432 	td = curthread;
13433 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13434 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13435 			VI_UNLOCK(lvp);
13436 			continue;
13437 		}
13438 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13439 		    td) != 0) {
13440 			failed_vnode = 1;
13441 			continue;
13442 		}
13443 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13444 			vput(lvp);
13445 			continue;
13446 		}
13447 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13448 		vput(lvp);
13449 	}
13450 	lvp = ump->um_devvp;
13451 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13452 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13453 		VOP_UNLOCK(lvp, 0);
13454 	}
13455 	return (failed_vnode);
13456 }
13457 
13458 static bool
13459 softdep_excess_items(struct ufsmount *ump, int item)
13460 {
13461 
13462 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13463 	return (dep_current[item] > max_softdeps &&
13464 	    ump->softdep_curdeps[item] > max_softdeps /
13465 	    stat_flush_threads);
13466 }
13467 
13468 static void
13469 schedule_cleanup(struct mount *mp)
13470 {
13471 	struct ufsmount *ump;
13472 	struct thread *td;
13473 
13474 	ump = VFSTOUFS(mp);
13475 	LOCK_OWNED(ump);
13476 	FREE_LOCK(ump);
13477 	td = curthread;
13478 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13479 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13480 		/*
13481 		 * No ast is delivered to kernel threads, so nobody
13482 		 * would deref the mp.  Some kernel threads
13483 		 * explicitely check for AST, e.g. NFS daemon does
13484 		 * this in the serving loop.
13485 		 */
13486 		return;
13487 	}
13488 	if (td->td_su != NULL)
13489 		vfs_rel(td->td_su);
13490 	vfs_ref(mp);
13491 	td->td_su = mp;
13492 	thread_lock(td);
13493 	td->td_flags |= TDF_ASTPENDING;
13494 	thread_unlock(td);
13495 }
13496 
13497 static void
13498 softdep_ast_cleanup_proc(struct thread *td)
13499 {
13500 	struct mount *mp;
13501 	struct ufsmount *ump;
13502 	int error;
13503 	bool req;
13504 
13505 	while ((mp = td->td_su) != NULL) {
13506 		td->td_su = NULL;
13507 		error = vfs_busy(mp, MBF_NOWAIT);
13508 		vfs_rel(mp);
13509 		if (error != 0)
13510 			return;
13511 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13512 			ump = VFSTOUFS(mp);
13513 			for (;;) {
13514 				req = false;
13515 				ACQUIRE_LOCK(ump);
13516 				if (softdep_excess_items(ump, D_INODEDEP)) {
13517 					req = true;
13518 					request_cleanup(mp, FLUSH_INODES);
13519 				}
13520 				if (softdep_excess_items(ump, D_DIRREM)) {
13521 					req = true;
13522 					request_cleanup(mp, FLUSH_BLOCKS);
13523 				}
13524 				FREE_LOCK(ump);
13525 				if (softdep_excess_items(ump, D_NEWBLK) ||
13526 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13527 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13528 					error = vn_start_write(NULL, &mp,
13529 					    V_WAIT);
13530 					if (error == 0) {
13531 						req = true;
13532 						VFS_SYNC(mp, MNT_WAIT);
13533 						vn_finished_write(mp);
13534 					}
13535 				}
13536 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13537 					break;
13538 			}
13539 		}
13540 		vfs_unbusy(mp);
13541 	}
13542 	if ((mp = td->td_su) != NULL) {
13543 		td->td_su = NULL;
13544 		vfs_rel(mp);
13545 	}
13546 }
13547 
13548 /*
13549  * If memory utilization has gotten too high, deliberately slow things
13550  * down and speed up the I/O processing.
13551  */
13552 static int
13553 request_cleanup(mp, resource)
13554 	struct mount *mp;
13555 	int resource;
13556 {
13557 	struct thread *td = curthread;
13558 	struct ufsmount *ump;
13559 
13560 	ump = VFSTOUFS(mp);
13561 	LOCK_OWNED(ump);
13562 	/*
13563 	 * We never hold up the filesystem syncer or buf daemon.
13564 	 */
13565 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13566 		return (0);
13567 	/*
13568 	 * First check to see if the work list has gotten backlogged.
13569 	 * If it has, co-opt this process to help clean up two entries.
13570 	 * Because this process may hold inodes locked, we cannot
13571 	 * handle any remove requests that might block on a locked
13572 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13573 	 * to avoid recursively processing the worklist.
13574 	 */
13575 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13576 		td->td_pflags |= TDP_SOFTDEP;
13577 		process_worklist_item(mp, 2, LK_NOWAIT);
13578 		td->td_pflags &= ~TDP_SOFTDEP;
13579 		stat_worklist_push += 2;
13580 		return(1);
13581 	}
13582 	/*
13583 	 * Next, we attempt to speed up the syncer process. If that
13584 	 * is successful, then we allow the process to continue.
13585 	 */
13586 	if (softdep_speedup(ump) &&
13587 	    resource != FLUSH_BLOCKS_WAIT &&
13588 	    resource != FLUSH_INODES_WAIT)
13589 		return(0);
13590 	/*
13591 	 * If we are resource constrained on inode dependencies, try
13592 	 * flushing some dirty inodes. Otherwise, we are constrained
13593 	 * by file deletions, so try accelerating flushes of directories
13594 	 * with removal dependencies. We would like to do the cleanup
13595 	 * here, but we probably hold an inode locked at this point and
13596 	 * that might deadlock against one that we try to clean. So,
13597 	 * the best that we can do is request the syncer daemon to do
13598 	 * the cleanup for us.
13599 	 */
13600 	switch (resource) {
13601 
13602 	case FLUSH_INODES:
13603 	case FLUSH_INODES_WAIT:
13604 		ACQUIRE_GBLLOCK(&lk);
13605 		stat_ino_limit_push += 1;
13606 		req_clear_inodedeps += 1;
13607 		FREE_GBLLOCK(&lk);
13608 		stat_countp = &stat_ino_limit_hit;
13609 		break;
13610 
13611 	case FLUSH_BLOCKS:
13612 	case FLUSH_BLOCKS_WAIT:
13613 		ACQUIRE_GBLLOCK(&lk);
13614 		stat_blk_limit_push += 1;
13615 		req_clear_remove += 1;
13616 		FREE_GBLLOCK(&lk);
13617 		stat_countp = &stat_blk_limit_hit;
13618 		break;
13619 
13620 	default:
13621 		panic("request_cleanup: unknown type");
13622 	}
13623 	/*
13624 	 * Hopefully the syncer daemon will catch up and awaken us.
13625 	 * We wait at most tickdelay before proceeding in any case.
13626 	 */
13627 	ACQUIRE_GBLLOCK(&lk);
13628 	FREE_LOCK(ump);
13629 	proc_waiting += 1;
13630 	if (callout_pending(&softdep_callout) == FALSE)
13631 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13632 		    pause_timer, 0);
13633 
13634 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13635 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13636 	proc_waiting -= 1;
13637 	FREE_GBLLOCK(&lk);
13638 	ACQUIRE_LOCK(ump);
13639 	return (1);
13640 }
13641 
13642 /*
13643  * Awaken processes pausing in request_cleanup and clear proc_waiting
13644  * to indicate that there is no longer a timer running. Pause_timer
13645  * will be called with the global softdep mutex (&lk) locked.
13646  */
13647 static void
13648 pause_timer(arg)
13649 	void *arg;
13650 {
13651 
13652 	GBLLOCK_OWNED(&lk);
13653 	/*
13654 	 * The callout_ API has acquired mtx and will hold it around this
13655 	 * function call.
13656 	 */
13657 	*stat_countp += proc_waiting;
13658 	wakeup(&proc_waiting);
13659 }
13660 
13661 /*
13662  * If requested, try removing inode or removal dependencies.
13663  */
13664 static void
13665 check_clear_deps(mp)
13666 	struct mount *mp;
13667 {
13668 
13669 	/*
13670 	 * If we are suspended, it may be because of our using
13671 	 * too many inodedeps, so help clear them out.
13672 	 */
13673 	if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13674 		clear_inodedeps(mp);
13675 	/*
13676 	 * General requests for cleanup of backed up dependencies
13677 	 */
13678 	ACQUIRE_GBLLOCK(&lk);
13679 	if (req_clear_inodedeps) {
13680 		req_clear_inodedeps -= 1;
13681 		FREE_GBLLOCK(&lk);
13682 		clear_inodedeps(mp);
13683 		ACQUIRE_GBLLOCK(&lk);
13684 		wakeup(&proc_waiting);
13685 	}
13686 	if (req_clear_remove) {
13687 		req_clear_remove -= 1;
13688 		FREE_GBLLOCK(&lk);
13689 		clear_remove(mp);
13690 		ACQUIRE_GBLLOCK(&lk);
13691 		wakeup(&proc_waiting);
13692 	}
13693 	FREE_GBLLOCK(&lk);
13694 }
13695 
13696 /*
13697  * Flush out a directory with at least one removal dependency in an effort to
13698  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13699  */
13700 static void
13701 clear_remove(mp)
13702 	struct mount *mp;
13703 {
13704 	struct pagedep_hashhead *pagedephd;
13705 	struct pagedep *pagedep;
13706 	struct ufsmount *ump;
13707 	struct vnode *vp;
13708 	struct bufobj *bo;
13709 	int error, cnt;
13710 	ino_t ino;
13711 
13712 	ump = VFSTOUFS(mp);
13713 	LOCK_OWNED(ump);
13714 
13715 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13716 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13717 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13718 			ump->pagedep_nextclean = 0;
13719 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13720 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13721 				continue;
13722 			ino = pagedep->pd_ino;
13723 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13724 				continue;
13725 			FREE_LOCK(ump);
13726 
13727 			/*
13728 			 * Let unmount clear deps
13729 			 */
13730 			error = vfs_busy(mp, MBF_NOWAIT);
13731 			if (error != 0)
13732 				goto finish_write;
13733 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13734 			     FFSV_FORCEINSMQ);
13735 			vfs_unbusy(mp);
13736 			if (error != 0) {
13737 				softdep_error("clear_remove: vget", error);
13738 				goto finish_write;
13739 			}
13740 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13741 				softdep_error("clear_remove: fsync", error);
13742 			bo = &vp->v_bufobj;
13743 			BO_LOCK(bo);
13744 			drain_output(vp);
13745 			BO_UNLOCK(bo);
13746 			vput(vp);
13747 		finish_write:
13748 			vn_finished_write(mp);
13749 			ACQUIRE_LOCK(ump);
13750 			return;
13751 		}
13752 	}
13753 }
13754 
13755 /*
13756  * Clear out a block of dirty inodes in an effort to reduce
13757  * the number of inodedep dependency structures.
13758  */
13759 static void
13760 clear_inodedeps(mp)
13761 	struct mount *mp;
13762 {
13763 	struct inodedep_hashhead *inodedephd;
13764 	struct inodedep *inodedep;
13765 	struct ufsmount *ump;
13766 	struct vnode *vp;
13767 	struct fs *fs;
13768 	int error, cnt;
13769 	ino_t firstino, lastino, ino;
13770 
13771 	ump = VFSTOUFS(mp);
13772 	fs = ump->um_fs;
13773 	LOCK_OWNED(ump);
13774 	/*
13775 	 * Pick a random inode dependency to be cleared.
13776 	 * We will then gather up all the inodes in its block
13777 	 * that have dependencies and flush them out.
13778 	 */
13779 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13780 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13781 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13782 			ump->inodedep_nextclean = 0;
13783 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13784 			break;
13785 	}
13786 	if (inodedep == NULL)
13787 		return;
13788 	/*
13789 	 * Find the last inode in the block with dependencies.
13790 	 */
13791 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13792 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13793 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13794 			break;
13795 	/*
13796 	 * Asynchronously push all but the last inode with dependencies.
13797 	 * Synchronously push the last inode with dependencies to ensure
13798 	 * that the inode block gets written to free up the inodedeps.
13799 	 */
13800 	for (ino = firstino; ino <= lastino; ino++) {
13801 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13802 			continue;
13803 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13804 			continue;
13805 		FREE_LOCK(ump);
13806 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13807 		if (error != 0) {
13808 			vn_finished_write(mp);
13809 			ACQUIRE_LOCK(ump);
13810 			return;
13811 		}
13812 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13813 		    FFSV_FORCEINSMQ)) != 0) {
13814 			softdep_error("clear_inodedeps: vget", error);
13815 			vfs_unbusy(mp);
13816 			vn_finished_write(mp);
13817 			ACQUIRE_LOCK(ump);
13818 			return;
13819 		}
13820 		vfs_unbusy(mp);
13821 		if (ino == lastino) {
13822 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13823 				softdep_error("clear_inodedeps: fsync1", error);
13824 		} else {
13825 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13826 				softdep_error("clear_inodedeps: fsync2", error);
13827 			BO_LOCK(&vp->v_bufobj);
13828 			drain_output(vp);
13829 			BO_UNLOCK(&vp->v_bufobj);
13830 		}
13831 		vput(vp);
13832 		vn_finished_write(mp);
13833 		ACQUIRE_LOCK(ump);
13834 	}
13835 }
13836 
13837 void
13838 softdep_buf_append(bp, wkhd)
13839 	struct buf *bp;
13840 	struct workhead *wkhd;
13841 {
13842 	struct worklist *wk;
13843 	struct ufsmount *ump;
13844 
13845 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13846 		return;
13847 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13848 	    ("softdep_buf_append called on non-softdep filesystem"));
13849 	ump = VFSTOUFS(wk->wk_mp);
13850 	ACQUIRE_LOCK(ump);
13851 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13852 		WORKLIST_REMOVE(wk);
13853 		WORKLIST_INSERT(&bp->b_dep, wk);
13854 	}
13855 	FREE_LOCK(ump);
13856 
13857 }
13858 
13859 void
13860 softdep_inode_append(ip, cred, wkhd)
13861 	struct inode *ip;
13862 	struct ucred *cred;
13863 	struct workhead *wkhd;
13864 {
13865 	struct buf *bp;
13866 	struct fs *fs;
13867 	struct ufsmount *ump;
13868 	int error;
13869 
13870 	ump = ITOUMP(ip);
13871 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13872 	    ("softdep_inode_append called on non-softdep filesystem"));
13873 	fs = ump->um_fs;
13874 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13875 	    (int)fs->fs_bsize, cred, &bp);
13876 	if (error) {
13877 		bqrelse(bp);
13878 		softdep_freework(wkhd);
13879 		return;
13880 	}
13881 	softdep_buf_append(bp, wkhd);
13882 	bqrelse(bp);
13883 }
13884 
13885 void
13886 softdep_freework(wkhd)
13887 	struct workhead *wkhd;
13888 {
13889 	struct worklist *wk;
13890 	struct ufsmount *ump;
13891 
13892 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13893 		return;
13894 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13895 	    ("softdep_freework called on non-softdep filesystem"));
13896 	ump = VFSTOUFS(wk->wk_mp);
13897 	ACQUIRE_LOCK(ump);
13898 	handle_jwork(wkhd);
13899 	FREE_LOCK(ump);
13900 }
13901 
13902 static struct ufsmount *
13903 softdep_bp_to_mp(bp)
13904 	struct buf *bp;
13905 {
13906 	struct mount *mp;
13907 	struct vnode *vp;
13908 
13909 	if (LIST_EMPTY(&bp->b_dep))
13910 		return (NULL);
13911 	vp = bp->b_vp;
13912 
13913 	/*
13914 	 * The ump mount point is stable after we get a correct
13915 	 * pointer, since bp is locked and this prevents unmount from
13916 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
13917 	 * head wk_mp, because we do not yet own SU ump lock and
13918 	 * workitem might be freed while dereferenced.
13919 	 */
13920 retry:
13921 	if (vp->v_type == VCHR) {
13922 		VI_LOCK(vp);
13923 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
13924 		VI_UNLOCK(vp);
13925 		if (mp == NULL)
13926 			goto retry;
13927 	} else if (vp->v_type == VREG || vp->v_type == VDIR ||
13928 	    vp->v_type == VLNK) {
13929 		mp = vp->v_mount;
13930 	} else {
13931 		return (NULL);
13932 	}
13933 	return (VFSTOUFS(mp));
13934 }
13935 
13936 /*
13937  * Function to determine if the buffer has outstanding dependencies
13938  * that will cause a roll-back if the buffer is written. If wantcount
13939  * is set, return number of dependencies, otherwise just yes or no.
13940  */
13941 static int
13942 softdep_count_dependencies(bp, wantcount)
13943 	struct buf *bp;
13944 	int wantcount;
13945 {
13946 	struct worklist *wk;
13947 	struct ufsmount *ump;
13948 	struct bmsafemap *bmsafemap;
13949 	struct freework *freework;
13950 	struct inodedep *inodedep;
13951 	struct indirdep *indirdep;
13952 	struct freeblks *freeblks;
13953 	struct allocindir *aip;
13954 	struct pagedep *pagedep;
13955 	struct dirrem *dirrem;
13956 	struct newblk *newblk;
13957 	struct mkdir *mkdir;
13958 	struct diradd *dap;
13959 	int i, retval;
13960 
13961 	ump = softdep_bp_to_mp(bp);
13962 	if (ump == NULL)
13963 		return (0);
13964 	retval = 0;
13965 	ACQUIRE_LOCK(ump);
13966 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13967 		switch (wk->wk_type) {
13968 
13969 		case D_INODEDEP:
13970 			inodedep = WK_INODEDEP(wk);
13971 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13972 				/* bitmap allocation dependency */
13973 				retval += 1;
13974 				if (!wantcount)
13975 					goto out;
13976 			}
13977 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13978 				/* direct block pointer dependency */
13979 				retval += 1;
13980 				if (!wantcount)
13981 					goto out;
13982 			}
13983 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13984 				/* direct block pointer dependency */
13985 				retval += 1;
13986 				if (!wantcount)
13987 					goto out;
13988 			}
13989 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13990 				/* Add reference dependency. */
13991 				retval += 1;
13992 				if (!wantcount)
13993 					goto out;
13994 			}
13995 			continue;
13996 
13997 		case D_INDIRDEP:
13998 			indirdep = WK_INDIRDEP(wk);
13999 
14000 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14001 				/* indirect truncation dependency */
14002 				retval += 1;
14003 				if (!wantcount)
14004 					goto out;
14005 			}
14006 
14007 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14008 				/* indirect block pointer dependency */
14009 				retval += 1;
14010 				if (!wantcount)
14011 					goto out;
14012 			}
14013 			continue;
14014 
14015 		case D_PAGEDEP:
14016 			pagedep = WK_PAGEDEP(wk);
14017 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14018 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14019 					/* Journal remove ref dependency. */
14020 					retval += 1;
14021 					if (!wantcount)
14022 						goto out;
14023 				}
14024 			}
14025 			for (i = 0; i < DAHASHSZ; i++) {
14026 
14027 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14028 					/* directory entry dependency */
14029 					retval += 1;
14030 					if (!wantcount)
14031 						goto out;
14032 				}
14033 			}
14034 			continue;
14035 
14036 		case D_BMSAFEMAP:
14037 			bmsafemap = WK_BMSAFEMAP(wk);
14038 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14039 				/* Add reference dependency. */
14040 				retval += 1;
14041 				if (!wantcount)
14042 					goto out;
14043 			}
14044 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14045 				/* Allocate block dependency. */
14046 				retval += 1;
14047 				if (!wantcount)
14048 					goto out;
14049 			}
14050 			continue;
14051 
14052 		case D_FREEBLKS:
14053 			freeblks = WK_FREEBLKS(wk);
14054 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14055 				/* Freeblk journal dependency. */
14056 				retval += 1;
14057 				if (!wantcount)
14058 					goto out;
14059 			}
14060 			continue;
14061 
14062 		case D_ALLOCDIRECT:
14063 		case D_ALLOCINDIR:
14064 			newblk = WK_NEWBLK(wk);
14065 			if (newblk->nb_jnewblk) {
14066 				/* Journal allocate dependency. */
14067 				retval += 1;
14068 				if (!wantcount)
14069 					goto out;
14070 			}
14071 			continue;
14072 
14073 		case D_MKDIR:
14074 			mkdir = WK_MKDIR(wk);
14075 			if (mkdir->md_jaddref) {
14076 				/* Journal reference dependency. */
14077 				retval += 1;
14078 				if (!wantcount)
14079 					goto out;
14080 			}
14081 			continue;
14082 
14083 		case D_FREEWORK:
14084 		case D_FREEDEP:
14085 		case D_JSEGDEP:
14086 		case D_JSEG:
14087 		case D_SBDEP:
14088 			/* never a dependency on these blocks */
14089 			continue;
14090 
14091 		default:
14092 			panic("softdep_count_dependencies: Unexpected type %s",
14093 			    TYPENAME(wk->wk_type));
14094 			/* NOTREACHED */
14095 		}
14096 	}
14097 out:
14098 	FREE_LOCK(ump);
14099 	return (retval);
14100 }
14101 
14102 /*
14103  * Acquire exclusive access to a buffer.
14104  * Must be called with a locked mtx parameter.
14105  * Return acquired buffer or NULL on failure.
14106  */
14107 static struct buf *
14108 getdirtybuf(bp, lock, waitfor)
14109 	struct buf *bp;
14110 	struct rwlock *lock;
14111 	int waitfor;
14112 {
14113 	int error;
14114 
14115 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14116 		if (waitfor != MNT_WAIT)
14117 			return (NULL);
14118 		error = BUF_LOCK(bp,
14119 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14120 		/*
14121 		 * Even if we successfully acquire bp here, we have dropped
14122 		 * lock, which may violates our guarantee.
14123 		 */
14124 		if (error == 0)
14125 			BUF_UNLOCK(bp);
14126 		else if (error != ENOLCK)
14127 			panic("getdirtybuf: inconsistent lock: %d", error);
14128 		rw_wlock(lock);
14129 		return (NULL);
14130 	}
14131 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14132 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14133 			rw_wunlock(lock);
14134 			BO_LOCK(bp->b_bufobj);
14135 			BUF_UNLOCK(bp);
14136 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14137 				bp->b_vflags |= BV_BKGRDWAIT;
14138 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14139 				       PRIBIO | PDROP, "getbuf", 0);
14140 			} else
14141 				BO_UNLOCK(bp->b_bufobj);
14142 			rw_wlock(lock);
14143 			return (NULL);
14144 		}
14145 		BUF_UNLOCK(bp);
14146 		if (waitfor != MNT_WAIT)
14147 			return (NULL);
14148 #ifdef DEBUG_VFS_LOCKS
14149 		if (bp->b_vp->v_type != VCHR)
14150 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14151 #endif
14152 		bp->b_vflags |= BV_BKGRDWAIT;
14153 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14154 		return (NULL);
14155 	}
14156 	if ((bp->b_flags & B_DELWRI) == 0) {
14157 		BUF_UNLOCK(bp);
14158 		return (NULL);
14159 	}
14160 	bremfree(bp);
14161 	return (bp);
14162 }
14163 
14164 
14165 /*
14166  * Check if it is safe to suspend the file system now.  On entry,
14167  * the vnode interlock for devvp should be held.  Return 0 with
14168  * the mount interlock held if the file system can be suspended now,
14169  * otherwise return EAGAIN with the mount interlock held.
14170  */
14171 int
14172 softdep_check_suspend(struct mount *mp,
14173 		      struct vnode *devvp,
14174 		      int softdep_depcnt,
14175 		      int softdep_accdepcnt,
14176 		      int secondary_writes,
14177 		      int secondary_accwrites)
14178 {
14179 	struct bufobj *bo;
14180 	struct ufsmount *ump;
14181 	struct inodedep *inodedep;
14182 	int error, unlinked;
14183 
14184 	bo = &devvp->v_bufobj;
14185 	ASSERT_BO_WLOCKED(bo);
14186 
14187 	/*
14188 	 * If we are not running with soft updates, then we need only
14189 	 * deal with secondary writes as we try to suspend.
14190 	 */
14191 	if (MOUNTEDSOFTDEP(mp) == 0) {
14192 		MNT_ILOCK(mp);
14193 		while (mp->mnt_secondary_writes != 0) {
14194 			BO_UNLOCK(bo);
14195 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14196 			    (PUSER - 1) | PDROP, "secwr", 0);
14197 			BO_LOCK(bo);
14198 			MNT_ILOCK(mp);
14199 		}
14200 
14201 		/*
14202 		 * Reasons for needing more work before suspend:
14203 		 * - Dirty buffers on devvp.
14204 		 * - Secondary writes occurred after start of vnode sync loop
14205 		 */
14206 		error = 0;
14207 		if (bo->bo_numoutput > 0 ||
14208 		    bo->bo_dirty.bv_cnt > 0 ||
14209 		    secondary_writes != 0 ||
14210 		    mp->mnt_secondary_writes != 0 ||
14211 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14212 			error = EAGAIN;
14213 		BO_UNLOCK(bo);
14214 		return (error);
14215 	}
14216 
14217 	/*
14218 	 * If we are running with soft updates, then we need to coordinate
14219 	 * with them as we try to suspend.
14220 	 */
14221 	ump = VFSTOUFS(mp);
14222 	for (;;) {
14223 		if (!TRY_ACQUIRE_LOCK(ump)) {
14224 			BO_UNLOCK(bo);
14225 			ACQUIRE_LOCK(ump);
14226 			FREE_LOCK(ump);
14227 			BO_LOCK(bo);
14228 			continue;
14229 		}
14230 		MNT_ILOCK(mp);
14231 		if (mp->mnt_secondary_writes != 0) {
14232 			FREE_LOCK(ump);
14233 			BO_UNLOCK(bo);
14234 			msleep(&mp->mnt_secondary_writes,
14235 			       MNT_MTX(mp),
14236 			       (PUSER - 1) | PDROP, "secwr", 0);
14237 			BO_LOCK(bo);
14238 			continue;
14239 		}
14240 		break;
14241 	}
14242 
14243 	unlinked = 0;
14244 	if (MOUNTEDSUJ(mp)) {
14245 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14246 		    inodedep != NULL;
14247 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14248 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14249 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14250 			    UNLINKONLIST) ||
14251 			    !check_inodedep_free(inodedep))
14252 				continue;
14253 			unlinked++;
14254 		}
14255 	}
14256 
14257 	/*
14258 	 * Reasons for needing more work before suspend:
14259 	 * - Dirty buffers on devvp.
14260 	 * - Softdep activity occurred after start of vnode sync loop
14261 	 * - Secondary writes occurred after start of vnode sync loop
14262 	 */
14263 	error = 0;
14264 	if (bo->bo_numoutput > 0 ||
14265 	    bo->bo_dirty.bv_cnt > 0 ||
14266 	    softdep_depcnt != unlinked ||
14267 	    ump->softdep_deps != unlinked ||
14268 	    softdep_accdepcnt != ump->softdep_accdeps ||
14269 	    secondary_writes != 0 ||
14270 	    mp->mnt_secondary_writes != 0 ||
14271 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14272 		error = EAGAIN;
14273 	FREE_LOCK(ump);
14274 	BO_UNLOCK(bo);
14275 	return (error);
14276 }
14277 
14278 
14279 /*
14280  * Get the number of dependency structures for the file system, both
14281  * the current number and the total number allocated.  These will
14282  * later be used to detect that softdep processing has occurred.
14283  */
14284 void
14285 softdep_get_depcounts(struct mount *mp,
14286 		      int *softdep_depsp,
14287 		      int *softdep_accdepsp)
14288 {
14289 	struct ufsmount *ump;
14290 
14291 	if (MOUNTEDSOFTDEP(mp) == 0) {
14292 		*softdep_depsp = 0;
14293 		*softdep_accdepsp = 0;
14294 		return;
14295 	}
14296 	ump = VFSTOUFS(mp);
14297 	ACQUIRE_LOCK(ump);
14298 	*softdep_depsp = ump->softdep_deps;
14299 	*softdep_accdepsp = ump->softdep_accdeps;
14300 	FREE_LOCK(ump);
14301 }
14302 
14303 /*
14304  * Wait for pending output on a vnode to complete.
14305  */
14306 static void
14307 drain_output(vp)
14308 	struct vnode *vp;
14309 {
14310 
14311 	ASSERT_VOP_LOCKED(vp, "drain_output");
14312 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14313 }
14314 
14315 /*
14316  * Called whenever a buffer that is being invalidated or reallocated
14317  * contains dependencies. This should only happen if an I/O error has
14318  * occurred. The routine is called with the buffer locked.
14319  */
14320 static void
14321 softdep_deallocate_dependencies(bp)
14322 	struct buf *bp;
14323 {
14324 
14325 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14326 		panic("softdep_deallocate_dependencies: dangling deps");
14327 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14328 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14329 	else
14330 		printf("softdep_deallocate_dependencies: "
14331 		    "got error %d while accessing filesystem\n", bp->b_error);
14332 	if (bp->b_error != ENXIO)
14333 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14334 }
14335 
14336 /*
14337  * Function to handle asynchronous write errors in the filesystem.
14338  */
14339 static void
14340 softdep_error(func, error)
14341 	char *func;
14342 	int error;
14343 {
14344 
14345 	/* XXX should do something better! */
14346 	printf("%s: got error %d while accessing filesystem\n", func, error);
14347 }
14348 
14349 #ifdef DDB
14350 
14351 static void
14352 inodedep_print(struct inodedep *inodedep, int verbose)
14353 {
14354 	db_printf("%p fs %p st %x ino %jd inoblk %jd delta %jd nlink %jd"
14355 	    " saveino %p\n",
14356 	    inodedep, inodedep->id_fs, inodedep->id_state,
14357 	    (intmax_t)inodedep->id_ino,
14358 	    (intmax_t)fsbtodb(inodedep->id_fs,
14359 	    ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14360 	    (intmax_t)inodedep->id_nlinkdelta,
14361 	    (intmax_t)inodedep->id_savednlink,
14362 	    inodedep->id_savedino1);
14363 
14364 	if (verbose == 0)
14365 		return;
14366 
14367 	db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
14368 	    "mkdiradd %p\n",
14369 	    LIST_FIRST(&inodedep->id_pendinghd),
14370 	    LIST_FIRST(&inodedep->id_bufwait),
14371 	    LIST_FIRST(&inodedep->id_inowait),
14372 	    TAILQ_FIRST(&inodedep->id_inoreflst),
14373 	    inodedep->id_mkdiradd);
14374 	db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
14375 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14376 	    TAILQ_FIRST(&inodedep->id_newinoupdt),
14377 	    TAILQ_FIRST(&inodedep->id_extupdt),
14378 	    TAILQ_FIRST(&inodedep->id_newextupdt));
14379 }
14380 
14381 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
14382 {
14383 
14384 	if (have_addr == 0) {
14385 		db_printf("Address required\n");
14386 		return;
14387 	}
14388 	inodedep_print((struct inodedep*)addr, 1);
14389 }
14390 
14391 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
14392 {
14393 	struct inodedep_hashhead *inodedephd;
14394 	struct inodedep *inodedep;
14395 	struct ufsmount *ump;
14396 	int cnt;
14397 
14398 	if (have_addr == 0) {
14399 		db_printf("Address required\n");
14400 		return;
14401 	}
14402 	ump = (struct ufsmount *)addr;
14403 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14404 		inodedephd = &ump->inodedep_hashtbl[cnt];
14405 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14406 			inodedep_print(inodedep, 0);
14407 		}
14408 	}
14409 }
14410 
14411 DB_SHOW_COMMAND(worklist, db_show_worklist)
14412 {
14413 	struct worklist *wk;
14414 
14415 	if (have_addr == 0) {
14416 		db_printf("Address required\n");
14417 		return;
14418 	}
14419 	wk = (struct worklist *)addr;
14420 	printf("worklist: %p type %s state 0x%X\n",
14421 	    wk, TYPENAME(wk->wk_type), wk->wk_state);
14422 }
14423 
14424 DB_SHOW_COMMAND(workhead, db_show_workhead)
14425 {
14426 	struct workhead *wkhd;
14427 	struct worklist *wk;
14428 	int i;
14429 
14430 	if (have_addr == 0) {
14431 		db_printf("Address required\n");
14432 		return;
14433 	}
14434 	wkhd = (struct workhead *)addr;
14435 	wk = LIST_FIRST(wkhd);
14436 	for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
14437 		db_printf("worklist: %p type %s state 0x%X",
14438 		    wk, TYPENAME(wk->wk_type), wk->wk_state);
14439 	if (i == 100)
14440 		db_printf("workhead overflow");
14441 	printf("\n");
14442 }
14443 
14444 
14445 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
14446 {
14447 	struct mkdirlist *mkdirlisthd;
14448 	struct jaddref *jaddref;
14449 	struct diradd *diradd;
14450 	struct mkdir *mkdir;
14451 
14452 	if (have_addr == 0) {
14453 		db_printf("Address required\n");
14454 		return;
14455 	}
14456 	mkdirlisthd = (struct mkdirlist *)addr;
14457 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14458 		diradd = mkdir->md_diradd;
14459 		db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
14460 		    mkdir, mkdir->md_state, diradd, diradd->da_state);
14461 		if ((jaddref = mkdir->md_jaddref) != NULL)
14462 			db_printf(" jaddref %p jaddref state 0x%X",
14463 			    jaddref, jaddref->ja_state);
14464 		db_printf("\n");
14465 	}
14466 }
14467 
14468 /* exported to ffs_vfsops.c */
14469 extern void db_print_ffs(struct ufsmount *ump);
14470 void
14471 db_print_ffs(struct ufsmount *ump)
14472 {
14473 	db_printf("mp %p %s devvp %p fs %p su_wl %d su_deps %d su_req %d\n",
14474 	    ump->um_mountp, ump->um_mountp->mnt_stat.f_mntonname,
14475 	    ump->um_devvp, ump->um_fs, ump->softdep_on_worklist,
14476 	    ump->softdep_deps, ump->softdep_req);
14477 }
14478 
14479 #endif /* DDB */
14480 
14481 #endif /* SOFTUPDATES */
14482