xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision f37852c17391fdf0e8309bcf684384dd0d854e43)
1 /*-
2  * Copyright 1998, 2000 Marshall Kirk McKusick.
3  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
4  * All rights reserved.
5  *
6  * The soft updates code is derived from the appendix of a University
7  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
8  * "Soft Updates: A Solution to the Metadata Update Problem in File
9  * Systems", CSE-TR-254-95, August 1995).
10  *
11  * Further information about soft updates can be obtained from:
12  *
13  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
14  *	1614 Oxford Street		mckusick@mckusick.com
15  *	Berkeley, CA 94709-1608		+1-510-843-9542
16  *	USA
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  *
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  *
39  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
40  */
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include "opt_ffs.h"
46 #include "opt_quota.h"
47 #include "opt_ddb.h"
48 
49 /*
50  * For now we want the safety net that the DEBUG flag provides.
51  */
52 #ifndef DEBUG
53 #define DEBUG
54 #endif
55 
56 #include <sys/param.h>
57 #include <sys/kernel.h>
58 #include <sys/systm.h>
59 #include <sys/bio.h>
60 #include <sys/buf.h>
61 #include <sys/kdb.h>
62 #include <sys/kthread.h>
63 #include <sys/ktr.h>
64 #include <sys/limits.h>
65 #include <sys/lock.h>
66 #include <sys/malloc.h>
67 #include <sys/mount.h>
68 #include <sys/mutex.h>
69 #include <sys/namei.h>
70 #include <sys/priv.h>
71 #include <sys/proc.h>
72 #include <sys/racct.h>
73 #include <sys/rwlock.h>
74 #include <sys/stat.h>
75 #include <sys/sysctl.h>
76 #include <sys/syslog.h>
77 #include <sys/vnode.h>
78 #include <sys/conf.h>
79 
80 #include <ufs/ufs/dir.h>
81 #include <ufs/ufs/extattr.h>
82 #include <ufs/ufs/quota.h>
83 #include <ufs/ufs/inode.h>
84 #include <ufs/ufs/ufsmount.h>
85 #include <ufs/ffs/fs.h>
86 #include <ufs/ffs/softdep.h>
87 #include <ufs/ffs/ffs_extern.h>
88 #include <ufs/ufs/ufs_extern.h>
89 
90 #include <vm/vm.h>
91 #include <vm/vm_extern.h>
92 #include <vm/vm_object.h>
93 
94 #include <geom/geom.h>
95 
96 #include <ddb/ddb.h>
97 
98 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
99 
100 #ifndef SOFTUPDATES
101 
102 int
103 softdep_flushfiles(oldmnt, flags, td)
104 	struct mount *oldmnt;
105 	int flags;
106 	struct thread *td;
107 {
108 
109 	panic("softdep_flushfiles called");
110 }
111 
112 int
113 softdep_mount(devvp, mp, fs, cred)
114 	struct vnode *devvp;
115 	struct mount *mp;
116 	struct fs *fs;
117 	struct ucred *cred;
118 {
119 
120 	return (0);
121 }
122 
123 void
124 softdep_initialize()
125 {
126 
127 	return;
128 }
129 
130 void
131 softdep_uninitialize()
132 {
133 
134 	return;
135 }
136 
137 void
138 softdep_unmount(mp)
139 	struct mount *mp;
140 {
141 
142 	panic("softdep_unmount called");
143 }
144 
145 void
146 softdep_setup_sbupdate(ump, fs, bp)
147 	struct ufsmount *ump;
148 	struct fs *fs;
149 	struct buf *bp;
150 {
151 
152 	panic("softdep_setup_sbupdate called");
153 }
154 
155 void
156 softdep_setup_inomapdep(bp, ip, newinum, mode)
157 	struct buf *bp;
158 	struct inode *ip;
159 	ino_t newinum;
160 	int mode;
161 {
162 
163 	panic("softdep_setup_inomapdep called");
164 }
165 
166 void
167 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
168 	struct buf *bp;
169 	struct mount *mp;
170 	ufs2_daddr_t newblkno;
171 	int frags;
172 	int oldfrags;
173 {
174 
175 	panic("softdep_setup_blkmapdep called");
176 }
177 
178 void
179 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
180 	struct inode *ip;
181 	ufs_lbn_t lbn;
182 	ufs2_daddr_t newblkno;
183 	ufs2_daddr_t oldblkno;
184 	long newsize;
185 	long oldsize;
186 	struct buf *bp;
187 {
188 
189 	panic("softdep_setup_allocdirect called");
190 }
191 
192 void
193 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
194 	struct inode *ip;
195 	ufs_lbn_t lbn;
196 	ufs2_daddr_t newblkno;
197 	ufs2_daddr_t oldblkno;
198 	long newsize;
199 	long oldsize;
200 	struct buf *bp;
201 {
202 
203 	panic("softdep_setup_allocext called");
204 }
205 
206 void
207 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
208 	struct inode *ip;
209 	ufs_lbn_t lbn;
210 	struct buf *bp;
211 	int ptrno;
212 	ufs2_daddr_t newblkno;
213 	ufs2_daddr_t oldblkno;
214 	struct buf *nbp;
215 {
216 
217 	panic("softdep_setup_allocindir_page called");
218 }
219 
220 void
221 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
222 	struct buf *nbp;
223 	struct inode *ip;
224 	struct buf *bp;
225 	int ptrno;
226 	ufs2_daddr_t newblkno;
227 {
228 
229 	panic("softdep_setup_allocindir_meta called");
230 }
231 
232 void
233 softdep_journal_freeblocks(ip, cred, length, flags)
234 	struct inode *ip;
235 	struct ucred *cred;
236 	off_t length;
237 	int flags;
238 {
239 
240 	panic("softdep_journal_freeblocks called");
241 }
242 
243 void
244 softdep_journal_fsync(ip)
245 	struct inode *ip;
246 {
247 
248 	panic("softdep_journal_fsync called");
249 }
250 
251 void
252 softdep_setup_freeblocks(ip, length, flags)
253 	struct inode *ip;
254 	off_t length;
255 	int flags;
256 {
257 
258 	panic("softdep_setup_freeblocks called");
259 }
260 
261 void
262 softdep_freefile(pvp, ino, mode)
263 		struct vnode *pvp;
264 		ino_t ino;
265 		int mode;
266 {
267 
268 	panic("softdep_freefile called");
269 }
270 
271 int
272 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
273 	struct buf *bp;
274 	struct inode *dp;
275 	off_t diroffset;
276 	ino_t newinum;
277 	struct buf *newdirbp;
278 	int isnewblk;
279 {
280 
281 	panic("softdep_setup_directory_add called");
282 }
283 
284 void
285 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
286 	struct buf *bp;
287 	struct inode *dp;
288 	caddr_t base;
289 	caddr_t oldloc;
290 	caddr_t newloc;
291 	int entrysize;
292 {
293 
294 	panic("softdep_change_directoryentry_offset called");
295 }
296 
297 void
298 softdep_setup_remove(bp, dp, ip, isrmdir)
299 	struct buf *bp;
300 	struct inode *dp;
301 	struct inode *ip;
302 	int isrmdir;
303 {
304 
305 	panic("softdep_setup_remove called");
306 }
307 
308 void
309 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
310 	struct buf *bp;
311 	struct inode *dp;
312 	struct inode *ip;
313 	ino_t newinum;
314 	int isrmdir;
315 {
316 
317 	panic("softdep_setup_directory_change called");
318 }
319 
320 void
321 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
322 	struct mount *mp;
323 	struct buf *bp;
324 	ufs2_daddr_t blkno;
325 	int frags;
326 	struct workhead *wkhd;
327 {
328 
329 	panic("%s called", __FUNCTION__);
330 }
331 
332 void
333 softdep_setup_inofree(mp, bp, ino, wkhd)
334 	struct mount *mp;
335 	struct buf *bp;
336 	ino_t ino;
337 	struct workhead *wkhd;
338 {
339 
340 	panic("%s called", __FUNCTION__);
341 }
342 
343 void
344 softdep_setup_unlink(dp, ip)
345 	struct inode *dp;
346 	struct inode *ip;
347 {
348 
349 	panic("%s called", __FUNCTION__);
350 }
351 
352 void
353 softdep_setup_link(dp, ip)
354 	struct inode *dp;
355 	struct inode *ip;
356 {
357 
358 	panic("%s called", __FUNCTION__);
359 }
360 
361 void
362 softdep_revert_link(dp, ip)
363 	struct inode *dp;
364 	struct inode *ip;
365 {
366 
367 	panic("%s called", __FUNCTION__);
368 }
369 
370 void
371 softdep_setup_rmdir(dp, ip)
372 	struct inode *dp;
373 	struct inode *ip;
374 {
375 
376 	panic("%s called", __FUNCTION__);
377 }
378 
379 void
380 softdep_revert_rmdir(dp, ip)
381 	struct inode *dp;
382 	struct inode *ip;
383 {
384 
385 	panic("%s called", __FUNCTION__);
386 }
387 
388 void
389 softdep_setup_create(dp, ip)
390 	struct inode *dp;
391 	struct inode *ip;
392 {
393 
394 	panic("%s called", __FUNCTION__);
395 }
396 
397 void
398 softdep_revert_create(dp, ip)
399 	struct inode *dp;
400 	struct inode *ip;
401 {
402 
403 	panic("%s called", __FUNCTION__);
404 }
405 
406 void
407 softdep_setup_mkdir(dp, ip)
408 	struct inode *dp;
409 	struct inode *ip;
410 {
411 
412 	panic("%s called", __FUNCTION__);
413 }
414 
415 void
416 softdep_revert_mkdir(dp, ip)
417 	struct inode *dp;
418 	struct inode *ip;
419 {
420 
421 	panic("%s called", __FUNCTION__);
422 }
423 
424 void
425 softdep_setup_dotdot_link(dp, ip)
426 	struct inode *dp;
427 	struct inode *ip;
428 {
429 
430 	panic("%s called", __FUNCTION__);
431 }
432 
433 int
434 softdep_prealloc(vp, waitok)
435 	struct vnode *vp;
436 	int waitok;
437 {
438 
439 	panic("%s called", __FUNCTION__);
440 }
441 
442 int
443 softdep_journal_lookup(mp, vpp)
444 	struct mount *mp;
445 	struct vnode **vpp;
446 {
447 
448 	return (ENOENT);
449 }
450 
451 void
452 softdep_change_linkcnt(ip)
453 	struct inode *ip;
454 {
455 
456 	panic("softdep_change_linkcnt called");
457 }
458 
459 void
460 softdep_load_inodeblock(ip)
461 	struct inode *ip;
462 {
463 
464 	panic("softdep_load_inodeblock called");
465 }
466 
467 void
468 softdep_update_inodeblock(ip, bp, waitfor)
469 	struct inode *ip;
470 	struct buf *bp;
471 	int waitfor;
472 {
473 
474 	panic("softdep_update_inodeblock called");
475 }
476 
477 int
478 softdep_fsync(vp)
479 	struct vnode *vp;	/* the "in_core" copy of the inode */
480 {
481 
482 	return (0);
483 }
484 
485 void
486 softdep_fsync_mountdev(vp)
487 	struct vnode *vp;
488 {
489 
490 	return;
491 }
492 
493 int
494 softdep_flushworklist(oldmnt, countp, td)
495 	struct mount *oldmnt;
496 	int *countp;
497 	struct thread *td;
498 {
499 
500 	*countp = 0;
501 	return (0);
502 }
503 
504 int
505 softdep_sync_metadata(struct vnode *vp)
506 {
507 
508 	panic("softdep_sync_metadata called");
509 }
510 
511 int
512 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
513 {
514 
515 	panic("softdep_sync_buf called");
516 }
517 
518 int
519 softdep_slowdown(vp)
520 	struct vnode *vp;
521 {
522 
523 	panic("softdep_slowdown called");
524 }
525 
526 int
527 softdep_request_cleanup(fs, vp, cred, resource)
528 	struct fs *fs;
529 	struct vnode *vp;
530 	struct ucred *cred;
531 	int resource;
532 {
533 
534 	return (0);
535 }
536 
537 int
538 softdep_check_suspend(struct mount *mp,
539 		      struct vnode *devvp,
540 		      int softdep_depcnt,
541 		      int softdep_accdepcnt,
542 		      int secondary_writes,
543 		      int secondary_accwrites)
544 {
545 	struct bufobj *bo;
546 	int error;
547 
548 	(void) softdep_depcnt,
549 	(void) softdep_accdepcnt;
550 
551 	bo = &devvp->v_bufobj;
552 	ASSERT_BO_WLOCKED(bo);
553 
554 	MNT_ILOCK(mp);
555 	while (mp->mnt_secondary_writes != 0) {
556 		BO_UNLOCK(bo);
557 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
558 		    (PUSER - 1) | PDROP, "secwr", 0);
559 		BO_LOCK(bo);
560 		MNT_ILOCK(mp);
561 	}
562 
563 	/*
564 	 * Reasons for needing more work before suspend:
565 	 * - Dirty buffers on devvp.
566 	 * - Secondary writes occurred after start of vnode sync loop
567 	 */
568 	error = 0;
569 	if (bo->bo_numoutput > 0 ||
570 	    bo->bo_dirty.bv_cnt > 0 ||
571 	    secondary_writes != 0 ||
572 	    mp->mnt_secondary_writes != 0 ||
573 	    secondary_accwrites != mp->mnt_secondary_accwrites)
574 		error = EAGAIN;
575 	BO_UNLOCK(bo);
576 	return (error);
577 }
578 
579 void
580 softdep_get_depcounts(struct mount *mp,
581 		      int *softdepactivep,
582 		      int *softdepactiveaccp)
583 {
584 	(void) mp;
585 	*softdepactivep = 0;
586 	*softdepactiveaccp = 0;
587 }
588 
589 void
590 softdep_buf_append(bp, wkhd)
591 	struct buf *bp;
592 	struct workhead *wkhd;
593 {
594 
595 	panic("softdep_buf_appendwork called");
596 }
597 
598 void
599 softdep_inode_append(ip, cred, wkhd)
600 	struct inode *ip;
601 	struct ucred *cred;
602 	struct workhead *wkhd;
603 {
604 
605 	panic("softdep_inode_appendwork called");
606 }
607 
608 void
609 softdep_freework(wkhd)
610 	struct workhead *wkhd;
611 {
612 
613 	panic("softdep_freework called");
614 }
615 
616 #else
617 
618 FEATURE(softupdates, "FFS soft-updates support");
619 
620 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
621     "soft updates stats");
622 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
623     "total dependencies allocated");
624 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
625     "high use dependencies allocated");
626 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
627     "current dependencies allocated");
628 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
629     "current dependencies written");
630 
631 unsigned long dep_current[D_LAST + 1];
632 unsigned long dep_highuse[D_LAST + 1];
633 unsigned long dep_total[D_LAST + 1];
634 unsigned long dep_write[D_LAST + 1];
635 
636 #define	SOFTDEP_TYPE(type, str, long)					\
637     static MALLOC_DEFINE(M_ ## type, #str, long);			\
638     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
639 	&dep_total[D_ ## type], 0, "");					\
640     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
641 	&dep_current[D_ ## type], 0, "");				\
642     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
643 	&dep_highuse[D_ ## type], 0, "");				\
644     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
645 	&dep_write[D_ ## type], 0, "");
646 
647 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
648 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
649 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
650     "Block or frag allocated from cyl group map");
651 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
652 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
653 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
654 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
655 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
656 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
657 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
658 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
659 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
660 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
661 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
662 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
663 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
664 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
665 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
666 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
667 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
668 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
669 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
670 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
671 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
672 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
673 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
674 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
675 
676 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
677 
678 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
679 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
680 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
681 
682 #define M_SOFTDEP_FLAGS	(M_WAITOK)
683 
684 /*
685  * translate from workitem type to memory type
686  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
687  */
688 static struct malloc_type *memtype[] = {
689 	M_PAGEDEP,
690 	M_INODEDEP,
691 	M_BMSAFEMAP,
692 	M_NEWBLK,
693 	M_ALLOCDIRECT,
694 	M_INDIRDEP,
695 	M_ALLOCINDIR,
696 	M_FREEFRAG,
697 	M_FREEBLKS,
698 	M_FREEFILE,
699 	M_DIRADD,
700 	M_MKDIR,
701 	M_DIRREM,
702 	M_NEWDIRBLK,
703 	M_FREEWORK,
704 	M_FREEDEP,
705 	M_JADDREF,
706 	M_JREMREF,
707 	M_JMVREF,
708 	M_JNEWBLK,
709 	M_JFREEBLK,
710 	M_JFREEFRAG,
711 	M_JSEG,
712 	M_JSEGDEP,
713 	M_SBDEP,
714 	M_JTRUNC,
715 	M_JFSYNC,
716 	M_SENTINEL
717 };
718 
719 #define DtoM(type) (memtype[type])
720 
721 /*
722  * Names of malloc types.
723  */
724 #define TYPENAME(type)  \
725 	((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
726 /*
727  * End system adaptation definitions.
728  */
729 
730 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
731 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
732 
733 /*
734  * Internal function prototypes.
735  */
736 static	void check_clear_deps(struct mount *);
737 static	void softdep_error(char *, int);
738 static	int softdep_process_worklist(struct mount *, int);
739 static	int softdep_waitidle(struct mount *, int);
740 static	void drain_output(struct vnode *);
741 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
742 static	int check_inodedep_free(struct inodedep *);
743 static	void clear_remove(struct mount *);
744 static	void clear_inodedeps(struct mount *);
745 static	void unlinked_inodedep(struct mount *, struct inodedep *);
746 static	void clear_unlinked_inodedep(struct inodedep *);
747 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
748 static	int flush_pagedep_deps(struct vnode *, struct mount *,
749 	    struct diraddhd *);
750 static	int free_pagedep(struct pagedep *);
751 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
752 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
753 static	int flush_deplist(struct allocdirectlst *, int, int *);
754 static	int sync_cgs(struct mount *, int);
755 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
756 static	int handle_written_sbdep(struct sbdep *, struct buf *);
757 static	void initiate_write_sbdep(struct sbdep *);
758 static	void diradd_inode_written(struct diradd *, struct inodedep *);
759 static	int handle_written_indirdep(struct indirdep *, struct buf *,
760 	    struct buf**, int);
761 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
762 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
763 	    uint8_t *);
764 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
765 static	void handle_written_jaddref(struct jaddref *);
766 static	void handle_written_jremref(struct jremref *);
767 static	void handle_written_jseg(struct jseg *, struct buf *);
768 static	void handle_written_jnewblk(struct jnewblk *);
769 static	void handle_written_jblkdep(struct jblkdep *);
770 static	void handle_written_jfreefrag(struct jfreefrag *);
771 static	void complete_jseg(struct jseg *);
772 static	void complete_jsegs(struct jseg *);
773 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
774 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
775 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
776 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
777 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
778 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
779 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
780 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
781 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
782 static	inline void inoref_write(struct inoref *, struct jseg *,
783 	    struct jrefrec *);
784 static	void handle_allocdirect_partdone(struct allocdirect *,
785 	    struct workhead *);
786 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
787 	    struct workhead *);
788 static	void indirdep_complete(struct indirdep *);
789 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
790 static	void indirblk_insert(struct freework *);
791 static	void indirblk_remove(struct freework *);
792 static	void handle_allocindir_partdone(struct allocindir *);
793 static	void initiate_write_filepage(struct pagedep *, struct buf *);
794 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
795 static	void handle_written_mkdir(struct mkdir *, int);
796 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
797 	    uint8_t *);
798 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
799 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
800 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
801 static	void handle_workitem_freefile(struct freefile *);
802 static	int handle_workitem_remove(struct dirrem *, int);
803 static	struct dirrem *newdirrem(struct buf *, struct inode *,
804 	    struct inode *, int, struct dirrem **);
805 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
806 	    struct buf *);
807 static	void cancel_indirdep(struct indirdep *, struct buf *,
808 	    struct freeblks *);
809 static	void free_indirdep(struct indirdep *);
810 static	void free_diradd(struct diradd *, struct workhead *);
811 static	void merge_diradd(struct inodedep *, struct diradd *);
812 static	void complete_diradd(struct diradd *);
813 static	struct diradd *diradd_lookup(struct pagedep *, int);
814 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
815 	    struct jremref *);
816 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
817 	    struct jremref *);
818 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
819 	    struct jremref *, struct jremref *);
820 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
821 	    struct jremref *);
822 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
823 	    struct freeblks *, int);
824 static	int setup_trunc_indir(struct freeblks *, struct inode *,
825 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
826 static	void complete_trunc_indir(struct freework *);
827 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
828 	    int);
829 static	void complete_mkdir(struct mkdir *);
830 static	void free_newdirblk(struct newdirblk *);
831 static	void free_jremref(struct jremref *);
832 static	void free_jaddref(struct jaddref *);
833 static	void free_jsegdep(struct jsegdep *);
834 static	void free_jsegs(struct jblocks *);
835 static	void rele_jseg(struct jseg *);
836 static	void free_jseg(struct jseg *, struct jblocks *);
837 static	void free_jnewblk(struct jnewblk *);
838 static	void free_jblkdep(struct jblkdep *);
839 static	void free_jfreefrag(struct jfreefrag *);
840 static	void free_freedep(struct freedep *);
841 static	void journal_jremref(struct dirrem *, struct jremref *,
842 	    struct inodedep *);
843 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
844 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
845 	    struct workhead *);
846 static	void cancel_jfreefrag(struct jfreefrag *);
847 static	inline void setup_freedirect(struct freeblks *, struct inode *,
848 	    int, int);
849 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
850 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
851 	    ufs_lbn_t, int);
852 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
853 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
854 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
855 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
856 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
857 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
858 	    int, int);
859 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
860 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
861 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
862 static	void newblk_freefrag(struct newblk*);
863 static	void free_newblk(struct newblk *);
864 static	void cancel_allocdirect(struct allocdirectlst *,
865 	    struct allocdirect *, struct freeblks *);
866 static	int check_inode_unwritten(struct inodedep *);
867 static	int free_inodedep(struct inodedep *);
868 static	void freework_freeblock(struct freework *);
869 static	void freework_enqueue(struct freework *);
870 static	int handle_workitem_freeblocks(struct freeblks *, int);
871 static	int handle_complete_freeblocks(struct freeblks *, int);
872 static	void handle_workitem_indirblk(struct freework *);
873 static	void handle_written_freework(struct freework *);
874 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
875 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
876 	    struct workhead *);
877 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
878 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
879 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
880 	    ufs2_daddr_t, ufs_lbn_t);
881 static	void handle_workitem_freefrag(struct freefrag *);
882 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
883 	    ufs_lbn_t);
884 static	void allocdirect_merge(struct allocdirectlst *,
885 	    struct allocdirect *, struct allocdirect *);
886 static	struct freefrag *allocindir_merge(struct allocindir *,
887 	    struct allocindir *);
888 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
889 	    struct bmsafemap **);
890 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
891 	    int cg, struct bmsafemap *);
892 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
893 	    struct newblk **);
894 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
895 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
896 	    struct inodedep **);
897 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
898 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
899 	    int, struct pagedep **);
900 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
901 	    struct pagedep **);
902 static	void pause_timer(void *);
903 static	int request_cleanup(struct mount *, int);
904 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
905 static	void schedule_cleanup(struct mount *);
906 static void softdep_ast_cleanup_proc(struct thread *);
907 static	int process_worklist_item(struct mount *, int, int);
908 static	void process_removes(struct vnode *);
909 static	void process_truncates(struct vnode *);
910 static	void jwork_move(struct workhead *, struct workhead *);
911 static	void jwork_insert(struct workhead *, struct jsegdep *);
912 static	void add_to_worklist(struct worklist *, int);
913 static	void wake_worklist(struct worklist *);
914 static	void wait_worklist(struct worklist *, char *);
915 static	void remove_from_worklist(struct worklist *);
916 static	void softdep_flush(void *);
917 static	void softdep_flushjournal(struct mount *);
918 static	int softdep_speedup(struct ufsmount *);
919 static	void worklist_speedup(struct mount *);
920 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
921 static	void journal_unmount(struct ufsmount *);
922 static	int journal_space(struct ufsmount *, int);
923 static	void journal_suspend(struct ufsmount *);
924 static	int journal_unsuspend(struct ufsmount *ump);
925 static	void softdep_prelink(struct vnode *, struct vnode *);
926 static	void add_to_journal(struct worklist *);
927 static	void remove_from_journal(struct worklist *);
928 static	bool softdep_excess_items(struct ufsmount *, int);
929 static	void softdep_process_journal(struct mount *, struct worklist *, int);
930 static	struct jremref *newjremref(struct dirrem *, struct inode *,
931 	    struct inode *ip, off_t, nlink_t);
932 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
933 	    uint16_t);
934 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
935 	    uint16_t);
936 static	inline struct jsegdep *inoref_jseg(struct inoref *);
937 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
938 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
939 	    ufs2_daddr_t, int);
940 static	void adjust_newfreework(struct freeblks *, int);
941 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
942 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
943 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
944 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
945 	    ufs2_daddr_t, long, ufs_lbn_t);
946 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
947 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
948 static	int jwait(struct worklist *, int);
949 static	struct inodedep *inodedep_lookup_ip(struct inode *);
950 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
951 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
952 static	void handle_jwork(struct workhead *);
953 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
954 	    struct mkdir **);
955 static	struct jblocks *jblocks_create(void);
956 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
957 static	void jblocks_free(struct jblocks *, struct mount *, int);
958 static	void jblocks_destroy(struct jblocks *);
959 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
960 
961 /*
962  * Exported softdep operations.
963  */
964 static	void softdep_disk_io_initiation(struct buf *);
965 static	void softdep_disk_write_complete(struct buf *);
966 static	void softdep_deallocate_dependencies(struct buf *);
967 static	int softdep_count_dependencies(struct buf *bp, int);
968 
969 /*
970  * Global lock over all of soft updates.
971  */
972 static struct mtx lk;
973 MTX_SYSINIT(softdep_lock, &lk, "Global Softdep Lock", MTX_DEF);
974 
975 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
976 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
977 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
978 
979 /*
980  * Per-filesystem soft-updates locking.
981  */
982 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
983 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
984 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
985 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
986 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
987 				    RA_WLOCKED)
988 
989 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
990 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
991 
992 /*
993  * Worklist queue management.
994  * These routines require that the lock be held.
995  */
996 #ifndef /* NOT */ DEBUG
997 #define WORKLIST_INSERT(head, item) do {	\
998 	(item)->wk_state |= ONWORKLIST;		\
999 	LIST_INSERT_HEAD(head, item, wk_list);	\
1000 } while (0)
1001 #define WORKLIST_REMOVE(item) do {		\
1002 	(item)->wk_state &= ~ONWORKLIST;	\
1003 	LIST_REMOVE(item, wk_list);		\
1004 } while (0)
1005 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1006 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1007 
1008 #else /* DEBUG */
1009 static	void worklist_insert(struct workhead *, struct worklist *, int);
1010 static	void worklist_remove(struct worklist *, int);
1011 
1012 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1013 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1014 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1015 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1016 
1017 static void
1018 worklist_insert(head, item, locked)
1019 	struct workhead *head;
1020 	struct worklist *item;
1021 	int locked;
1022 {
1023 
1024 	if (locked)
1025 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1026 	if (item->wk_state & ONWORKLIST)
1027 		panic("worklist_insert: %p %s(0x%X) already on list",
1028 		    item, TYPENAME(item->wk_type), item->wk_state);
1029 	item->wk_state |= ONWORKLIST;
1030 	LIST_INSERT_HEAD(head, item, wk_list);
1031 }
1032 
1033 static void
1034 worklist_remove(item, locked)
1035 	struct worklist *item;
1036 	int locked;
1037 {
1038 
1039 	if (locked)
1040 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1041 	if ((item->wk_state & ONWORKLIST) == 0)
1042 		panic("worklist_remove: %p %s(0x%X) not on list",
1043 		    item, TYPENAME(item->wk_type), item->wk_state);
1044 	item->wk_state &= ~ONWORKLIST;
1045 	LIST_REMOVE(item, wk_list);
1046 }
1047 #endif /* DEBUG */
1048 
1049 /*
1050  * Merge two jsegdeps keeping only the oldest one as newer references
1051  * can't be discarded until after older references.
1052  */
1053 static inline struct jsegdep *
1054 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1055 {
1056 	struct jsegdep *swp;
1057 
1058 	if (two == NULL)
1059 		return (one);
1060 
1061 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1062 		swp = one;
1063 		one = two;
1064 		two = swp;
1065 	}
1066 	WORKLIST_REMOVE(&two->jd_list);
1067 	free_jsegdep(two);
1068 
1069 	return (one);
1070 }
1071 
1072 /*
1073  * If two freedeps are compatible free one to reduce list size.
1074  */
1075 static inline struct freedep *
1076 freedep_merge(struct freedep *one, struct freedep *two)
1077 {
1078 	if (two == NULL)
1079 		return (one);
1080 
1081 	if (one->fd_freework == two->fd_freework) {
1082 		WORKLIST_REMOVE(&two->fd_list);
1083 		free_freedep(two);
1084 	}
1085 	return (one);
1086 }
1087 
1088 /*
1089  * Move journal work from one list to another.  Duplicate freedeps and
1090  * jsegdeps are coalesced to keep the lists as small as possible.
1091  */
1092 static void
1093 jwork_move(dst, src)
1094 	struct workhead *dst;
1095 	struct workhead *src;
1096 {
1097 	struct freedep *freedep;
1098 	struct jsegdep *jsegdep;
1099 	struct worklist *wkn;
1100 	struct worklist *wk;
1101 
1102 	KASSERT(dst != src,
1103 	    ("jwork_move: dst == src"));
1104 	freedep = NULL;
1105 	jsegdep = NULL;
1106 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1107 		if (wk->wk_type == D_JSEGDEP)
1108 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1109 		else if (wk->wk_type == D_FREEDEP)
1110 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1111 	}
1112 
1113 	while ((wk = LIST_FIRST(src)) != NULL) {
1114 		WORKLIST_REMOVE(wk);
1115 		WORKLIST_INSERT(dst, wk);
1116 		if (wk->wk_type == D_JSEGDEP) {
1117 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1118 			continue;
1119 		}
1120 		if (wk->wk_type == D_FREEDEP)
1121 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1122 	}
1123 }
1124 
1125 static void
1126 jwork_insert(dst, jsegdep)
1127 	struct workhead *dst;
1128 	struct jsegdep *jsegdep;
1129 {
1130 	struct jsegdep *jsegdepn;
1131 	struct worklist *wk;
1132 
1133 	LIST_FOREACH(wk, dst, wk_list)
1134 		if (wk->wk_type == D_JSEGDEP)
1135 			break;
1136 	if (wk == NULL) {
1137 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1138 		return;
1139 	}
1140 	jsegdepn = WK_JSEGDEP(wk);
1141 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1142 		WORKLIST_REMOVE(wk);
1143 		free_jsegdep(jsegdepn);
1144 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1145 	} else
1146 		free_jsegdep(jsegdep);
1147 }
1148 
1149 /*
1150  * Routines for tracking and managing workitems.
1151  */
1152 static	void workitem_free(struct worklist *, int);
1153 static	void workitem_alloc(struct worklist *, int, struct mount *);
1154 static	void workitem_reassign(struct worklist *, int);
1155 
1156 #define	WORKITEM_FREE(item, type) \
1157 	workitem_free((struct worklist *)(item), (type))
1158 #define	WORKITEM_REASSIGN(item, type) \
1159 	workitem_reassign((struct worklist *)(item), (type))
1160 
1161 static void
1162 workitem_free(item, type)
1163 	struct worklist *item;
1164 	int type;
1165 {
1166 	struct ufsmount *ump;
1167 
1168 #ifdef DEBUG
1169 	if (item->wk_state & ONWORKLIST)
1170 		panic("workitem_free: %s(0x%X) still on list",
1171 		    TYPENAME(item->wk_type), item->wk_state);
1172 	if (item->wk_type != type && type != D_NEWBLK)
1173 		panic("workitem_free: type mismatch %s != %s",
1174 		    TYPENAME(item->wk_type), TYPENAME(type));
1175 #endif
1176 	if (item->wk_state & IOWAITING)
1177 		wakeup(item);
1178 	ump = VFSTOUFS(item->wk_mp);
1179 	LOCK_OWNED(ump);
1180 	KASSERT(ump->softdep_deps > 0,
1181 	    ("workitem_free: %s: softdep_deps going negative",
1182 	    ump->um_fs->fs_fsmnt));
1183 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1184 		wakeup(&ump->softdep_deps);
1185 	KASSERT(dep_current[item->wk_type] > 0,
1186 	    ("workitem_free: %s: dep_current[%s] going negative",
1187 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1188 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1189 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1190 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1191 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1192 	ump->softdep_curdeps[item->wk_type] -= 1;
1193 	free(item, DtoM(type));
1194 }
1195 
1196 static void
1197 workitem_alloc(item, type, mp)
1198 	struct worklist *item;
1199 	int type;
1200 	struct mount *mp;
1201 {
1202 	struct ufsmount *ump;
1203 
1204 	item->wk_type = type;
1205 	item->wk_mp = mp;
1206 	item->wk_state = 0;
1207 
1208 	ump = VFSTOUFS(mp);
1209 	ACQUIRE_GBLLOCK(&lk);
1210 	dep_current[type]++;
1211 	if (dep_current[type] > dep_highuse[type])
1212 		dep_highuse[type] = dep_current[type];
1213 	dep_total[type]++;
1214 	FREE_GBLLOCK(&lk);
1215 	ACQUIRE_LOCK(ump);
1216 	ump->softdep_curdeps[type] += 1;
1217 	ump->softdep_deps++;
1218 	ump->softdep_accdeps++;
1219 	FREE_LOCK(ump);
1220 }
1221 
1222 static void
1223 workitem_reassign(item, newtype)
1224 	struct worklist *item;
1225 	int newtype;
1226 {
1227 	struct ufsmount *ump;
1228 
1229 	ump = VFSTOUFS(item->wk_mp);
1230 	LOCK_OWNED(ump);
1231 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1232 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1233 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1234 	ump->softdep_curdeps[item->wk_type] -= 1;
1235 	ump->softdep_curdeps[newtype] += 1;
1236 	KASSERT(dep_current[item->wk_type] > 0,
1237 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1238 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1239 	ACQUIRE_GBLLOCK(&lk);
1240 	dep_current[newtype]++;
1241 	dep_current[item->wk_type]--;
1242 	if (dep_current[newtype] > dep_highuse[newtype])
1243 		dep_highuse[newtype] = dep_current[newtype];
1244 	dep_total[newtype]++;
1245 	FREE_GBLLOCK(&lk);
1246 	item->wk_type = newtype;
1247 }
1248 
1249 /*
1250  * Workitem queue management
1251  */
1252 static int max_softdeps;	/* maximum number of structs before slowdown */
1253 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1254 static int proc_waiting;	/* tracks whether we have a timeout posted */
1255 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1256 static struct callout softdep_callout;
1257 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1258 static int req_clear_remove;	/* syncer process flush some freeblks */
1259 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1260 
1261 /*
1262  * runtime statistics
1263  */
1264 static int stat_flush_threads;	/* number of softdep flushing threads */
1265 static int stat_worklist_push;	/* number of worklist cleanups */
1266 static int stat_blk_limit_push;	/* number of times block limit neared */
1267 static int stat_ino_limit_push;	/* number of times inode limit neared */
1268 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1269 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1270 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1271 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1272 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1273 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1274 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1275 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1276 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1277 static int stat_journal_min;	/* Times hit journal min threshold */
1278 static int stat_journal_low;	/* Times hit journal low threshold */
1279 static int stat_journal_wait;	/* Times blocked in jwait(). */
1280 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1281 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1282 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1283 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1284 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1285 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1286 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1287 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1288 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1289 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1290 
1291 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1292     &max_softdeps, 0, "");
1293 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1294     &tickdelay, 0, "");
1295 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1296     &stat_flush_threads, 0, "");
1297 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1298     &stat_worklist_push, 0,"");
1299 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1300     &stat_blk_limit_push, 0,"");
1301 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1302     &stat_ino_limit_push, 0,"");
1303 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1304     &stat_blk_limit_hit, 0, "");
1305 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1306     &stat_ino_limit_hit, 0, "");
1307 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1308     &stat_sync_limit_hit, 0, "");
1309 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1310     &stat_indir_blk_ptrs, 0, "");
1311 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1312     &stat_inode_bitmap, 0, "");
1313 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1314     &stat_direct_blk_ptrs, 0, "");
1315 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1316     &stat_dir_entry, 0, "");
1317 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1318     &stat_jaddref, 0, "");
1319 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1320     &stat_jnewblk, 0, "");
1321 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1322     &stat_journal_low, 0, "");
1323 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1324     &stat_journal_min, 0, "");
1325 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1326     &stat_journal_wait, 0, "");
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1328     &stat_jwait_filepage, 0, "");
1329 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1330     &stat_jwait_freeblks, 0, "");
1331 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1332     &stat_jwait_inode, 0, "");
1333 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1334     &stat_jwait_newblk, 0, "");
1335 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1336     &stat_cleanup_blkrequests, 0, "");
1337 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1338     &stat_cleanup_inorequests, 0, "");
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1340     &stat_cleanup_high_delay, 0, "");
1341 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1342     &stat_cleanup_retries, 0, "");
1343 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1344     &stat_cleanup_failures, 0, "");
1345 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1346     &softdep_flushcache, 0, "");
1347 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1348     &stat_emptyjblocks, 0, "");
1349 
1350 SYSCTL_DECL(_vfs_ffs);
1351 
1352 /* Whether to recompute the summary at mount time */
1353 static int compute_summary_at_mount = 0;
1354 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1355 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1356 static int print_threads = 0;
1357 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1358     &print_threads, 0, "Notify flusher thread start/stop");
1359 
1360 /* List of all filesystems mounted with soft updates */
1361 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1362 
1363 /*
1364  * This function cleans the worklist for a filesystem.
1365  * Each filesystem running with soft dependencies gets its own
1366  * thread to run in this function. The thread is started up in
1367  * softdep_mount and shutdown in softdep_unmount. They show up
1368  * as part of the kernel "bufdaemon" process whose process
1369  * entry is available in bufdaemonproc.
1370  */
1371 static int searchfailed;
1372 extern struct proc *bufdaemonproc;
1373 static void
1374 softdep_flush(addr)
1375 	void *addr;
1376 {
1377 	struct mount *mp;
1378 	struct thread *td;
1379 	struct ufsmount *ump;
1380 
1381 	td = curthread;
1382 	td->td_pflags |= TDP_NORUNNINGBUF;
1383 	mp = (struct mount *)addr;
1384 	ump = VFSTOUFS(mp);
1385 	atomic_add_int(&stat_flush_threads, 1);
1386 	ACQUIRE_LOCK(ump);
1387 	ump->softdep_flags &= ~FLUSH_STARTING;
1388 	wakeup(&ump->softdep_flushtd);
1389 	FREE_LOCK(ump);
1390 	if (print_threads) {
1391 		if (stat_flush_threads == 1)
1392 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1393 			    bufdaemonproc->p_pid);
1394 		printf("Start thread %s\n", td->td_name);
1395 	}
1396 	for (;;) {
1397 		while (softdep_process_worklist(mp, 0) > 0 ||
1398 		    (MOUNTEDSUJ(mp) &&
1399 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1400 			kthread_suspend_check();
1401 		ACQUIRE_LOCK(ump);
1402 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1403 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1404 			    "sdflush", hz / 2);
1405 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1406 		/*
1407 		 * Check to see if we are done and need to exit.
1408 		 */
1409 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1410 			FREE_LOCK(ump);
1411 			continue;
1412 		}
1413 		ump->softdep_flags &= ~FLUSH_EXIT;
1414 		FREE_LOCK(ump);
1415 		wakeup(&ump->softdep_flags);
1416 		if (print_threads)
1417 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1418 		atomic_subtract_int(&stat_flush_threads, 1);
1419 		kthread_exit();
1420 		panic("kthread_exit failed\n");
1421 	}
1422 }
1423 
1424 static void
1425 worklist_speedup(mp)
1426 	struct mount *mp;
1427 {
1428 	struct ufsmount *ump;
1429 
1430 	ump = VFSTOUFS(mp);
1431 	LOCK_OWNED(ump);
1432 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1433 		ump->softdep_flags |= FLUSH_CLEANUP;
1434 	wakeup(&ump->softdep_flushtd);
1435 }
1436 
1437 static int
1438 softdep_speedup(ump)
1439 	struct ufsmount *ump;
1440 {
1441 	struct ufsmount *altump;
1442 	struct mount_softdeps *sdp;
1443 
1444 	LOCK_OWNED(ump);
1445 	worklist_speedup(ump->um_mountp);
1446 	bd_speedup();
1447 	/*
1448 	 * If we have global shortages, then we need other
1449 	 * filesystems to help with the cleanup. Here we wakeup a
1450 	 * flusher thread for a filesystem that is over its fair
1451 	 * share of resources.
1452 	 */
1453 	if (req_clear_inodedeps || req_clear_remove) {
1454 		ACQUIRE_GBLLOCK(&lk);
1455 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1456 			if ((altump = sdp->sd_ump) == ump)
1457 				continue;
1458 			if (((req_clear_inodedeps &&
1459 			    altump->softdep_curdeps[D_INODEDEP] >
1460 			    max_softdeps / stat_flush_threads) ||
1461 			    (req_clear_remove &&
1462 			    altump->softdep_curdeps[D_DIRREM] >
1463 			    (max_softdeps / 2) / stat_flush_threads)) &&
1464 			    TRY_ACQUIRE_LOCK(altump))
1465 				break;
1466 		}
1467 		if (sdp == NULL) {
1468 			searchfailed++;
1469 			FREE_GBLLOCK(&lk);
1470 		} else {
1471 			/*
1472 			 * Move to the end of the list so we pick a
1473 			 * different one on out next try.
1474 			 */
1475 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1476 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1477 			FREE_GBLLOCK(&lk);
1478 			if ((altump->softdep_flags &
1479 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1480 				altump->softdep_flags |= FLUSH_CLEANUP;
1481 			altump->um_softdep->sd_cleanups++;
1482 			wakeup(&altump->softdep_flushtd);
1483 			FREE_LOCK(altump);
1484 		}
1485 	}
1486 	return (speedup_syncer());
1487 }
1488 
1489 /*
1490  * Add an item to the end of the work queue.
1491  * This routine requires that the lock be held.
1492  * This is the only routine that adds items to the list.
1493  * The following routine is the only one that removes items
1494  * and does so in order from first to last.
1495  */
1496 
1497 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1498 #define	WK_NODELAY	0x0002	/* Process immediately. */
1499 
1500 static void
1501 add_to_worklist(wk, flags)
1502 	struct worklist *wk;
1503 	int flags;
1504 {
1505 	struct ufsmount *ump;
1506 
1507 	ump = VFSTOUFS(wk->wk_mp);
1508 	LOCK_OWNED(ump);
1509 	if (wk->wk_state & ONWORKLIST)
1510 		panic("add_to_worklist: %s(0x%X) already on list",
1511 		    TYPENAME(wk->wk_type), wk->wk_state);
1512 	wk->wk_state |= ONWORKLIST;
1513 	if (ump->softdep_on_worklist == 0) {
1514 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1515 		ump->softdep_worklist_tail = wk;
1516 	} else if (flags & WK_HEAD) {
1517 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1518 	} else {
1519 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1520 		ump->softdep_worklist_tail = wk;
1521 	}
1522 	ump->softdep_on_worklist += 1;
1523 	if (flags & WK_NODELAY)
1524 		worklist_speedup(wk->wk_mp);
1525 }
1526 
1527 /*
1528  * Remove the item to be processed. If we are removing the last
1529  * item on the list, we need to recalculate the tail pointer.
1530  */
1531 static void
1532 remove_from_worklist(wk)
1533 	struct worklist *wk;
1534 {
1535 	struct ufsmount *ump;
1536 
1537 	ump = VFSTOUFS(wk->wk_mp);
1538 	WORKLIST_REMOVE(wk);
1539 	if (ump->softdep_worklist_tail == wk)
1540 		ump->softdep_worklist_tail =
1541 		    (struct worklist *)wk->wk_list.le_prev;
1542 	ump->softdep_on_worklist -= 1;
1543 }
1544 
1545 static void
1546 wake_worklist(wk)
1547 	struct worklist *wk;
1548 {
1549 	if (wk->wk_state & IOWAITING) {
1550 		wk->wk_state &= ~IOWAITING;
1551 		wakeup(wk);
1552 	}
1553 }
1554 
1555 static void
1556 wait_worklist(wk, wmesg)
1557 	struct worklist *wk;
1558 	char *wmesg;
1559 {
1560 	struct ufsmount *ump;
1561 
1562 	ump = VFSTOUFS(wk->wk_mp);
1563 	wk->wk_state |= IOWAITING;
1564 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1565 }
1566 
1567 /*
1568  * Process that runs once per second to handle items in the background queue.
1569  *
1570  * Note that we ensure that everything is done in the order in which they
1571  * appear in the queue. The code below depends on this property to ensure
1572  * that blocks of a file are freed before the inode itself is freed. This
1573  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1574  * until all the old ones have been purged from the dependency lists.
1575  */
1576 static int
1577 softdep_process_worklist(mp, full)
1578 	struct mount *mp;
1579 	int full;
1580 {
1581 	int cnt, matchcnt;
1582 	struct ufsmount *ump;
1583 	long starttime;
1584 
1585 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1586 	if (MOUNTEDSOFTDEP(mp) == 0)
1587 		return (0);
1588 	matchcnt = 0;
1589 	ump = VFSTOUFS(mp);
1590 	ACQUIRE_LOCK(ump);
1591 	starttime = time_second;
1592 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1593 	check_clear_deps(mp);
1594 	while (ump->softdep_on_worklist > 0) {
1595 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1596 			break;
1597 		else
1598 			matchcnt += cnt;
1599 		check_clear_deps(mp);
1600 		/*
1601 		 * We do not generally want to stop for buffer space, but if
1602 		 * we are really being a buffer hog, we will stop and wait.
1603 		 */
1604 		if (should_yield()) {
1605 			FREE_LOCK(ump);
1606 			kern_yield(PRI_USER);
1607 			bwillwrite();
1608 			ACQUIRE_LOCK(ump);
1609 		}
1610 		/*
1611 		 * Never allow processing to run for more than one
1612 		 * second. This gives the syncer thread the opportunity
1613 		 * to pause if appropriate.
1614 		 */
1615 		if (!full && starttime != time_second)
1616 			break;
1617 	}
1618 	if (full == 0)
1619 		journal_unsuspend(ump);
1620 	FREE_LOCK(ump);
1621 	return (matchcnt);
1622 }
1623 
1624 /*
1625  * Process all removes associated with a vnode if we are running out of
1626  * journal space.  Any other process which attempts to flush these will
1627  * be unable as we have the vnodes locked.
1628  */
1629 static void
1630 process_removes(vp)
1631 	struct vnode *vp;
1632 {
1633 	struct inodedep *inodedep;
1634 	struct dirrem *dirrem;
1635 	struct ufsmount *ump;
1636 	struct mount *mp;
1637 	ino_t inum;
1638 
1639 	mp = vp->v_mount;
1640 	ump = VFSTOUFS(mp);
1641 	LOCK_OWNED(ump);
1642 	inum = VTOI(vp)->i_number;
1643 	for (;;) {
1644 top:
1645 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1646 			return;
1647 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1648 			/*
1649 			 * If another thread is trying to lock this vnode
1650 			 * it will fail but we must wait for it to do so
1651 			 * before we can proceed.
1652 			 */
1653 			if (dirrem->dm_state & INPROGRESS) {
1654 				wait_worklist(&dirrem->dm_list, "pwrwait");
1655 				goto top;
1656 			}
1657 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1658 			    (COMPLETE | ONWORKLIST))
1659 				break;
1660 		}
1661 		if (dirrem == NULL)
1662 			return;
1663 		remove_from_worklist(&dirrem->dm_list);
1664 		FREE_LOCK(ump);
1665 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1666 			panic("process_removes: suspended filesystem");
1667 		handle_workitem_remove(dirrem, 0);
1668 		vn_finished_secondary_write(mp);
1669 		ACQUIRE_LOCK(ump);
1670 	}
1671 }
1672 
1673 /*
1674  * Process all truncations associated with a vnode if we are running out
1675  * of journal space.  This is called when the vnode lock is already held
1676  * and no other process can clear the truncation.  This function returns
1677  * a value greater than zero if it did any work.
1678  */
1679 static void
1680 process_truncates(vp)
1681 	struct vnode *vp;
1682 {
1683 	struct inodedep *inodedep;
1684 	struct freeblks *freeblks;
1685 	struct ufsmount *ump;
1686 	struct mount *mp;
1687 	ino_t inum;
1688 	int cgwait;
1689 
1690 	mp = vp->v_mount;
1691 	ump = VFSTOUFS(mp);
1692 	LOCK_OWNED(ump);
1693 	inum = VTOI(vp)->i_number;
1694 	for (;;) {
1695 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1696 			return;
1697 		cgwait = 0;
1698 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1699 			/* Journal entries not yet written.  */
1700 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1701 				jwait(&LIST_FIRST(
1702 				    &freeblks->fb_jblkdephd)->jb_list,
1703 				    MNT_WAIT);
1704 				break;
1705 			}
1706 			/* Another thread is executing this item. */
1707 			if (freeblks->fb_state & INPROGRESS) {
1708 				wait_worklist(&freeblks->fb_list, "ptrwait");
1709 				break;
1710 			}
1711 			/* Freeblks is waiting on a inode write. */
1712 			if ((freeblks->fb_state & COMPLETE) == 0) {
1713 				FREE_LOCK(ump);
1714 				ffs_update(vp, 1);
1715 				ACQUIRE_LOCK(ump);
1716 				break;
1717 			}
1718 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1719 			    (ALLCOMPLETE | ONWORKLIST)) {
1720 				remove_from_worklist(&freeblks->fb_list);
1721 				freeblks->fb_state |= INPROGRESS;
1722 				FREE_LOCK(ump);
1723 				if (vn_start_secondary_write(NULL, &mp,
1724 				    V_NOWAIT))
1725 					panic("process_truncates: "
1726 					    "suspended filesystem");
1727 				handle_workitem_freeblocks(freeblks, 0);
1728 				vn_finished_secondary_write(mp);
1729 				ACQUIRE_LOCK(ump);
1730 				break;
1731 			}
1732 			if (freeblks->fb_cgwait)
1733 				cgwait++;
1734 		}
1735 		if (cgwait) {
1736 			FREE_LOCK(ump);
1737 			sync_cgs(mp, MNT_WAIT);
1738 			ffs_sync_snap(mp, MNT_WAIT);
1739 			ACQUIRE_LOCK(ump);
1740 			continue;
1741 		}
1742 		if (freeblks == NULL)
1743 			break;
1744 	}
1745 	return;
1746 }
1747 
1748 /*
1749  * Process one item on the worklist.
1750  */
1751 static int
1752 process_worklist_item(mp, target, flags)
1753 	struct mount *mp;
1754 	int target;
1755 	int flags;
1756 {
1757 	struct worklist sentinel;
1758 	struct worklist *wk;
1759 	struct ufsmount *ump;
1760 	int matchcnt;
1761 	int error;
1762 
1763 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1764 	/*
1765 	 * If we are being called because of a process doing a
1766 	 * copy-on-write, then it is not safe to write as we may
1767 	 * recurse into the copy-on-write routine.
1768 	 */
1769 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1770 		return (-1);
1771 	PHOLD(curproc);	/* Don't let the stack go away. */
1772 	ump = VFSTOUFS(mp);
1773 	LOCK_OWNED(ump);
1774 	matchcnt = 0;
1775 	sentinel.wk_mp = NULL;
1776 	sentinel.wk_type = D_SENTINEL;
1777 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1778 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1779 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1780 		if (wk->wk_type == D_SENTINEL) {
1781 			LIST_REMOVE(&sentinel, wk_list);
1782 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1783 			continue;
1784 		}
1785 		if (wk->wk_state & INPROGRESS)
1786 			panic("process_worklist_item: %p already in progress.",
1787 			    wk);
1788 		wk->wk_state |= INPROGRESS;
1789 		remove_from_worklist(wk);
1790 		FREE_LOCK(ump);
1791 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1792 			panic("process_worklist_item: suspended filesystem");
1793 		switch (wk->wk_type) {
1794 		case D_DIRREM:
1795 			/* removal of a directory entry */
1796 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1797 			break;
1798 
1799 		case D_FREEBLKS:
1800 			/* releasing blocks and/or fragments from a file */
1801 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1802 			    flags);
1803 			break;
1804 
1805 		case D_FREEFRAG:
1806 			/* releasing a fragment when replaced as a file grows */
1807 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1808 			error = 0;
1809 			break;
1810 
1811 		case D_FREEFILE:
1812 			/* releasing an inode when its link count drops to 0 */
1813 			handle_workitem_freefile(WK_FREEFILE(wk));
1814 			error = 0;
1815 			break;
1816 
1817 		default:
1818 			panic("%s_process_worklist: Unknown type %s",
1819 			    "softdep", TYPENAME(wk->wk_type));
1820 			/* NOTREACHED */
1821 		}
1822 		vn_finished_secondary_write(mp);
1823 		ACQUIRE_LOCK(ump);
1824 		if (error == 0) {
1825 			if (++matchcnt == target)
1826 				break;
1827 			continue;
1828 		}
1829 		/*
1830 		 * We have to retry the worklist item later.  Wake up any
1831 		 * waiters who may be able to complete it immediately and
1832 		 * add the item back to the head so we don't try to execute
1833 		 * it again.
1834 		 */
1835 		wk->wk_state &= ~INPROGRESS;
1836 		wake_worklist(wk);
1837 		add_to_worklist(wk, WK_HEAD);
1838 	}
1839 	LIST_REMOVE(&sentinel, wk_list);
1840 	/* Sentinal could've become the tail from remove_from_worklist. */
1841 	if (ump->softdep_worklist_tail == &sentinel)
1842 		ump->softdep_worklist_tail =
1843 		    (struct worklist *)sentinel.wk_list.le_prev;
1844 	PRELE(curproc);
1845 	return (matchcnt);
1846 }
1847 
1848 /*
1849  * Move dependencies from one buffer to another.
1850  */
1851 int
1852 softdep_move_dependencies(oldbp, newbp)
1853 	struct buf *oldbp;
1854 	struct buf *newbp;
1855 {
1856 	struct worklist *wk, *wktail;
1857 	struct ufsmount *ump;
1858 	int dirty;
1859 
1860 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1861 		return (0);
1862 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1863 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1864 	dirty = 0;
1865 	wktail = NULL;
1866 	ump = VFSTOUFS(wk->wk_mp);
1867 	ACQUIRE_LOCK(ump);
1868 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1869 		LIST_REMOVE(wk, wk_list);
1870 		if (wk->wk_type == D_BMSAFEMAP &&
1871 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1872 			dirty = 1;
1873 		if (wktail == NULL)
1874 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1875 		else
1876 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1877 		wktail = wk;
1878 	}
1879 	FREE_LOCK(ump);
1880 
1881 	return (dirty);
1882 }
1883 
1884 /*
1885  * Purge the work list of all items associated with a particular mount point.
1886  */
1887 int
1888 softdep_flushworklist(oldmnt, countp, td)
1889 	struct mount *oldmnt;
1890 	int *countp;
1891 	struct thread *td;
1892 {
1893 	struct vnode *devvp;
1894 	struct ufsmount *ump;
1895 	int count, error;
1896 
1897 	/*
1898 	 * Alternately flush the block device associated with the mount
1899 	 * point and process any dependencies that the flushing
1900 	 * creates. We continue until no more worklist dependencies
1901 	 * are found.
1902 	 */
1903 	*countp = 0;
1904 	error = 0;
1905 	ump = VFSTOUFS(oldmnt);
1906 	devvp = ump->um_devvp;
1907 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1908 		*countp += count;
1909 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1910 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1911 		VOP_UNLOCK(devvp, 0);
1912 		if (error != 0)
1913 			break;
1914 	}
1915 	return (error);
1916 }
1917 
1918 #define	SU_WAITIDLE_RETRIES	20
1919 static int
1920 softdep_waitidle(struct mount *mp, int flags __unused)
1921 {
1922 	struct ufsmount *ump;
1923 	struct vnode *devvp;
1924 	struct thread *td;
1925 	int error, i;
1926 
1927 	ump = VFSTOUFS(mp);
1928 	devvp = ump->um_devvp;
1929 	td = curthread;
1930 	error = 0;
1931 	ACQUIRE_LOCK(ump);
1932 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1933 		ump->softdep_req = 1;
1934 		KASSERT((flags & FORCECLOSE) == 0 ||
1935 		    ump->softdep_on_worklist == 0,
1936 		    ("softdep_waitidle: work added after flush"));
1937 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1938 		    "softdeps", 10 * hz);
1939 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1940 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1941 		VOP_UNLOCK(devvp, 0);
1942 		ACQUIRE_LOCK(ump);
1943 		if (error != 0)
1944 			break;
1945 	}
1946 	ump->softdep_req = 0;
1947 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1948 		error = EBUSY;
1949 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1950 		    mp);
1951 	}
1952 	FREE_LOCK(ump);
1953 	return (error);
1954 }
1955 
1956 /*
1957  * Flush all vnodes and worklist items associated with a specified mount point.
1958  */
1959 int
1960 softdep_flushfiles(oldmnt, flags, td)
1961 	struct mount *oldmnt;
1962 	int flags;
1963 	struct thread *td;
1964 {
1965 #ifdef QUOTA
1966 	struct ufsmount *ump;
1967 	int i;
1968 #endif
1969 	int error, early, depcount, loopcnt, retry_flush_count, retry;
1970 	int morework;
1971 
1972 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1973 	    ("softdep_flushfiles called on non-softdep filesystem"));
1974 	loopcnt = 10;
1975 	retry_flush_count = 3;
1976 retry_flush:
1977 	error = 0;
1978 
1979 	/*
1980 	 * Alternately flush the vnodes associated with the mount
1981 	 * point and process any dependencies that the flushing
1982 	 * creates. In theory, this loop can happen at most twice,
1983 	 * but we give it a few extra just to be sure.
1984 	 */
1985 	for (; loopcnt > 0; loopcnt--) {
1986 		/*
1987 		 * Do another flush in case any vnodes were brought in
1988 		 * as part of the cleanup operations.
1989 		 */
1990 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
1991 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
1992 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
1993 			break;
1994 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1995 		    depcount == 0)
1996 			break;
1997 	}
1998 	/*
1999 	 * If we are unmounting then it is an error to fail. If we
2000 	 * are simply trying to downgrade to read-only, then filesystem
2001 	 * activity can keep us busy forever, so we just fail with EBUSY.
2002 	 */
2003 	if (loopcnt == 0) {
2004 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2005 			panic("softdep_flushfiles: looping");
2006 		error = EBUSY;
2007 	}
2008 	if (!error)
2009 		error = softdep_waitidle(oldmnt, flags);
2010 	if (!error) {
2011 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2012 			retry = 0;
2013 			MNT_ILOCK(oldmnt);
2014 			KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
2015 			    ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
2016 			morework = oldmnt->mnt_nvnodelistsize > 0;
2017 #ifdef QUOTA
2018 			ump = VFSTOUFS(oldmnt);
2019 			UFS_LOCK(ump);
2020 			for (i = 0; i < MAXQUOTAS; i++) {
2021 				if (ump->um_quotas[i] != NULLVP)
2022 					morework = 1;
2023 			}
2024 			UFS_UNLOCK(ump);
2025 #endif
2026 			if (morework) {
2027 				if (--retry_flush_count > 0) {
2028 					retry = 1;
2029 					loopcnt = 3;
2030 				} else
2031 					error = EBUSY;
2032 			}
2033 			MNT_IUNLOCK(oldmnt);
2034 			if (retry)
2035 				goto retry_flush;
2036 		}
2037 	}
2038 	return (error);
2039 }
2040 
2041 /*
2042  * Structure hashing.
2043  *
2044  * There are four types of structures that can be looked up:
2045  *	1) pagedep structures identified by mount point, inode number,
2046  *	   and logical block.
2047  *	2) inodedep structures identified by mount point and inode number.
2048  *	3) newblk structures identified by mount point and
2049  *	   physical block number.
2050  *	4) bmsafemap structures identified by mount point and
2051  *	   cylinder group number.
2052  *
2053  * The "pagedep" and "inodedep" dependency structures are hashed
2054  * separately from the file blocks and inodes to which they correspond.
2055  * This separation helps when the in-memory copy of an inode or
2056  * file block must be replaced. It also obviates the need to access
2057  * an inode or file page when simply updating (or de-allocating)
2058  * dependency structures. Lookup of newblk structures is needed to
2059  * find newly allocated blocks when trying to associate them with
2060  * their allocdirect or allocindir structure.
2061  *
2062  * The lookup routines optionally create and hash a new instance when
2063  * an existing entry is not found. The bmsafemap lookup routine always
2064  * allocates a new structure if an existing one is not found.
2065  */
2066 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2067 
2068 /*
2069  * Structures and routines associated with pagedep caching.
2070  */
2071 #define	PAGEDEP_HASH(ump, inum, lbn) \
2072 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2073 
2074 static int
2075 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2076 	struct pagedep_hashhead *pagedephd;
2077 	ino_t ino;
2078 	ufs_lbn_t lbn;
2079 	struct pagedep **pagedeppp;
2080 {
2081 	struct pagedep *pagedep;
2082 
2083 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2084 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2085 			*pagedeppp = pagedep;
2086 			return (1);
2087 		}
2088 	}
2089 	*pagedeppp = NULL;
2090 	return (0);
2091 }
2092 /*
2093  * Look up a pagedep. Return 1 if found, 0 otherwise.
2094  * If not found, allocate if DEPALLOC flag is passed.
2095  * Found or allocated entry is returned in pagedeppp.
2096  * This routine must be called with splbio interrupts blocked.
2097  */
2098 static int
2099 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2100 	struct mount *mp;
2101 	struct buf *bp;
2102 	ino_t ino;
2103 	ufs_lbn_t lbn;
2104 	int flags;
2105 	struct pagedep **pagedeppp;
2106 {
2107 	struct pagedep *pagedep;
2108 	struct pagedep_hashhead *pagedephd;
2109 	struct worklist *wk;
2110 	struct ufsmount *ump;
2111 	int ret;
2112 	int i;
2113 
2114 	ump = VFSTOUFS(mp);
2115 	LOCK_OWNED(ump);
2116 	if (bp) {
2117 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2118 			if (wk->wk_type == D_PAGEDEP) {
2119 				*pagedeppp = WK_PAGEDEP(wk);
2120 				return (1);
2121 			}
2122 		}
2123 	}
2124 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2125 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2126 	if (ret) {
2127 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2128 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2129 		return (1);
2130 	}
2131 	if ((flags & DEPALLOC) == 0)
2132 		return (0);
2133 	FREE_LOCK(ump);
2134 	pagedep = malloc(sizeof(struct pagedep),
2135 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2136 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2137 	ACQUIRE_LOCK(ump);
2138 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2139 	if (*pagedeppp) {
2140 		/*
2141 		 * This should never happen since we only create pagedeps
2142 		 * with the vnode lock held.  Could be an assert.
2143 		 */
2144 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2145 		return (ret);
2146 	}
2147 	pagedep->pd_ino = ino;
2148 	pagedep->pd_lbn = lbn;
2149 	LIST_INIT(&pagedep->pd_dirremhd);
2150 	LIST_INIT(&pagedep->pd_pendinghd);
2151 	for (i = 0; i < DAHASHSZ; i++)
2152 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2153 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2154 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2155 	*pagedeppp = pagedep;
2156 	return (0);
2157 }
2158 
2159 /*
2160  * Structures and routines associated with inodedep caching.
2161  */
2162 #define	INODEDEP_HASH(ump, inum) \
2163       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2164 
2165 static int
2166 inodedep_find(inodedephd, inum, inodedeppp)
2167 	struct inodedep_hashhead *inodedephd;
2168 	ino_t inum;
2169 	struct inodedep **inodedeppp;
2170 {
2171 	struct inodedep *inodedep;
2172 
2173 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2174 		if (inum == inodedep->id_ino)
2175 			break;
2176 	if (inodedep) {
2177 		*inodedeppp = inodedep;
2178 		return (1);
2179 	}
2180 	*inodedeppp = NULL;
2181 
2182 	return (0);
2183 }
2184 /*
2185  * Look up an inodedep. Return 1 if found, 0 if not found.
2186  * If not found, allocate if DEPALLOC flag is passed.
2187  * Found or allocated entry is returned in inodedeppp.
2188  * This routine must be called with splbio interrupts blocked.
2189  */
2190 static int
2191 inodedep_lookup(mp, inum, flags, inodedeppp)
2192 	struct mount *mp;
2193 	ino_t inum;
2194 	int flags;
2195 	struct inodedep **inodedeppp;
2196 {
2197 	struct inodedep *inodedep;
2198 	struct inodedep_hashhead *inodedephd;
2199 	struct ufsmount *ump;
2200 	struct fs *fs;
2201 
2202 	ump = VFSTOUFS(mp);
2203 	LOCK_OWNED(ump);
2204 	fs = ump->um_fs;
2205 	inodedephd = INODEDEP_HASH(ump, inum);
2206 
2207 	if (inodedep_find(inodedephd, inum, inodedeppp))
2208 		return (1);
2209 	if ((flags & DEPALLOC) == 0)
2210 		return (0);
2211 	/*
2212 	 * If the system is over its limit and our filesystem is
2213 	 * responsible for more than our share of that usage and
2214 	 * we are not in a rush, request some inodedep cleanup.
2215 	 */
2216 	if (softdep_excess_items(ump, D_INODEDEP))
2217 		schedule_cleanup(mp);
2218 	else
2219 		FREE_LOCK(ump);
2220 	inodedep = malloc(sizeof(struct inodedep),
2221 		M_INODEDEP, M_SOFTDEP_FLAGS);
2222 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2223 	ACQUIRE_LOCK(ump);
2224 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2225 		WORKITEM_FREE(inodedep, D_INODEDEP);
2226 		return (1);
2227 	}
2228 	inodedep->id_fs = fs;
2229 	inodedep->id_ino = inum;
2230 	inodedep->id_state = ALLCOMPLETE;
2231 	inodedep->id_nlinkdelta = 0;
2232 	inodedep->id_savedino1 = NULL;
2233 	inodedep->id_savedsize = -1;
2234 	inodedep->id_savedextsize = -1;
2235 	inodedep->id_savednlink = -1;
2236 	inodedep->id_bmsafemap = NULL;
2237 	inodedep->id_mkdiradd = NULL;
2238 	LIST_INIT(&inodedep->id_dirremhd);
2239 	LIST_INIT(&inodedep->id_pendinghd);
2240 	LIST_INIT(&inodedep->id_inowait);
2241 	LIST_INIT(&inodedep->id_bufwait);
2242 	TAILQ_INIT(&inodedep->id_inoreflst);
2243 	TAILQ_INIT(&inodedep->id_inoupdt);
2244 	TAILQ_INIT(&inodedep->id_newinoupdt);
2245 	TAILQ_INIT(&inodedep->id_extupdt);
2246 	TAILQ_INIT(&inodedep->id_newextupdt);
2247 	TAILQ_INIT(&inodedep->id_freeblklst);
2248 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2249 	*inodedeppp = inodedep;
2250 	return (0);
2251 }
2252 
2253 /*
2254  * Structures and routines associated with newblk caching.
2255  */
2256 #define	NEWBLK_HASH(ump, inum) \
2257 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2258 
2259 static int
2260 newblk_find(newblkhd, newblkno, flags, newblkpp)
2261 	struct newblk_hashhead *newblkhd;
2262 	ufs2_daddr_t newblkno;
2263 	int flags;
2264 	struct newblk **newblkpp;
2265 {
2266 	struct newblk *newblk;
2267 
2268 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2269 		if (newblkno != newblk->nb_newblkno)
2270 			continue;
2271 		/*
2272 		 * If we're creating a new dependency don't match those that
2273 		 * have already been converted to allocdirects.  This is for
2274 		 * a frag extend.
2275 		 */
2276 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2277 			continue;
2278 		break;
2279 	}
2280 	if (newblk) {
2281 		*newblkpp = newblk;
2282 		return (1);
2283 	}
2284 	*newblkpp = NULL;
2285 	return (0);
2286 }
2287 
2288 /*
2289  * Look up a newblk. Return 1 if found, 0 if not found.
2290  * If not found, allocate if DEPALLOC flag is passed.
2291  * Found or allocated entry is returned in newblkpp.
2292  */
2293 static int
2294 newblk_lookup(mp, newblkno, flags, newblkpp)
2295 	struct mount *mp;
2296 	ufs2_daddr_t newblkno;
2297 	int flags;
2298 	struct newblk **newblkpp;
2299 {
2300 	struct newblk *newblk;
2301 	struct newblk_hashhead *newblkhd;
2302 	struct ufsmount *ump;
2303 
2304 	ump = VFSTOUFS(mp);
2305 	LOCK_OWNED(ump);
2306 	newblkhd = NEWBLK_HASH(ump, newblkno);
2307 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2308 		return (1);
2309 	if ((flags & DEPALLOC) == 0)
2310 		return (0);
2311 	if (softdep_excess_items(ump, D_NEWBLK) ||
2312 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2313 	    softdep_excess_items(ump, D_ALLOCINDIR))
2314 		schedule_cleanup(mp);
2315 	else
2316 		FREE_LOCK(ump);
2317 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2318 	    M_SOFTDEP_FLAGS | M_ZERO);
2319 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2320 	ACQUIRE_LOCK(ump);
2321 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2322 		WORKITEM_FREE(newblk, D_NEWBLK);
2323 		return (1);
2324 	}
2325 	newblk->nb_freefrag = NULL;
2326 	LIST_INIT(&newblk->nb_indirdeps);
2327 	LIST_INIT(&newblk->nb_newdirblk);
2328 	LIST_INIT(&newblk->nb_jwork);
2329 	newblk->nb_state = ATTACHED;
2330 	newblk->nb_newblkno = newblkno;
2331 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2332 	*newblkpp = newblk;
2333 	return (0);
2334 }
2335 
2336 /*
2337  * Structures and routines associated with freed indirect block caching.
2338  */
2339 #define	INDIR_HASH(ump, blkno) \
2340 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2341 
2342 /*
2343  * Lookup an indirect block in the indir hash table.  The freework is
2344  * removed and potentially freed.  The caller must do a blocking journal
2345  * write before writing to the blkno.
2346  */
2347 static int
2348 indirblk_lookup(mp, blkno)
2349 	struct mount *mp;
2350 	ufs2_daddr_t blkno;
2351 {
2352 	struct freework *freework;
2353 	struct indir_hashhead *wkhd;
2354 	struct ufsmount *ump;
2355 
2356 	ump = VFSTOUFS(mp);
2357 	wkhd = INDIR_HASH(ump, blkno);
2358 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2359 		if (freework->fw_blkno != blkno)
2360 			continue;
2361 		indirblk_remove(freework);
2362 		return (1);
2363 	}
2364 	return (0);
2365 }
2366 
2367 /*
2368  * Insert an indirect block represented by freework into the indirblk
2369  * hash table so that it may prevent the block from being re-used prior
2370  * to the journal being written.
2371  */
2372 static void
2373 indirblk_insert(freework)
2374 	struct freework *freework;
2375 {
2376 	struct jblocks *jblocks;
2377 	struct jseg *jseg;
2378 	struct ufsmount *ump;
2379 
2380 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2381 	jblocks = ump->softdep_jblocks;
2382 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2383 	if (jseg == NULL)
2384 		return;
2385 
2386 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2387 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2388 	    fw_next);
2389 	freework->fw_state &= ~DEPCOMPLETE;
2390 }
2391 
2392 static void
2393 indirblk_remove(freework)
2394 	struct freework *freework;
2395 {
2396 	struct ufsmount *ump;
2397 
2398 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2399 	LIST_REMOVE(freework, fw_segs);
2400 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2401 	freework->fw_state |= DEPCOMPLETE;
2402 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2403 		WORKITEM_FREE(freework, D_FREEWORK);
2404 }
2405 
2406 /*
2407  * Executed during filesystem system initialization before
2408  * mounting any filesystems.
2409  */
2410 void
2411 softdep_initialize()
2412 {
2413 
2414 	TAILQ_INIT(&softdepmounts);
2415 #ifdef __LP64__
2416 	max_softdeps = desiredvnodes * 4;
2417 #else
2418 	max_softdeps = desiredvnodes * 2;
2419 #endif
2420 
2421 	/* initialise bioops hack */
2422 	bioops.io_start = softdep_disk_io_initiation;
2423 	bioops.io_complete = softdep_disk_write_complete;
2424 	bioops.io_deallocate = softdep_deallocate_dependencies;
2425 	bioops.io_countdeps = softdep_count_dependencies;
2426 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2427 
2428 	/* Initialize the callout with an mtx. */
2429 	callout_init_mtx(&softdep_callout, &lk, 0);
2430 }
2431 
2432 /*
2433  * Executed after all filesystems have been unmounted during
2434  * filesystem module unload.
2435  */
2436 void
2437 softdep_uninitialize()
2438 {
2439 
2440 	/* clear bioops hack */
2441 	bioops.io_start = NULL;
2442 	bioops.io_complete = NULL;
2443 	bioops.io_deallocate = NULL;
2444 	bioops.io_countdeps = NULL;
2445 	softdep_ast_cleanup = NULL;
2446 
2447 	callout_drain(&softdep_callout);
2448 }
2449 
2450 /*
2451  * Called at mount time to notify the dependency code that a
2452  * filesystem wishes to use it.
2453  */
2454 int
2455 softdep_mount(devvp, mp, fs, cred)
2456 	struct vnode *devvp;
2457 	struct mount *mp;
2458 	struct fs *fs;
2459 	struct ucred *cred;
2460 {
2461 	struct csum_total cstotal;
2462 	struct mount_softdeps *sdp;
2463 	struct ufsmount *ump;
2464 	struct cg *cgp;
2465 	struct buf *bp;
2466 	int i, error, cyl;
2467 
2468 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2469 	    M_WAITOK | M_ZERO);
2470 	MNT_ILOCK(mp);
2471 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2472 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2473 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2474 			MNTK_SOFTDEP | MNTK_NOASYNC;
2475 	}
2476 	ump = VFSTOUFS(mp);
2477 	ump->um_softdep = sdp;
2478 	MNT_IUNLOCK(mp);
2479 	rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2480 	sdp->sd_ump = ump;
2481 	LIST_INIT(&ump->softdep_workitem_pending);
2482 	LIST_INIT(&ump->softdep_journal_pending);
2483 	TAILQ_INIT(&ump->softdep_unlinked);
2484 	LIST_INIT(&ump->softdep_dirtycg);
2485 	ump->softdep_worklist_tail = NULL;
2486 	ump->softdep_on_worklist = 0;
2487 	ump->softdep_deps = 0;
2488 	LIST_INIT(&ump->softdep_mkdirlisthd);
2489 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2490 	    &ump->pagedep_hash_size);
2491 	ump->pagedep_nextclean = 0;
2492 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2493 	    &ump->inodedep_hash_size);
2494 	ump->inodedep_nextclean = 0;
2495 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2496 	    &ump->newblk_hash_size);
2497 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2498 	    &ump->bmsafemap_hash_size);
2499 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2500 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2501 	    M_FREEWORK, M_WAITOK);
2502 	ump->indir_hash_size = i - 1;
2503 	for (i = 0; i <= ump->indir_hash_size; i++)
2504 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2505 	ACQUIRE_GBLLOCK(&lk);
2506 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2507 	FREE_GBLLOCK(&lk);
2508 	if ((fs->fs_flags & FS_SUJ) &&
2509 	    (error = journal_mount(mp, fs, cred)) != 0) {
2510 		printf("Failed to start journal: %d\n", error);
2511 		softdep_unmount(mp);
2512 		return (error);
2513 	}
2514 	/*
2515 	 * Start our flushing thread in the bufdaemon process.
2516 	 */
2517 	ACQUIRE_LOCK(ump);
2518 	ump->softdep_flags |= FLUSH_STARTING;
2519 	FREE_LOCK(ump);
2520 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2521 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2522 	    mp->mnt_stat.f_mntonname);
2523 	ACQUIRE_LOCK(ump);
2524 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2525 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2526 		    hz / 2);
2527 	}
2528 	FREE_LOCK(ump);
2529 	/*
2530 	 * When doing soft updates, the counters in the
2531 	 * superblock may have gotten out of sync. Recomputation
2532 	 * can take a long time and can be deferred for background
2533 	 * fsck.  However, the old behavior of scanning the cylinder
2534 	 * groups and recalculating them at mount time is available
2535 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2536 	 */
2537 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2538 		return (0);
2539 	bzero(&cstotal, sizeof cstotal);
2540 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2541 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2542 		    fs->fs_cgsize, cred, &bp)) != 0) {
2543 			brelse(bp);
2544 			softdep_unmount(mp);
2545 			return (error);
2546 		}
2547 		cgp = (struct cg *)bp->b_data;
2548 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2549 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2550 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2551 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2552 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2553 		brelse(bp);
2554 	}
2555 #ifdef DEBUG
2556 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2557 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2558 #endif
2559 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2560 	return (0);
2561 }
2562 
2563 void
2564 softdep_unmount(mp)
2565 	struct mount *mp;
2566 {
2567 	struct ufsmount *ump;
2568 #ifdef INVARIANTS
2569 	int i;
2570 #endif
2571 
2572 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2573 	    ("softdep_unmount called on non-softdep filesystem"));
2574 	ump = VFSTOUFS(mp);
2575 	MNT_ILOCK(mp);
2576 	mp->mnt_flag &= ~MNT_SOFTDEP;
2577 	if (MOUNTEDSUJ(mp) == 0) {
2578 		MNT_IUNLOCK(mp);
2579 	} else {
2580 		mp->mnt_flag &= ~MNT_SUJ;
2581 		MNT_IUNLOCK(mp);
2582 		journal_unmount(ump);
2583 	}
2584 	/*
2585 	 * Shut down our flushing thread. Check for NULL is if
2586 	 * softdep_mount errors out before the thread has been created.
2587 	 */
2588 	if (ump->softdep_flushtd != NULL) {
2589 		ACQUIRE_LOCK(ump);
2590 		ump->softdep_flags |= FLUSH_EXIT;
2591 		wakeup(&ump->softdep_flushtd);
2592 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2593 		    "sdwait", 0);
2594 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2595 		    ("Thread shutdown failed"));
2596 	}
2597 	/*
2598 	 * Free up our resources.
2599 	 */
2600 	ACQUIRE_GBLLOCK(&lk);
2601 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2602 	FREE_GBLLOCK(&lk);
2603 	rw_destroy(LOCK_PTR(ump));
2604 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2605 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2606 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2607 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2608 	    ump->bmsafemap_hash_size);
2609 	free(ump->indir_hashtbl, M_FREEWORK);
2610 #ifdef INVARIANTS
2611 	for (i = 0; i <= D_LAST; i++)
2612 		KASSERT(ump->softdep_curdeps[i] == 0,
2613 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2614 		    TYPENAME(i), ump->softdep_curdeps[i]));
2615 #endif
2616 	free(ump->um_softdep, M_MOUNTDATA);
2617 }
2618 
2619 static struct jblocks *
2620 jblocks_create(void)
2621 {
2622 	struct jblocks *jblocks;
2623 
2624 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2625 	TAILQ_INIT(&jblocks->jb_segs);
2626 	jblocks->jb_avail = 10;
2627 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2628 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2629 
2630 	return (jblocks);
2631 }
2632 
2633 static ufs2_daddr_t
2634 jblocks_alloc(jblocks, bytes, actual)
2635 	struct jblocks *jblocks;
2636 	int bytes;
2637 	int *actual;
2638 {
2639 	ufs2_daddr_t daddr;
2640 	struct jextent *jext;
2641 	int freecnt;
2642 	int blocks;
2643 
2644 	blocks = bytes / DEV_BSIZE;
2645 	jext = &jblocks->jb_extent[jblocks->jb_head];
2646 	freecnt = jext->je_blocks - jblocks->jb_off;
2647 	if (freecnt == 0) {
2648 		jblocks->jb_off = 0;
2649 		if (++jblocks->jb_head > jblocks->jb_used)
2650 			jblocks->jb_head = 0;
2651 		jext = &jblocks->jb_extent[jblocks->jb_head];
2652 		freecnt = jext->je_blocks;
2653 	}
2654 	if (freecnt > blocks)
2655 		freecnt = blocks;
2656 	*actual = freecnt * DEV_BSIZE;
2657 	daddr = jext->je_daddr + jblocks->jb_off;
2658 	jblocks->jb_off += freecnt;
2659 	jblocks->jb_free -= freecnt;
2660 
2661 	return (daddr);
2662 }
2663 
2664 static void
2665 jblocks_free(jblocks, mp, bytes)
2666 	struct jblocks *jblocks;
2667 	struct mount *mp;
2668 	int bytes;
2669 {
2670 
2671 	LOCK_OWNED(VFSTOUFS(mp));
2672 	jblocks->jb_free += bytes / DEV_BSIZE;
2673 	if (jblocks->jb_suspended)
2674 		worklist_speedup(mp);
2675 	wakeup(jblocks);
2676 }
2677 
2678 static void
2679 jblocks_destroy(jblocks)
2680 	struct jblocks *jblocks;
2681 {
2682 
2683 	if (jblocks->jb_extent)
2684 		free(jblocks->jb_extent, M_JBLOCKS);
2685 	free(jblocks, M_JBLOCKS);
2686 }
2687 
2688 static void
2689 jblocks_add(jblocks, daddr, blocks)
2690 	struct jblocks *jblocks;
2691 	ufs2_daddr_t daddr;
2692 	int blocks;
2693 {
2694 	struct jextent *jext;
2695 
2696 	jblocks->jb_blocks += blocks;
2697 	jblocks->jb_free += blocks;
2698 	jext = &jblocks->jb_extent[jblocks->jb_used];
2699 	/* Adding the first block. */
2700 	if (jext->je_daddr == 0) {
2701 		jext->je_daddr = daddr;
2702 		jext->je_blocks = blocks;
2703 		return;
2704 	}
2705 	/* Extending the last extent. */
2706 	if (jext->je_daddr + jext->je_blocks == daddr) {
2707 		jext->je_blocks += blocks;
2708 		return;
2709 	}
2710 	/* Adding a new extent. */
2711 	if (++jblocks->jb_used == jblocks->jb_avail) {
2712 		jblocks->jb_avail *= 2;
2713 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2714 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2715 		memcpy(jext, jblocks->jb_extent,
2716 		    sizeof(struct jextent) * jblocks->jb_used);
2717 		free(jblocks->jb_extent, M_JBLOCKS);
2718 		jblocks->jb_extent = jext;
2719 	}
2720 	jext = &jblocks->jb_extent[jblocks->jb_used];
2721 	jext->je_daddr = daddr;
2722 	jext->je_blocks = blocks;
2723 	return;
2724 }
2725 
2726 int
2727 softdep_journal_lookup(mp, vpp)
2728 	struct mount *mp;
2729 	struct vnode **vpp;
2730 {
2731 	struct componentname cnp;
2732 	struct vnode *dvp;
2733 	ino_t sujournal;
2734 	int error;
2735 
2736 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2737 	if (error)
2738 		return (error);
2739 	bzero(&cnp, sizeof(cnp));
2740 	cnp.cn_nameiop = LOOKUP;
2741 	cnp.cn_flags = ISLASTCN;
2742 	cnp.cn_thread = curthread;
2743 	cnp.cn_cred = curthread->td_ucred;
2744 	cnp.cn_pnbuf = SUJ_FILE;
2745 	cnp.cn_nameptr = SUJ_FILE;
2746 	cnp.cn_namelen = strlen(SUJ_FILE);
2747 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2748 	vput(dvp);
2749 	if (error != 0)
2750 		return (error);
2751 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2752 	return (error);
2753 }
2754 
2755 /*
2756  * Open and verify the journal file.
2757  */
2758 static int
2759 journal_mount(mp, fs, cred)
2760 	struct mount *mp;
2761 	struct fs *fs;
2762 	struct ucred *cred;
2763 {
2764 	struct jblocks *jblocks;
2765 	struct ufsmount *ump;
2766 	struct vnode *vp;
2767 	struct inode *ip;
2768 	ufs2_daddr_t blkno;
2769 	int bcount;
2770 	int error;
2771 	int i;
2772 
2773 	ump = VFSTOUFS(mp);
2774 	ump->softdep_journal_tail = NULL;
2775 	ump->softdep_on_journal = 0;
2776 	ump->softdep_accdeps = 0;
2777 	ump->softdep_req = 0;
2778 	ump->softdep_jblocks = NULL;
2779 	error = softdep_journal_lookup(mp, &vp);
2780 	if (error != 0) {
2781 		printf("Failed to find journal.  Use tunefs to create one\n");
2782 		return (error);
2783 	}
2784 	ip = VTOI(vp);
2785 	if (ip->i_size < SUJ_MIN) {
2786 		error = ENOSPC;
2787 		goto out;
2788 	}
2789 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2790 	jblocks = jblocks_create();
2791 	for (i = 0; i < bcount; i++) {
2792 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2793 		if (error)
2794 			break;
2795 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2796 	}
2797 	if (error) {
2798 		jblocks_destroy(jblocks);
2799 		goto out;
2800 	}
2801 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2802 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2803 	ump->softdep_jblocks = jblocks;
2804 out:
2805 	if (error == 0) {
2806 		MNT_ILOCK(mp);
2807 		mp->mnt_flag |= MNT_SUJ;
2808 		mp->mnt_flag &= ~MNT_SOFTDEP;
2809 		MNT_IUNLOCK(mp);
2810 		/*
2811 		 * Only validate the journal contents if the
2812 		 * filesystem is clean, otherwise we write the logs
2813 		 * but they'll never be used.  If the filesystem was
2814 		 * still dirty when we mounted it the journal is
2815 		 * invalid and a new journal can only be valid if it
2816 		 * starts from a clean mount.
2817 		 */
2818 		if (fs->fs_clean) {
2819 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2820 			ip->i_flags |= IN_MODIFIED;
2821 			ffs_update(vp, 1);
2822 		}
2823 	}
2824 	vput(vp);
2825 	return (error);
2826 }
2827 
2828 static void
2829 journal_unmount(ump)
2830 	struct ufsmount *ump;
2831 {
2832 
2833 	if (ump->softdep_jblocks)
2834 		jblocks_destroy(ump->softdep_jblocks);
2835 	ump->softdep_jblocks = NULL;
2836 }
2837 
2838 /*
2839  * Called when a journal record is ready to be written.  Space is allocated
2840  * and the journal entry is created when the journal is flushed to stable
2841  * store.
2842  */
2843 static void
2844 add_to_journal(wk)
2845 	struct worklist *wk;
2846 {
2847 	struct ufsmount *ump;
2848 
2849 	ump = VFSTOUFS(wk->wk_mp);
2850 	LOCK_OWNED(ump);
2851 	if (wk->wk_state & ONWORKLIST)
2852 		panic("add_to_journal: %s(0x%X) already on list",
2853 		    TYPENAME(wk->wk_type), wk->wk_state);
2854 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2855 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2856 		ump->softdep_jblocks->jb_age = ticks;
2857 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2858 	} else
2859 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2860 	ump->softdep_journal_tail = wk;
2861 	ump->softdep_on_journal += 1;
2862 }
2863 
2864 /*
2865  * Remove an arbitrary item for the journal worklist maintain the tail
2866  * pointer.  This happens when a new operation obviates the need to
2867  * journal an old operation.
2868  */
2869 static void
2870 remove_from_journal(wk)
2871 	struct worklist *wk;
2872 {
2873 	struct ufsmount *ump;
2874 
2875 	ump = VFSTOUFS(wk->wk_mp);
2876 	LOCK_OWNED(ump);
2877 #ifdef SUJ_DEBUG
2878 	{
2879 		struct worklist *wkn;
2880 
2881 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2882 			if (wkn == wk)
2883 				break;
2884 		if (wkn == NULL)
2885 			panic("remove_from_journal: %p is not in journal", wk);
2886 	}
2887 #endif
2888 	/*
2889 	 * We emulate a TAILQ to save space in most structures which do not
2890 	 * require TAILQ semantics.  Here we must update the tail position
2891 	 * when removing the tail which is not the final entry. This works
2892 	 * only if the worklist linkage are at the beginning of the structure.
2893 	 */
2894 	if (ump->softdep_journal_tail == wk)
2895 		ump->softdep_journal_tail =
2896 		    (struct worklist *)wk->wk_list.le_prev;
2897 
2898 	WORKLIST_REMOVE(wk);
2899 	ump->softdep_on_journal -= 1;
2900 }
2901 
2902 /*
2903  * Check for journal space as well as dependency limits so the prelink
2904  * code can throttle both journaled and non-journaled filesystems.
2905  * Threshold is 0 for low and 1 for min.
2906  */
2907 static int
2908 journal_space(ump, thresh)
2909 	struct ufsmount *ump;
2910 	int thresh;
2911 {
2912 	struct jblocks *jblocks;
2913 	int limit, avail;
2914 
2915 	jblocks = ump->softdep_jblocks;
2916 	if (jblocks == NULL)
2917 		return (1);
2918 	/*
2919 	 * We use a tighter restriction here to prevent request_cleanup()
2920 	 * running in threads from running into locks we currently hold.
2921 	 * We have to be over the limit and our filesystem has to be
2922 	 * responsible for more than our share of that usage.
2923 	 */
2924 	limit = (max_softdeps / 10) * 9;
2925 	if (dep_current[D_INODEDEP] > limit &&
2926 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2927 		return (0);
2928 	if (thresh)
2929 		thresh = jblocks->jb_min;
2930 	else
2931 		thresh = jblocks->jb_low;
2932 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2933 	avail = jblocks->jb_free - avail;
2934 
2935 	return (avail > thresh);
2936 }
2937 
2938 static void
2939 journal_suspend(ump)
2940 	struct ufsmount *ump;
2941 {
2942 	struct jblocks *jblocks;
2943 	struct mount *mp;
2944 
2945 	mp = UFSTOVFS(ump);
2946 	jblocks = ump->softdep_jblocks;
2947 	MNT_ILOCK(mp);
2948 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2949 		stat_journal_min++;
2950 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2951 		mp->mnt_susp_owner = ump->softdep_flushtd;
2952 	}
2953 	jblocks->jb_suspended = 1;
2954 	MNT_IUNLOCK(mp);
2955 }
2956 
2957 static int
2958 journal_unsuspend(struct ufsmount *ump)
2959 {
2960 	struct jblocks *jblocks;
2961 	struct mount *mp;
2962 
2963 	mp = UFSTOVFS(ump);
2964 	jblocks = ump->softdep_jblocks;
2965 
2966 	if (jblocks != NULL && jblocks->jb_suspended &&
2967 	    journal_space(ump, jblocks->jb_min)) {
2968 		jblocks->jb_suspended = 0;
2969 		FREE_LOCK(ump);
2970 		mp->mnt_susp_owner = curthread;
2971 		vfs_write_resume(mp, 0);
2972 		ACQUIRE_LOCK(ump);
2973 		return (1);
2974 	}
2975 	return (0);
2976 }
2977 
2978 /*
2979  * Called before any allocation function to be certain that there is
2980  * sufficient space in the journal prior to creating any new records.
2981  * Since in the case of block allocation we may have multiple locked
2982  * buffers at the time of the actual allocation we can not block
2983  * when the journal records are created.  Doing so would create a deadlock
2984  * if any of these buffers needed to be flushed to reclaim space.  Instead
2985  * we require a sufficiently large amount of available space such that
2986  * each thread in the system could have passed this allocation check and
2987  * still have sufficient free space.  With 20% of a minimum journal size
2988  * of 1MB we have 6553 records available.
2989  */
2990 int
2991 softdep_prealloc(vp, waitok)
2992 	struct vnode *vp;
2993 	int waitok;
2994 {
2995 	struct ufsmount *ump;
2996 
2997 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
2998 	    ("softdep_prealloc called on non-softdep filesystem"));
2999 	/*
3000 	 * Nothing to do if we are not running journaled soft updates.
3001 	 * If we currently hold the snapshot lock, we must avoid
3002 	 * handling other resources that could cause deadlock.  Do not
3003 	 * touch quotas vnode since it is typically recursed with
3004 	 * other vnode locks held.
3005 	 */
3006 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3007 	    (vp->v_vflag & VV_SYSTEM) != 0)
3008 		return (0);
3009 	ump = VFSTOUFS(vp->v_mount);
3010 	ACQUIRE_LOCK(ump);
3011 	if (journal_space(ump, 0)) {
3012 		FREE_LOCK(ump);
3013 		return (0);
3014 	}
3015 	stat_journal_low++;
3016 	FREE_LOCK(ump);
3017 	if (waitok == MNT_NOWAIT)
3018 		return (ENOSPC);
3019 	/*
3020 	 * Attempt to sync this vnode once to flush any journal
3021 	 * work attached to it.
3022 	 */
3023 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3024 		ffs_syncvnode(vp, waitok, 0);
3025 	ACQUIRE_LOCK(ump);
3026 	process_removes(vp);
3027 	process_truncates(vp);
3028 	if (journal_space(ump, 0) == 0) {
3029 		softdep_speedup(ump);
3030 		if (journal_space(ump, 1) == 0)
3031 			journal_suspend(ump);
3032 	}
3033 	FREE_LOCK(ump);
3034 
3035 	return (0);
3036 }
3037 
3038 /*
3039  * Before adjusting a link count on a vnode verify that we have sufficient
3040  * journal space.  If not, process operations that depend on the currently
3041  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3042  * and softdep flush threads can not acquire these locks to reclaim space.
3043  */
3044 static void
3045 softdep_prelink(dvp, vp)
3046 	struct vnode *dvp;
3047 	struct vnode *vp;
3048 {
3049 	struct ufsmount *ump;
3050 
3051 	ump = VFSTOUFS(dvp->v_mount);
3052 	LOCK_OWNED(ump);
3053 	/*
3054 	 * Nothing to do if we have sufficient journal space.
3055 	 * If we currently hold the snapshot lock, we must avoid
3056 	 * handling other resources that could cause deadlock.
3057 	 */
3058 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3059 		return;
3060 	stat_journal_low++;
3061 	FREE_LOCK(ump);
3062 	if (vp)
3063 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3064 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3065 	ACQUIRE_LOCK(ump);
3066 	/* Process vp before dvp as it may create .. removes. */
3067 	if (vp) {
3068 		process_removes(vp);
3069 		process_truncates(vp);
3070 	}
3071 	process_removes(dvp);
3072 	process_truncates(dvp);
3073 	softdep_speedup(ump);
3074 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3075 	if (journal_space(ump, 0) == 0) {
3076 		softdep_speedup(ump);
3077 		if (journal_space(ump, 1) == 0)
3078 			journal_suspend(ump);
3079 	}
3080 }
3081 
3082 static void
3083 jseg_write(ump, jseg, data)
3084 	struct ufsmount *ump;
3085 	struct jseg *jseg;
3086 	uint8_t *data;
3087 {
3088 	struct jsegrec *rec;
3089 
3090 	rec = (struct jsegrec *)data;
3091 	rec->jsr_seq = jseg->js_seq;
3092 	rec->jsr_oldest = jseg->js_oldseq;
3093 	rec->jsr_cnt = jseg->js_cnt;
3094 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3095 	rec->jsr_crc = 0;
3096 	rec->jsr_time = ump->um_fs->fs_mtime;
3097 }
3098 
3099 static inline void
3100 inoref_write(inoref, jseg, rec)
3101 	struct inoref *inoref;
3102 	struct jseg *jseg;
3103 	struct jrefrec *rec;
3104 {
3105 
3106 	inoref->if_jsegdep->jd_seg = jseg;
3107 	rec->jr_ino = inoref->if_ino;
3108 	rec->jr_parent = inoref->if_parent;
3109 	rec->jr_nlink = inoref->if_nlink;
3110 	rec->jr_mode = inoref->if_mode;
3111 	rec->jr_diroff = inoref->if_diroff;
3112 }
3113 
3114 static void
3115 jaddref_write(jaddref, jseg, data)
3116 	struct jaddref *jaddref;
3117 	struct jseg *jseg;
3118 	uint8_t *data;
3119 {
3120 	struct jrefrec *rec;
3121 
3122 	rec = (struct jrefrec *)data;
3123 	rec->jr_op = JOP_ADDREF;
3124 	inoref_write(&jaddref->ja_ref, jseg, rec);
3125 }
3126 
3127 static void
3128 jremref_write(jremref, jseg, data)
3129 	struct jremref *jremref;
3130 	struct jseg *jseg;
3131 	uint8_t *data;
3132 {
3133 	struct jrefrec *rec;
3134 
3135 	rec = (struct jrefrec *)data;
3136 	rec->jr_op = JOP_REMREF;
3137 	inoref_write(&jremref->jr_ref, jseg, rec);
3138 }
3139 
3140 static void
3141 jmvref_write(jmvref, jseg, data)
3142 	struct jmvref *jmvref;
3143 	struct jseg *jseg;
3144 	uint8_t *data;
3145 {
3146 	struct jmvrec *rec;
3147 
3148 	rec = (struct jmvrec *)data;
3149 	rec->jm_op = JOP_MVREF;
3150 	rec->jm_ino = jmvref->jm_ino;
3151 	rec->jm_parent = jmvref->jm_parent;
3152 	rec->jm_oldoff = jmvref->jm_oldoff;
3153 	rec->jm_newoff = jmvref->jm_newoff;
3154 }
3155 
3156 static void
3157 jnewblk_write(jnewblk, jseg, data)
3158 	struct jnewblk *jnewblk;
3159 	struct jseg *jseg;
3160 	uint8_t *data;
3161 {
3162 	struct jblkrec *rec;
3163 
3164 	jnewblk->jn_jsegdep->jd_seg = jseg;
3165 	rec = (struct jblkrec *)data;
3166 	rec->jb_op = JOP_NEWBLK;
3167 	rec->jb_ino = jnewblk->jn_ino;
3168 	rec->jb_blkno = jnewblk->jn_blkno;
3169 	rec->jb_lbn = jnewblk->jn_lbn;
3170 	rec->jb_frags = jnewblk->jn_frags;
3171 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3172 }
3173 
3174 static void
3175 jfreeblk_write(jfreeblk, jseg, data)
3176 	struct jfreeblk *jfreeblk;
3177 	struct jseg *jseg;
3178 	uint8_t *data;
3179 {
3180 	struct jblkrec *rec;
3181 
3182 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3183 	rec = (struct jblkrec *)data;
3184 	rec->jb_op = JOP_FREEBLK;
3185 	rec->jb_ino = jfreeblk->jf_ino;
3186 	rec->jb_blkno = jfreeblk->jf_blkno;
3187 	rec->jb_lbn = jfreeblk->jf_lbn;
3188 	rec->jb_frags = jfreeblk->jf_frags;
3189 	rec->jb_oldfrags = 0;
3190 }
3191 
3192 static void
3193 jfreefrag_write(jfreefrag, jseg, data)
3194 	struct jfreefrag *jfreefrag;
3195 	struct jseg *jseg;
3196 	uint8_t *data;
3197 {
3198 	struct jblkrec *rec;
3199 
3200 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3201 	rec = (struct jblkrec *)data;
3202 	rec->jb_op = JOP_FREEBLK;
3203 	rec->jb_ino = jfreefrag->fr_ino;
3204 	rec->jb_blkno = jfreefrag->fr_blkno;
3205 	rec->jb_lbn = jfreefrag->fr_lbn;
3206 	rec->jb_frags = jfreefrag->fr_frags;
3207 	rec->jb_oldfrags = 0;
3208 }
3209 
3210 static void
3211 jtrunc_write(jtrunc, jseg, data)
3212 	struct jtrunc *jtrunc;
3213 	struct jseg *jseg;
3214 	uint8_t *data;
3215 {
3216 	struct jtrncrec *rec;
3217 
3218 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3219 	rec = (struct jtrncrec *)data;
3220 	rec->jt_op = JOP_TRUNC;
3221 	rec->jt_ino = jtrunc->jt_ino;
3222 	rec->jt_size = jtrunc->jt_size;
3223 	rec->jt_extsize = jtrunc->jt_extsize;
3224 }
3225 
3226 static void
3227 jfsync_write(jfsync, jseg, data)
3228 	struct jfsync *jfsync;
3229 	struct jseg *jseg;
3230 	uint8_t *data;
3231 {
3232 	struct jtrncrec *rec;
3233 
3234 	rec = (struct jtrncrec *)data;
3235 	rec->jt_op = JOP_SYNC;
3236 	rec->jt_ino = jfsync->jfs_ino;
3237 	rec->jt_size = jfsync->jfs_size;
3238 	rec->jt_extsize = jfsync->jfs_extsize;
3239 }
3240 
3241 static void
3242 softdep_flushjournal(mp)
3243 	struct mount *mp;
3244 {
3245 	struct jblocks *jblocks;
3246 	struct ufsmount *ump;
3247 
3248 	if (MOUNTEDSUJ(mp) == 0)
3249 		return;
3250 	ump = VFSTOUFS(mp);
3251 	jblocks = ump->softdep_jblocks;
3252 	ACQUIRE_LOCK(ump);
3253 	while (ump->softdep_on_journal) {
3254 		jblocks->jb_needseg = 1;
3255 		softdep_process_journal(mp, NULL, MNT_WAIT);
3256 	}
3257 	FREE_LOCK(ump);
3258 }
3259 
3260 static void softdep_synchronize_completed(struct bio *);
3261 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3262 
3263 static void
3264 softdep_synchronize_completed(bp)
3265         struct bio *bp;
3266 {
3267 	struct jseg *oldest;
3268 	struct jseg *jseg;
3269 	struct ufsmount *ump;
3270 
3271 	/*
3272 	 * caller1 marks the last segment written before we issued the
3273 	 * synchronize cache.
3274 	 */
3275 	jseg = bp->bio_caller1;
3276 	if (jseg == NULL) {
3277 		g_destroy_bio(bp);
3278 		return;
3279 	}
3280 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3281 	ACQUIRE_LOCK(ump);
3282 	oldest = NULL;
3283 	/*
3284 	 * Mark all the journal entries waiting on the synchronize cache
3285 	 * as completed so they may continue on.
3286 	 */
3287 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3288 		jseg->js_state |= COMPLETE;
3289 		oldest = jseg;
3290 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3291 	}
3292 	/*
3293 	 * Restart deferred journal entry processing from the oldest
3294 	 * completed jseg.
3295 	 */
3296 	if (oldest)
3297 		complete_jsegs(oldest);
3298 
3299 	FREE_LOCK(ump);
3300 	g_destroy_bio(bp);
3301 }
3302 
3303 /*
3304  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3305  * barriers.  The journal must be written prior to any blocks that depend
3306  * on it and the journal can not be released until the blocks have be
3307  * written.  This code handles both barriers simultaneously.
3308  */
3309 static void
3310 softdep_synchronize(bp, ump, caller1)
3311 	struct bio *bp;
3312 	struct ufsmount *ump;
3313 	void *caller1;
3314 {
3315 
3316 	bp->bio_cmd = BIO_FLUSH;
3317 	bp->bio_flags |= BIO_ORDERED;
3318 	bp->bio_data = NULL;
3319 	bp->bio_offset = ump->um_cp->provider->mediasize;
3320 	bp->bio_length = 0;
3321 	bp->bio_done = softdep_synchronize_completed;
3322 	bp->bio_caller1 = caller1;
3323 	g_io_request(bp,
3324 	    (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3325 }
3326 
3327 /*
3328  * Flush some journal records to disk.
3329  */
3330 static void
3331 softdep_process_journal(mp, needwk, flags)
3332 	struct mount *mp;
3333 	struct worklist *needwk;
3334 	int flags;
3335 {
3336 	struct jblocks *jblocks;
3337 	struct ufsmount *ump;
3338 	struct worklist *wk;
3339 	struct jseg *jseg;
3340 	struct buf *bp;
3341 	struct bio *bio;
3342 	uint8_t *data;
3343 	struct fs *fs;
3344 	int shouldflush;
3345 	int segwritten;
3346 	int jrecmin;	/* Minimum records per block. */
3347 	int jrecmax;	/* Maximum records per block. */
3348 	int size;
3349 	int cnt;
3350 	int off;
3351 	int devbsize;
3352 
3353 	if (MOUNTEDSUJ(mp) == 0)
3354 		return;
3355 	shouldflush = softdep_flushcache;
3356 	bio = NULL;
3357 	jseg = NULL;
3358 	ump = VFSTOUFS(mp);
3359 	LOCK_OWNED(ump);
3360 	fs = ump->um_fs;
3361 	jblocks = ump->softdep_jblocks;
3362 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3363 	/*
3364 	 * We write anywhere between a disk block and fs block.  The upper
3365 	 * bound is picked to prevent buffer cache fragmentation and limit
3366 	 * processing time per I/O.
3367 	 */
3368 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3369 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3370 	segwritten = 0;
3371 	for (;;) {
3372 		cnt = ump->softdep_on_journal;
3373 		/*
3374 		 * Criteria for writing a segment:
3375 		 * 1) We have a full block.
3376 		 * 2) We're called from jwait() and haven't found the
3377 		 *    journal item yet.
3378 		 * 3) Always write if needseg is set.
3379 		 * 4) If we are called from process_worklist and have
3380 		 *    not yet written anything we write a partial block
3381 		 *    to enforce a 1 second maximum latency on journal
3382 		 *    entries.
3383 		 */
3384 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3385 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3386 			break;
3387 		cnt++;
3388 		/*
3389 		 * Verify some free journal space.  softdep_prealloc() should
3390 		 * guarantee that we don't run out so this is indicative of
3391 		 * a problem with the flow control.  Try to recover
3392 		 * gracefully in any event.
3393 		 */
3394 		while (jblocks->jb_free == 0) {
3395 			if (flags != MNT_WAIT)
3396 				break;
3397 			printf("softdep: Out of journal space!\n");
3398 			softdep_speedup(ump);
3399 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3400 		}
3401 		FREE_LOCK(ump);
3402 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3403 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3404 		LIST_INIT(&jseg->js_entries);
3405 		LIST_INIT(&jseg->js_indirs);
3406 		jseg->js_state = ATTACHED;
3407 		if (shouldflush == 0)
3408 			jseg->js_state |= COMPLETE;
3409 		else if (bio == NULL)
3410 			bio = g_alloc_bio();
3411 		jseg->js_jblocks = jblocks;
3412 		bp = geteblk(fs->fs_bsize, 0);
3413 		ACQUIRE_LOCK(ump);
3414 		/*
3415 		 * If there was a race while we were allocating the block
3416 		 * and jseg the entry we care about was likely written.
3417 		 * We bail out in both the WAIT and NOWAIT case and assume
3418 		 * the caller will loop if the entry it cares about is
3419 		 * not written.
3420 		 */
3421 		cnt = ump->softdep_on_journal;
3422 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3423 			bp->b_flags |= B_INVAL | B_NOCACHE;
3424 			WORKITEM_FREE(jseg, D_JSEG);
3425 			FREE_LOCK(ump);
3426 			brelse(bp);
3427 			ACQUIRE_LOCK(ump);
3428 			break;
3429 		}
3430 		/*
3431 		 * Calculate the disk block size required for the available
3432 		 * records rounded to the min size.
3433 		 */
3434 		if (cnt == 0)
3435 			size = devbsize;
3436 		else if (cnt < jrecmax)
3437 			size = howmany(cnt, jrecmin) * devbsize;
3438 		else
3439 			size = fs->fs_bsize;
3440 		/*
3441 		 * Allocate a disk block for this journal data and account
3442 		 * for truncation of the requested size if enough contiguous
3443 		 * space was not available.
3444 		 */
3445 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3446 		bp->b_lblkno = bp->b_blkno;
3447 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3448 		bp->b_bcount = size;
3449 		bp->b_flags &= ~B_INVAL;
3450 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3451 		/*
3452 		 * Initialize our jseg with cnt records.  Assign the next
3453 		 * sequence number to it and link it in-order.
3454 		 */
3455 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3456 		jseg->js_buf = bp;
3457 		jseg->js_cnt = cnt;
3458 		jseg->js_refs = cnt + 1;	/* Self ref. */
3459 		jseg->js_size = size;
3460 		jseg->js_seq = jblocks->jb_nextseq++;
3461 		if (jblocks->jb_oldestseg == NULL)
3462 			jblocks->jb_oldestseg = jseg;
3463 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3464 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3465 		if (jblocks->jb_writeseg == NULL)
3466 			jblocks->jb_writeseg = jseg;
3467 		/*
3468 		 * Start filling in records from the pending list.
3469 		 */
3470 		data = bp->b_data;
3471 		off = 0;
3472 
3473 		/*
3474 		 * Always put a header on the first block.
3475 		 * XXX As with below, there might not be a chance to get
3476 		 * into the loop.  Ensure that something valid is written.
3477 		 */
3478 		jseg_write(ump, jseg, data);
3479 		off += JREC_SIZE;
3480 		data = bp->b_data + off;
3481 
3482 		/*
3483 		 * XXX Something is wrong here.  There's no work to do,
3484 		 * but we need to perform and I/O and allow it to complete
3485 		 * anyways.
3486 		 */
3487 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3488 			stat_emptyjblocks++;
3489 
3490 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3491 		    != NULL) {
3492 			if (cnt == 0)
3493 				break;
3494 			/* Place a segment header on every device block. */
3495 			if ((off % devbsize) == 0) {
3496 				jseg_write(ump, jseg, data);
3497 				off += JREC_SIZE;
3498 				data = bp->b_data + off;
3499 			}
3500 			if (wk == needwk)
3501 				needwk = NULL;
3502 			remove_from_journal(wk);
3503 			wk->wk_state |= INPROGRESS;
3504 			WORKLIST_INSERT(&jseg->js_entries, wk);
3505 			switch (wk->wk_type) {
3506 			case D_JADDREF:
3507 				jaddref_write(WK_JADDREF(wk), jseg, data);
3508 				break;
3509 			case D_JREMREF:
3510 				jremref_write(WK_JREMREF(wk), jseg, data);
3511 				break;
3512 			case D_JMVREF:
3513 				jmvref_write(WK_JMVREF(wk), jseg, data);
3514 				break;
3515 			case D_JNEWBLK:
3516 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3517 				break;
3518 			case D_JFREEBLK:
3519 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3520 				break;
3521 			case D_JFREEFRAG:
3522 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3523 				break;
3524 			case D_JTRUNC:
3525 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3526 				break;
3527 			case D_JFSYNC:
3528 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3529 				break;
3530 			default:
3531 				panic("process_journal: Unknown type %s",
3532 				    TYPENAME(wk->wk_type));
3533 				/* NOTREACHED */
3534 			}
3535 			off += JREC_SIZE;
3536 			data = bp->b_data + off;
3537 			cnt--;
3538 		}
3539 
3540 		/* Clear any remaining space so we don't leak kernel data */
3541 		if (size > off)
3542 			bzero(data, size - off);
3543 
3544 		/*
3545 		 * Write this one buffer and continue.
3546 		 */
3547 		segwritten = 1;
3548 		jblocks->jb_needseg = 0;
3549 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3550 		FREE_LOCK(ump);
3551 		pbgetvp(ump->um_devvp, bp);
3552 		/*
3553 		 * We only do the blocking wait once we find the journal
3554 		 * entry we're looking for.
3555 		 */
3556 		if (needwk == NULL && flags == MNT_WAIT)
3557 			bwrite(bp);
3558 		else
3559 			bawrite(bp);
3560 		ACQUIRE_LOCK(ump);
3561 	}
3562 	/*
3563 	 * If we wrote a segment issue a synchronize cache so the journal
3564 	 * is reflected on disk before the data is written.  Since reclaiming
3565 	 * journal space also requires writing a journal record this
3566 	 * process also enforces a barrier before reclamation.
3567 	 */
3568 	if (segwritten && shouldflush) {
3569 		softdep_synchronize(bio, ump,
3570 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3571 	} else if (bio)
3572 		g_destroy_bio(bio);
3573 	/*
3574 	 * If we've suspended the filesystem because we ran out of journal
3575 	 * space either try to sync it here to make some progress or
3576 	 * unsuspend it if we already have.
3577 	 */
3578 	if (flags == 0 && jblocks->jb_suspended) {
3579 		if (journal_unsuspend(ump))
3580 			return;
3581 		FREE_LOCK(ump);
3582 		VFS_SYNC(mp, MNT_NOWAIT);
3583 		ffs_sbupdate(ump, MNT_WAIT, 0);
3584 		ACQUIRE_LOCK(ump);
3585 	}
3586 }
3587 
3588 /*
3589  * Complete a jseg, allowing all dependencies awaiting journal writes
3590  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3591  * structures so that the journal segment can be freed to reclaim space.
3592  */
3593 static void
3594 complete_jseg(jseg)
3595 	struct jseg *jseg;
3596 {
3597 	struct worklist *wk;
3598 	struct jmvref *jmvref;
3599 	int waiting;
3600 #ifdef INVARIANTS
3601 	int i = 0;
3602 #endif
3603 
3604 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3605 		WORKLIST_REMOVE(wk);
3606 		waiting = wk->wk_state & IOWAITING;
3607 		wk->wk_state &= ~(INPROGRESS | IOWAITING);
3608 		wk->wk_state |= COMPLETE;
3609 		KASSERT(i++ < jseg->js_cnt,
3610 		    ("handle_written_jseg: overflow %d >= %d",
3611 		    i - 1, jseg->js_cnt));
3612 		switch (wk->wk_type) {
3613 		case D_JADDREF:
3614 			handle_written_jaddref(WK_JADDREF(wk));
3615 			break;
3616 		case D_JREMREF:
3617 			handle_written_jremref(WK_JREMREF(wk));
3618 			break;
3619 		case D_JMVREF:
3620 			rele_jseg(jseg);	/* No jsegdep. */
3621 			jmvref = WK_JMVREF(wk);
3622 			LIST_REMOVE(jmvref, jm_deps);
3623 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3624 				free_pagedep(jmvref->jm_pagedep);
3625 			WORKITEM_FREE(jmvref, D_JMVREF);
3626 			break;
3627 		case D_JNEWBLK:
3628 			handle_written_jnewblk(WK_JNEWBLK(wk));
3629 			break;
3630 		case D_JFREEBLK:
3631 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3632 			break;
3633 		case D_JTRUNC:
3634 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3635 			break;
3636 		case D_JFSYNC:
3637 			rele_jseg(jseg);	/* No jsegdep. */
3638 			WORKITEM_FREE(wk, D_JFSYNC);
3639 			break;
3640 		case D_JFREEFRAG:
3641 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3642 			break;
3643 		default:
3644 			panic("handle_written_jseg: Unknown type %s",
3645 			    TYPENAME(wk->wk_type));
3646 			/* NOTREACHED */
3647 		}
3648 		if (waiting)
3649 			wakeup(wk);
3650 	}
3651 	/* Release the self reference so the structure may be freed. */
3652 	rele_jseg(jseg);
3653 }
3654 
3655 /*
3656  * Determine which jsegs are ready for completion processing.  Waits for
3657  * synchronize cache to complete as well as forcing in-order completion
3658  * of journal entries.
3659  */
3660 static void
3661 complete_jsegs(jseg)
3662 	struct jseg *jseg;
3663 {
3664 	struct jblocks *jblocks;
3665 	struct jseg *jsegn;
3666 
3667 	jblocks = jseg->js_jblocks;
3668 	/*
3669 	 * Don't allow out of order completions.  If this isn't the first
3670 	 * block wait for it to write before we're done.
3671 	 */
3672 	if (jseg != jblocks->jb_writeseg)
3673 		return;
3674 	/* Iterate through available jsegs processing their entries. */
3675 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3676 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3677 		jsegn = TAILQ_NEXT(jseg, js_next);
3678 		complete_jseg(jseg);
3679 		jseg = jsegn;
3680 	}
3681 	jblocks->jb_writeseg = jseg;
3682 	/*
3683 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3684 	 */
3685 	free_jsegs(jblocks);
3686 }
3687 
3688 /*
3689  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3690  * the final completions.
3691  */
3692 static void
3693 handle_written_jseg(jseg, bp)
3694 	struct jseg *jseg;
3695 	struct buf *bp;
3696 {
3697 
3698 	if (jseg->js_refs == 0)
3699 		panic("handle_written_jseg: No self-reference on %p", jseg);
3700 	jseg->js_state |= DEPCOMPLETE;
3701 	/*
3702 	 * We'll never need this buffer again, set flags so it will be
3703 	 * discarded.
3704 	 */
3705 	bp->b_flags |= B_INVAL | B_NOCACHE;
3706 	pbrelvp(bp);
3707 	complete_jsegs(jseg);
3708 }
3709 
3710 static inline struct jsegdep *
3711 inoref_jseg(inoref)
3712 	struct inoref *inoref;
3713 {
3714 	struct jsegdep *jsegdep;
3715 
3716 	jsegdep = inoref->if_jsegdep;
3717 	inoref->if_jsegdep = NULL;
3718 
3719 	return (jsegdep);
3720 }
3721 
3722 /*
3723  * Called once a jremref has made it to stable store.  The jremref is marked
3724  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3725  * for the jremref to complete will be awoken by free_jremref.
3726  */
3727 static void
3728 handle_written_jremref(jremref)
3729 	struct jremref *jremref;
3730 {
3731 	struct inodedep *inodedep;
3732 	struct jsegdep *jsegdep;
3733 	struct dirrem *dirrem;
3734 
3735 	/* Grab the jsegdep. */
3736 	jsegdep = inoref_jseg(&jremref->jr_ref);
3737 	/*
3738 	 * Remove us from the inoref list.
3739 	 */
3740 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3741 	    0, &inodedep) == 0)
3742 		panic("handle_written_jremref: Lost inodedep");
3743 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3744 	/*
3745 	 * Complete the dirrem.
3746 	 */
3747 	dirrem = jremref->jr_dirrem;
3748 	jremref->jr_dirrem = NULL;
3749 	LIST_REMOVE(jremref, jr_deps);
3750 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3751 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3752 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3753 	    (dirrem->dm_state & COMPLETE) != 0)
3754 		add_to_worklist(&dirrem->dm_list, 0);
3755 	free_jremref(jremref);
3756 }
3757 
3758 /*
3759  * Called once a jaddref has made it to stable store.  The dependency is
3760  * marked complete and any dependent structures are added to the inode
3761  * bufwait list to be completed as soon as it is written.  If a bitmap write
3762  * depends on this entry we move the inode into the inodedephd of the
3763  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3764  */
3765 static void
3766 handle_written_jaddref(jaddref)
3767 	struct jaddref *jaddref;
3768 {
3769 	struct jsegdep *jsegdep;
3770 	struct inodedep *inodedep;
3771 	struct diradd *diradd;
3772 	struct mkdir *mkdir;
3773 
3774 	/* Grab the jsegdep. */
3775 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3776 	mkdir = NULL;
3777 	diradd = NULL;
3778 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3779 	    0, &inodedep) == 0)
3780 		panic("handle_written_jaddref: Lost inodedep.");
3781 	if (jaddref->ja_diradd == NULL)
3782 		panic("handle_written_jaddref: No dependency");
3783 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3784 		diradd = jaddref->ja_diradd;
3785 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3786 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3787 		mkdir = jaddref->ja_mkdir;
3788 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3789 	} else if (jaddref->ja_state & MKDIR_BODY)
3790 		mkdir = jaddref->ja_mkdir;
3791 	else
3792 		panic("handle_written_jaddref: Unknown dependency %p",
3793 		    jaddref->ja_diradd);
3794 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3795 	/*
3796 	 * Remove us from the inode list.
3797 	 */
3798 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3799 	/*
3800 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3801 	 */
3802 	if (mkdir) {
3803 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3804 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3805 		    TYPENAME(mkdir->md_list.wk_type)));
3806 		mkdir->md_jaddref = NULL;
3807 		diradd = mkdir->md_diradd;
3808 		mkdir->md_state |= DEPCOMPLETE;
3809 		complete_mkdir(mkdir);
3810 	}
3811 	jwork_insert(&diradd->da_jwork, jsegdep);
3812 	if (jaddref->ja_state & NEWBLOCK) {
3813 		inodedep->id_state |= ONDEPLIST;
3814 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3815 		    inodedep, id_deps);
3816 	}
3817 	free_jaddref(jaddref);
3818 }
3819 
3820 /*
3821  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3822  * is placed in the bmsafemap to await notification of a written bitmap.  If
3823  * the operation was canceled we add the segdep to the appropriate
3824  * dependency to free the journal space once the canceling operation
3825  * completes.
3826  */
3827 static void
3828 handle_written_jnewblk(jnewblk)
3829 	struct jnewblk *jnewblk;
3830 {
3831 	struct bmsafemap *bmsafemap;
3832 	struct freefrag *freefrag;
3833 	struct freework *freework;
3834 	struct jsegdep *jsegdep;
3835 	struct newblk *newblk;
3836 
3837 	/* Grab the jsegdep. */
3838 	jsegdep = jnewblk->jn_jsegdep;
3839 	jnewblk->jn_jsegdep = NULL;
3840 	if (jnewblk->jn_dep == NULL)
3841 		panic("handle_written_jnewblk: No dependency for the segdep.");
3842 	switch (jnewblk->jn_dep->wk_type) {
3843 	case D_NEWBLK:
3844 	case D_ALLOCDIRECT:
3845 	case D_ALLOCINDIR:
3846 		/*
3847 		 * Add the written block to the bmsafemap so it can
3848 		 * be notified when the bitmap is on disk.
3849 		 */
3850 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3851 		newblk->nb_jnewblk = NULL;
3852 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3853 			bmsafemap = newblk->nb_bmsafemap;
3854 			newblk->nb_state |= ONDEPLIST;
3855 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3856 			    nb_deps);
3857 		}
3858 		jwork_insert(&newblk->nb_jwork, jsegdep);
3859 		break;
3860 	case D_FREEFRAG:
3861 		/*
3862 		 * A newblock being removed by a freefrag when replaced by
3863 		 * frag extension.
3864 		 */
3865 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3866 		freefrag->ff_jdep = NULL;
3867 		jwork_insert(&freefrag->ff_jwork, jsegdep);
3868 		break;
3869 	case D_FREEWORK:
3870 		/*
3871 		 * A direct block was removed by truncate.
3872 		 */
3873 		freework = WK_FREEWORK(jnewblk->jn_dep);
3874 		freework->fw_jnewblk = NULL;
3875 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3876 		break;
3877 	default:
3878 		panic("handle_written_jnewblk: Unknown type %d.",
3879 		    jnewblk->jn_dep->wk_type);
3880 	}
3881 	jnewblk->jn_dep = NULL;
3882 	free_jnewblk(jnewblk);
3883 }
3884 
3885 /*
3886  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3887  * an in-flight allocation that has not yet been committed.  Divorce us
3888  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3889  * to the worklist.
3890  */
3891 static void
3892 cancel_jfreefrag(jfreefrag)
3893 	struct jfreefrag *jfreefrag;
3894 {
3895 	struct freefrag *freefrag;
3896 
3897 	if (jfreefrag->fr_jsegdep) {
3898 		free_jsegdep(jfreefrag->fr_jsegdep);
3899 		jfreefrag->fr_jsegdep = NULL;
3900 	}
3901 	freefrag = jfreefrag->fr_freefrag;
3902 	jfreefrag->fr_freefrag = NULL;
3903 	free_jfreefrag(jfreefrag);
3904 	freefrag->ff_state |= DEPCOMPLETE;
3905 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3906 }
3907 
3908 /*
3909  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3910  */
3911 static void
3912 free_jfreefrag(jfreefrag)
3913 	struct jfreefrag *jfreefrag;
3914 {
3915 
3916 	if (jfreefrag->fr_state & INPROGRESS)
3917 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3918 	else if (jfreefrag->fr_state & ONWORKLIST)
3919 		remove_from_journal(&jfreefrag->fr_list);
3920 	if (jfreefrag->fr_freefrag != NULL)
3921 		panic("free_jfreefrag:  Still attached to a freefrag.");
3922 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3923 }
3924 
3925 /*
3926  * Called when the journal write for a jfreefrag completes.  The parent
3927  * freefrag is added to the worklist if this completes its dependencies.
3928  */
3929 static void
3930 handle_written_jfreefrag(jfreefrag)
3931 	struct jfreefrag *jfreefrag;
3932 {
3933 	struct jsegdep *jsegdep;
3934 	struct freefrag *freefrag;
3935 
3936 	/* Grab the jsegdep. */
3937 	jsegdep = jfreefrag->fr_jsegdep;
3938 	jfreefrag->fr_jsegdep = NULL;
3939 	freefrag = jfreefrag->fr_freefrag;
3940 	if (freefrag == NULL)
3941 		panic("handle_written_jfreefrag: No freefrag.");
3942 	freefrag->ff_state |= DEPCOMPLETE;
3943 	freefrag->ff_jdep = NULL;
3944 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3945 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3946 		add_to_worklist(&freefrag->ff_list, 0);
3947 	jfreefrag->fr_freefrag = NULL;
3948 	free_jfreefrag(jfreefrag);
3949 }
3950 
3951 /*
3952  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3953  * is removed from the freeblks list of pending journal writes and the
3954  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3955  * have been reclaimed.
3956  */
3957 static void
3958 handle_written_jblkdep(jblkdep)
3959 	struct jblkdep *jblkdep;
3960 {
3961 	struct freeblks *freeblks;
3962 	struct jsegdep *jsegdep;
3963 
3964 	/* Grab the jsegdep. */
3965 	jsegdep = jblkdep->jb_jsegdep;
3966 	jblkdep->jb_jsegdep = NULL;
3967 	freeblks = jblkdep->jb_freeblks;
3968 	LIST_REMOVE(jblkdep, jb_deps);
3969 	jwork_insert(&freeblks->fb_jwork, jsegdep);
3970 	/*
3971 	 * If the freeblks is all journaled, we can add it to the worklist.
3972 	 */
3973 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3974 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3975 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3976 
3977 	free_jblkdep(jblkdep);
3978 }
3979 
3980 static struct jsegdep *
3981 newjsegdep(struct worklist *wk)
3982 {
3983 	struct jsegdep *jsegdep;
3984 
3985 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3986 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3987 	jsegdep->jd_seg = NULL;
3988 
3989 	return (jsegdep);
3990 }
3991 
3992 static struct jmvref *
3993 newjmvref(dp, ino, oldoff, newoff)
3994 	struct inode *dp;
3995 	ino_t ino;
3996 	off_t oldoff;
3997 	off_t newoff;
3998 {
3999 	struct jmvref *jmvref;
4000 
4001 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4002 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4003 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4004 	jmvref->jm_parent = dp->i_number;
4005 	jmvref->jm_ino = ino;
4006 	jmvref->jm_oldoff = oldoff;
4007 	jmvref->jm_newoff = newoff;
4008 
4009 	return (jmvref);
4010 }
4011 
4012 /*
4013  * Allocate a new jremref that tracks the removal of ip from dp with the
4014  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4015  * DEPCOMPLETE as we have all the information required for the journal write
4016  * and the directory has already been removed from the buffer.  The caller
4017  * is responsible for linking the jremref into the pagedep and adding it
4018  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4019  * a DOTDOT addition so handle_workitem_remove() can properly assign
4020  * the jsegdep when we're done.
4021  */
4022 static struct jremref *
4023 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4024     off_t diroff, nlink_t nlink)
4025 {
4026 	struct jremref *jremref;
4027 
4028 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4029 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4030 	jremref->jr_state = ATTACHED;
4031 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4032 	   nlink, ip->i_mode);
4033 	jremref->jr_dirrem = dirrem;
4034 
4035 	return (jremref);
4036 }
4037 
4038 static inline void
4039 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4040     nlink_t nlink, uint16_t mode)
4041 {
4042 
4043 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4044 	inoref->if_diroff = diroff;
4045 	inoref->if_ino = ino;
4046 	inoref->if_parent = parent;
4047 	inoref->if_nlink = nlink;
4048 	inoref->if_mode = mode;
4049 }
4050 
4051 /*
4052  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4053  * directory offset may not be known until later.  The caller is responsible
4054  * adding the entry to the journal when this information is available.  nlink
4055  * should be the link count prior to the addition and mode is only required
4056  * to have the correct FMT.
4057  */
4058 static struct jaddref *
4059 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4060     uint16_t mode)
4061 {
4062 	struct jaddref *jaddref;
4063 
4064 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4065 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4066 	jaddref->ja_state = ATTACHED;
4067 	jaddref->ja_mkdir = NULL;
4068 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4069 
4070 	return (jaddref);
4071 }
4072 
4073 /*
4074  * Create a new free dependency for a freework.  The caller is responsible
4075  * for adjusting the reference count when it has the lock held.  The freedep
4076  * will track an outstanding bitmap write that will ultimately clear the
4077  * freework to continue.
4078  */
4079 static struct freedep *
4080 newfreedep(struct freework *freework)
4081 {
4082 	struct freedep *freedep;
4083 
4084 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4085 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4086 	freedep->fd_freework = freework;
4087 
4088 	return (freedep);
4089 }
4090 
4091 /*
4092  * Free a freedep structure once the buffer it is linked to is written.  If
4093  * this is the last reference to the freework schedule it for completion.
4094  */
4095 static void
4096 free_freedep(freedep)
4097 	struct freedep *freedep;
4098 {
4099 	struct freework *freework;
4100 
4101 	freework = freedep->fd_freework;
4102 	freework->fw_freeblks->fb_cgwait--;
4103 	if (--freework->fw_ref == 0)
4104 		freework_enqueue(freework);
4105 	WORKITEM_FREE(freedep, D_FREEDEP);
4106 }
4107 
4108 /*
4109  * Allocate a new freework structure that may be a level in an indirect
4110  * when parent is not NULL or a top level block when it is.  The top level
4111  * freework structures are allocated without the per-filesystem lock held
4112  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4113  */
4114 static struct freework *
4115 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4116 	struct ufsmount *ump;
4117 	struct freeblks *freeblks;
4118 	struct freework *parent;
4119 	ufs_lbn_t lbn;
4120 	ufs2_daddr_t nb;
4121 	int frags;
4122 	int off;
4123 	int journal;
4124 {
4125 	struct freework *freework;
4126 
4127 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4128 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4129 	freework->fw_state = ATTACHED;
4130 	freework->fw_jnewblk = NULL;
4131 	freework->fw_freeblks = freeblks;
4132 	freework->fw_parent = parent;
4133 	freework->fw_lbn = lbn;
4134 	freework->fw_blkno = nb;
4135 	freework->fw_frags = frags;
4136 	freework->fw_indir = NULL;
4137 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4138 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4139 	freework->fw_start = freework->fw_off = off;
4140 	if (journal)
4141 		newjfreeblk(freeblks, lbn, nb, frags);
4142 	if (parent == NULL) {
4143 		ACQUIRE_LOCK(ump);
4144 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4145 		freeblks->fb_ref++;
4146 		FREE_LOCK(ump);
4147 	}
4148 
4149 	return (freework);
4150 }
4151 
4152 /*
4153  * Eliminate a jfreeblk for a block that does not need journaling.
4154  */
4155 static void
4156 cancel_jfreeblk(freeblks, blkno)
4157 	struct freeblks *freeblks;
4158 	ufs2_daddr_t blkno;
4159 {
4160 	struct jfreeblk *jfreeblk;
4161 	struct jblkdep *jblkdep;
4162 
4163 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4164 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4165 			continue;
4166 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4167 		if (jfreeblk->jf_blkno == blkno)
4168 			break;
4169 	}
4170 	if (jblkdep == NULL)
4171 		return;
4172 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4173 	free_jsegdep(jblkdep->jb_jsegdep);
4174 	LIST_REMOVE(jblkdep, jb_deps);
4175 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4176 }
4177 
4178 /*
4179  * Allocate a new jfreeblk to journal top level block pointer when truncating
4180  * a file.  The caller must add this to the worklist when the per-filesystem
4181  * lock is held.
4182  */
4183 static struct jfreeblk *
4184 newjfreeblk(freeblks, lbn, blkno, frags)
4185 	struct freeblks *freeblks;
4186 	ufs_lbn_t lbn;
4187 	ufs2_daddr_t blkno;
4188 	int frags;
4189 {
4190 	struct jfreeblk *jfreeblk;
4191 
4192 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4193 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4194 	    freeblks->fb_list.wk_mp);
4195 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4196 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4197 	jfreeblk->jf_ino = freeblks->fb_inum;
4198 	jfreeblk->jf_lbn = lbn;
4199 	jfreeblk->jf_blkno = blkno;
4200 	jfreeblk->jf_frags = frags;
4201 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4202 
4203 	return (jfreeblk);
4204 }
4205 
4206 /*
4207  * The journal is only prepared to handle full-size block numbers, so we
4208  * have to adjust the record to reflect the change to a full-size block.
4209  * For example, suppose we have a block made up of fragments 8-15 and
4210  * want to free its last two fragments. We are given a request that says:
4211  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4212  * where frags are the number of fragments to free and oldfrags are the
4213  * number of fragments to keep. To block align it, we have to change it to
4214  * have a valid full-size blkno, so it becomes:
4215  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4216  */
4217 static void
4218 adjust_newfreework(freeblks, frag_offset)
4219 	struct freeblks *freeblks;
4220 	int frag_offset;
4221 {
4222 	struct jfreeblk *jfreeblk;
4223 
4224 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4225 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4226 	    ("adjust_newfreework: Missing freeblks dependency"));
4227 
4228 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4229 	jfreeblk->jf_blkno -= frag_offset;
4230 	jfreeblk->jf_frags += frag_offset;
4231 }
4232 
4233 /*
4234  * Allocate a new jtrunc to track a partial truncation.
4235  */
4236 static struct jtrunc *
4237 newjtrunc(freeblks, size, extsize)
4238 	struct freeblks *freeblks;
4239 	off_t size;
4240 	int extsize;
4241 {
4242 	struct jtrunc *jtrunc;
4243 
4244 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4245 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4246 	    freeblks->fb_list.wk_mp);
4247 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4248 	jtrunc->jt_dep.jb_freeblks = freeblks;
4249 	jtrunc->jt_ino = freeblks->fb_inum;
4250 	jtrunc->jt_size = size;
4251 	jtrunc->jt_extsize = extsize;
4252 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4253 
4254 	return (jtrunc);
4255 }
4256 
4257 /*
4258  * If we're canceling a new bitmap we have to search for another ref
4259  * to move into the bmsafemap dep.  This might be better expressed
4260  * with another structure.
4261  */
4262 static void
4263 move_newblock_dep(jaddref, inodedep)
4264 	struct jaddref *jaddref;
4265 	struct inodedep *inodedep;
4266 {
4267 	struct inoref *inoref;
4268 	struct jaddref *jaddrefn;
4269 
4270 	jaddrefn = NULL;
4271 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4272 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4273 		if ((jaddref->ja_state & NEWBLOCK) &&
4274 		    inoref->if_list.wk_type == D_JADDREF) {
4275 			jaddrefn = (struct jaddref *)inoref;
4276 			break;
4277 		}
4278 	}
4279 	if (jaddrefn == NULL)
4280 		return;
4281 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4282 	jaddrefn->ja_state |= jaddref->ja_state &
4283 	    (ATTACHED | UNDONE | NEWBLOCK);
4284 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4285 	jaddref->ja_state |= ATTACHED;
4286 	LIST_REMOVE(jaddref, ja_bmdeps);
4287 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4288 	    ja_bmdeps);
4289 }
4290 
4291 /*
4292  * Cancel a jaddref either before it has been written or while it is being
4293  * written.  This happens when a link is removed before the add reaches
4294  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4295  * and inode to prevent the link count or bitmap from reaching the disk
4296  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4297  * required.
4298  *
4299  * Returns 1 if the canceled addref requires journaling of the remove and
4300  * 0 otherwise.
4301  */
4302 static int
4303 cancel_jaddref(jaddref, inodedep, wkhd)
4304 	struct jaddref *jaddref;
4305 	struct inodedep *inodedep;
4306 	struct workhead *wkhd;
4307 {
4308 	struct inoref *inoref;
4309 	struct jsegdep *jsegdep;
4310 	int needsj;
4311 
4312 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4313 	    ("cancel_jaddref: Canceling complete jaddref"));
4314 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4315 		needsj = 1;
4316 	else
4317 		needsj = 0;
4318 	if (inodedep == NULL)
4319 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4320 		    0, &inodedep) == 0)
4321 			panic("cancel_jaddref: Lost inodedep");
4322 	/*
4323 	 * We must adjust the nlink of any reference operation that follows
4324 	 * us so that it is consistent with the in-memory reference.  This
4325 	 * ensures that inode nlink rollbacks always have the correct link.
4326 	 */
4327 	if (needsj == 0) {
4328 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4329 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4330 			if (inoref->if_state & GOINGAWAY)
4331 				break;
4332 			inoref->if_nlink--;
4333 		}
4334 	}
4335 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4336 	if (jaddref->ja_state & NEWBLOCK)
4337 		move_newblock_dep(jaddref, inodedep);
4338 	wake_worklist(&jaddref->ja_list);
4339 	jaddref->ja_mkdir = NULL;
4340 	if (jaddref->ja_state & INPROGRESS) {
4341 		jaddref->ja_state &= ~INPROGRESS;
4342 		WORKLIST_REMOVE(&jaddref->ja_list);
4343 		jwork_insert(wkhd, jsegdep);
4344 	} else {
4345 		free_jsegdep(jsegdep);
4346 		if (jaddref->ja_state & DEPCOMPLETE)
4347 			remove_from_journal(&jaddref->ja_list);
4348 	}
4349 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4350 	/*
4351 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4352 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4353 	 * no longer need this addref attached to the inoreflst and it
4354 	 * will incorrectly adjust nlink if we leave it.
4355 	 */
4356 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4357 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4358 		    if_deps);
4359 		jaddref->ja_state |= COMPLETE;
4360 		free_jaddref(jaddref);
4361 		return (needsj);
4362 	}
4363 	/*
4364 	 * Leave the head of the list for jsegdeps for fast merging.
4365 	 */
4366 	if (LIST_FIRST(wkhd) != NULL) {
4367 		jaddref->ja_state |= ONWORKLIST;
4368 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4369 	} else
4370 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4371 
4372 	return (needsj);
4373 }
4374 
4375 /*
4376  * Attempt to free a jaddref structure when some work completes.  This
4377  * should only succeed once the entry is written and all dependencies have
4378  * been notified.
4379  */
4380 static void
4381 free_jaddref(jaddref)
4382 	struct jaddref *jaddref;
4383 {
4384 
4385 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4386 		return;
4387 	if (jaddref->ja_ref.if_jsegdep)
4388 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4389 		    jaddref, jaddref->ja_state);
4390 	if (jaddref->ja_state & NEWBLOCK)
4391 		LIST_REMOVE(jaddref, ja_bmdeps);
4392 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4393 		panic("free_jaddref: Bad state %p(0x%X)",
4394 		    jaddref, jaddref->ja_state);
4395 	if (jaddref->ja_mkdir != NULL)
4396 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4397 	WORKITEM_FREE(jaddref, D_JADDREF);
4398 }
4399 
4400 /*
4401  * Free a jremref structure once it has been written or discarded.
4402  */
4403 static void
4404 free_jremref(jremref)
4405 	struct jremref *jremref;
4406 {
4407 
4408 	if (jremref->jr_ref.if_jsegdep)
4409 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4410 	if (jremref->jr_state & INPROGRESS)
4411 		panic("free_jremref: IO still pending");
4412 	WORKITEM_FREE(jremref, D_JREMREF);
4413 }
4414 
4415 /*
4416  * Free a jnewblk structure.
4417  */
4418 static void
4419 free_jnewblk(jnewblk)
4420 	struct jnewblk *jnewblk;
4421 {
4422 
4423 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4424 		return;
4425 	LIST_REMOVE(jnewblk, jn_deps);
4426 	if (jnewblk->jn_dep != NULL)
4427 		panic("free_jnewblk: Dependency still attached.");
4428 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4429 }
4430 
4431 /*
4432  * Cancel a jnewblk which has been been made redundant by frag extension.
4433  */
4434 static void
4435 cancel_jnewblk(jnewblk, wkhd)
4436 	struct jnewblk *jnewblk;
4437 	struct workhead *wkhd;
4438 {
4439 	struct jsegdep *jsegdep;
4440 
4441 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4442 	jsegdep = jnewblk->jn_jsegdep;
4443 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4444 		panic("cancel_jnewblk: Invalid state");
4445 	jnewblk->jn_jsegdep  = NULL;
4446 	jnewblk->jn_dep = NULL;
4447 	jnewblk->jn_state |= GOINGAWAY;
4448 	if (jnewblk->jn_state & INPROGRESS) {
4449 		jnewblk->jn_state &= ~INPROGRESS;
4450 		WORKLIST_REMOVE(&jnewblk->jn_list);
4451 		jwork_insert(wkhd, jsegdep);
4452 	} else {
4453 		free_jsegdep(jsegdep);
4454 		remove_from_journal(&jnewblk->jn_list);
4455 	}
4456 	wake_worklist(&jnewblk->jn_list);
4457 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4458 }
4459 
4460 static void
4461 free_jblkdep(jblkdep)
4462 	struct jblkdep *jblkdep;
4463 {
4464 
4465 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4466 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4467 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4468 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4469 	else
4470 		panic("free_jblkdep: Unexpected type %s",
4471 		    TYPENAME(jblkdep->jb_list.wk_type));
4472 }
4473 
4474 /*
4475  * Free a single jseg once it is no longer referenced in memory or on
4476  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4477  * to disappear.
4478  */
4479 static void
4480 free_jseg(jseg, jblocks)
4481 	struct jseg *jseg;
4482 	struct jblocks *jblocks;
4483 {
4484 	struct freework *freework;
4485 
4486 	/*
4487 	 * Free freework structures that were lingering to indicate freed
4488 	 * indirect blocks that forced journal write ordering on reallocate.
4489 	 */
4490 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4491 		indirblk_remove(freework);
4492 	if (jblocks->jb_oldestseg == jseg)
4493 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4494 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4495 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4496 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4497 	    ("free_jseg: Freed jseg has valid entries."));
4498 	WORKITEM_FREE(jseg, D_JSEG);
4499 }
4500 
4501 /*
4502  * Free all jsegs that meet the criteria for being reclaimed and update
4503  * oldestseg.
4504  */
4505 static void
4506 free_jsegs(jblocks)
4507 	struct jblocks *jblocks;
4508 {
4509 	struct jseg *jseg;
4510 
4511 	/*
4512 	 * Free only those jsegs which have none allocated before them to
4513 	 * preserve the journal space ordering.
4514 	 */
4515 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4516 		/*
4517 		 * Only reclaim space when nothing depends on this journal
4518 		 * set and another set has written that it is no longer
4519 		 * valid.
4520 		 */
4521 		if (jseg->js_refs != 0) {
4522 			jblocks->jb_oldestseg = jseg;
4523 			return;
4524 		}
4525 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4526 			break;
4527 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4528 			break;
4529 		/*
4530 		 * We can free jsegs that didn't write entries when
4531 		 * oldestwrseq == js_seq.
4532 		 */
4533 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4534 		    jseg->js_cnt != 0)
4535 			break;
4536 		free_jseg(jseg, jblocks);
4537 	}
4538 	/*
4539 	 * If we exited the loop above we still must discover the
4540 	 * oldest valid segment.
4541 	 */
4542 	if (jseg)
4543 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4544 		     jseg = TAILQ_NEXT(jseg, js_next))
4545 			if (jseg->js_refs != 0)
4546 				break;
4547 	jblocks->jb_oldestseg = jseg;
4548 	/*
4549 	 * The journal has no valid records but some jsegs may still be
4550 	 * waiting on oldestwrseq to advance.  We force a small record
4551 	 * out to permit these lingering records to be reclaimed.
4552 	 */
4553 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4554 		jblocks->jb_needseg = 1;
4555 }
4556 
4557 /*
4558  * Release one reference to a jseg and free it if the count reaches 0.  This
4559  * should eventually reclaim journal space as well.
4560  */
4561 static void
4562 rele_jseg(jseg)
4563 	struct jseg *jseg;
4564 {
4565 
4566 	KASSERT(jseg->js_refs > 0,
4567 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4568 	if (--jseg->js_refs != 0)
4569 		return;
4570 	free_jsegs(jseg->js_jblocks);
4571 }
4572 
4573 /*
4574  * Release a jsegdep and decrement the jseg count.
4575  */
4576 static void
4577 free_jsegdep(jsegdep)
4578 	struct jsegdep *jsegdep;
4579 {
4580 
4581 	if (jsegdep->jd_seg)
4582 		rele_jseg(jsegdep->jd_seg);
4583 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4584 }
4585 
4586 /*
4587  * Wait for a journal item to make it to disk.  Initiate journal processing
4588  * if required.
4589  */
4590 static int
4591 jwait(wk, waitfor)
4592 	struct worklist *wk;
4593 	int waitfor;
4594 {
4595 
4596 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4597 	/*
4598 	 * Blocking journal waits cause slow synchronous behavior.  Record
4599 	 * stats on the frequency of these blocking operations.
4600 	 */
4601 	if (waitfor == MNT_WAIT) {
4602 		stat_journal_wait++;
4603 		switch (wk->wk_type) {
4604 		case D_JREMREF:
4605 		case D_JMVREF:
4606 			stat_jwait_filepage++;
4607 			break;
4608 		case D_JTRUNC:
4609 		case D_JFREEBLK:
4610 			stat_jwait_freeblks++;
4611 			break;
4612 		case D_JNEWBLK:
4613 			stat_jwait_newblk++;
4614 			break;
4615 		case D_JADDREF:
4616 			stat_jwait_inode++;
4617 			break;
4618 		default:
4619 			break;
4620 		}
4621 	}
4622 	/*
4623 	 * If IO has not started we process the journal.  We can't mark the
4624 	 * worklist item as IOWAITING because we drop the lock while
4625 	 * processing the journal and the worklist entry may be freed after
4626 	 * this point.  The caller may call back in and re-issue the request.
4627 	 */
4628 	if ((wk->wk_state & INPROGRESS) == 0) {
4629 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4630 		if (waitfor != MNT_WAIT)
4631 			return (EBUSY);
4632 		return (0);
4633 	}
4634 	if (waitfor != MNT_WAIT)
4635 		return (EBUSY);
4636 	wait_worklist(wk, "jwait");
4637 	return (0);
4638 }
4639 
4640 /*
4641  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4642  * appropriate.  This is a convenience function to reduce duplicate code
4643  * for the setup and revert functions below.
4644  */
4645 static struct inodedep *
4646 inodedep_lookup_ip(ip)
4647 	struct inode *ip;
4648 {
4649 	struct inodedep *inodedep;
4650 
4651 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4652 	    ("inodedep_lookup_ip: bad delta"));
4653 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4654 	    &inodedep);
4655 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4656 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4657 
4658 	return (inodedep);
4659 }
4660 
4661 /*
4662  * Called prior to creating a new inode and linking it to a directory.  The
4663  * jaddref structure must already be allocated by softdep_setup_inomapdep
4664  * and it is discovered here so we can initialize the mode and update
4665  * nlinkdelta.
4666  */
4667 void
4668 softdep_setup_create(dp, ip)
4669 	struct inode *dp;
4670 	struct inode *ip;
4671 {
4672 	struct inodedep *inodedep;
4673 	struct jaddref *jaddref;
4674 	struct vnode *dvp;
4675 
4676 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4677 	    ("softdep_setup_create called on non-softdep filesystem"));
4678 	KASSERT(ip->i_nlink == 1,
4679 	    ("softdep_setup_create: Invalid link count."));
4680 	dvp = ITOV(dp);
4681 	ACQUIRE_LOCK(ITOUMP(dp));
4682 	inodedep = inodedep_lookup_ip(ip);
4683 	if (DOINGSUJ(dvp)) {
4684 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4685 		    inoreflst);
4686 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4687 		    ("softdep_setup_create: No addref structure present."));
4688 	}
4689 	softdep_prelink(dvp, NULL);
4690 	FREE_LOCK(ITOUMP(dp));
4691 }
4692 
4693 /*
4694  * Create a jaddref structure to track the addition of a DOTDOT link when
4695  * we are reparenting an inode as part of a rename.  This jaddref will be
4696  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4697  * non-journaling softdep.
4698  */
4699 void
4700 softdep_setup_dotdot_link(dp, ip)
4701 	struct inode *dp;
4702 	struct inode *ip;
4703 {
4704 	struct inodedep *inodedep;
4705 	struct jaddref *jaddref;
4706 	struct vnode *dvp;
4707 
4708 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4709 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4710 	dvp = ITOV(dp);
4711 	jaddref = NULL;
4712 	/*
4713 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4714 	 * is used as a normal link would be.
4715 	 */
4716 	if (DOINGSUJ(dvp))
4717 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4718 		    dp->i_effnlink - 1, dp->i_mode);
4719 	ACQUIRE_LOCK(ITOUMP(dp));
4720 	inodedep = inodedep_lookup_ip(dp);
4721 	if (jaddref)
4722 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4723 		    if_deps);
4724 	softdep_prelink(dvp, ITOV(ip));
4725 	FREE_LOCK(ITOUMP(dp));
4726 }
4727 
4728 /*
4729  * Create a jaddref structure to track a new link to an inode.  The directory
4730  * offset is not known until softdep_setup_directory_add or
4731  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4732  * softdep.
4733  */
4734 void
4735 softdep_setup_link(dp, ip)
4736 	struct inode *dp;
4737 	struct inode *ip;
4738 {
4739 	struct inodedep *inodedep;
4740 	struct jaddref *jaddref;
4741 	struct vnode *dvp;
4742 
4743 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4744 	    ("softdep_setup_link called on non-softdep filesystem"));
4745 	dvp = ITOV(dp);
4746 	jaddref = NULL;
4747 	if (DOINGSUJ(dvp))
4748 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4749 		    ip->i_mode);
4750 	ACQUIRE_LOCK(ITOUMP(dp));
4751 	inodedep = inodedep_lookup_ip(ip);
4752 	if (jaddref)
4753 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4754 		    if_deps);
4755 	softdep_prelink(dvp, ITOV(ip));
4756 	FREE_LOCK(ITOUMP(dp));
4757 }
4758 
4759 /*
4760  * Called to create the jaddref structures to track . and .. references as
4761  * well as lookup and further initialize the incomplete jaddref created
4762  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4763  * nlinkdelta for non-journaling softdep.
4764  */
4765 void
4766 softdep_setup_mkdir(dp, ip)
4767 	struct inode *dp;
4768 	struct inode *ip;
4769 {
4770 	struct inodedep *inodedep;
4771 	struct jaddref *dotdotaddref;
4772 	struct jaddref *dotaddref;
4773 	struct jaddref *jaddref;
4774 	struct vnode *dvp;
4775 
4776 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4777 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
4778 	dvp = ITOV(dp);
4779 	dotaddref = dotdotaddref = NULL;
4780 	if (DOINGSUJ(dvp)) {
4781 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4782 		    ip->i_mode);
4783 		dotaddref->ja_state |= MKDIR_BODY;
4784 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4785 		    dp->i_effnlink - 1, dp->i_mode);
4786 		dotdotaddref->ja_state |= MKDIR_PARENT;
4787 	}
4788 	ACQUIRE_LOCK(ITOUMP(dp));
4789 	inodedep = inodedep_lookup_ip(ip);
4790 	if (DOINGSUJ(dvp)) {
4791 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4792 		    inoreflst);
4793 		KASSERT(jaddref != NULL,
4794 		    ("softdep_setup_mkdir: No addref structure present."));
4795 		KASSERT(jaddref->ja_parent == dp->i_number,
4796 		    ("softdep_setup_mkdir: bad parent %ju",
4797 		    (uintmax_t)jaddref->ja_parent));
4798 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4799 		    if_deps);
4800 	}
4801 	inodedep = inodedep_lookup_ip(dp);
4802 	if (DOINGSUJ(dvp))
4803 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4804 		    &dotdotaddref->ja_ref, if_deps);
4805 	softdep_prelink(ITOV(dp), NULL);
4806 	FREE_LOCK(ITOUMP(dp));
4807 }
4808 
4809 /*
4810  * Called to track nlinkdelta of the inode and parent directories prior to
4811  * unlinking a directory.
4812  */
4813 void
4814 softdep_setup_rmdir(dp, ip)
4815 	struct inode *dp;
4816 	struct inode *ip;
4817 {
4818 	struct vnode *dvp;
4819 
4820 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4821 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4822 	dvp = ITOV(dp);
4823 	ACQUIRE_LOCK(ITOUMP(dp));
4824 	(void) inodedep_lookup_ip(ip);
4825 	(void) inodedep_lookup_ip(dp);
4826 	softdep_prelink(dvp, ITOV(ip));
4827 	FREE_LOCK(ITOUMP(dp));
4828 }
4829 
4830 /*
4831  * Called to track nlinkdelta of the inode and parent directories prior to
4832  * unlink.
4833  */
4834 void
4835 softdep_setup_unlink(dp, ip)
4836 	struct inode *dp;
4837 	struct inode *ip;
4838 {
4839 	struct vnode *dvp;
4840 
4841 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4842 	    ("softdep_setup_unlink called on non-softdep filesystem"));
4843 	dvp = ITOV(dp);
4844 	ACQUIRE_LOCK(ITOUMP(dp));
4845 	(void) inodedep_lookup_ip(ip);
4846 	(void) inodedep_lookup_ip(dp);
4847 	softdep_prelink(dvp, ITOV(ip));
4848 	FREE_LOCK(ITOUMP(dp));
4849 }
4850 
4851 /*
4852  * Called to release the journal structures created by a failed non-directory
4853  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4854  */
4855 void
4856 softdep_revert_create(dp, ip)
4857 	struct inode *dp;
4858 	struct inode *ip;
4859 {
4860 	struct inodedep *inodedep;
4861 	struct jaddref *jaddref;
4862 	struct vnode *dvp;
4863 
4864 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4865 	    ("softdep_revert_create called on non-softdep filesystem"));
4866 	dvp = ITOV(dp);
4867 	ACQUIRE_LOCK(ITOUMP(dp));
4868 	inodedep = inodedep_lookup_ip(ip);
4869 	if (DOINGSUJ(dvp)) {
4870 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4871 		    inoreflst);
4872 		KASSERT(jaddref->ja_parent == dp->i_number,
4873 		    ("softdep_revert_create: addref parent mismatch"));
4874 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4875 	}
4876 	FREE_LOCK(ITOUMP(dp));
4877 }
4878 
4879 /*
4880  * Called to release the journal structures created by a failed link
4881  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4882  */
4883 void
4884 softdep_revert_link(dp, ip)
4885 	struct inode *dp;
4886 	struct inode *ip;
4887 {
4888 	struct inodedep *inodedep;
4889 	struct jaddref *jaddref;
4890 	struct vnode *dvp;
4891 
4892 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4893 	    ("softdep_revert_link called on non-softdep filesystem"));
4894 	dvp = ITOV(dp);
4895 	ACQUIRE_LOCK(ITOUMP(dp));
4896 	inodedep = inodedep_lookup_ip(ip);
4897 	if (DOINGSUJ(dvp)) {
4898 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4899 		    inoreflst);
4900 		KASSERT(jaddref->ja_parent == dp->i_number,
4901 		    ("softdep_revert_link: addref parent mismatch"));
4902 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4903 	}
4904 	FREE_LOCK(ITOUMP(dp));
4905 }
4906 
4907 /*
4908  * Called to release the journal structures created by a failed mkdir
4909  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4910  */
4911 void
4912 softdep_revert_mkdir(dp, ip)
4913 	struct inode *dp;
4914 	struct inode *ip;
4915 {
4916 	struct inodedep *inodedep;
4917 	struct jaddref *jaddref;
4918 	struct jaddref *dotaddref;
4919 	struct vnode *dvp;
4920 
4921 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4922 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4923 	dvp = ITOV(dp);
4924 
4925 	ACQUIRE_LOCK(ITOUMP(dp));
4926 	inodedep = inodedep_lookup_ip(dp);
4927 	if (DOINGSUJ(dvp)) {
4928 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4929 		    inoreflst);
4930 		KASSERT(jaddref->ja_parent == ip->i_number,
4931 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4932 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4933 	}
4934 	inodedep = inodedep_lookup_ip(ip);
4935 	if (DOINGSUJ(dvp)) {
4936 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4937 		    inoreflst);
4938 		KASSERT(jaddref->ja_parent == dp->i_number,
4939 		    ("softdep_revert_mkdir: addref parent mismatch"));
4940 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4941 		    inoreflst, if_deps);
4942 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4943 		KASSERT(dotaddref->ja_parent == ip->i_number,
4944 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4945 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4946 	}
4947 	FREE_LOCK(ITOUMP(dp));
4948 }
4949 
4950 /*
4951  * Called to correct nlinkdelta after a failed rmdir.
4952  */
4953 void
4954 softdep_revert_rmdir(dp, ip)
4955 	struct inode *dp;
4956 	struct inode *ip;
4957 {
4958 
4959 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4960 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
4961 	ACQUIRE_LOCK(ITOUMP(dp));
4962 	(void) inodedep_lookup_ip(ip);
4963 	(void) inodedep_lookup_ip(dp);
4964 	FREE_LOCK(ITOUMP(dp));
4965 }
4966 
4967 /*
4968  * Protecting the freemaps (or bitmaps).
4969  *
4970  * To eliminate the need to execute fsck before mounting a filesystem
4971  * after a power failure, one must (conservatively) guarantee that the
4972  * on-disk copy of the bitmaps never indicate that a live inode or block is
4973  * free.  So, when a block or inode is allocated, the bitmap should be
4974  * updated (on disk) before any new pointers.  When a block or inode is
4975  * freed, the bitmap should not be updated until all pointers have been
4976  * reset.  The latter dependency is handled by the delayed de-allocation
4977  * approach described below for block and inode de-allocation.  The former
4978  * dependency is handled by calling the following procedure when a block or
4979  * inode is allocated. When an inode is allocated an "inodedep" is created
4980  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4981  * Each "inodedep" is also inserted into the hash indexing structure so
4982  * that any additional link additions can be made dependent on the inode
4983  * allocation.
4984  *
4985  * The ufs filesystem maintains a number of free block counts (e.g., per
4986  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4987  * in addition to the bitmaps.  These counts are used to improve efficiency
4988  * during allocation and therefore must be consistent with the bitmaps.
4989  * There is no convenient way to guarantee post-crash consistency of these
4990  * counts with simple update ordering, for two main reasons: (1) The counts
4991  * and bitmaps for a single cylinder group block are not in the same disk
4992  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4993  * be written and the other not.  (2) Some of the counts are located in the
4994  * superblock rather than the cylinder group block. So, we focus our soft
4995  * updates implementation on protecting the bitmaps. When mounting a
4996  * filesystem, we recompute the auxiliary counts from the bitmaps.
4997  */
4998 
4999 /*
5000  * Called just after updating the cylinder group block to allocate an inode.
5001  */
5002 void
5003 softdep_setup_inomapdep(bp, ip, newinum, mode)
5004 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5005 	struct inode *ip;	/* inode related to allocation */
5006 	ino_t newinum;		/* new inode number being allocated */
5007 	int mode;
5008 {
5009 	struct inodedep *inodedep;
5010 	struct bmsafemap *bmsafemap;
5011 	struct jaddref *jaddref;
5012 	struct mount *mp;
5013 	struct fs *fs;
5014 
5015 	mp = ITOVFS(ip);
5016 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5017 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5018 	fs = VFSTOUFS(mp)->um_fs;
5019 	jaddref = NULL;
5020 
5021 	/*
5022 	 * Allocate the journal reference add structure so that the bitmap
5023 	 * can be dependent on it.
5024 	 */
5025 	if (MOUNTEDSUJ(mp)) {
5026 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5027 		jaddref->ja_state |= NEWBLOCK;
5028 	}
5029 
5030 	/*
5031 	 * Create a dependency for the newly allocated inode.
5032 	 * Panic if it already exists as something is seriously wrong.
5033 	 * Otherwise add it to the dependency list for the buffer holding
5034 	 * the cylinder group map from which it was allocated.
5035 	 *
5036 	 * We have to preallocate a bmsafemap entry in case it is needed
5037 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5038 	 * have to finish initializing it before we can FREE_LOCK().
5039 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5040 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5041 	 * creating the inodedep as it can be freed during the time
5042 	 * that we FREE_LOCK() while allocating the inodedep. We must
5043 	 * call workitem_alloc() before entering the locked section as
5044 	 * it also acquires the lock and we must avoid trying doing so
5045 	 * recursively.
5046 	 */
5047 	bmsafemap = malloc(sizeof(struct bmsafemap),
5048 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5049 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5050 	ACQUIRE_LOCK(ITOUMP(ip));
5051 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5052 		panic("softdep_setup_inomapdep: dependency %p for new"
5053 		    "inode already exists", inodedep);
5054 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5055 	if (jaddref) {
5056 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5057 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5058 		    if_deps);
5059 	} else {
5060 		inodedep->id_state |= ONDEPLIST;
5061 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5062 	}
5063 	inodedep->id_bmsafemap = bmsafemap;
5064 	inodedep->id_state &= ~DEPCOMPLETE;
5065 	FREE_LOCK(ITOUMP(ip));
5066 }
5067 
5068 /*
5069  * Called just after updating the cylinder group block to
5070  * allocate block or fragment.
5071  */
5072 void
5073 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5074 	struct buf *bp;		/* buffer for cylgroup block with block map */
5075 	struct mount *mp;	/* filesystem doing allocation */
5076 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5077 	int frags;		/* Number of fragments. */
5078 	int oldfrags;		/* Previous number of fragments for extend. */
5079 {
5080 	struct newblk *newblk;
5081 	struct bmsafemap *bmsafemap;
5082 	struct jnewblk *jnewblk;
5083 	struct ufsmount *ump;
5084 	struct fs *fs;
5085 
5086 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5087 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5088 	ump = VFSTOUFS(mp);
5089 	fs = ump->um_fs;
5090 	jnewblk = NULL;
5091 	/*
5092 	 * Create a dependency for the newly allocated block.
5093 	 * Add it to the dependency list for the buffer holding
5094 	 * the cylinder group map from which it was allocated.
5095 	 */
5096 	if (MOUNTEDSUJ(mp)) {
5097 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5098 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5099 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5100 		jnewblk->jn_state = ATTACHED;
5101 		jnewblk->jn_blkno = newblkno;
5102 		jnewblk->jn_frags = frags;
5103 		jnewblk->jn_oldfrags = oldfrags;
5104 #ifdef SUJ_DEBUG
5105 		{
5106 			struct cg *cgp;
5107 			uint8_t *blksfree;
5108 			long bno;
5109 			int i;
5110 
5111 			cgp = (struct cg *)bp->b_data;
5112 			blksfree = cg_blksfree(cgp);
5113 			bno = dtogd(fs, jnewblk->jn_blkno);
5114 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5115 			    i++) {
5116 				if (isset(blksfree, bno + i))
5117 					panic("softdep_setup_blkmapdep: "
5118 					    "free fragment %d from %d-%d "
5119 					    "state 0x%X dep %p", i,
5120 					    jnewblk->jn_oldfrags,
5121 					    jnewblk->jn_frags,
5122 					    jnewblk->jn_state,
5123 					    jnewblk->jn_dep);
5124 			}
5125 		}
5126 #endif
5127 	}
5128 
5129 	CTR3(KTR_SUJ,
5130 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5131 	    newblkno, frags, oldfrags);
5132 	ACQUIRE_LOCK(ump);
5133 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5134 		panic("softdep_setup_blkmapdep: found block");
5135 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5136 	    dtog(fs, newblkno), NULL);
5137 	if (jnewblk) {
5138 		jnewblk->jn_dep = (struct worklist *)newblk;
5139 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5140 	} else {
5141 		newblk->nb_state |= ONDEPLIST;
5142 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5143 	}
5144 	newblk->nb_bmsafemap = bmsafemap;
5145 	newblk->nb_jnewblk = jnewblk;
5146 	FREE_LOCK(ump);
5147 }
5148 
5149 #define	BMSAFEMAP_HASH(ump, cg) \
5150       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5151 
5152 static int
5153 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5154 	struct bmsafemap_hashhead *bmsafemaphd;
5155 	int cg;
5156 	struct bmsafemap **bmsafemapp;
5157 {
5158 	struct bmsafemap *bmsafemap;
5159 
5160 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5161 		if (bmsafemap->sm_cg == cg)
5162 			break;
5163 	if (bmsafemap) {
5164 		*bmsafemapp = bmsafemap;
5165 		return (1);
5166 	}
5167 	*bmsafemapp = NULL;
5168 
5169 	return (0);
5170 }
5171 
5172 /*
5173  * Find the bmsafemap associated with a cylinder group buffer.
5174  * If none exists, create one. The buffer must be locked when
5175  * this routine is called and this routine must be called with
5176  * the softdep lock held. To avoid giving up the lock while
5177  * allocating a new bmsafemap, a preallocated bmsafemap may be
5178  * provided. If it is provided but not needed, it is freed.
5179  */
5180 static struct bmsafemap *
5181 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5182 	struct mount *mp;
5183 	struct buf *bp;
5184 	int cg;
5185 	struct bmsafemap *newbmsafemap;
5186 {
5187 	struct bmsafemap_hashhead *bmsafemaphd;
5188 	struct bmsafemap *bmsafemap, *collision;
5189 	struct worklist *wk;
5190 	struct ufsmount *ump;
5191 
5192 	ump = VFSTOUFS(mp);
5193 	LOCK_OWNED(ump);
5194 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5195 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5196 		if (wk->wk_type == D_BMSAFEMAP) {
5197 			if (newbmsafemap)
5198 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5199 			return (WK_BMSAFEMAP(wk));
5200 		}
5201 	}
5202 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5203 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5204 		if (newbmsafemap)
5205 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5206 		return (bmsafemap);
5207 	}
5208 	if (newbmsafemap) {
5209 		bmsafemap = newbmsafemap;
5210 	} else {
5211 		FREE_LOCK(ump);
5212 		bmsafemap = malloc(sizeof(struct bmsafemap),
5213 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5214 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5215 		ACQUIRE_LOCK(ump);
5216 	}
5217 	bmsafemap->sm_buf = bp;
5218 	LIST_INIT(&bmsafemap->sm_inodedephd);
5219 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5220 	LIST_INIT(&bmsafemap->sm_newblkhd);
5221 	LIST_INIT(&bmsafemap->sm_newblkwr);
5222 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5223 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5224 	LIST_INIT(&bmsafemap->sm_freehd);
5225 	LIST_INIT(&bmsafemap->sm_freewr);
5226 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5227 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5228 		return (collision);
5229 	}
5230 	bmsafemap->sm_cg = cg;
5231 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5232 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5233 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5234 	return (bmsafemap);
5235 }
5236 
5237 /*
5238  * Direct block allocation dependencies.
5239  *
5240  * When a new block is allocated, the corresponding disk locations must be
5241  * initialized (with zeros or new data) before the on-disk inode points to
5242  * them.  Also, the freemap from which the block was allocated must be
5243  * updated (on disk) before the inode's pointer. These two dependencies are
5244  * independent of each other and are needed for all file blocks and indirect
5245  * blocks that are pointed to directly by the inode.  Just before the
5246  * "in-core" version of the inode is updated with a newly allocated block
5247  * number, a procedure (below) is called to setup allocation dependency
5248  * structures.  These structures are removed when the corresponding
5249  * dependencies are satisfied or when the block allocation becomes obsolete
5250  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5251  * fragment that gets upgraded).  All of these cases are handled in
5252  * procedures described later.
5253  *
5254  * When a file extension causes a fragment to be upgraded, either to a larger
5255  * fragment or to a full block, the on-disk location may change (if the
5256  * previous fragment could not simply be extended). In this case, the old
5257  * fragment must be de-allocated, but not until after the inode's pointer has
5258  * been updated. In most cases, this is handled by later procedures, which
5259  * will construct a "freefrag" structure to be added to the workitem queue
5260  * when the inode update is complete (or obsolete).  The main exception to
5261  * this is when an allocation occurs while a pending allocation dependency
5262  * (for the same block pointer) remains.  This case is handled in the main
5263  * allocation dependency setup procedure by immediately freeing the
5264  * unreferenced fragments.
5265  */
5266 void
5267 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5268 	struct inode *ip;	/* inode to which block is being added */
5269 	ufs_lbn_t off;		/* block pointer within inode */
5270 	ufs2_daddr_t newblkno;	/* disk block number being added */
5271 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5272 	long newsize;		/* size of new block */
5273 	long oldsize;		/* size of new block */
5274 	struct buf *bp;		/* bp for allocated block */
5275 {
5276 	struct allocdirect *adp, *oldadp;
5277 	struct allocdirectlst *adphead;
5278 	struct freefrag *freefrag;
5279 	struct inodedep *inodedep;
5280 	struct pagedep *pagedep;
5281 	struct jnewblk *jnewblk;
5282 	struct newblk *newblk;
5283 	struct mount *mp;
5284 	ufs_lbn_t lbn;
5285 
5286 	lbn = bp->b_lblkno;
5287 	mp = ITOVFS(ip);
5288 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5289 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5290 	if (oldblkno && oldblkno != newblkno)
5291 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5292 	else
5293 		freefrag = NULL;
5294 
5295 	CTR6(KTR_SUJ,
5296 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5297 	    "off %jd newsize %ld oldsize %d",
5298 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5299 	ACQUIRE_LOCK(ITOUMP(ip));
5300 	if (off >= UFS_NDADDR) {
5301 		if (lbn > 0)
5302 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5303 			    lbn, off);
5304 		/* allocating an indirect block */
5305 		if (oldblkno != 0)
5306 			panic("softdep_setup_allocdirect: non-zero indir");
5307 	} else {
5308 		if (off != lbn)
5309 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5310 			    lbn, off);
5311 		/*
5312 		 * Allocating a direct block.
5313 		 *
5314 		 * If we are allocating a directory block, then we must
5315 		 * allocate an associated pagedep to track additions and
5316 		 * deletions.
5317 		 */
5318 		if ((ip->i_mode & IFMT) == IFDIR)
5319 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5320 			    &pagedep);
5321 	}
5322 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5323 		panic("softdep_setup_allocdirect: lost block");
5324 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5325 	    ("softdep_setup_allocdirect: newblk already initialized"));
5326 	/*
5327 	 * Convert the newblk to an allocdirect.
5328 	 */
5329 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5330 	adp = (struct allocdirect *)newblk;
5331 	newblk->nb_freefrag = freefrag;
5332 	adp->ad_offset = off;
5333 	adp->ad_oldblkno = oldblkno;
5334 	adp->ad_newsize = newsize;
5335 	adp->ad_oldsize = oldsize;
5336 
5337 	/*
5338 	 * Finish initializing the journal.
5339 	 */
5340 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5341 		jnewblk->jn_ino = ip->i_number;
5342 		jnewblk->jn_lbn = lbn;
5343 		add_to_journal(&jnewblk->jn_list);
5344 	}
5345 	if (freefrag && freefrag->ff_jdep != NULL &&
5346 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5347 		add_to_journal(freefrag->ff_jdep);
5348 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5349 	adp->ad_inodedep = inodedep;
5350 
5351 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5352 	/*
5353 	 * The list of allocdirects must be kept in sorted and ascending
5354 	 * order so that the rollback routines can quickly determine the
5355 	 * first uncommitted block (the size of the file stored on disk
5356 	 * ends at the end of the lowest committed fragment, or if there
5357 	 * are no fragments, at the end of the highest committed block).
5358 	 * Since files generally grow, the typical case is that the new
5359 	 * block is to be added at the end of the list. We speed this
5360 	 * special case by checking against the last allocdirect in the
5361 	 * list before laboriously traversing the list looking for the
5362 	 * insertion point.
5363 	 */
5364 	adphead = &inodedep->id_newinoupdt;
5365 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5366 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5367 		/* insert at end of list */
5368 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5369 		if (oldadp != NULL && oldadp->ad_offset == off)
5370 			allocdirect_merge(adphead, adp, oldadp);
5371 		FREE_LOCK(ITOUMP(ip));
5372 		return;
5373 	}
5374 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5375 		if (oldadp->ad_offset >= off)
5376 			break;
5377 	}
5378 	if (oldadp == NULL)
5379 		panic("softdep_setup_allocdirect: lost entry");
5380 	/* insert in middle of list */
5381 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5382 	if (oldadp->ad_offset == off)
5383 		allocdirect_merge(adphead, adp, oldadp);
5384 
5385 	FREE_LOCK(ITOUMP(ip));
5386 }
5387 
5388 /*
5389  * Merge a newer and older journal record to be stored either in a
5390  * newblock or freefrag.  This handles aggregating journal records for
5391  * fragment allocation into a second record as well as replacing a
5392  * journal free with an aborted journal allocation.  A segment for the
5393  * oldest record will be placed on wkhd if it has been written.  If not
5394  * the segment for the newer record will suffice.
5395  */
5396 static struct worklist *
5397 jnewblk_merge(new, old, wkhd)
5398 	struct worklist *new;
5399 	struct worklist *old;
5400 	struct workhead *wkhd;
5401 {
5402 	struct jnewblk *njnewblk;
5403 	struct jnewblk *jnewblk;
5404 
5405 	/* Handle NULLs to simplify callers. */
5406 	if (new == NULL)
5407 		return (old);
5408 	if (old == NULL)
5409 		return (new);
5410 	/* Replace a jfreefrag with a jnewblk. */
5411 	if (new->wk_type == D_JFREEFRAG) {
5412 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5413 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5414 			    old, new);
5415 		cancel_jfreefrag(WK_JFREEFRAG(new));
5416 		return (old);
5417 	}
5418 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5419 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5420 		    old->wk_type, new->wk_type);
5421 	/*
5422 	 * Handle merging of two jnewblk records that describe
5423 	 * different sets of fragments in the same block.
5424 	 */
5425 	jnewblk = WK_JNEWBLK(old);
5426 	njnewblk = WK_JNEWBLK(new);
5427 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5428 		panic("jnewblk_merge: Merging disparate blocks.");
5429 	/*
5430 	 * The record may be rolled back in the cg.
5431 	 */
5432 	if (jnewblk->jn_state & UNDONE) {
5433 		jnewblk->jn_state &= ~UNDONE;
5434 		njnewblk->jn_state |= UNDONE;
5435 		njnewblk->jn_state &= ~ATTACHED;
5436 	}
5437 	/*
5438 	 * We modify the newer addref and free the older so that if neither
5439 	 * has been written the most up-to-date copy will be on disk.  If
5440 	 * both have been written but rolled back we only temporarily need
5441 	 * one of them to fix the bits when the cg write completes.
5442 	 */
5443 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5444 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5445 	cancel_jnewblk(jnewblk, wkhd);
5446 	WORKLIST_REMOVE(&jnewblk->jn_list);
5447 	free_jnewblk(jnewblk);
5448 	return (new);
5449 }
5450 
5451 /*
5452  * Replace an old allocdirect dependency with a newer one.
5453  * This routine must be called with splbio interrupts blocked.
5454  */
5455 static void
5456 allocdirect_merge(adphead, newadp, oldadp)
5457 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5458 	struct allocdirect *newadp;	/* allocdirect being added */
5459 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5460 {
5461 	struct worklist *wk;
5462 	struct freefrag *freefrag;
5463 
5464 	freefrag = NULL;
5465 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5466 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5467 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5468 	    newadp->ad_offset >= UFS_NDADDR)
5469 		panic("%s %jd != new %jd || old size %ld != new %ld",
5470 		    "allocdirect_merge: old blkno",
5471 		    (intmax_t)newadp->ad_oldblkno,
5472 		    (intmax_t)oldadp->ad_newblkno,
5473 		    newadp->ad_oldsize, oldadp->ad_newsize);
5474 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5475 	newadp->ad_oldsize = oldadp->ad_oldsize;
5476 	/*
5477 	 * If the old dependency had a fragment to free or had never
5478 	 * previously had a block allocated, then the new dependency
5479 	 * can immediately post its freefrag and adopt the old freefrag.
5480 	 * This action is done by swapping the freefrag dependencies.
5481 	 * The new dependency gains the old one's freefrag, and the
5482 	 * old one gets the new one and then immediately puts it on
5483 	 * the worklist when it is freed by free_newblk. It is
5484 	 * not possible to do this swap when the old dependency had a
5485 	 * non-zero size but no previous fragment to free. This condition
5486 	 * arises when the new block is an extension of the old block.
5487 	 * Here, the first part of the fragment allocated to the new
5488 	 * dependency is part of the block currently claimed on disk by
5489 	 * the old dependency, so cannot legitimately be freed until the
5490 	 * conditions for the new dependency are fulfilled.
5491 	 */
5492 	freefrag = newadp->ad_freefrag;
5493 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5494 		newadp->ad_freefrag = oldadp->ad_freefrag;
5495 		oldadp->ad_freefrag = freefrag;
5496 	}
5497 	/*
5498 	 * If we are tracking a new directory-block allocation,
5499 	 * move it from the old allocdirect to the new allocdirect.
5500 	 */
5501 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5502 		WORKLIST_REMOVE(wk);
5503 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5504 			panic("allocdirect_merge: extra newdirblk");
5505 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5506 	}
5507 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5508 	/*
5509 	 * We need to move any journal dependencies over to the freefrag
5510 	 * that releases this block if it exists.  Otherwise we are
5511 	 * extending an existing block and we'll wait until that is
5512 	 * complete to release the journal space and extend the
5513 	 * new journal to cover this old space as well.
5514 	 */
5515 	if (freefrag == NULL) {
5516 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5517 			panic("allocdirect_merge: %jd != %jd",
5518 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5519 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5520 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5521 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5522 		    &newadp->ad_block.nb_jwork);
5523 		oldadp->ad_block.nb_jnewblk = NULL;
5524 		cancel_newblk(&oldadp->ad_block, NULL,
5525 		    &newadp->ad_block.nb_jwork);
5526 	} else {
5527 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5528 		    &freefrag->ff_list, &freefrag->ff_jwork);
5529 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5530 		    &freefrag->ff_jwork);
5531 	}
5532 	free_newblk(&oldadp->ad_block);
5533 }
5534 
5535 /*
5536  * Allocate a jfreefrag structure to journal a single block free.
5537  */
5538 static struct jfreefrag *
5539 newjfreefrag(freefrag, ip, blkno, size, lbn)
5540 	struct freefrag *freefrag;
5541 	struct inode *ip;
5542 	ufs2_daddr_t blkno;
5543 	long size;
5544 	ufs_lbn_t lbn;
5545 {
5546 	struct jfreefrag *jfreefrag;
5547 	struct fs *fs;
5548 
5549 	fs = ITOFS(ip);
5550 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5551 	    M_SOFTDEP_FLAGS);
5552 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5553 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5554 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5555 	jfreefrag->fr_ino = ip->i_number;
5556 	jfreefrag->fr_lbn = lbn;
5557 	jfreefrag->fr_blkno = blkno;
5558 	jfreefrag->fr_frags = numfrags(fs, size);
5559 	jfreefrag->fr_freefrag = freefrag;
5560 
5561 	return (jfreefrag);
5562 }
5563 
5564 /*
5565  * Allocate a new freefrag structure.
5566  */
5567 static struct freefrag *
5568 newfreefrag(ip, blkno, size, lbn)
5569 	struct inode *ip;
5570 	ufs2_daddr_t blkno;
5571 	long size;
5572 	ufs_lbn_t lbn;
5573 {
5574 	struct freefrag *freefrag;
5575 	struct ufsmount *ump;
5576 	struct fs *fs;
5577 
5578 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5579 	    ip->i_number, blkno, size, lbn);
5580 	ump = ITOUMP(ip);
5581 	fs = ump->um_fs;
5582 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5583 		panic("newfreefrag: frag size");
5584 	freefrag = malloc(sizeof(struct freefrag),
5585 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5586 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5587 	freefrag->ff_state = ATTACHED;
5588 	LIST_INIT(&freefrag->ff_jwork);
5589 	freefrag->ff_inum = ip->i_number;
5590 	freefrag->ff_vtype = ITOV(ip)->v_type;
5591 	freefrag->ff_blkno = blkno;
5592 	freefrag->ff_fragsize = size;
5593 
5594 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5595 		freefrag->ff_jdep = (struct worklist *)
5596 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5597 	} else {
5598 		freefrag->ff_state |= DEPCOMPLETE;
5599 		freefrag->ff_jdep = NULL;
5600 	}
5601 
5602 	return (freefrag);
5603 }
5604 
5605 /*
5606  * This workitem de-allocates fragments that were replaced during
5607  * file block allocation.
5608  */
5609 static void
5610 handle_workitem_freefrag(freefrag)
5611 	struct freefrag *freefrag;
5612 {
5613 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5614 	struct workhead wkhd;
5615 
5616 	CTR3(KTR_SUJ,
5617 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5618 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5619 	/*
5620 	 * It would be illegal to add new completion items to the
5621 	 * freefrag after it was schedule to be done so it must be
5622 	 * safe to modify the list head here.
5623 	 */
5624 	LIST_INIT(&wkhd);
5625 	ACQUIRE_LOCK(ump);
5626 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5627 	/*
5628 	 * If the journal has not been written we must cancel it here.
5629 	 */
5630 	if (freefrag->ff_jdep) {
5631 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5632 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5633 			    freefrag->ff_jdep->wk_type);
5634 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5635 	}
5636 	FREE_LOCK(ump);
5637 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5638 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5639 	ACQUIRE_LOCK(ump);
5640 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5641 	FREE_LOCK(ump);
5642 }
5643 
5644 /*
5645  * Set up a dependency structure for an external attributes data block.
5646  * This routine follows much of the structure of softdep_setup_allocdirect.
5647  * See the description of softdep_setup_allocdirect above for details.
5648  */
5649 void
5650 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5651 	struct inode *ip;
5652 	ufs_lbn_t off;
5653 	ufs2_daddr_t newblkno;
5654 	ufs2_daddr_t oldblkno;
5655 	long newsize;
5656 	long oldsize;
5657 	struct buf *bp;
5658 {
5659 	struct allocdirect *adp, *oldadp;
5660 	struct allocdirectlst *adphead;
5661 	struct freefrag *freefrag;
5662 	struct inodedep *inodedep;
5663 	struct jnewblk *jnewblk;
5664 	struct newblk *newblk;
5665 	struct mount *mp;
5666 	struct ufsmount *ump;
5667 	ufs_lbn_t lbn;
5668 
5669 	mp = ITOVFS(ip);
5670 	ump = VFSTOUFS(mp);
5671 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5672 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5673 	KASSERT(off < UFS_NXADDR,
5674 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5675 
5676 	lbn = bp->b_lblkno;
5677 	if (oldblkno && oldblkno != newblkno)
5678 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5679 	else
5680 		freefrag = NULL;
5681 
5682 	ACQUIRE_LOCK(ump);
5683 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5684 		panic("softdep_setup_allocext: lost block");
5685 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5686 	    ("softdep_setup_allocext: newblk already initialized"));
5687 	/*
5688 	 * Convert the newblk to an allocdirect.
5689 	 */
5690 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5691 	adp = (struct allocdirect *)newblk;
5692 	newblk->nb_freefrag = freefrag;
5693 	adp->ad_offset = off;
5694 	adp->ad_oldblkno = oldblkno;
5695 	adp->ad_newsize = newsize;
5696 	adp->ad_oldsize = oldsize;
5697 	adp->ad_state |=  EXTDATA;
5698 
5699 	/*
5700 	 * Finish initializing the journal.
5701 	 */
5702 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5703 		jnewblk->jn_ino = ip->i_number;
5704 		jnewblk->jn_lbn = lbn;
5705 		add_to_journal(&jnewblk->jn_list);
5706 	}
5707 	if (freefrag && freefrag->ff_jdep != NULL &&
5708 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5709 		add_to_journal(freefrag->ff_jdep);
5710 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5711 	adp->ad_inodedep = inodedep;
5712 
5713 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5714 	/*
5715 	 * The list of allocdirects must be kept in sorted and ascending
5716 	 * order so that the rollback routines can quickly determine the
5717 	 * first uncommitted block (the size of the file stored on disk
5718 	 * ends at the end of the lowest committed fragment, or if there
5719 	 * are no fragments, at the end of the highest committed block).
5720 	 * Since files generally grow, the typical case is that the new
5721 	 * block is to be added at the end of the list. We speed this
5722 	 * special case by checking against the last allocdirect in the
5723 	 * list before laboriously traversing the list looking for the
5724 	 * insertion point.
5725 	 */
5726 	adphead = &inodedep->id_newextupdt;
5727 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5728 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5729 		/* insert at end of list */
5730 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5731 		if (oldadp != NULL && oldadp->ad_offset == off)
5732 			allocdirect_merge(adphead, adp, oldadp);
5733 		FREE_LOCK(ump);
5734 		return;
5735 	}
5736 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5737 		if (oldadp->ad_offset >= off)
5738 			break;
5739 	}
5740 	if (oldadp == NULL)
5741 		panic("softdep_setup_allocext: lost entry");
5742 	/* insert in middle of list */
5743 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5744 	if (oldadp->ad_offset == off)
5745 		allocdirect_merge(adphead, adp, oldadp);
5746 	FREE_LOCK(ump);
5747 }
5748 
5749 /*
5750  * Indirect block allocation dependencies.
5751  *
5752  * The same dependencies that exist for a direct block also exist when
5753  * a new block is allocated and pointed to by an entry in a block of
5754  * indirect pointers. The undo/redo states described above are also
5755  * used here. Because an indirect block contains many pointers that
5756  * may have dependencies, a second copy of the entire in-memory indirect
5757  * block is kept. The buffer cache copy is always completely up-to-date.
5758  * The second copy, which is used only as a source for disk writes,
5759  * contains only the safe pointers (i.e., those that have no remaining
5760  * update dependencies). The second copy is freed when all pointers
5761  * are safe. The cache is not allowed to replace indirect blocks with
5762  * pending update dependencies. If a buffer containing an indirect
5763  * block with dependencies is written, these routines will mark it
5764  * dirty again. It can only be successfully written once all the
5765  * dependencies are removed. The ffs_fsync routine in conjunction with
5766  * softdep_sync_metadata work together to get all the dependencies
5767  * removed so that a file can be successfully written to disk. Three
5768  * procedures are used when setting up indirect block pointer
5769  * dependencies. The division is necessary because of the organization
5770  * of the "balloc" routine and because of the distinction between file
5771  * pages and file metadata blocks.
5772  */
5773 
5774 /*
5775  * Allocate a new allocindir structure.
5776  */
5777 static struct allocindir *
5778 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5779 	struct inode *ip;	/* inode for file being extended */
5780 	int ptrno;		/* offset of pointer in indirect block */
5781 	ufs2_daddr_t newblkno;	/* disk block number being added */
5782 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5783 	ufs_lbn_t lbn;
5784 {
5785 	struct newblk *newblk;
5786 	struct allocindir *aip;
5787 	struct freefrag *freefrag;
5788 	struct jnewblk *jnewblk;
5789 
5790 	if (oldblkno)
5791 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn);
5792 	else
5793 		freefrag = NULL;
5794 	ACQUIRE_LOCK(ITOUMP(ip));
5795 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5796 		panic("new_allocindir: lost block");
5797 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5798 	    ("newallocindir: newblk already initialized"));
5799 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5800 	newblk->nb_freefrag = freefrag;
5801 	aip = (struct allocindir *)newblk;
5802 	aip->ai_offset = ptrno;
5803 	aip->ai_oldblkno = oldblkno;
5804 	aip->ai_lbn = lbn;
5805 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5806 		jnewblk->jn_ino = ip->i_number;
5807 		jnewblk->jn_lbn = lbn;
5808 		add_to_journal(&jnewblk->jn_list);
5809 	}
5810 	if (freefrag && freefrag->ff_jdep != NULL &&
5811 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5812 		add_to_journal(freefrag->ff_jdep);
5813 	return (aip);
5814 }
5815 
5816 /*
5817  * Called just before setting an indirect block pointer
5818  * to a newly allocated file page.
5819  */
5820 void
5821 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5822 	struct inode *ip;	/* inode for file being extended */
5823 	ufs_lbn_t lbn;		/* allocated block number within file */
5824 	struct buf *bp;		/* buffer with indirect blk referencing page */
5825 	int ptrno;		/* offset of pointer in indirect block */
5826 	ufs2_daddr_t newblkno;	/* disk block number being added */
5827 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5828 	struct buf *nbp;	/* buffer holding allocated page */
5829 {
5830 	struct inodedep *inodedep;
5831 	struct freefrag *freefrag;
5832 	struct allocindir *aip;
5833 	struct pagedep *pagedep;
5834 	struct mount *mp;
5835 	struct ufsmount *ump;
5836 
5837 	mp = ITOVFS(ip);
5838 	ump = VFSTOUFS(mp);
5839 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5840 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5841 	KASSERT(lbn == nbp->b_lblkno,
5842 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5843 	    lbn, bp->b_lblkno));
5844 	CTR4(KTR_SUJ,
5845 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5846 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5847 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5848 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5849 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5850 	/*
5851 	 * If we are allocating a directory page, then we must
5852 	 * allocate an associated pagedep to track additions and
5853 	 * deletions.
5854 	 */
5855 	if ((ip->i_mode & IFMT) == IFDIR)
5856 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5857 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5858 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5859 	FREE_LOCK(ump);
5860 	if (freefrag)
5861 		handle_workitem_freefrag(freefrag);
5862 }
5863 
5864 /*
5865  * Called just before setting an indirect block pointer to a
5866  * newly allocated indirect block.
5867  */
5868 void
5869 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5870 	struct buf *nbp;	/* newly allocated indirect block */
5871 	struct inode *ip;	/* inode for file being extended */
5872 	struct buf *bp;		/* indirect block referencing allocated block */
5873 	int ptrno;		/* offset of pointer in indirect block */
5874 	ufs2_daddr_t newblkno;	/* disk block number being added */
5875 {
5876 	struct inodedep *inodedep;
5877 	struct allocindir *aip;
5878 	struct ufsmount *ump;
5879 	ufs_lbn_t lbn;
5880 
5881 	ump = ITOUMP(ip);
5882 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5883 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5884 	CTR3(KTR_SUJ,
5885 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5886 	    ip->i_number, newblkno, ptrno);
5887 	lbn = nbp->b_lblkno;
5888 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5889 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5890 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5891 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5892 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5893 		panic("softdep_setup_allocindir_meta: Block already existed");
5894 	FREE_LOCK(ump);
5895 }
5896 
5897 static void
5898 indirdep_complete(indirdep)
5899 	struct indirdep *indirdep;
5900 {
5901 	struct allocindir *aip;
5902 
5903 	LIST_REMOVE(indirdep, ir_next);
5904 	indirdep->ir_state |= DEPCOMPLETE;
5905 
5906 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5907 		LIST_REMOVE(aip, ai_next);
5908 		free_newblk(&aip->ai_block);
5909 	}
5910 	/*
5911 	 * If this indirdep is not attached to a buf it was simply waiting
5912 	 * on completion to clear completehd.  free_indirdep() asserts
5913 	 * that nothing is dangling.
5914 	 */
5915 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5916 		free_indirdep(indirdep);
5917 }
5918 
5919 static struct indirdep *
5920 indirdep_lookup(mp, ip, bp)
5921 	struct mount *mp;
5922 	struct inode *ip;
5923 	struct buf *bp;
5924 {
5925 	struct indirdep *indirdep, *newindirdep;
5926 	struct newblk *newblk;
5927 	struct ufsmount *ump;
5928 	struct worklist *wk;
5929 	struct fs *fs;
5930 	ufs2_daddr_t blkno;
5931 
5932 	ump = VFSTOUFS(mp);
5933 	LOCK_OWNED(ump);
5934 	indirdep = NULL;
5935 	newindirdep = NULL;
5936 	fs = ump->um_fs;
5937 	for (;;) {
5938 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5939 			if (wk->wk_type != D_INDIRDEP)
5940 				continue;
5941 			indirdep = WK_INDIRDEP(wk);
5942 			break;
5943 		}
5944 		/* Found on the buffer worklist, no new structure to free. */
5945 		if (indirdep != NULL && newindirdep == NULL)
5946 			return (indirdep);
5947 		if (indirdep != NULL && newindirdep != NULL)
5948 			panic("indirdep_lookup: simultaneous create");
5949 		/* None found on the buffer and a new structure is ready. */
5950 		if (indirdep == NULL && newindirdep != NULL)
5951 			break;
5952 		/* None found and no new structure available. */
5953 		FREE_LOCK(ump);
5954 		newindirdep = malloc(sizeof(struct indirdep),
5955 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
5956 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5957 		newindirdep->ir_state = ATTACHED;
5958 		if (I_IS_UFS1(ip))
5959 			newindirdep->ir_state |= UFS1FMT;
5960 		TAILQ_INIT(&newindirdep->ir_trunc);
5961 		newindirdep->ir_saveddata = NULL;
5962 		LIST_INIT(&newindirdep->ir_deplisthd);
5963 		LIST_INIT(&newindirdep->ir_donehd);
5964 		LIST_INIT(&newindirdep->ir_writehd);
5965 		LIST_INIT(&newindirdep->ir_completehd);
5966 		if (bp->b_blkno == bp->b_lblkno) {
5967 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5968 			    NULL, NULL);
5969 			bp->b_blkno = blkno;
5970 		}
5971 		newindirdep->ir_freeblks = NULL;
5972 		newindirdep->ir_savebp =
5973 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5974 		newindirdep->ir_bp = bp;
5975 		BUF_KERNPROC(newindirdep->ir_savebp);
5976 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5977 		ACQUIRE_LOCK(ump);
5978 	}
5979 	indirdep = newindirdep;
5980 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5981 	/*
5982 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
5983 	 * that we don't free dependencies until the pointers are valid.
5984 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5985 	 * than using the hash.
5986 	 */
5987 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5988 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5989 	else
5990 		indirdep->ir_state |= DEPCOMPLETE;
5991 	return (indirdep);
5992 }
5993 
5994 /*
5995  * Called to finish the allocation of the "aip" allocated
5996  * by one of the two routines above.
5997  */
5998 static struct freefrag *
5999 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6000 	struct buf *bp;		/* in-memory copy of the indirect block */
6001 	struct inode *ip;	/* inode for file being extended */
6002 	struct inodedep *inodedep; /* Inodedep for ip */
6003 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6004 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6005 {
6006 	struct fs *fs;
6007 	struct indirdep *indirdep;
6008 	struct allocindir *oldaip;
6009 	struct freefrag *freefrag;
6010 	struct mount *mp;
6011 	struct ufsmount *ump;
6012 
6013 	mp = ITOVFS(ip);
6014 	ump = VFSTOUFS(mp);
6015 	LOCK_OWNED(ump);
6016 	fs = ump->um_fs;
6017 	if (bp->b_lblkno >= 0)
6018 		panic("setup_allocindir_phase2: not indir blk");
6019 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6020 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6021 	indirdep = indirdep_lookup(mp, ip, bp);
6022 	KASSERT(indirdep->ir_savebp != NULL,
6023 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6024 	aip->ai_indirdep = indirdep;
6025 	/*
6026 	 * Check for an unwritten dependency for this indirect offset.  If
6027 	 * there is, merge the old dependency into the new one.  This happens
6028 	 * as a result of reallocblk only.
6029 	 */
6030 	freefrag = NULL;
6031 	if (aip->ai_oldblkno != 0) {
6032 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6033 			if (oldaip->ai_offset == aip->ai_offset) {
6034 				freefrag = allocindir_merge(aip, oldaip);
6035 				goto done;
6036 			}
6037 		}
6038 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6039 			if (oldaip->ai_offset == aip->ai_offset) {
6040 				freefrag = allocindir_merge(aip, oldaip);
6041 				goto done;
6042 			}
6043 		}
6044 	}
6045 done:
6046 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6047 	return (freefrag);
6048 }
6049 
6050 /*
6051  * Merge two allocindirs which refer to the same block.  Move newblock
6052  * dependencies and setup the freefrags appropriately.
6053  */
6054 static struct freefrag *
6055 allocindir_merge(aip, oldaip)
6056 	struct allocindir *aip;
6057 	struct allocindir *oldaip;
6058 {
6059 	struct freefrag *freefrag;
6060 	struct worklist *wk;
6061 
6062 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6063 		panic("allocindir_merge: blkno");
6064 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6065 	freefrag = aip->ai_freefrag;
6066 	aip->ai_freefrag = oldaip->ai_freefrag;
6067 	oldaip->ai_freefrag = NULL;
6068 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6069 	/*
6070 	 * If we are tracking a new directory-block allocation,
6071 	 * move it from the old allocindir to the new allocindir.
6072 	 */
6073 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6074 		WORKLIST_REMOVE(wk);
6075 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6076 			panic("allocindir_merge: extra newdirblk");
6077 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6078 	}
6079 	/*
6080 	 * We can skip journaling for this freefrag and just complete
6081 	 * any pending journal work for the allocindir that is being
6082 	 * removed after the freefrag completes.
6083 	 */
6084 	if (freefrag->ff_jdep)
6085 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6086 	LIST_REMOVE(oldaip, ai_next);
6087 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6088 	    &freefrag->ff_list, &freefrag->ff_jwork);
6089 	free_newblk(&oldaip->ai_block);
6090 
6091 	return (freefrag);
6092 }
6093 
6094 static inline void
6095 setup_freedirect(freeblks, ip, i, needj)
6096 	struct freeblks *freeblks;
6097 	struct inode *ip;
6098 	int i;
6099 	int needj;
6100 {
6101 	struct ufsmount *ump;
6102 	ufs2_daddr_t blkno;
6103 	int frags;
6104 
6105 	blkno = DIP(ip, i_db[i]);
6106 	if (blkno == 0)
6107 		return;
6108 	DIP_SET(ip, i_db[i], 0);
6109 	ump = ITOUMP(ip);
6110 	frags = sblksize(ump->um_fs, ip->i_size, i);
6111 	frags = numfrags(ump->um_fs, frags);
6112 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6113 }
6114 
6115 static inline void
6116 setup_freeext(freeblks, ip, i, needj)
6117 	struct freeblks *freeblks;
6118 	struct inode *ip;
6119 	int i;
6120 	int needj;
6121 {
6122 	struct ufsmount *ump;
6123 	ufs2_daddr_t blkno;
6124 	int frags;
6125 
6126 	blkno = ip->i_din2->di_extb[i];
6127 	if (blkno == 0)
6128 		return;
6129 	ip->i_din2->di_extb[i] = 0;
6130 	ump = ITOUMP(ip);
6131 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6132 	frags = numfrags(ump->um_fs, frags);
6133 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6134 }
6135 
6136 static inline void
6137 setup_freeindir(freeblks, ip, i, lbn, needj)
6138 	struct freeblks *freeblks;
6139 	struct inode *ip;
6140 	int i;
6141 	ufs_lbn_t lbn;
6142 	int needj;
6143 {
6144 	struct ufsmount *ump;
6145 	ufs2_daddr_t blkno;
6146 
6147 	blkno = DIP(ip, i_ib[i]);
6148 	if (blkno == 0)
6149 		return;
6150 	DIP_SET(ip, i_ib[i], 0);
6151 	ump = ITOUMP(ip);
6152 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6153 	    0, needj);
6154 }
6155 
6156 static inline struct freeblks *
6157 newfreeblks(mp, ip)
6158 	struct mount *mp;
6159 	struct inode *ip;
6160 {
6161 	struct freeblks *freeblks;
6162 
6163 	freeblks = malloc(sizeof(struct freeblks),
6164 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6165 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6166 	LIST_INIT(&freeblks->fb_jblkdephd);
6167 	LIST_INIT(&freeblks->fb_jwork);
6168 	freeblks->fb_ref = 0;
6169 	freeblks->fb_cgwait = 0;
6170 	freeblks->fb_state = ATTACHED;
6171 	freeblks->fb_uid = ip->i_uid;
6172 	freeblks->fb_inum = ip->i_number;
6173 	freeblks->fb_vtype = ITOV(ip)->v_type;
6174 	freeblks->fb_modrev = DIP(ip, i_modrev);
6175 	freeblks->fb_devvp = ITODEVVP(ip);
6176 	freeblks->fb_chkcnt = 0;
6177 	freeblks->fb_len = 0;
6178 
6179 	return (freeblks);
6180 }
6181 
6182 static void
6183 trunc_indirdep(indirdep, freeblks, bp, off)
6184 	struct indirdep *indirdep;
6185 	struct freeblks *freeblks;
6186 	struct buf *bp;
6187 	int off;
6188 {
6189 	struct allocindir *aip, *aipn;
6190 
6191 	/*
6192 	 * The first set of allocindirs won't be in savedbp.
6193 	 */
6194 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6195 		if (aip->ai_offset > off)
6196 			cancel_allocindir(aip, bp, freeblks, 1);
6197 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6198 		if (aip->ai_offset > off)
6199 			cancel_allocindir(aip, bp, freeblks, 1);
6200 	/*
6201 	 * These will exist in savedbp.
6202 	 */
6203 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6204 		if (aip->ai_offset > off)
6205 			cancel_allocindir(aip, NULL, freeblks, 0);
6206 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6207 		if (aip->ai_offset > off)
6208 			cancel_allocindir(aip, NULL, freeblks, 0);
6209 }
6210 
6211 /*
6212  * Follow the chain of indirects down to lastlbn creating a freework
6213  * structure for each.  This will be used to start indir_trunc() at
6214  * the right offset and create the journal records for the parrtial
6215  * truncation.  A second step will handle the truncated dependencies.
6216  */
6217 static int
6218 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6219 	struct freeblks *freeblks;
6220 	struct inode *ip;
6221 	ufs_lbn_t lbn;
6222 	ufs_lbn_t lastlbn;
6223 	ufs2_daddr_t blkno;
6224 {
6225 	struct indirdep *indirdep;
6226 	struct indirdep *indirn;
6227 	struct freework *freework;
6228 	struct newblk *newblk;
6229 	struct mount *mp;
6230 	struct ufsmount *ump;
6231 	struct buf *bp;
6232 	uint8_t *start;
6233 	uint8_t *end;
6234 	ufs_lbn_t lbnadd;
6235 	int level;
6236 	int error;
6237 	int off;
6238 
6239 
6240 	freework = NULL;
6241 	if (blkno == 0)
6242 		return (0);
6243 	mp = freeblks->fb_list.wk_mp;
6244 	ump = VFSTOUFS(mp);
6245 	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6246 	if ((bp->b_flags & B_CACHE) == 0) {
6247 		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6248 		bp->b_iocmd = BIO_READ;
6249 		bp->b_flags &= ~B_INVAL;
6250 		bp->b_ioflags &= ~BIO_ERROR;
6251 		vfs_busy_pages(bp, 0);
6252 		bp->b_iooffset = dbtob(bp->b_blkno);
6253 		bstrategy(bp);
6254 #ifdef RACCT
6255 		if (racct_enable) {
6256 			PROC_LOCK(curproc);
6257 			racct_add_buf(curproc, bp, 0);
6258 			PROC_UNLOCK(curproc);
6259 		}
6260 #endif /* RACCT */
6261 		curthread->td_ru.ru_inblock++;
6262 		error = bufwait(bp);
6263 		if (error) {
6264 			brelse(bp);
6265 			return (error);
6266 		}
6267 	}
6268 	level = lbn_level(lbn);
6269 	lbnadd = lbn_offset(ump->um_fs, level);
6270 	/*
6271 	 * Compute the offset of the last block we want to keep.  Store
6272 	 * in the freework the first block we want to completely free.
6273 	 */
6274 	off = (lastlbn - -(lbn + level)) / lbnadd;
6275 	if (off + 1 == NINDIR(ump->um_fs))
6276 		goto nowork;
6277 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6278 	/*
6279 	 * Link the freework into the indirdep.  This will prevent any new
6280 	 * allocations from proceeding until we are finished with the
6281 	 * truncate and the block is written.
6282 	 */
6283 	ACQUIRE_LOCK(ump);
6284 	indirdep = indirdep_lookup(mp, ip, bp);
6285 	if (indirdep->ir_freeblks)
6286 		panic("setup_trunc_indir: indirdep already truncated.");
6287 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6288 	freework->fw_indir = indirdep;
6289 	/*
6290 	 * Cancel any allocindirs that will not make it to disk.
6291 	 * We have to do this for all copies of the indirdep that
6292 	 * live on this newblk.
6293 	 */
6294 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6295 		newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0, &newblk);
6296 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6297 			trunc_indirdep(indirn, freeblks, bp, off);
6298 	} else
6299 		trunc_indirdep(indirdep, freeblks, bp, off);
6300 	FREE_LOCK(ump);
6301 	/*
6302 	 * Creation is protected by the buf lock. The saveddata is only
6303 	 * needed if a full truncation follows a partial truncation but it
6304 	 * is difficult to allocate in that case so we fetch it anyway.
6305 	 */
6306 	if (indirdep->ir_saveddata == NULL)
6307 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6308 		    M_SOFTDEP_FLAGS);
6309 nowork:
6310 	/* Fetch the blkno of the child and the zero start offset. */
6311 	if (I_IS_UFS1(ip)) {
6312 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6313 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6314 	} else {
6315 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6316 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6317 	}
6318 	if (freework) {
6319 		/* Zero the truncated pointers. */
6320 		end = bp->b_data + bp->b_bcount;
6321 		bzero(start, end - start);
6322 		bdwrite(bp);
6323 	} else
6324 		bqrelse(bp);
6325 	if (level == 0)
6326 		return (0);
6327 	lbn++; /* adjust level */
6328 	lbn -= (off * lbnadd);
6329 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6330 }
6331 
6332 /*
6333  * Complete the partial truncation of an indirect block setup by
6334  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6335  * copy and writes them to disk before the freeblks is allowed to complete.
6336  */
6337 static void
6338 complete_trunc_indir(freework)
6339 	struct freework *freework;
6340 {
6341 	struct freework *fwn;
6342 	struct indirdep *indirdep;
6343 	struct ufsmount *ump;
6344 	struct buf *bp;
6345 	uintptr_t start;
6346 	int count;
6347 
6348 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6349 	LOCK_OWNED(ump);
6350 	indirdep = freework->fw_indir;
6351 	for (;;) {
6352 		bp = indirdep->ir_bp;
6353 		/* See if the block was discarded. */
6354 		if (bp == NULL)
6355 			break;
6356 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6357 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6358 			break;
6359 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6360 		    LOCK_PTR(ump)) == 0)
6361 			BUF_UNLOCK(bp);
6362 		ACQUIRE_LOCK(ump);
6363 	}
6364 	freework->fw_state |= DEPCOMPLETE;
6365 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6366 	/*
6367 	 * Zero the pointers in the saved copy.
6368 	 */
6369 	if (indirdep->ir_state & UFS1FMT)
6370 		start = sizeof(ufs1_daddr_t);
6371 	else
6372 		start = sizeof(ufs2_daddr_t);
6373 	start *= freework->fw_start;
6374 	count = indirdep->ir_savebp->b_bcount - start;
6375 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6376 	bzero((char *)start, count);
6377 	/*
6378 	 * We need to start the next truncation in the list if it has not
6379 	 * been started yet.
6380 	 */
6381 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6382 	if (fwn != NULL) {
6383 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6384 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6385 		if ((fwn->fw_state & ONWORKLIST) == 0)
6386 			freework_enqueue(fwn);
6387 	}
6388 	/*
6389 	 * If bp is NULL the block was fully truncated, restore
6390 	 * the saved block list otherwise free it if it is no
6391 	 * longer needed.
6392 	 */
6393 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6394 		if (bp == NULL)
6395 			bcopy(indirdep->ir_saveddata,
6396 			    indirdep->ir_savebp->b_data,
6397 			    indirdep->ir_savebp->b_bcount);
6398 		free(indirdep->ir_saveddata, M_INDIRDEP);
6399 		indirdep->ir_saveddata = NULL;
6400 	}
6401 	/*
6402 	 * When bp is NULL there is a full truncation pending.  We
6403 	 * must wait for this full truncation to be journaled before
6404 	 * we can release this freework because the disk pointers will
6405 	 * never be written as zero.
6406 	 */
6407 	if (bp == NULL)  {
6408 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6409 			handle_written_freework(freework);
6410 		else
6411 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6412 			   &freework->fw_list);
6413 	} else {
6414 		/* Complete when the real copy is written. */
6415 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6416 		BUF_UNLOCK(bp);
6417 	}
6418 }
6419 
6420 /*
6421  * Calculate the number of blocks we are going to release where datablocks
6422  * is the current total and length is the new file size.
6423  */
6424 static ufs2_daddr_t
6425 blkcount(fs, datablocks, length)
6426 	struct fs *fs;
6427 	ufs2_daddr_t datablocks;
6428 	off_t length;
6429 {
6430 	off_t totblks, numblks;
6431 
6432 	totblks = 0;
6433 	numblks = howmany(length, fs->fs_bsize);
6434 	if (numblks <= UFS_NDADDR) {
6435 		totblks = howmany(length, fs->fs_fsize);
6436 		goto out;
6437 	}
6438         totblks = blkstofrags(fs, numblks);
6439 	numblks -= UFS_NDADDR;
6440 	/*
6441 	 * Count all single, then double, then triple indirects required.
6442 	 * Subtracting one indirects worth of blocks for each pass
6443 	 * acknowledges one of each pointed to by the inode.
6444 	 */
6445 	for (;;) {
6446 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6447 		numblks -= NINDIR(fs);
6448 		if (numblks <= 0)
6449 			break;
6450 		numblks = howmany(numblks, NINDIR(fs));
6451 	}
6452 out:
6453 	totblks = fsbtodb(fs, totblks);
6454 	/*
6455 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6456 	 * references.  We will correct it later in handle_complete_freeblks()
6457 	 * when we know the real count.
6458 	 */
6459 	if (totblks > datablocks)
6460 		return (0);
6461 	return (datablocks - totblks);
6462 }
6463 
6464 /*
6465  * Handle freeblocks for journaled softupdate filesystems.
6466  *
6467  * Contrary to normal softupdates, we must preserve the block pointers in
6468  * indirects until their subordinates are free.  This is to avoid journaling
6469  * every block that is freed which may consume more space than the journal
6470  * itself.  The recovery program will see the free block journals at the
6471  * base of the truncated area and traverse them to reclaim space.  The
6472  * pointers in the inode may be cleared immediately after the journal
6473  * records are written because each direct and indirect pointer in the
6474  * inode is recorded in a journal.  This permits full truncation to proceed
6475  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6476  *
6477  * The algorithm is as follows:
6478  * 1) Traverse the in-memory state and create journal entries to release
6479  *    the relevant blocks and full indirect trees.
6480  * 2) Traverse the indirect block chain adding partial truncation freework
6481  *    records to indirects in the path to lastlbn.  The freework will
6482  *    prevent new allocation dependencies from being satisfied in this
6483  *    indirect until the truncation completes.
6484  * 3) Read and lock the inode block, performing an update with the new size
6485  *    and pointers.  This prevents truncated data from becoming valid on
6486  *    disk through step 4.
6487  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6488  *    eliminate journal work for those records that do not require it.
6489  * 5) Schedule the journal records to be written followed by the inode block.
6490  * 6) Allocate any necessary frags for the end of file.
6491  * 7) Zero any partially truncated blocks.
6492  *
6493  * From this truncation proceeds asynchronously using the freework and
6494  * indir_trunc machinery.  The file will not be extended again into a
6495  * partially truncated indirect block until all work is completed but
6496  * the normal dependency mechanism ensures that it is rolled back/forward
6497  * as appropriate.  Further truncation may occur without delay and is
6498  * serialized in indir_trunc().
6499  */
6500 void
6501 softdep_journal_freeblocks(ip, cred, length, flags)
6502 	struct inode *ip;	/* The inode whose length is to be reduced */
6503 	struct ucred *cred;
6504 	off_t length;		/* The new length for the file */
6505 	int flags;		/* IO_EXT and/or IO_NORMAL */
6506 {
6507 	struct freeblks *freeblks, *fbn;
6508 	struct worklist *wk, *wkn;
6509 	struct inodedep *inodedep;
6510 	struct jblkdep *jblkdep;
6511 	struct allocdirect *adp, *adpn;
6512 	struct ufsmount *ump;
6513 	struct fs *fs;
6514 	struct buf *bp;
6515 	struct vnode *vp;
6516 	struct mount *mp;
6517 	ufs2_daddr_t extblocks, datablocks;
6518 	ufs_lbn_t tmpval, lbn, lastlbn;
6519 	int frags, lastoff, iboff, allocblock, needj, error, i;
6520 
6521 	ump = ITOUMP(ip);
6522 	mp = UFSTOVFS(ump);
6523 	fs = ump->um_fs;
6524 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6525 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6526 	vp = ITOV(ip);
6527 	needj = 1;
6528 	iboff = -1;
6529 	allocblock = 0;
6530 	extblocks = 0;
6531 	datablocks = 0;
6532 	frags = 0;
6533 	freeblks = newfreeblks(mp, ip);
6534 	ACQUIRE_LOCK(ump);
6535 	/*
6536 	 * If we're truncating a removed file that will never be written
6537 	 * we don't need to journal the block frees.  The canceled journals
6538 	 * for the allocations will suffice.
6539 	 */
6540 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6541 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6542 	    length == 0)
6543 		needj = 0;
6544 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6545 	    ip->i_number, length, needj);
6546 	FREE_LOCK(ump);
6547 	/*
6548 	 * Calculate the lbn that we are truncating to.  This results in -1
6549 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6550 	 * to keep, not the first lbn we want to truncate.
6551 	 */
6552 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6553 	lastoff = blkoff(fs, length);
6554 	/*
6555 	 * Compute frags we are keeping in lastlbn.  0 means all.
6556 	 */
6557 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6558 		frags = fragroundup(fs, lastoff);
6559 		/* adp offset of last valid allocdirect. */
6560 		iboff = lastlbn;
6561 	} else if (lastlbn > 0)
6562 		iboff = UFS_NDADDR;
6563 	if (fs->fs_magic == FS_UFS2_MAGIC)
6564 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6565 	/*
6566 	 * Handle normal data blocks and indirects.  This section saves
6567 	 * values used after the inode update to complete frag and indirect
6568 	 * truncation.
6569 	 */
6570 	if ((flags & IO_NORMAL) != 0) {
6571 		/*
6572 		 * Handle truncation of whole direct and indirect blocks.
6573 		 */
6574 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6575 			setup_freedirect(freeblks, ip, i, needj);
6576 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6577 		    i < UFS_NIADDR;
6578 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6579 			/* Release a whole indirect tree. */
6580 			if (lbn > lastlbn) {
6581 				setup_freeindir(freeblks, ip, i, -lbn -i,
6582 				    needj);
6583 				continue;
6584 			}
6585 			iboff = i + UFS_NDADDR;
6586 			/*
6587 			 * Traverse partially truncated indirect tree.
6588 			 */
6589 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6590 				setup_trunc_indir(freeblks, ip, -lbn - i,
6591 				    lastlbn, DIP(ip, i_ib[i]));
6592 		}
6593 		/*
6594 		 * Handle partial truncation to a frag boundary.
6595 		 */
6596 		if (frags) {
6597 			ufs2_daddr_t blkno;
6598 			long oldfrags;
6599 
6600 			oldfrags = blksize(fs, ip, lastlbn);
6601 			blkno = DIP(ip, i_db[lastlbn]);
6602 			if (blkno && oldfrags != frags) {
6603 				oldfrags -= frags;
6604 				oldfrags = numfrags(fs, oldfrags);
6605 				blkno += numfrags(fs, frags);
6606 				newfreework(ump, freeblks, NULL, lastlbn,
6607 				    blkno, oldfrags, 0, needj);
6608 				if (needj)
6609 					adjust_newfreework(freeblks,
6610 					    numfrags(fs, frags));
6611 			} else if (blkno == 0)
6612 				allocblock = 1;
6613 		}
6614 		/*
6615 		 * Add a journal record for partial truncate if we are
6616 		 * handling indirect blocks.  Non-indirects need no extra
6617 		 * journaling.
6618 		 */
6619 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6620 			ip->i_flag |= IN_TRUNCATED;
6621 			newjtrunc(freeblks, length, 0);
6622 		}
6623 		ip->i_size = length;
6624 		DIP_SET(ip, i_size, ip->i_size);
6625 		datablocks = DIP(ip, i_blocks) - extblocks;
6626 		if (length != 0)
6627 			datablocks = blkcount(fs, datablocks, length);
6628 		freeblks->fb_len = length;
6629 	}
6630 	if ((flags & IO_EXT) != 0) {
6631 		for (i = 0; i < UFS_NXADDR; i++)
6632 			setup_freeext(freeblks, ip, i, needj);
6633 		ip->i_din2->di_extsize = 0;
6634 		datablocks += extblocks;
6635 	}
6636 #ifdef QUOTA
6637 	/* Reference the quotas in case the block count is wrong in the end. */
6638 	quotaref(vp, freeblks->fb_quota);
6639 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6640 #endif
6641 	freeblks->fb_chkcnt = -datablocks;
6642 	UFS_LOCK(ump);
6643 	fs->fs_pendingblocks += datablocks;
6644 	UFS_UNLOCK(ump);
6645 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6646 	/*
6647 	 * Handle truncation of incomplete alloc direct dependencies.  We
6648 	 * hold the inode block locked to prevent incomplete dependencies
6649 	 * from reaching the disk while we are eliminating those that
6650 	 * have been truncated.  This is a partially inlined ffs_update().
6651 	 */
6652 	ufs_itimes(vp);
6653 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6654 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6655 	    (int)fs->fs_bsize, cred, &bp);
6656 	if (error) {
6657 		brelse(bp);
6658 		softdep_error("softdep_journal_freeblocks", error);
6659 		return;
6660 	}
6661 	if (bp->b_bufsize == fs->fs_bsize)
6662 		bp->b_flags |= B_CLUSTEROK;
6663 	softdep_update_inodeblock(ip, bp, 0);
6664 	if (ump->um_fstype == UFS1)
6665 		*((struct ufs1_dinode *)bp->b_data +
6666 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6667 	else
6668 		*((struct ufs2_dinode *)bp->b_data +
6669 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6670 	ACQUIRE_LOCK(ump);
6671 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6672 	if ((inodedep->id_state & IOSTARTED) != 0)
6673 		panic("softdep_setup_freeblocks: inode busy");
6674 	/*
6675 	 * Add the freeblks structure to the list of operations that
6676 	 * must await the zero'ed inode being written to disk. If we
6677 	 * still have a bitmap dependency (needj), then the inode
6678 	 * has never been written to disk, so we can process the
6679 	 * freeblks below once we have deleted the dependencies.
6680 	 */
6681 	if (needj)
6682 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6683 	else
6684 		freeblks->fb_state |= COMPLETE;
6685 	if ((flags & IO_NORMAL) != 0) {
6686 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6687 			if (adp->ad_offset > iboff)
6688 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6689 				    freeblks);
6690 			/*
6691 			 * Truncate the allocdirect.  We could eliminate
6692 			 * or modify journal records as well.
6693 			 */
6694 			else if (adp->ad_offset == iboff && frags)
6695 				adp->ad_newsize = frags;
6696 		}
6697 	}
6698 	if ((flags & IO_EXT) != 0)
6699 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6700 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6701 			    freeblks);
6702 	/*
6703 	 * Scan the bufwait list for newblock dependencies that will never
6704 	 * make it to disk.
6705 	 */
6706 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6707 		if (wk->wk_type != D_ALLOCDIRECT)
6708 			continue;
6709 		adp = WK_ALLOCDIRECT(wk);
6710 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6711 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6712 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6713 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6714 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6715 		}
6716 	}
6717 	/*
6718 	 * Add journal work.
6719 	 */
6720 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6721 		add_to_journal(&jblkdep->jb_list);
6722 	FREE_LOCK(ump);
6723 	bdwrite(bp);
6724 	/*
6725 	 * Truncate dependency structures beyond length.
6726 	 */
6727 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6728 	/*
6729 	 * This is only set when we need to allocate a fragment because
6730 	 * none existed at the end of a frag-sized file.  It handles only
6731 	 * allocating a new, zero filled block.
6732 	 */
6733 	if (allocblock) {
6734 		ip->i_size = length - lastoff;
6735 		DIP_SET(ip, i_size, ip->i_size);
6736 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6737 		if (error != 0) {
6738 			softdep_error("softdep_journal_freeblks", error);
6739 			return;
6740 		}
6741 		ip->i_size = length;
6742 		DIP_SET(ip, i_size, length);
6743 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6744 		allocbuf(bp, frags);
6745 		ffs_update(vp, 0);
6746 		bawrite(bp);
6747 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6748 		int size;
6749 
6750 		/*
6751 		 * Zero the end of a truncated frag or block.
6752 		 */
6753 		size = sblksize(fs, length, lastlbn);
6754 		error = bread(vp, lastlbn, size, cred, &bp);
6755 		if (error) {
6756 			softdep_error("softdep_journal_freeblks", error);
6757 			return;
6758 		}
6759 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6760 		bawrite(bp);
6761 
6762 	}
6763 	ACQUIRE_LOCK(ump);
6764 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6765 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6766 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6767 	/*
6768 	 * We zero earlier truncations so they don't erroneously
6769 	 * update i_blocks.
6770 	 */
6771 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6772 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6773 			fbn->fb_len = 0;
6774 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6775 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6776 		freeblks->fb_state |= INPROGRESS;
6777 	else
6778 		freeblks = NULL;
6779 	FREE_LOCK(ump);
6780 	if (freeblks)
6781 		handle_workitem_freeblocks(freeblks, 0);
6782 	trunc_pages(ip, length, extblocks, flags);
6783 
6784 }
6785 
6786 /*
6787  * Flush a JOP_SYNC to the journal.
6788  */
6789 void
6790 softdep_journal_fsync(ip)
6791 	struct inode *ip;
6792 {
6793 	struct jfsync *jfsync;
6794 	struct ufsmount *ump;
6795 
6796 	ump = ITOUMP(ip);
6797 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6798 	    ("softdep_journal_fsync called on non-softdep filesystem"));
6799 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6800 		return;
6801 	ip->i_flag &= ~IN_TRUNCATED;
6802 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6803 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6804 	jfsync->jfs_size = ip->i_size;
6805 	jfsync->jfs_ino = ip->i_number;
6806 	ACQUIRE_LOCK(ump);
6807 	add_to_journal(&jfsync->jfs_list);
6808 	jwait(&jfsync->jfs_list, MNT_WAIT);
6809 	FREE_LOCK(ump);
6810 }
6811 
6812 /*
6813  * Block de-allocation dependencies.
6814  *
6815  * When blocks are de-allocated, the on-disk pointers must be nullified before
6816  * the blocks are made available for use by other files.  (The true
6817  * requirement is that old pointers must be nullified before new on-disk
6818  * pointers are set.  We chose this slightly more stringent requirement to
6819  * reduce complexity.) Our implementation handles this dependency by updating
6820  * the inode (or indirect block) appropriately but delaying the actual block
6821  * de-allocation (i.e., freemap and free space count manipulation) until
6822  * after the updated versions reach stable storage.  After the disk is
6823  * updated, the blocks can be safely de-allocated whenever it is convenient.
6824  * This implementation handles only the common case of reducing a file's
6825  * length to zero. Other cases are handled by the conventional synchronous
6826  * write approach.
6827  *
6828  * The ffs implementation with which we worked double-checks
6829  * the state of the block pointers and file size as it reduces
6830  * a file's length.  Some of this code is replicated here in our
6831  * soft updates implementation.  The freeblks->fb_chkcnt field is
6832  * used to transfer a part of this information to the procedure
6833  * that eventually de-allocates the blocks.
6834  *
6835  * This routine should be called from the routine that shortens
6836  * a file's length, before the inode's size or block pointers
6837  * are modified. It will save the block pointer information for
6838  * later release and zero the inode so that the calling routine
6839  * can release it.
6840  */
6841 void
6842 softdep_setup_freeblocks(ip, length, flags)
6843 	struct inode *ip;	/* The inode whose length is to be reduced */
6844 	off_t length;		/* The new length for the file */
6845 	int flags;		/* IO_EXT and/or IO_NORMAL */
6846 {
6847 	struct ufs1_dinode *dp1;
6848 	struct ufs2_dinode *dp2;
6849 	struct freeblks *freeblks;
6850 	struct inodedep *inodedep;
6851 	struct allocdirect *adp;
6852 	struct ufsmount *ump;
6853 	struct buf *bp;
6854 	struct fs *fs;
6855 	ufs2_daddr_t extblocks, datablocks;
6856 	struct mount *mp;
6857 	int i, delay, error;
6858 	ufs_lbn_t tmpval;
6859 	ufs_lbn_t lbn;
6860 
6861 	ump = ITOUMP(ip);
6862 	mp = UFSTOVFS(ump);
6863 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6864 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6865 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6866 	    ip->i_number, length);
6867 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6868 	fs = ump->um_fs;
6869 	if ((error = bread(ump->um_devvp,
6870 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6871 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6872 		brelse(bp);
6873 		softdep_error("softdep_setup_freeblocks", error);
6874 		return;
6875 	}
6876 	freeblks = newfreeblks(mp, ip);
6877 	extblocks = 0;
6878 	datablocks = 0;
6879 	if (fs->fs_magic == FS_UFS2_MAGIC)
6880 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6881 	if ((flags & IO_NORMAL) != 0) {
6882 		for (i = 0; i < UFS_NDADDR; i++)
6883 			setup_freedirect(freeblks, ip, i, 0);
6884 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6885 		    i < UFS_NIADDR;
6886 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6887 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6888 		ip->i_size = 0;
6889 		DIP_SET(ip, i_size, 0);
6890 		datablocks = DIP(ip, i_blocks) - extblocks;
6891 	}
6892 	if ((flags & IO_EXT) != 0) {
6893 		for (i = 0; i < UFS_NXADDR; i++)
6894 			setup_freeext(freeblks, ip, i, 0);
6895 		ip->i_din2->di_extsize = 0;
6896 		datablocks += extblocks;
6897 	}
6898 #ifdef QUOTA
6899 	/* Reference the quotas in case the block count is wrong in the end. */
6900 	quotaref(ITOV(ip), freeblks->fb_quota);
6901 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6902 #endif
6903 	freeblks->fb_chkcnt = -datablocks;
6904 	UFS_LOCK(ump);
6905 	fs->fs_pendingblocks += datablocks;
6906 	UFS_UNLOCK(ump);
6907 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6908 	/*
6909 	 * Push the zero'ed inode to to its disk buffer so that we are free
6910 	 * to delete its dependencies below. Once the dependencies are gone
6911 	 * the buffer can be safely released.
6912 	 */
6913 	if (ump->um_fstype == UFS1) {
6914 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6915 		    ino_to_fsbo(fs, ip->i_number));
6916 		ip->i_din1->di_freelink = dp1->di_freelink;
6917 		*dp1 = *ip->i_din1;
6918 	} else {
6919 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6920 		    ino_to_fsbo(fs, ip->i_number));
6921 		ip->i_din2->di_freelink = dp2->di_freelink;
6922 		*dp2 = *ip->i_din2;
6923 	}
6924 	/*
6925 	 * Find and eliminate any inode dependencies.
6926 	 */
6927 	ACQUIRE_LOCK(ump);
6928 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6929 	if ((inodedep->id_state & IOSTARTED) != 0)
6930 		panic("softdep_setup_freeblocks: inode busy");
6931 	/*
6932 	 * Add the freeblks structure to the list of operations that
6933 	 * must await the zero'ed inode being written to disk. If we
6934 	 * still have a bitmap dependency (delay == 0), then the inode
6935 	 * has never been written to disk, so we can process the
6936 	 * freeblks below once we have deleted the dependencies.
6937 	 */
6938 	delay = (inodedep->id_state & DEPCOMPLETE);
6939 	if (delay)
6940 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6941 	else
6942 		freeblks->fb_state |= COMPLETE;
6943 	/*
6944 	 * Because the file length has been truncated to zero, any
6945 	 * pending block allocation dependency structures associated
6946 	 * with this inode are obsolete and can simply be de-allocated.
6947 	 * We must first merge the two dependency lists to get rid of
6948 	 * any duplicate freefrag structures, then purge the merged list.
6949 	 * If we still have a bitmap dependency, then the inode has never
6950 	 * been written to disk, so we can free any fragments without delay.
6951 	 */
6952 	if (flags & IO_NORMAL) {
6953 		merge_inode_lists(&inodedep->id_newinoupdt,
6954 		    &inodedep->id_inoupdt);
6955 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
6956 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
6957 			    freeblks);
6958 	}
6959 	if (flags & IO_EXT) {
6960 		merge_inode_lists(&inodedep->id_newextupdt,
6961 		    &inodedep->id_extupdt);
6962 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6963 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6964 			    freeblks);
6965 	}
6966 	FREE_LOCK(ump);
6967 	bdwrite(bp);
6968 	trunc_dependencies(ip, freeblks, -1, 0, flags);
6969 	ACQUIRE_LOCK(ump);
6970 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6971 		(void) free_inodedep(inodedep);
6972 	freeblks->fb_state |= DEPCOMPLETE;
6973 	/*
6974 	 * If the inode with zeroed block pointers is now on disk
6975 	 * we can start freeing blocks.
6976 	 */
6977 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6978 		freeblks->fb_state |= INPROGRESS;
6979 	else
6980 		freeblks = NULL;
6981 	FREE_LOCK(ump);
6982 	if (freeblks)
6983 		handle_workitem_freeblocks(freeblks, 0);
6984 	trunc_pages(ip, length, extblocks, flags);
6985 }
6986 
6987 /*
6988  * Eliminate pages from the page cache that back parts of this inode and
6989  * adjust the vnode pager's idea of our size.  This prevents stale data
6990  * from hanging around in the page cache.
6991  */
6992 static void
6993 trunc_pages(ip, length, extblocks, flags)
6994 	struct inode *ip;
6995 	off_t length;
6996 	ufs2_daddr_t extblocks;
6997 	int flags;
6998 {
6999 	struct vnode *vp;
7000 	struct fs *fs;
7001 	ufs_lbn_t lbn;
7002 	off_t end, extend;
7003 
7004 	vp = ITOV(ip);
7005 	fs = ITOFS(ip);
7006 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7007 	if ((flags & IO_EXT) != 0)
7008 		vn_pages_remove(vp, extend, 0);
7009 	if ((flags & IO_NORMAL) == 0)
7010 		return;
7011 	BO_LOCK(&vp->v_bufobj);
7012 	drain_output(vp);
7013 	BO_UNLOCK(&vp->v_bufobj);
7014 	/*
7015 	 * The vnode pager eliminates file pages we eliminate indirects
7016 	 * below.
7017 	 */
7018 	vnode_pager_setsize(vp, length);
7019 	/*
7020 	 * Calculate the end based on the last indirect we want to keep.  If
7021 	 * the block extends into indirects we can just use the negative of
7022 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7023 	 * be careful not to remove those, if they exist.  double and triple
7024 	 * indirect lbns do not overlap with others so it is not important
7025 	 * to verify how many levels are required.
7026 	 */
7027 	lbn = lblkno(fs, length);
7028 	if (lbn >= UFS_NDADDR) {
7029 		/* Calculate the virtual lbn of the triple indirect. */
7030 		lbn = -lbn - (UFS_NIADDR - 1);
7031 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7032 	} else
7033 		end = extend;
7034 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7035 }
7036 
7037 /*
7038  * See if the buf bp is in the range eliminated by truncation.
7039  */
7040 static int
7041 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7042 	struct buf *bp;
7043 	int *blkoffp;
7044 	ufs_lbn_t lastlbn;
7045 	int lastoff;
7046 	int flags;
7047 {
7048 	ufs_lbn_t lbn;
7049 
7050 	*blkoffp = 0;
7051 	/* Only match ext/normal blocks as appropriate. */
7052 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7053 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7054 		return (0);
7055 	/* ALTDATA is always a full truncation. */
7056 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7057 		return (1);
7058 	/* -1 is full truncation. */
7059 	if (lastlbn == -1)
7060 		return (1);
7061 	/*
7062 	 * If this is a partial truncate we only want those
7063 	 * blocks and indirect blocks that cover the range
7064 	 * we're after.
7065 	 */
7066 	lbn = bp->b_lblkno;
7067 	if (lbn < 0)
7068 		lbn = -(lbn + lbn_level(lbn));
7069 	if (lbn < lastlbn)
7070 		return (0);
7071 	/* Here we only truncate lblkno if it's partial. */
7072 	if (lbn == lastlbn) {
7073 		if (lastoff == 0)
7074 			return (0);
7075 		*blkoffp = lastoff;
7076 	}
7077 	return (1);
7078 }
7079 
7080 /*
7081  * Eliminate any dependencies that exist in memory beyond lblkno:off
7082  */
7083 static void
7084 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7085 	struct inode *ip;
7086 	struct freeblks *freeblks;
7087 	ufs_lbn_t lastlbn;
7088 	int lastoff;
7089 	int flags;
7090 {
7091 	struct bufobj *bo;
7092 	struct vnode *vp;
7093 	struct buf *bp;
7094 	int blkoff;
7095 
7096 	/*
7097 	 * We must wait for any I/O in progress to finish so that
7098 	 * all potential buffers on the dirty list will be visible.
7099 	 * Once they are all there, walk the list and get rid of
7100 	 * any dependencies.
7101 	 */
7102 	vp = ITOV(ip);
7103 	bo = &vp->v_bufobj;
7104 	BO_LOCK(bo);
7105 	drain_output(vp);
7106 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7107 		bp->b_vflags &= ~BV_SCANNED;
7108 restart:
7109 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7110 		if (bp->b_vflags & BV_SCANNED)
7111 			continue;
7112 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7113 			bp->b_vflags |= BV_SCANNED;
7114 			continue;
7115 		}
7116 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7117 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7118 			goto restart;
7119 		BO_UNLOCK(bo);
7120 		if (deallocate_dependencies(bp, freeblks, blkoff))
7121 			bqrelse(bp);
7122 		else
7123 			brelse(bp);
7124 		BO_LOCK(bo);
7125 		goto restart;
7126 	}
7127 	/*
7128 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7129 	 */
7130 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7131 		bp->b_vflags &= ~BV_SCANNED;
7132 cleanrestart:
7133 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7134 		if (bp->b_vflags & BV_SCANNED)
7135 			continue;
7136 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7137 			bp->b_vflags |= BV_SCANNED;
7138 			continue;
7139 		}
7140 		if (BUF_LOCK(bp,
7141 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7142 		    BO_LOCKPTR(bo)) == ENOLCK) {
7143 			BO_LOCK(bo);
7144 			goto cleanrestart;
7145 		}
7146 		bp->b_vflags |= BV_SCANNED;
7147 		bremfree(bp);
7148 		if (blkoff != 0) {
7149 			allocbuf(bp, blkoff);
7150 			bqrelse(bp);
7151 		} else {
7152 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7153 			brelse(bp);
7154 		}
7155 		BO_LOCK(bo);
7156 		goto cleanrestart;
7157 	}
7158 	drain_output(vp);
7159 	BO_UNLOCK(bo);
7160 }
7161 
7162 static int
7163 cancel_pagedep(pagedep, freeblks, blkoff)
7164 	struct pagedep *pagedep;
7165 	struct freeblks *freeblks;
7166 	int blkoff;
7167 {
7168 	struct jremref *jremref;
7169 	struct jmvref *jmvref;
7170 	struct dirrem *dirrem, *tmp;
7171 	int i;
7172 
7173 	/*
7174 	 * Copy any directory remove dependencies to the list
7175 	 * to be processed after the freeblks proceeds.  If
7176 	 * directory entry never made it to disk they
7177 	 * can be dumped directly onto the work list.
7178 	 */
7179 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7180 		/* Skip this directory removal if it is intended to remain. */
7181 		if (dirrem->dm_offset < blkoff)
7182 			continue;
7183 		/*
7184 		 * If there are any dirrems we wait for the journal write
7185 		 * to complete and then restart the buf scan as the lock
7186 		 * has been dropped.
7187 		 */
7188 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7189 			jwait(&jremref->jr_list, MNT_WAIT);
7190 			return (ERESTART);
7191 		}
7192 		LIST_REMOVE(dirrem, dm_next);
7193 		dirrem->dm_dirinum = pagedep->pd_ino;
7194 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7195 	}
7196 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7197 		jwait(&jmvref->jm_list, MNT_WAIT);
7198 		return (ERESTART);
7199 	}
7200 	/*
7201 	 * When we're partially truncating a pagedep we just want to flush
7202 	 * journal entries and return.  There can not be any adds in the
7203 	 * truncated portion of the directory and newblk must remain if
7204 	 * part of the block remains.
7205 	 */
7206 	if (blkoff != 0) {
7207 		struct diradd *dap;
7208 
7209 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7210 			if (dap->da_offset > blkoff)
7211 				panic("cancel_pagedep: diradd %p off %d > %d",
7212 				    dap, dap->da_offset, blkoff);
7213 		for (i = 0; i < DAHASHSZ; i++)
7214 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7215 				if (dap->da_offset > blkoff)
7216 					panic("cancel_pagedep: diradd %p off %d > %d",
7217 					    dap, dap->da_offset, blkoff);
7218 		return (0);
7219 	}
7220 	/*
7221 	 * There should be no directory add dependencies present
7222 	 * as the directory could not be truncated until all
7223 	 * children were removed.
7224 	 */
7225 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7226 	    ("deallocate_dependencies: pendinghd != NULL"));
7227 	for (i = 0; i < DAHASHSZ; i++)
7228 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7229 		    ("deallocate_dependencies: diraddhd != NULL"));
7230 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7231 		free_newdirblk(pagedep->pd_newdirblk);
7232 	if (free_pagedep(pagedep) == 0)
7233 		panic("Failed to free pagedep %p", pagedep);
7234 	return (0);
7235 }
7236 
7237 /*
7238  * Reclaim any dependency structures from a buffer that is about to
7239  * be reallocated to a new vnode. The buffer must be locked, thus,
7240  * no I/O completion operations can occur while we are manipulating
7241  * its associated dependencies. The mutex is held so that other I/O's
7242  * associated with related dependencies do not occur.
7243  */
7244 static int
7245 deallocate_dependencies(bp, freeblks, off)
7246 	struct buf *bp;
7247 	struct freeblks *freeblks;
7248 	int off;
7249 {
7250 	struct indirdep *indirdep;
7251 	struct pagedep *pagedep;
7252 	struct worklist *wk, *wkn;
7253 	struct ufsmount *ump;
7254 
7255 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
7256 		goto done;
7257 	ump = VFSTOUFS(wk->wk_mp);
7258 	ACQUIRE_LOCK(ump);
7259 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7260 		switch (wk->wk_type) {
7261 		case D_INDIRDEP:
7262 			indirdep = WK_INDIRDEP(wk);
7263 			if (bp->b_lblkno >= 0 ||
7264 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7265 				panic("deallocate_dependencies: not indir");
7266 			cancel_indirdep(indirdep, bp, freeblks);
7267 			continue;
7268 
7269 		case D_PAGEDEP:
7270 			pagedep = WK_PAGEDEP(wk);
7271 			if (cancel_pagedep(pagedep, freeblks, off)) {
7272 				FREE_LOCK(ump);
7273 				return (ERESTART);
7274 			}
7275 			continue;
7276 
7277 		case D_ALLOCINDIR:
7278 			/*
7279 			 * Simply remove the allocindir, we'll find it via
7280 			 * the indirdep where we can clear pointers if
7281 			 * needed.
7282 			 */
7283 			WORKLIST_REMOVE(wk);
7284 			continue;
7285 
7286 		case D_FREEWORK:
7287 			/*
7288 			 * A truncation is waiting for the zero'd pointers
7289 			 * to be written.  It can be freed when the freeblks
7290 			 * is journaled.
7291 			 */
7292 			WORKLIST_REMOVE(wk);
7293 			wk->wk_state |= ONDEPLIST;
7294 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7295 			break;
7296 
7297 		case D_ALLOCDIRECT:
7298 			if (off != 0)
7299 				continue;
7300 			/* FALLTHROUGH */
7301 		default:
7302 			panic("deallocate_dependencies: Unexpected type %s",
7303 			    TYPENAME(wk->wk_type));
7304 			/* NOTREACHED */
7305 		}
7306 	}
7307 	FREE_LOCK(ump);
7308 done:
7309 	/*
7310 	 * Don't throw away this buf, we were partially truncating and
7311 	 * some deps may always remain.
7312 	 */
7313 	if (off) {
7314 		allocbuf(bp, off);
7315 		bp->b_vflags |= BV_SCANNED;
7316 		return (EBUSY);
7317 	}
7318 	bp->b_flags |= B_INVAL | B_NOCACHE;
7319 
7320 	return (0);
7321 }
7322 
7323 /*
7324  * An allocdirect is being canceled due to a truncate.  We must make sure
7325  * the journal entry is released in concert with the blkfree that releases
7326  * the storage.  Completed journal entries must not be released until the
7327  * space is no longer pointed to by the inode or in the bitmap.
7328  */
7329 static void
7330 cancel_allocdirect(adphead, adp, freeblks)
7331 	struct allocdirectlst *adphead;
7332 	struct allocdirect *adp;
7333 	struct freeblks *freeblks;
7334 {
7335 	struct freework *freework;
7336 	struct newblk *newblk;
7337 	struct worklist *wk;
7338 
7339 	TAILQ_REMOVE(adphead, adp, ad_next);
7340 	newblk = (struct newblk *)adp;
7341 	freework = NULL;
7342 	/*
7343 	 * Find the correct freework structure.
7344 	 */
7345 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7346 		if (wk->wk_type != D_FREEWORK)
7347 			continue;
7348 		freework = WK_FREEWORK(wk);
7349 		if (freework->fw_blkno == newblk->nb_newblkno)
7350 			break;
7351 	}
7352 	if (freework == NULL)
7353 		panic("cancel_allocdirect: Freework not found");
7354 	/*
7355 	 * If a newblk exists at all we still have the journal entry that
7356 	 * initiated the allocation so we do not need to journal the free.
7357 	 */
7358 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7359 	/*
7360 	 * If the journal hasn't been written the jnewblk must be passed
7361 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7362 	 * this by linking the journal dependency into the freework to be
7363 	 * freed when freework_freeblock() is called.  If the journal has
7364 	 * been written we can simply reclaim the journal space when the
7365 	 * freeblks work is complete.
7366 	 */
7367 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7368 	    &freeblks->fb_jwork);
7369 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7370 }
7371 
7372 
7373 /*
7374  * Cancel a new block allocation.  May be an indirect or direct block.  We
7375  * remove it from various lists and return any journal record that needs to
7376  * be resolved by the caller.
7377  *
7378  * A special consideration is made for indirects which were never pointed
7379  * at on disk and will never be found once this block is released.
7380  */
7381 static struct jnewblk *
7382 cancel_newblk(newblk, wk, wkhd)
7383 	struct newblk *newblk;
7384 	struct worklist *wk;
7385 	struct workhead *wkhd;
7386 {
7387 	struct jnewblk *jnewblk;
7388 
7389 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7390 
7391 	newblk->nb_state |= GOINGAWAY;
7392 	/*
7393 	 * Previously we traversed the completedhd on each indirdep
7394 	 * attached to this newblk to cancel them and gather journal
7395 	 * work.  Since we need only the oldest journal segment and
7396 	 * the lowest point on the tree will always have the oldest
7397 	 * journal segment we are free to release the segments
7398 	 * of any subordinates and may leave the indirdep list to
7399 	 * indirdep_complete() when this newblk is freed.
7400 	 */
7401 	if (newblk->nb_state & ONDEPLIST) {
7402 		newblk->nb_state &= ~ONDEPLIST;
7403 		LIST_REMOVE(newblk, nb_deps);
7404 	}
7405 	if (newblk->nb_state & ONWORKLIST)
7406 		WORKLIST_REMOVE(&newblk->nb_list);
7407 	/*
7408 	 * If the journal entry hasn't been written we save a pointer to
7409 	 * the dependency that frees it until it is written or the
7410 	 * superseding operation completes.
7411 	 */
7412 	jnewblk = newblk->nb_jnewblk;
7413 	if (jnewblk != NULL && wk != NULL) {
7414 		newblk->nb_jnewblk = NULL;
7415 		jnewblk->jn_dep = wk;
7416 	}
7417 	if (!LIST_EMPTY(&newblk->nb_jwork))
7418 		jwork_move(wkhd, &newblk->nb_jwork);
7419 	/*
7420 	 * When truncating we must free the newdirblk early to remove
7421 	 * the pagedep from the hash before returning.
7422 	 */
7423 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7424 		free_newdirblk(WK_NEWDIRBLK(wk));
7425 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7426 		panic("cancel_newblk: extra newdirblk");
7427 
7428 	return (jnewblk);
7429 }
7430 
7431 /*
7432  * Schedule the freefrag associated with a newblk to be released once
7433  * the pointers are written and the previous block is no longer needed.
7434  */
7435 static void
7436 newblk_freefrag(newblk)
7437 	struct newblk *newblk;
7438 {
7439 	struct freefrag *freefrag;
7440 
7441 	if (newblk->nb_freefrag == NULL)
7442 		return;
7443 	freefrag = newblk->nb_freefrag;
7444 	newblk->nb_freefrag = NULL;
7445 	freefrag->ff_state |= COMPLETE;
7446 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7447 		add_to_worklist(&freefrag->ff_list, 0);
7448 }
7449 
7450 /*
7451  * Free a newblk. Generate a new freefrag work request if appropriate.
7452  * This must be called after the inode pointer and any direct block pointers
7453  * are valid or fully removed via truncate or frag extension.
7454  */
7455 static void
7456 free_newblk(newblk)
7457 	struct newblk *newblk;
7458 {
7459 	struct indirdep *indirdep;
7460 	struct worklist *wk;
7461 
7462 	KASSERT(newblk->nb_jnewblk == NULL,
7463 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7464 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7465 	    ("free_newblk: unclaimed newblk"));
7466 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7467 	newblk_freefrag(newblk);
7468 	if (newblk->nb_state & ONDEPLIST)
7469 		LIST_REMOVE(newblk, nb_deps);
7470 	if (newblk->nb_state & ONWORKLIST)
7471 		WORKLIST_REMOVE(&newblk->nb_list);
7472 	LIST_REMOVE(newblk, nb_hash);
7473 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7474 		free_newdirblk(WK_NEWDIRBLK(wk));
7475 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7476 		panic("free_newblk: extra newdirblk");
7477 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7478 		indirdep_complete(indirdep);
7479 	handle_jwork(&newblk->nb_jwork);
7480 	WORKITEM_FREE(newblk, D_NEWBLK);
7481 }
7482 
7483 /*
7484  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7485  * This routine must be called with splbio interrupts blocked.
7486  */
7487 static void
7488 free_newdirblk(newdirblk)
7489 	struct newdirblk *newdirblk;
7490 {
7491 	struct pagedep *pagedep;
7492 	struct diradd *dap;
7493 	struct worklist *wk;
7494 
7495 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7496 	WORKLIST_REMOVE(&newdirblk->db_list);
7497 	/*
7498 	 * If the pagedep is still linked onto the directory buffer
7499 	 * dependency chain, then some of the entries on the
7500 	 * pd_pendinghd list may not be committed to disk yet. In
7501 	 * this case, we will simply clear the NEWBLOCK flag and
7502 	 * let the pd_pendinghd list be processed when the pagedep
7503 	 * is next written. If the pagedep is no longer on the buffer
7504 	 * dependency chain, then all the entries on the pd_pending
7505 	 * list are committed to disk and we can free them here.
7506 	 */
7507 	pagedep = newdirblk->db_pagedep;
7508 	pagedep->pd_state &= ~NEWBLOCK;
7509 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7510 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7511 			free_diradd(dap, NULL);
7512 		/*
7513 		 * If no dependencies remain, the pagedep will be freed.
7514 		 */
7515 		free_pagedep(pagedep);
7516 	}
7517 	/* Should only ever be one item in the list. */
7518 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7519 		WORKLIST_REMOVE(wk);
7520 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7521 	}
7522 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7523 }
7524 
7525 /*
7526  * Prepare an inode to be freed. The actual free operation is not
7527  * done until the zero'ed inode has been written to disk.
7528  */
7529 void
7530 softdep_freefile(pvp, ino, mode)
7531 	struct vnode *pvp;
7532 	ino_t ino;
7533 	int mode;
7534 {
7535 	struct inode *ip = VTOI(pvp);
7536 	struct inodedep *inodedep;
7537 	struct freefile *freefile;
7538 	struct freeblks *freeblks;
7539 	struct ufsmount *ump;
7540 
7541 	ump = ITOUMP(ip);
7542 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7543 	    ("softdep_freefile called on non-softdep filesystem"));
7544 	/*
7545 	 * This sets up the inode de-allocation dependency.
7546 	 */
7547 	freefile = malloc(sizeof(struct freefile),
7548 		M_FREEFILE, M_SOFTDEP_FLAGS);
7549 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7550 	freefile->fx_mode = mode;
7551 	freefile->fx_oldinum = ino;
7552 	freefile->fx_devvp = ump->um_devvp;
7553 	LIST_INIT(&freefile->fx_jwork);
7554 	UFS_LOCK(ump);
7555 	ump->um_fs->fs_pendinginodes += 1;
7556 	UFS_UNLOCK(ump);
7557 
7558 	/*
7559 	 * If the inodedep does not exist, then the zero'ed inode has
7560 	 * been written to disk. If the allocated inode has never been
7561 	 * written to disk, then the on-disk inode is zero'ed. In either
7562 	 * case we can free the file immediately.  If the journal was
7563 	 * canceled before being written the inode will never make it to
7564 	 * disk and we must send the canceled journal entrys to
7565 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7566 	 * Any blocks waiting on the inode to write can be safely freed
7567 	 * here as it will never been written.
7568 	 */
7569 	ACQUIRE_LOCK(ump);
7570 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7571 	if (inodedep) {
7572 		/*
7573 		 * Clear out freeblks that no longer need to reference
7574 		 * this inode.
7575 		 */
7576 		while ((freeblks =
7577 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7578 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7579 			    fb_next);
7580 			freeblks->fb_state &= ~ONDEPLIST;
7581 		}
7582 		/*
7583 		 * Remove this inode from the unlinked list.
7584 		 */
7585 		if (inodedep->id_state & UNLINKED) {
7586 			/*
7587 			 * Save the journal work to be freed with the bitmap
7588 			 * before we clear UNLINKED.  Otherwise it can be lost
7589 			 * if the inode block is written.
7590 			 */
7591 			handle_bufwait(inodedep, &freefile->fx_jwork);
7592 			clear_unlinked_inodedep(inodedep);
7593 			/*
7594 			 * Re-acquire inodedep as we've dropped the
7595 			 * per-filesystem lock in clear_unlinked_inodedep().
7596 			 */
7597 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7598 		}
7599 	}
7600 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7601 		FREE_LOCK(ump);
7602 		handle_workitem_freefile(freefile);
7603 		return;
7604 	}
7605 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7606 		inodedep->id_state |= GOINGAWAY;
7607 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7608 	FREE_LOCK(ump);
7609 	if (ip->i_number == ino)
7610 		ip->i_flag |= IN_MODIFIED;
7611 }
7612 
7613 /*
7614  * Check to see if an inode has never been written to disk. If
7615  * so free the inodedep and return success, otherwise return failure.
7616  * This routine must be called with splbio interrupts blocked.
7617  *
7618  * If we still have a bitmap dependency, then the inode has never
7619  * been written to disk. Drop the dependency as it is no longer
7620  * necessary since the inode is being deallocated. We set the
7621  * ALLCOMPLETE flags since the bitmap now properly shows that the
7622  * inode is not allocated. Even if the inode is actively being
7623  * written, it has been rolled back to its zero'ed state, so we
7624  * are ensured that a zero inode is what is on the disk. For short
7625  * lived files, this change will usually result in removing all the
7626  * dependencies from the inode so that it can be freed immediately.
7627  */
7628 static int
7629 check_inode_unwritten(inodedep)
7630 	struct inodedep *inodedep;
7631 {
7632 
7633 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7634 
7635 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7636 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7637 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7638 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7639 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7640 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7641 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7642 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7643 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7644 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7645 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7646 	    inodedep->id_mkdiradd != NULL ||
7647 	    inodedep->id_nlinkdelta != 0)
7648 		return (0);
7649 	/*
7650 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7651 	 * trying to allocate memory without holding "Softdep Lock".
7652 	 */
7653 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7654 	    inodedep->id_savedino1 == NULL)
7655 		return (0);
7656 
7657 	if (inodedep->id_state & ONDEPLIST)
7658 		LIST_REMOVE(inodedep, id_deps);
7659 	inodedep->id_state &= ~ONDEPLIST;
7660 	inodedep->id_state |= ALLCOMPLETE;
7661 	inodedep->id_bmsafemap = NULL;
7662 	if (inodedep->id_state & ONWORKLIST)
7663 		WORKLIST_REMOVE(&inodedep->id_list);
7664 	if (inodedep->id_savedino1 != NULL) {
7665 		free(inodedep->id_savedino1, M_SAVEDINO);
7666 		inodedep->id_savedino1 = NULL;
7667 	}
7668 	if (free_inodedep(inodedep) == 0)
7669 		panic("check_inode_unwritten: busy inode");
7670 	return (1);
7671 }
7672 
7673 static int
7674 check_inodedep_free(inodedep)
7675 	struct inodedep *inodedep;
7676 {
7677 
7678 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7679 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7680 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7681 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7682 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7683 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7684 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7685 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7686 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7687 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7688 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7689 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7690 	    inodedep->id_mkdiradd != NULL ||
7691 	    inodedep->id_nlinkdelta != 0 ||
7692 	    inodedep->id_savedino1 != NULL)
7693 		return (0);
7694 	return (1);
7695 }
7696 
7697 /*
7698  * Try to free an inodedep structure. Return 1 if it could be freed.
7699  */
7700 static int
7701 free_inodedep(inodedep)
7702 	struct inodedep *inodedep;
7703 {
7704 
7705 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7706 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7707 	    !check_inodedep_free(inodedep))
7708 		return (0);
7709 	if (inodedep->id_state & ONDEPLIST)
7710 		LIST_REMOVE(inodedep, id_deps);
7711 	LIST_REMOVE(inodedep, id_hash);
7712 	WORKITEM_FREE(inodedep, D_INODEDEP);
7713 	return (1);
7714 }
7715 
7716 /*
7717  * Free the block referenced by a freework structure.  The parent freeblks
7718  * structure is released and completed when the final cg bitmap reaches
7719  * the disk.  This routine may be freeing a jnewblk which never made it to
7720  * disk in which case we do not have to wait as the operation is undone
7721  * in memory immediately.
7722  */
7723 static void
7724 freework_freeblock(freework)
7725 	struct freework *freework;
7726 {
7727 	struct freeblks *freeblks;
7728 	struct jnewblk *jnewblk;
7729 	struct ufsmount *ump;
7730 	struct workhead wkhd;
7731 	struct fs *fs;
7732 	int bsize;
7733 	int needj;
7734 
7735 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7736 	LOCK_OWNED(ump);
7737 	/*
7738 	 * Handle partial truncate separately.
7739 	 */
7740 	if (freework->fw_indir) {
7741 		complete_trunc_indir(freework);
7742 		return;
7743 	}
7744 	freeblks = freework->fw_freeblks;
7745 	fs = ump->um_fs;
7746 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7747 	bsize = lfragtosize(fs, freework->fw_frags);
7748 	LIST_INIT(&wkhd);
7749 	/*
7750 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7751 	 * on the indirblk hashtable and prevents premature freeing.
7752 	 */
7753 	freework->fw_state |= DEPCOMPLETE;
7754 	/*
7755 	 * SUJ needs to wait for the segment referencing freed indirect
7756 	 * blocks to expire so that we know the checker will not confuse
7757 	 * a re-allocated indirect block with its old contents.
7758 	 */
7759 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7760 		indirblk_insert(freework);
7761 	/*
7762 	 * If we are canceling an existing jnewblk pass it to the free
7763 	 * routine, otherwise pass the freeblk which will ultimately
7764 	 * release the freeblks.  If we're not journaling, we can just
7765 	 * free the freeblks immediately.
7766 	 */
7767 	jnewblk = freework->fw_jnewblk;
7768 	if (jnewblk != NULL) {
7769 		cancel_jnewblk(jnewblk, &wkhd);
7770 		needj = 0;
7771 	} else if (needj) {
7772 		freework->fw_state |= DELAYEDFREE;
7773 		freeblks->fb_cgwait++;
7774 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7775 	}
7776 	FREE_LOCK(ump);
7777 	freeblks_free(ump, freeblks, btodb(bsize));
7778 	CTR4(KTR_SUJ,
7779 	    "freework_freeblock: ino %d blkno %jd lbn %jd size %ld",
7780 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7781 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7782 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7783 	ACQUIRE_LOCK(ump);
7784 	/*
7785 	 * The jnewblk will be discarded and the bits in the map never
7786 	 * made it to disk.  We can immediately free the freeblk.
7787 	 */
7788 	if (needj == 0)
7789 		handle_written_freework(freework);
7790 }
7791 
7792 /*
7793  * We enqueue freework items that need processing back on the freeblks and
7794  * add the freeblks to the worklist.  This makes it easier to find all work
7795  * required to flush a truncation in process_truncates().
7796  */
7797 static void
7798 freework_enqueue(freework)
7799 	struct freework *freework;
7800 {
7801 	struct freeblks *freeblks;
7802 
7803 	freeblks = freework->fw_freeblks;
7804 	if ((freework->fw_state & INPROGRESS) == 0)
7805 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7806 	if ((freeblks->fb_state &
7807 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7808 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7809 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7810 }
7811 
7812 /*
7813  * Start, continue, or finish the process of freeing an indirect block tree.
7814  * The free operation may be paused at any point with fw_off containing the
7815  * offset to restart from.  This enables us to implement some flow control
7816  * for large truncates which may fan out and generate a huge number of
7817  * dependencies.
7818  */
7819 static void
7820 handle_workitem_indirblk(freework)
7821 	struct freework *freework;
7822 {
7823 	struct freeblks *freeblks;
7824 	struct ufsmount *ump;
7825 	struct fs *fs;
7826 
7827 	freeblks = freework->fw_freeblks;
7828 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7829 	fs = ump->um_fs;
7830 	if (freework->fw_state & DEPCOMPLETE) {
7831 		handle_written_freework(freework);
7832 		return;
7833 	}
7834 	if (freework->fw_off == NINDIR(fs)) {
7835 		freework_freeblock(freework);
7836 		return;
7837 	}
7838 	freework->fw_state |= INPROGRESS;
7839 	FREE_LOCK(ump);
7840 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7841 	    freework->fw_lbn);
7842 	ACQUIRE_LOCK(ump);
7843 }
7844 
7845 /*
7846  * Called when a freework structure attached to a cg buf is written.  The
7847  * ref on either the parent or the freeblks structure is released and
7848  * the freeblks is added back to the worklist if there is more work to do.
7849  */
7850 static void
7851 handle_written_freework(freework)
7852 	struct freework *freework;
7853 {
7854 	struct freeblks *freeblks;
7855 	struct freework *parent;
7856 
7857 	freeblks = freework->fw_freeblks;
7858 	parent = freework->fw_parent;
7859 	if (freework->fw_state & DELAYEDFREE)
7860 		freeblks->fb_cgwait--;
7861 	freework->fw_state |= COMPLETE;
7862 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7863 		WORKITEM_FREE(freework, D_FREEWORK);
7864 	if (parent) {
7865 		if (--parent->fw_ref == 0)
7866 			freework_enqueue(parent);
7867 		return;
7868 	}
7869 	if (--freeblks->fb_ref != 0)
7870 		return;
7871 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7872 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7873 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7874 }
7875 
7876 /*
7877  * This workitem routine performs the block de-allocation.
7878  * The workitem is added to the pending list after the updated
7879  * inode block has been written to disk.  As mentioned above,
7880  * checks regarding the number of blocks de-allocated (compared
7881  * to the number of blocks allocated for the file) are also
7882  * performed in this function.
7883  */
7884 static int
7885 handle_workitem_freeblocks(freeblks, flags)
7886 	struct freeblks *freeblks;
7887 	int flags;
7888 {
7889 	struct freework *freework;
7890 	struct newblk *newblk;
7891 	struct allocindir *aip;
7892 	struct ufsmount *ump;
7893 	struct worklist *wk;
7894 
7895 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7896 	    ("handle_workitem_freeblocks: Journal entries not written."));
7897 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7898 	ACQUIRE_LOCK(ump);
7899 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7900 		WORKLIST_REMOVE(wk);
7901 		switch (wk->wk_type) {
7902 		case D_DIRREM:
7903 			wk->wk_state |= COMPLETE;
7904 			add_to_worklist(wk, 0);
7905 			continue;
7906 
7907 		case D_ALLOCDIRECT:
7908 			free_newblk(WK_NEWBLK(wk));
7909 			continue;
7910 
7911 		case D_ALLOCINDIR:
7912 			aip = WK_ALLOCINDIR(wk);
7913 			freework = NULL;
7914 			if (aip->ai_state & DELAYEDFREE) {
7915 				FREE_LOCK(ump);
7916 				freework = newfreework(ump, freeblks, NULL,
7917 				    aip->ai_lbn, aip->ai_newblkno,
7918 				    ump->um_fs->fs_frag, 0, 0);
7919 				ACQUIRE_LOCK(ump);
7920 			}
7921 			newblk = WK_NEWBLK(wk);
7922 			if (newblk->nb_jnewblk) {
7923 				freework->fw_jnewblk = newblk->nb_jnewblk;
7924 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7925 				newblk->nb_jnewblk = NULL;
7926 			}
7927 			free_newblk(newblk);
7928 			continue;
7929 
7930 		case D_FREEWORK:
7931 			freework = WK_FREEWORK(wk);
7932 			if (freework->fw_lbn <= -UFS_NDADDR)
7933 				handle_workitem_indirblk(freework);
7934 			else
7935 				freework_freeblock(freework);
7936 			continue;
7937 		default:
7938 			panic("handle_workitem_freeblocks: Unknown type %s",
7939 			    TYPENAME(wk->wk_type));
7940 		}
7941 	}
7942 	if (freeblks->fb_ref != 0) {
7943 		freeblks->fb_state &= ~INPROGRESS;
7944 		wake_worklist(&freeblks->fb_list);
7945 		freeblks = NULL;
7946 	}
7947 	FREE_LOCK(ump);
7948 	if (freeblks)
7949 		return handle_complete_freeblocks(freeblks, flags);
7950 	return (0);
7951 }
7952 
7953 /*
7954  * Handle completion of block free via truncate.  This allows fs_pending
7955  * to track the actual free block count more closely than if we only updated
7956  * it at the end.  We must be careful to handle cases where the block count
7957  * on free was incorrect.
7958  */
7959 static void
7960 freeblks_free(ump, freeblks, blocks)
7961 	struct ufsmount *ump;
7962 	struct freeblks *freeblks;
7963 	int blocks;
7964 {
7965 	struct fs *fs;
7966 	ufs2_daddr_t remain;
7967 
7968 	UFS_LOCK(ump);
7969 	remain = -freeblks->fb_chkcnt;
7970 	freeblks->fb_chkcnt += blocks;
7971 	if (remain > 0) {
7972 		if (remain < blocks)
7973 			blocks = remain;
7974 		fs = ump->um_fs;
7975 		fs->fs_pendingblocks -= blocks;
7976 	}
7977 	UFS_UNLOCK(ump);
7978 }
7979 
7980 /*
7981  * Once all of the freework workitems are complete we can retire the
7982  * freeblocks dependency and any journal work awaiting completion.  This
7983  * can not be called until all other dependencies are stable on disk.
7984  */
7985 static int
7986 handle_complete_freeblocks(freeblks, flags)
7987 	struct freeblks *freeblks;
7988 	int flags;
7989 {
7990 	struct inodedep *inodedep;
7991 	struct inode *ip;
7992 	struct vnode *vp;
7993 	struct fs *fs;
7994 	struct ufsmount *ump;
7995 	ufs2_daddr_t spare;
7996 
7997 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7998 	fs = ump->um_fs;
7999 	flags = LK_EXCLUSIVE | flags;
8000 	spare = freeblks->fb_chkcnt;
8001 
8002 	/*
8003 	 * If we did not release the expected number of blocks we may have
8004 	 * to adjust the inode block count here.  Only do so if it wasn't
8005 	 * a truncation to zero and the modrev still matches.
8006 	 */
8007 	if (spare && freeblks->fb_len != 0) {
8008 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8009 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8010 			return (EBUSY);
8011 		ip = VTOI(vp);
8012 		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8013 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8014 			ip->i_flag |= IN_CHANGE;
8015 			/*
8016 			 * We must wait so this happens before the
8017 			 * journal is reclaimed.
8018 			 */
8019 			ffs_update(vp, 1);
8020 		}
8021 		vput(vp);
8022 	}
8023 	if (spare < 0) {
8024 		UFS_LOCK(ump);
8025 		fs->fs_pendingblocks += spare;
8026 		UFS_UNLOCK(ump);
8027 	}
8028 #ifdef QUOTA
8029 	/* Handle spare. */
8030 	if (spare)
8031 		quotaadj(freeblks->fb_quota, ump, -spare);
8032 	quotarele(freeblks->fb_quota);
8033 #endif
8034 	ACQUIRE_LOCK(ump);
8035 	if (freeblks->fb_state & ONDEPLIST) {
8036 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8037 		    0, &inodedep);
8038 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8039 		freeblks->fb_state &= ~ONDEPLIST;
8040 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8041 			free_inodedep(inodedep);
8042 	}
8043 	/*
8044 	 * All of the freeblock deps must be complete prior to this call
8045 	 * so it's now safe to complete earlier outstanding journal entries.
8046 	 */
8047 	handle_jwork(&freeblks->fb_jwork);
8048 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8049 	FREE_LOCK(ump);
8050 	return (0);
8051 }
8052 
8053 /*
8054  * Release blocks associated with the freeblks and stored in the indirect
8055  * block dbn. If level is greater than SINGLE, the block is an indirect block
8056  * and recursive calls to indirtrunc must be used to cleanse other indirect
8057  * blocks.
8058  *
8059  * This handles partial and complete truncation of blocks.  Partial is noted
8060  * with goingaway == 0.  In this case the freework is completed after the
8061  * zero'd indirects are written to disk.  For full truncation the freework
8062  * is completed after the block is freed.
8063  */
8064 static void
8065 indir_trunc(freework, dbn, lbn)
8066 	struct freework *freework;
8067 	ufs2_daddr_t dbn;
8068 	ufs_lbn_t lbn;
8069 {
8070 	struct freework *nfreework;
8071 	struct workhead wkhd;
8072 	struct freeblks *freeblks;
8073 	struct buf *bp;
8074 	struct fs *fs;
8075 	struct indirdep *indirdep;
8076 	struct ufsmount *ump;
8077 	ufs1_daddr_t *bap1;
8078 	ufs2_daddr_t nb, nnb, *bap2;
8079 	ufs_lbn_t lbnadd, nlbn;
8080 	int i, nblocks, ufs1fmt;
8081 	int freedblocks;
8082 	int goingaway;
8083 	int freedeps;
8084 	int needj;
8085 	int level;
8086 	int cnt;
8087 
8088 	freeblks = freework->fw_freeblks;
8089 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8090 	fs = ump->um_fs;
8091 	/*
8092 	 * Get buffer of block pointers to be freed.  There are three cases:
8093 	 *
8094 	 * 1) Partial truncate caches the indirdep pointer in the freework
8095 	 *    which provides us a back copy to the save bp which holds the
8096 	 *    pointers we want to clear.  When this completes the zero
8097 	 *    pointers are written to the real copy.
8098 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8099 	 *    eliminated the real copy and placed the indirdep on the saved
8100 	 *    copy.  The indirdep and buf are discarded when this completes.
8101 	 * 3) The indirect was not in memory, we read a copy off of the disk
8102 	 *    using the devvp and drop and invalidate the buffer when we're
8103 	 *    done.
8104 	 */
8105 	goingaway = 1;
8106 	indirdep = NULL;
8107 	if (freework->fw_indir != NULL) {
8108 		goingaway = 0;
8109 		indirdep = freework->fw_indir;
8110 		bp = indirdep->ir_savebp;
8111 		if (bp == NULL || bp->b_blkno != dbn)
8112 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8113 			    bp, (intmax_t)dbn);
8114 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8115 		/*
8116 		 * The lock prevents the buf dep list from changing and
8117 	 	 * indirects on devvp should only ever have one dependency.
8118 		 */
8119 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8120 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8121 			panic("indir_trunc: Bad indirdep %p from buf %p",
8122 			    indirdep, bp);
8123 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8124 	    NOCRED, &bp) != 0) {
8125 		brelse(bp);
8126 		return;
8127 	}
8128 	ACQUIRE_LOCK(ump);
8129 	/* Protects against a race with complete_trunc_indir(). */
8130 	freework->fw_state &= ~INPROGRESS;
8131 	/*
8132 	 * If we have an indirdep we need to enforce the truncation order
8133 	 * and discard it when it is complete.
8134 	 */
8135 	if (indirdep) {
8136 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8137 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8138 			/*
8139 			 * Add the complete truncate to the list on the
8140 			 * indirdep to enforce in-order processing.
8141 			 */
8142 			if (freework->fw_indir == NULL)
8143 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8144 				    freework, fw_next);
8145 			FREE_LOCK(ump);
8146 			return;
8147 		}
8148 		/*
8149 		 * If we're goingaway, free the indirdep.  Otherwise it will
8150 		 * linger until the write completes.
8151 		 */
8152 		if (goingaway)
8153 			free_indirdep(indirdep);
8154 	}
8155 	FREE_LOCK(ump);
8156 	/* Initialize pointers depending on block size. */
8157 	if (ump->um_fstype == UFS1) {
8158 		bap1 = (ufs1_daddr_t *)bp->b_data;
8159 		nb = bap1[freework->fw_off];
8160 		ufs1fmt = 1;
8161 		bap2 = NULL;
8162 	} else {
8163 		bap2 = (ufs2_daddr_t *)bp->b_data;
8164 		nb = bap2[freework->fw_off];
8165 		ufs1fmt = 0;
8166 		bap1 = NULL;
8167 	}
8168 	level = lbn_level(lbn);
8169 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8170 	lbnadd = lbn_offset(fs, level);
8171 	nblocks = btodb(fs->fs_bsize);
8172 	nfreework = freework;
8173 	freedeps = 0;
8174 	cnt = 0;
8175 	/*
8176 	 * Reclaim blocks.  Traverses into nested indirect levels and
8177 	 * arranges for the current level to be freed when subordinates
8178 	 * are free when journaling.
8179 	 */
8180 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8181 		if (i != NINDIR(fs) - 1) {
8182 			if (ufs1fmt)
8183 				nnb = bap1[i+1];
8184 			else
8185 				nnb = bap2[i+1];
8186 		} else
8187 			nnb = 0;
8188 		if (nb == 0)
8189 			continue;
8190 		cnt++;
8191 		if (level != 0) {
8192 			nlbn = (lbn + 1) - (i * lbnadd);
8193 			if (needj != 0) {
8194 				nfreework = newfreework(ump, freeblks, freework,
8195 				    nlbn, nb, fs->fs_frag, 0, 0);
8196 				freedeps++;
8197 			}
8198 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8199 		} else {
8200 			struct freedep *freedep;
8201 
8202 			/*
8203 			 * Attempt to aggregate freedep dependencies for
8204 			 * all blocks being released to the same CG.
8205 			 */
8206 			LIST_INIT(&wkhd);
8207 			if (needj != 0 &&
8208 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8209 				freedep = newfreedep(freework);
8210 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8211 				    &freedep->fd_list);
8212 				freedeps++;
8213 			}
8214 			CTR3(KTR_SUJ,
8215 			    "indir_trunc: ino %d blkno %jd size %ld",
8216 			    freeblks->fb_inum, nb, fs->fs_bsize);
8217 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8218 			    fs->fs_bsize, freeblks->fb_inum,
8219 			    freeblks->fb_vtype, &wkhd);
8220 		}
8221 	}
8222 	if (goingaway) {
8223 		bp->b_flags |= B_INVAL | B_NOCACHE;
8224 		brelse(bp);
8225 	}
8226 	freedblocks = 0;
8227 	if (level == 0)
8228 		freedblocks = (nblocks * cnt);
8229 	if (needj == 0)
8230 		freedblocks += nblocks;
8231 	freeblks_free(ump, freeblks, freedblocks);
8232 	/*
8233 	 * If we are journaling set up the ref counts and offset so this
8234 	 * indirect can be completed when its children are free.
8235 	 */
8236 	if (needj) {
8237 		ACQUIRE_LOCK(ump);
8238 		freework->fw_off = i;
8239 		freework->fw_ref += freedeps;
8240 		freework->fw_ref -= NINDIR(fs) + 1;
8241 		if (level == 0)
8242 			freeblks->fb_cgwait += freedeps;
8243 		if (freework->fw_ref == 0)
8244 			freework_freeblock(freework);
8245 		FREE_LOCK(ump);
8246 		return;
8247 	}
8248 	/*
8249 	 * If we're not journaling we can free the indirect now.
8250 	 */
8251 	dbn = dbtofsb(fs, dbn);
8252 	CTR3(KTR_SUJ,
8253 	    "indir_trunc 2: ino %d blkno %jd size %ld",
8254 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8255 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8256 	    freeblks->fb_inum, freeblks->fb_vtype, NULL);
8257 	/* Non SUJ softdep does single-threaded truncations. */
8258 	if (freework->fw_blkno == dbn) {
8259 		freework->fw_state |= ALLCOMPLETE;
8260 		ACQUIRE_LOCK(ump);
8261 		handle_written_freework(freework);
8262 		FREE_LOCK(ump);
8263 	}
8264 	return;
8265 }
8266 
8267 /*
8268  * Cancel an allocindir when it is removed via truncation.  When bp is not
8269  * NULL the indirect never appeared on disk and is scheduled to be freed
8270  * independently of the indir so we can more easily track journal work.
8271  */
8272 static void
8273 cancel_allocindir(aip, bp, freeblks, trunc)
8274 	struct allocindir *aip;
8275 	struct buf *bp;
8276 	struct freeblks *freeblks;
8277 	int trunc;
8278 {
8279 	struct indirdep *indirdep;
8280 	struct freefrag *freefrag;
8281 	struct newblk *newblk;
8282 
8283 	newblk = (struct newblk *)aip;
8284 	LIST_REMOVE(aip, ai_next);
8285 	/*
8286 	 * We must eliminate the pointer in bp if it must be freed on its
8287 	 * own due to partial truncate or pending journal work.
8288 	 */
8289 	if (bp && (trunc || newblk->nb_jnewblk)) {
8290 		/*
8291 		 * Clear the pointer and mark the aip to be freed
8292 		 * directly if it never existed on disk.
8293 		 */
8294 		aip->ai_state |= DELAYEDFREE;
8295 		indirdep = aip->ai_indirdep;
8296 		if (indirdep->ir_state & UFS1FMT)
8297 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8298 		else
8299 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8300 	}
8301 	/*
8302 	 * When truncating the previous pointer will be freed via
8303 	 * savedbp.  Eliminate the freefrag which would dup free.
8304 	 */
8305 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8306 		newblk->nb_freefrag = NULL;
8307 		if (freefrag->ff_jdep)
8308 			cancel_jfreefrag(
8309 			    WK_JFREEFRAG(freefrag->ff_jdep));
8310 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8311 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8312 	}
8313 	/*
8314 	 * If the journal hasn't been written the jnewblk must be passed
8315 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8316 	 * this by leaving the journal dependency on the newblk to be freed
8317 	 * when a freework is created in handle_workitem_freeblocks().
8318 	 */
8319 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8320 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8321 }
8322 
8323 /*
8324  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8325  * in to a newdirblk so any subsequent additions are tracked properly.  The
8326  * caller is responsible for adding the mkdir1 dependency to the journal
8327  * and updating id_mkdiradd.  This function returns with the per-filesystem
8328  * lock held.
8329  */
8330 static struct mkdir *
8331 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8332 	struct diradd *dap;
8333 	ino_t newinum;
8334 	ino_t dinum;
8335 	struct buf *newdirbp;
8336 	struct mkdir **mkdirp;
8337 {
8338 	struct newblk *newblk;
8339 	struct pagedep *pagedep;
8340 	struct inodedep *inodedep;
8341 	struct newdirblk *newdirblk;
8342 	struct mkdir *mkdir1, *mkdir2;
8343 	struct worklist *wk;
8344 	struct jaddref *jaddref;
8345 	struct ufsmount *ump;
8346 	struct mount *mp;
8347 
8348 	mp = dap->da_list.wk_mp;
8349 	ump = VFSTOUFS(mp);
8350 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8351 	    M_SOFTDEP_FLAGS);
8352 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8353 	LIST_INIT(&newdirblk->db_mkdir);
8354 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8355 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8356 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8357 	mkdir1->md_diradd = dap;
8358 	mkdir1->md_jaddref = NULL;
8359 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8360 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8361 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8362 	mkdir2->md_diradd = dap;
8363 	mkdir2->md_jaddref = NULL;
8364 	if (MOUNTEDSUJ(mp) == 0) {
8365 		mkdir1->md_state |= DEPCOMPLETE;
8366 		mkdir2->md_state |= DEPCOMPLETE;
8367 	}
8368 	/*
8369 	 * Dependency on "." and ".." being written to disk.
8370 	 */
8371 	mkdir1->md_buf = newdirbp;
8372 	ACQUIRE_LOCK(VFSTOUFS(mp));
8373 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8374 	/*
8375 	 * We must link the pagedep, allocdirect, and newdirblk for
8376 	 * the initial file page so the pointer to the new directory
8377 	 * is not written until the directory contents are live and
8378 	 * any subsequent additions are not marked live until the
8379 	 * block is reachable via the inode.
8380 	 */
8381 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8382 		panic("setup_newdir: lost pagedep");
8383 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8384 		if (wk->wk_type == D_ALLOCDIRECT)
8385 			break;
8386 	if (wk == NULL)
8387 		panic("setup_newdir: lost allocdirect");
8388 	if (pagedep->pd_state & NEWBLOCK)
8389 		panic("setup_newdir: NEWBLOCK already set");
8390 	newblk = WK_NEWBLK(wk);
8391 	pagedep->pd_state |= NEWBLOCK;
8392 	pagedep->pd_newdirblk = newdirblk;
8393 	newdirblk->db_pagedep = pagedep;
8394 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8395 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8396 	/*
8397 	 * Look up the inodedep for the parent directory so that we
8398 	 * can link mkdir2 into the pending dotdot jaddref or
8399 	 * the inode write if there is none.  If the inode is
8400 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8401 	 * been satisfied and mkdir2 can be freed.
8402 	 */
8403 	inodedep_lookup(mp, dinum, 0, &inodedep);
8404 	if (MOUNTEDSUJ(mp)) {
8405 		if (inodedep == NULL)
8406 			panic("setup_newdir: Lost parent.");
8407 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8408 		    inoreflst);
8409 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8410 		    (jaddref->ja_state & MKDIR_PARENT),
8411 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8412 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8413 		mkdir2->md_jaddref = jaddref;
8414 		jaddref->ja_mkdir = mkdir2;
8415 	} else if (inodedep == NULL ||
8416 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8417 		dap->da_state &= ~MKDIR_PARENT;
8418 		WORKITEM_FREE(mkdir2, D_MKDIR);
8419 		mkdir2 = NULL;
8420 	} else {
8421 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8422 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8423 	}
8424 	*mkdirp = mkdir2;
8425 
8426 	return (mkdir1);
8427 }
8428 
8429 /*
8430  * Directory entry addition dependencies.
8431  *
8432  * When adding a new directory entry, the inode (with its incremented link
8433  * count) must be written to disk before the directory entry's pointer to it.
8434  * Also, if the inode is newly allocated, the corresponding freemap must be
8435  * updated (on disk) before the directory entry's pointer. These requirements
8436  * are met via undo/redo on the directory entry's pointer, which consists
8437  * simply of the inode number.
8438  *
8439  * As directory entries are added and deleted, the free space within a
8440  * directory block can become fragmented.  The ufs filesystem will compact
8441  * a fragmented directory block to make space for a new entry. When this
8442  * occurs, the offsets of previously added entries change. Any "diradd"
8443  * dependency structures corresponding to these entries must be updated with
8444  * the new offsets.
8445  */
8446 
8447 /*
8448  * This routine is called after the in-memory inode's link
8449  * count has been incremented, but before the directory entry's
8450  * pointer to the inode has been set.
8451  */
8452 int
8453 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8454 	struct buf *bp;		/* buffer containing directory block */
8455 	struct inode *dp;	/* inode for directory */
8456 	off_t diroffset;	/* offset of new entry in directory */
8457 	ino_t newinum;		/* inode referenced by new directory entry */
8458 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8459 	int isnewblk;		/* entry is in a newly allocated block */
8460 {
8461 	int offset;		/* offset of new entry within directory block */
8462 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8463 	struct fs *fs;
8464 	struct diradd *dap;
8465 	struct newblk *newblk;
8466 	struct pagedep *pagedep;
8467 	struct inodedep *inodedep;
8468 	struct newdirblk *newdirblk;
8469 	struct mkdir *mkdir1, *mkdir2;
8470 	struct jaddref *jaddref;
8471 	struct ufsmount *ump;
8472 	struct mount *mp;
8473 	int isindir;
8474 
8475 	mp = ITOVFS(dp);
8476 	ump = VFSTOUFS(mp);
8477 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8478 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8479 	/*
8480 	 * Whiteouts have no dependencies.
8481 	 */
8482 	if (newinum == UFS_WINO) {
8483 		if (newdirbp != NULL)
8484 			bdwrite(newdirbp);
8485 		return (0);
8486 	}
8487 	jaddref = NULL;
8488 	mkdir1 = mkdir2 = NULL;
8489 	fs = ump->um_fs;
8490 	lbn = lblkno(fs, diroffset);
8491 	offset = blkoff(fs, diroffset);
8492 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8493 		M_SOFTDEP_FLAGS|M_ZERO);
8494 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8495 	dap->da_offset = offset;
8496 	dap->da_newinum = newinum;
8497 	dap->da_state = ATTACHED;
8498 	LIST_INIT(&dap->da_jwork);
8499 	isindir = bp->b_lblkno >= UFS_NDADDR;
8500 	newdirblk = NULL;
8501 	if (isnewblk &&
8502 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8503 		newdirblk = malloc(sizeof(struct newdirblk),
8504 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8505 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8506 		LIST_INIT(&newdirblk->db_mkdir);
8507 	}
8508 	/*
8509 	 * If we're creating a new directory setup the dependencies and set
8510 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8511 	 * we can move on.
8512 	 */
8513 	if (newdirbp == NULL) {
8514 		dap->da_state |= DEPCOMPLETE;
8515 		ACQUIRE_LOCK(ump);
8516 	} else {
8517 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8518 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8519 		    &mkdir2);
8520 	}
8521 	/*
8522 	 * Link into parent directory pagedep to await its being written.
8523 	 */
8524 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8525 #ifdef DEBUG
8526 	if (diradd_lookup(pagedep, offset) != NULL)
8527 		panic("softdep_setup_directory_add: %p already at off %d\n",
8528 		    diradd_lookup(pagedep, offset), offset);
8529 #endif
8530 	dap->da_pagedep = pagedep;
8531 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8532 	    da_pdlist);
8533 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8534 	/*
8535 	 * If we're journaling, link the diradd into the jaddref so it
8536 	 * may be completed after the journal entry is written.  Otherwise,
8537 	 * link the diradd into its inodedep.  If the inode is not yet
8538 	 * written place it on the bufwait list, otherwise do the post-inode
8539 	 * write processing to put it on the id_pendinghd list.
8540 	 */
8541 	if (MOUNTEDSUJ(mp)) {
8542 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8543 		    inoreflst);
8544 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8545 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8546 		jaddref->ja_diroff = diroffset;
8547 		jaddref->ja_diradd = dap;
8548 		add_to_journal(&jaddref->ja_list);
8549 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8550 		diradd_inode_written(dap, inodedep);
8551 	else
8552 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8553 	/*
8554 	 * Add the journal entries for . and .. links now that the primary
8555 	 * link is written.
8556 	 */
8557 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8558 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8559 		    inoreflst, if_deps);
8560 		KASSERT(jaddref != NULL &&
8561 		    jaddref->ja_ino == jaddref->ja_parent &&
8562 		    (jaddref->ja_state & MKDIR_BODY),
8563 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8564 		    jaddref));
8565 		mkdir1->md_jaddref = jaddref;
8566 		jaddref->ja_mkdir = mkdir1;
8567 		/*
8568 		 * It is important that the dotdot journal entry
8569 		 * is added prior to the dot entry since dot writes
8570 		 * both the dot and dotdot links.  These both must
8571 		 * be added after the primary link for the journal
8572 		 * to remain consistent.
8573 		 */
8574 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8575 		add_to_journal(&jaddref->ja_list);
8576 	}
8577 	/*
8578 	 * If we are adding a new directory remember this diradd so that if
8579 	 * we rename it we can keep the dot and dotdot dependencies.  If
8580 	 * we are adding a new name for an inode that has a mkdiradd we
8581 	 * must be in rename and we have to move the dot and dotdot
8582 	 * dependencies to this new name.  The old name is being orphaned
8583 	 * soon.
8584 	 */
8585 	if (mkdir1 != NULL) {
8586 		if (inodedep->id_mkdiradd != NULL)
8587 			panic("softdep_setup_directory_add: Existing mkdir");
8588 		inodedep->id_mkdiradd = dap;
8589 	} else if (inodedep->id_mkdiradd)
8590 		merge_diradd(inodedep, dap);
8591 	if (newdirblk != NULL) {
8592 		/*
8593 		 * There is nothing to do if we are already tracking
8594 		 * this block.
8595 		 */
8596 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8597 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8598 			FREE_LOCK(ump);
8599 			return (0);
8600 		}
8601 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8602 		    == 0)
8603 			panic("softdep_setup_directory_add: lost entry");
8604 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8605 		pagedep->pd_state |= NEWBLOCK;
8606 		pagedep->pd_newdirblk = newdirblk;
8607 		newdirblk->db_pagedep = pagedep;
8608 		FREE_LOCK(ump);
8609 		/*
8610 		 * If we extended into an indirect signal direnter to sync.
8611 		 */
8612 		if (isindir)
8613 			return (1);
8614 		return (0);
8615 	}
8616 	FREE_LOCK(ump);
8617 	return (0);
8618 }
8619 
8620 /*
8621  * This procedure is called to change the offset of a directory
8622  * entry when compacting a directory block which must be owned
8623  * exclusively by the caller. Note that the actual entry movement
8624  * must be done in this procedure to ensure that no I/O completions
8625  * occur while the move is in progress.
8626  */
8627 void
8628 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8629 	struct buf *bp;		/* Buffer holding directory block. */
8630 	struct inode *dp;	/* inode for directory */
8631 	caddr_t base;		/* address of dp->i_offset */
8632 	caddr_t oldloc;		/* address of old directory location */
8633 	caddr_t newloc;		/* address of new directory location */
8634 	int entrysize;		/* size of directory entry */
8635 {
8636 	int offset, oldoffset, newoffset;
8637 	struct pagedep *pagedep;
8638 	struct jmvref *jmvref;
8639 	struct diradd *dap;
8640 	struct direct *de;
8641 	struct mount *mp;
8642 	struct ufsmount *ump;
8643 	ufs_lbn_t lbn;
8644 	int flags;
8645 
8646 	mp = ITOVFS(dp);
8647 	ump = VFSTOUFS(mp);
8648 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8649 	    ("softdep_change_directoryentry_offset called on "
8650 	     "non-softdep filesystem"));
8651 	de = (struct direct *)oldloc;
8652 	jmvref = NULL;
8653 	flags = 0;
8654 	/*
8655 	 * Moves are always journaled as it would be too complex to
8656 	 * determine if any affected adds or removes are present in the
8657 	 * journal.
8658 	 */
8659 	if (MOUNTEDSUJ(mp)) {
8660 		flags = DEPALLOC;
8661 		jmvref = newjmvref(dp, de->d_ino,
8662 		    dp->i_offset + (oldloc - base),
8663 		    dp->i_offset + (newloc - base));
8664 	}
8665 	lbn = lblkno(ump->um_fs, dp->i_offset);
8666 	offset = blkoff(ump->um_fs, dp->i_offset);
8667 	oldoffset = offset + (oldloc - base);
8668 	newoffset = offset + (newloc - base);
8669 	ACQUIRE_LOCK(ump);
8670 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8671 		goto done;
8672 	dap = diradd_lookup(pagedep, oldoffset);
8673 	if (dap) {
8674 		dap->da_offset = newoffset;
8675 		newoffset = DIRADDHASH(newoffset);
8676 		oldoffset = DIRADDHASH(oldoffset);
8677 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8678 		    newoffset != oldoffset) {
8679 			LIST_REMOVE(dap, da_pdlist);
8680 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8681 			    dap, da_pdlist);
8682 		}
8683 	}
8684 done:
8685 	if (jmvref) {
8686 		jmvref->jm_pagedep = pagedep;
8687 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8688 		add_to_journal(&jmvref->jm_list);
8689 	}
8690 	bcopy(oldloc, newloc, entrysize);
8691 	FREE_LOCK(ump);
8692 }
8693 
8694 /*
8695  * Move the mkdir dependencies and journal work from one diradd to another
8696  * when renaming a directory.  The new name must depend on the mkdir deps
8697  * completing as the old name did.  Directories can only have one valid link
8698  * at a time so one must be canonical.
8699  */
8700 static void
8701 merge_diradd(inodedep, newdap)
8702 	struct inodedep *inodedep;
8703 	struct diradd *newdap;
8704 {
8705 	struct diradd *olddap;
8706 	struct mkdir *mkdir, *nextmd;
8707 	struct ufsmount *ump;
8708 	short state;
8709 
8710 	olddap = inodedep->id_mkdiradd;
8711 	inodedep->id_mkdiradd = newdap;
8712 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8713 		newdap->da_state &= ~DEPCOMPLETE;
8714 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8715 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8716 		     mkdir = nextmd) {
8717 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8718 			if (mkdir->md_diradd != olddap)
8719 				continue;
8720 			mkdir->md_diradd = newdap;
8721 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8722 			newdap->da_state |= state;
8723 			olddap->da_state &= ~state;
8724 			if ((olddap->da_state &
8725 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8726 				break;
8727 		}
8728 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8729 			panic("merge_diradd: unfound ref");
8730 	}
8731 	/*
8732 	 * Any mkdir related journal items are not safe to be freed until
8733 	 * the new name is stable.
8734 	 */
8735 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8736 	olddap->da_state |= DEPCOMPLETE;
8737 	complete_diradd(olddap);
8738 }
8739 
8740 /*
8741  * Move the diradd to the pending list when all diradd dependencies are
8742  * complete.
8743  */
8744 static void
8745 complete_diradd(dap)
8746 	struct diradd *dap;
8747 {
8748 	struct pagedep *pagedep;
8749 
8750 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8751 		if (dap->da_state & DIRCHG)
8752 			pagedep = dap->da_previous->dm_pagedep;
8753 		else
8754 			pagedep = dap->da_pagedep;
8755 		LIST_REMOVE(dap, da_pdlist);
8756 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8757 	}
8758 }
8759 
8760 /*
8761  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8762  * add entries and conditonally journal the remove.
8763  */
8764 static void
8765 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8766 	struct diradd *dap;
8767 	struct dirrem *dirrem;
8768 	struct jremref *jremref;
8769 	struct jremref *dotremref;
8770 	struct jremref *dotdotremref;
8771 {
8772 	struct inodedep *inodedep;
8773 	struct jaddref *jaddref;
8774 	struct inoref *inoref;
8775 	struct ufsmount *ump;
8776 	struct mkdir *mkdir;
8777 
8778 	/*
8779 	 * If no remove references were allocated we're on a non-journaled
8780 	 * filesystem and can skip the cancel step.
8781 	 */
8782 	if (jremref == NULL) {
8783 		free_diradd(dap, NULL);
8784 		return;
8785 	}
8786 	/*
8787 	 * Cancel the primary name an free it if it does not require
8788 	 * journaling.
8789 	 */
8790 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8791 	    0, &inodedep) != 0) {
8792 		/* Abort the addref that reference this diradd.  */
8793 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8794 			if (inoref->if_list.wk_type != D_JADDREF)
8795 				continue;
8796 			jaddref = (struct jaddref *)inoref;
8797 			if (jaddref->ja_diradd != dap)
8798 				continue;
8799 			if (cancel_jaddref(jaddref, inodedep,
8800 			    &dirrem->dm_jwork) == 0) {
8801 				free_jremref(jremref);
8802 				jremref = NULL;
8803 			}
8804 			break;
8805 		}
8806 	}
8807 	/*
8808 	 * Cancel subordinate names and free them if they do not require
8809 	 * journaling.
8810 	 */
8811 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8812 		ump = VFSTOUFS(dap->da_list.wk_mp);
8813 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8814 			if (mkdir->md_diradd != dap)
8815 				continue;
8816 			if ((jaddref = mkdir->md_jaddref) == NULL)
8817 				continue;
8818 			mkdir->md_jaddref = NULL;
8819 			if (mkdir->md_state & MKDIR_PARENT) {
8820 				if (cancel_jaddref(jaddref, NULL,
8821 				    &dirrem->dm_jwork) == 0) {
8822 					free_jremref(dotdotremref);
8823 					dotdotremref = NULL;
8824 				}
8825 			} else {
8826 				if (cancel_jaddref(jaddref, inodedep,
8827 				    &dirrem->dm_jwork) == 0) {
8828 					free_jremref(dotremref);
8829 					dotremref = NULL;
8830 				}
8831 			}
8832 		}
8833 	}
8834 
8835 	if (jremref)
8836 		journal_jremref(dirrem, jremref, inodedep);
8837 	if (dotremref)
8838 		journal_jremref(dirrem, dotremref, inodedep);
8839 	if (dotdotremref)
8840 		journal_jremref(dirrem, dotdotremref, NULL);
8841 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8842 	free_diradd(dap, &dirrem->dm_jwork);
8843 }
8844 
8845 /*
8846  * Free a diradd dependency structure. This routine must be called
8847  * with splbio interrupts blocked.
8848  */
8849 static void
8850 free_diradd(dap, wkhd)
8851 	struct diradd *dap;
8852 	struct workhead *wkhd;
8853 {
8854 	struct dirrem *dirrem;
8855 	struct pagedep *pagedep;
8856 	struct inodedep *inodedep;
8857 	struct mkdir *mkdir, *nextmd;
8858 	struct ufsmount *ump;
8859 
8860 	ump = VFSTOUFS(dap->da_list.wk_mp);
8861 	LOCK_OWNED(ump);
8862 	LIST_REMOVE(dap, da_pdlist);
8863 	if (dap->da_state & ONWORKLIST)
8864 		WORKLIST_REMOVE(&dap->da_list);
8865 	if ((dap->da_state & DIRCHG) == 0) {
8866 		pagedep = dap->da_pagedep;
8867 	} else {
8868 		dirrem = dap->da_previous;
8869 		pagedep = dirrem->dm_pagedep;
8870 		dirrem->dm_dirinum = pagedep->pd_ino;
8871 		dirrem->dm_state |= COMPLETE;
8872 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8873 			add_to_worklist(&dirrem->dm_list, 0);
8874 	}
8875 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8876 	    0, &inodedep) != 0)
8877 		if (inodedep->id_mkdiradd == dap)
8878 			inodedep->id_mkdiradd = NULL;
8879 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8880 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8881 		     mkdir = nextmd) {
8882 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8883 			if (mkdir->md_diradd != dap)
8884 				continue;
8885 			dap->da_state &=
8886 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8887 			LIST_REMOVE(mkdir, md_mkdirs);
8888 			if (mkdir->md_state & ONWORKLIST)
8889 				WORKLIST_REMOVE(&mkdir->md_list);
8890 			if (mkdir->md_jaddref != NULL)
8891 				panic("free_diradd: Unexpected jaddref");
8892 			WORKITEM_FREE(mkdir, D_MKDIR);
8893 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8894 				break;
8895 		}
8896 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8897 			panic("free_diradd: unfound ref");
8898 	}
8899 	if (inodedep)
8900 		free_inodedep(inodedep);
8901 	/*
8902 	 * Free any journal segments waiting for the directory write.
8903 	 */
8904 	handle_jwork(&dap->da_jwork);
8905 	WORKITEM_FREE(dap, D_DIRADD);
8906 }
8907 
8908 /*
8909  * Directory entry removal dependencies.
8910  *
8911  * When removing a directory entry, the entry's inode pointer must be
8912  * zero'ed on disk before the corresponding inode's link count is decremented
8913  * (possibly freeing the inode for re-use). This dependency is handled by
8914  * updating the directory entry but delaying the inode count reduction until
8915  * after the directory block has been written to disk. After this point, the
8916  * inode count can be decremented whenever it is convenient.
8917  */
8918 
8919 /*
8920  * This routine should be called immediately after removing
8921  * a directory entry.  The inode's link count should not be
8922  * decremented by the calling procedure -- the soft updates
8923  * code will do this task when it is safe.
8924  */
8925 void
8926 softdep_setup_remove(bp, dp, ip, isrmdir)
8927 	struct buf *bp;		/* buffer containing directory block */
8928 	struct inode *dp;	/* inode for the directory being modified */
8929 	struct inode *ip;	/* inode for directory entry being removed */
8930 	int isrmdir;		/* indicates if doing RMDIR */
8931 {
8932 	struct dirrem *dirrem, *prevdirrem;
8933 	struct inodedep *inodedep;
8934 	struct ufsmount *ump;
8935 	int direct;
8936 
8937 	ump = ITOUMP(ip);
8938 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8939 	    ("softdep_setup_remove called on non-softdep filesystem"));
8940 	/*
8941 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8942 	 * newdirrem() to setup the full directory remove which requires
8943 	 * isrmdir > 1.
8944 	 */
8945 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8946 	/*
8947 	 * Add the dirrem to the inodedep's pending remove list for quick
8948 	 * discovery later.
8949 	 */
8950 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
8951 		panic("softdep_setup_remove: Lost inodedep.");
8952 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8953 	dirrem->dm_state |= ONDEPLIST;
8954 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8955 
8956 	/*
8957 	 * If the COMPLETE flag is clear, then there were no active
8958 	 * entries and we want to roll back to a zeroed entry until
8959 	 * the new inode is committed to disk. If the COMPLETE flag is
8960 	 * set then we have deleted an entry that never made it to
8961 	 * disk. If the entry we deleted resulted from a name change,
8962 	 * then the old name still resides on disk. We cannot delete
8963 	 * its inode (returned to us in prevdirrem) until the zeroed
8964 	 * directory entry gets to disk. The new inode has never been
8965 	 * referenced on the disk, so can be deleted immediately.
8966 	 */
8967 	if ((dirrem->dm_state & COMPLETE) == 0) {
8968 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8969 		    dm_next);
8970 		FREE_LOCK(ump);
8971 	} else {
8972 		if (prevdirrem != NULL)
8973 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8974 			    prevdirrem, dm_next);
8975 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8976 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8977 		FREE_LOCK(ump);
8978 		if (direct)
8979 			handle_workitem_remove(dirrem, 0);
8980 	}
8981 }
8982 
8983 /*
8984  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8985  * pd_pendinghd list of a pagedep.
8986  */
8987 static struct diradd *
8988 diradd_lookup(pagedep, offset)
8989 	struct pagedep *pagedep;
8990 	int offset;
8991 {
8992 	struct diradd *dap;
8993 
8994 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8995 		if (dap->da_offset == offset)
8996 			return (dap);
8997 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8998 		if (dap->da_offset == offset)
8999 			return (dap);
9000 	return (NULL);
9001 }
9002 
9003 /*
9004  * Search for a .. diradd dependency in a directory that is being removed.
9005  * If the directory was renamed to a new parent we have a diradd rather
9006  * than a mkdir for the .. entry.  We need to cancel it now before
9007  * it is found in truncate().
9008  */
9009 static struct jremref *
9010 cancel_diradd_dotdot(ip, dirrem, jremref)
9011 	struct inode *ip;
9012 	struct dirrem *dirrem;
9013 	struct jremref *jremref;
9014 {
9015 	struct pagedep *pagedep;
9016 	struct diradd *dap;
9017 	struct worklist *wk;
9018 
9019 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9020 		return (jremref);
9021 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9022 	if (dap == NULL)
9023 		return (jremref);
9024 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9025 	/*
9026 	 * Mark any journal work as belonging to the parent so it is freed
9027 	 * with the .. reference.
9028 	 */
9029 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9030 		wk->wk_state |= MKDIR_PARENT;
9031 	return (NULL);
9032 }
9033 
9034 /*
9035  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9036  * replace it with a dirrem/diradd pair as a result of re-parenting a
9037  * directory.  This ensures that we don't simultaneously have a mkdir and
9038  * a diradd for the same .. entry.
9039  */
9040 static struct jremref *
9041 cancel_mkdir_dotdot(ip, dirrem, jremref)
9042 	struct inode *ip;
9043 	struct dirrem *dirrem;
9044 	struct jremref *jremref;
9045 {
9046 	struct inodedep *inodedep;
9047 	struct jaddref *jaddref;
9048 	struct ufsmount *ump;
9049 	struct mkdir *mkdir;
9050 	struct diradd *dap;
9051 	struct mount *mp;
9052 
9053 	mp = ITOVFS(ip);
9054 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9055 		return (jremref);
9056 	dap = inodedep->id_mkdiradd;
9057 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9058 		return (jremref);
9059 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9060 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9061 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9062 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9063 			break;
9064 	if (mkdir == NULL)
9065 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9066 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9067 		mkdir->md_jaddref = NULL;
9068 		jaddref->ja_state &= ~MKDIR_PARENT;
9069 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9070 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9071 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9072 			journal_jremref(dirrem, jremref, inodedep);
9073 			jremref = NULL;
9074 		}
9075 	}
9076 	if (mkdir->md_state & ONWORKLIST)
9077 		WORKLIST_REMOVE(&mkdir->md_list);
9078 	mkdir->md_state |= ALLCOMPLETE;
9079 	complete_mkdir(mkdir);
9080 	return (jremref);
9081 }
9082 
9083 static void
9084 journal_jremref(dirrem, jremref, inodedep)
9085 	struct dirrem *dirrem;
9086 	struct jremref *jremref;
9087 	struct inodedep *inodedep;
9088 {
9089 
9090 	if (inodedep == NULL)
9091 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9092 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9093 			panic("journal_jremref: Lost inodedep");
9094 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9095 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9096 	add_to_journal(&jremref->jr_list);
9097 }
9098 
9099 static void
9100 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9101 	struct dirrem *dirrem;
9102 	struct jremref *jremref;
9103 	struct jremref *dotremref;
9104 	struct jremref *dotdotremref;
9105 {
9106 	struct inodedep *inodedep;
9107 
9108 
9109 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9110 	    &inodedep) == 0)
9111 		panic("dirrem_journal: Lost inodedep");
9112 	journal_jremref(dirrem, jremref, inodedep);
9113 	if (dotremref)
9114 		journal_jremref(dirrem, dotremref, inodedep);
9115 	if (dotdotremref)
9116 		journal_jremref(dirrem, dotdotremref, NULL);
9117 }
9118 
9119 /*
9120  * Allocate a new dirrem if appropriate and return it along with
9121  * its associated pagedep. Called without a lock, returns with lock.
9122  */
9123 static struct dirrem *
9124 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9125 	struct buf *bp;		/* buffer containing directory block */
9126 	struct inode *dp;	/* inode for the directory being modified */
9127 	struct inode *ip;	/* inode for directory entry being removed */
9128 	int isrmdir;		/* indicates if doing RMDIR */
9129 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9130 {
9131 	int offset;
9132 	ufs_lbn_t lbn;
9133 	struct diradd *dap;
9134 	struct dirrem *dirrem;
9135 	struct pagedep *pagedep;
9136 	struct jremref *jremref;
9137 	struct jremref *dotremref;
9138 	struct jremref *dotdotremref;
9139 	struct vnode *dvp;
9140 	struct ufsmount *ump;
9141 
9142 	/*
9143 	 * Whiteouts have no deletion dependencies.
9144 	 */
9145 	if (ip == NULL)
9146 		panic("newdirrem: whiteout");
9147 	dvp = ITOV(dp);
9148 	ump = ITOUMP(dp);
9149 
9150 	/*
9151 	 * If the system is over its limit and our filesystem is
9152 	 * responsible for more than our share of that usage and
9153 	 * we are not a snapshot, request some inodedep cleanup.
9154 	 * Limiting the number of dirrem structures will also limit
9155 	 * the number of freefile and freeblks structures.
9156 	 */
9157 	ACQUIRE_LOCK(ump);
9158 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9159 		schedule_cleanup(UFSTOVFS(ump));
9160 	else
9161 		FREE_LOCK(ump);
9162 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9163 	    M_ZERO);
9164 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9165 	LIST_INIT(&dirrem->dm_jremrefhd);
9166 	LIST_INIT(&dirrem->dm_jwork);
9167 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9168 	dirrem->dm_oldinum = ip->i_number;
9169 	*prevdirremp = NULL;
9170 	/*
9171 	 * Allocate remove reference structures to track journal write
9172 	 * dependencies.  We will always have one for the link and
9173 	 * when doing directories we will always have one more for dot.
9174 	 * When renaming a directory we skip the dotdot link change so
9175 	 * this is not needed.
9176 	 */
9177 	jremref = dotremref = dotdotremref = NULL;
9178 	if (DOINGSUJ(dvp)) {
9179 		if (isrmdir) {
9180 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9181 			    ip->i_effnlink + 2);
9182 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9183 			    ip->i_effnlink + 1);
9184 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9185 			    dp->i_effnlink + 1);
9186 			dotdotremref->jr_state |= MKDIR_PARENT;
9187 		} else
9188 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9189 			    ip->i_effnlink + 1);
9190 	}
9191 	ACQUIRE_LOCK(ump);
9192 	lbn = lblkno(ump->um_fs, dp->i_offset);
9193 	offset = blkoff(ump->um_fs, dp->i_offset);
9194 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9195 	    &pagedep);
9196 	dirrem->dm_pagedep = pagedep;
9197 	dirrem->dm_offset = offset;
9198 	/*
9199 	 * If we're renaming a .. link to a new directory, cancel any
9200 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9201 	 * the jremref is preserved for any potential diradd in this
9202 	 * location.  This can not coincide with a rmdir.
9203 	 */
9204 	if (dp->i_offset == DOTDOT_OFFSET) {
9205 		if (isrmdir)
9206 			panic("newdirrem: .. directory change during remove?");
9207 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9208 	}
9209 	/*
9210 	 * If we're removing a directory search for the .. dependency now and
9211 	 * cancel it.  Any pending journal work will be added to the dirrem
9212 	 * to be completed when the workitem remove completes.
9213 	 */
9214 	if (isrmdir)
9215 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9216 	/*
9217 	 * Check for a diradd dependency for the same directory entry.
9218 	 * If present, then both dependencies become obsolete and can
9219 	 * be de-allocated.
9220 	 */
9221 	dap = diradd_lookup(pagedep, offset);
9222 	if (dap == NULL) {
9223 		/*
9224 		 * Link the jremref structures into the dirrem so they are
9225 		 * written prior to the pagedep.
9226 		 */
9227 		if (jremref)
9228 			dirrem_journal(dirrem, jremref, dotremref,
9229 			    dotdotremref);
9230 		return (dirrem);
9231 	}
9232 	/*
9233 	 * Must be ATTACHED at this point.
9234 	 */
9235 	if ((dap->da_state & ATTACHED) == 0)
9236 		panic("newdirrem: not ATTACHED");
9237 	if (dap->da_newinum != ip->i_number)
9238 		panic("newdirrem: inum %ju should be %ju",
9239 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9240 	/*
9241 	 * If we are deleting a changed name that never made it to disk,
9242 	 * then return the dirrem describing the previous inode (which
9243 	 * represents the inode currently referenced from this entry on disk).
9244 	 */
9245 	if ((dap->da_state & DIRCHG) != 0) {
9246 		*prevdirremp = dap->da_previous;
9247 		dap->da_state &= ~DIRCHG;
9248 		dap->da_pagedep = pagedep;
9249 	}
9250 	/*
9251 	 * We are deleting an entry that never made it to disk.
9252 	 * Mark it COMPLETE so we can delete its inode immediately.
9253 	 */
9254 	dirrem->dm_state |= COMPLETE;
9255 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9256 #ifdef SUJ_DEBUG
9257 	if (isrmdir == 0) {
9258 		struct worklist *wk;
9259 
9260 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9261 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9262 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9263 	}
9264 #endif
9265 
9266 	return (dirrem);
9267 }
9268 
9269 /*
9270  * Directory entry change dependencies.
9271  *
9272  * Changing an existing directory entry requires that an add operation
9273  * be completed first followed by a deletion. The semantics for the addition
9274  * are identical to the description of adding a new entry above except
9275  * that the rollback is to the old inode number rather than zero. Once
9276  * the addition dependency is completed, the removal is done as described
9277  * in the removal routine above.
9278  */
9279 
9280 /*
9281  * This routine should be called immediately after changing
9282  * a directory entry.  The inode's link count should not be
9283  * decremented by the calling procedure -- the soft updates
9284  * code will perform this task when it is safe.
9285  */
9286 void
9287 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9288 	struct buf *bp;		/* buffer containing directory block */
9289 	struct inode *dp;	/* inode for the directory being modified */
9290 	struct inode *ip;	/* inode for directory entry being removed */
9291 	ino_t newinum;		/* new inode number for changed entry */
9292 	int isrmdir;		/* indicates if doing RMDIR */
9293 {
9294 	int offset;
9295 	struct diradd *dap = NULL;
9296 	struct dirrem *dirrem, *prevdirrem;
9297 	struct pagedep *pagedep;
9298 	struct inodedep *inodedep;
9299 	struct jaddref *jaddref;
9300 	struct mount *mp;
9301 	struct ufsmount *ump;
9302 
9303 	mp = ITOVFS(dp);
9304 	ump = VFSTOUFS(mp);
9305 	offset = blkoff(ump->um_fs, dp->i_offset);
9306 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9307 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9308 
9309 	/*
9310 	 * Whiteouts do not need diradd dependencies.
9311 	 */
9312 	if (newinum != UFS_WINO) {
9313 		dap = malloc(sizeof(struct diradd),
9314 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9315 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9316 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9317 		dap->da_offset = offset;
9318 		dap->da_newinum = newinum;
9319 		LIST_INIT(&dap->da_jwork);
9320 	}
9321 
9322 	/*
9323 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9324 	 */
9325 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9326 	pagedep = dirrem->dm_pagedep;
9327 	/*
9328 	 * The possible values for isrmdir:
9329 	 *	0 - non-directory file rename
9330 	 *	1 - directory rename within same directory
9331 	 *   inum - directory rename to new directory of given inode number
9332 	 * When renaming to a new directory, we are both deleting and
9333 	 * creating a new directory entry, so the link count on the new
9334 	 * directory should not change. Thus we do not need the followup
9335 	 * dirrem which is usually done in handle_workitem_remove. We set
9336 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9337 	 * followup dirrem.
9338 	 */
9339 	if (isrmdir > 1)
9340 		dirrem->dm_state |= DIRCHG;
9341 
9342 	/*
9343 	 * Whiteouts have no additional dependencies,
9344 	 * so just put the dirrem on the correct list.
9345 	 */
9346 	if (newinum == UFS_WINO) {
9347 		if ((dirrem->dm_state & COMPLETE) == 0) {
9348 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9349 			    dm_next);
9350 		} else {
9351 			dirrem->dm_dirinum = pagedep->pd_ino;
9352 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9353 				add_to_worklist(&dirrem->dm_list, 0);
9354 		}
9355 		FREE_LOCK(ump);
9356 		return;
9357 	}
9358 	/*
9359 	 * Add the dirrem to the inodedep's pending remove list for quick
9360 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9361 	 * will not fail.
9362 	 */
9363 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9364 		panic("softdep_setup_directory_change: Lost inodedep.");
9365 	dirrem->dm_state |= ONDEPLIST;
9366 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9367 
9368 	/*
9369 	 * If the COMPLETE flag is clear, then there were no active
9370 	 * entries and we want to roll back to the previous inode until
9371 	 * the new inode is committed to disk. If the COMPLETE flag is
9372 	 * set, then we have deleted an entry that never made it to disk.
9373 	 * If the entry we deleted resulted from a name change, then the old
9374 	 * inode reference still resides on disk. Any rollback that we do
9375 	 * needs to be to that old inode (returned to us in prevdirrem). If
9376 	 * the entry we deleted resulted from a create, then there is
9377 	 * no entry on the disk, so we want to roll back to zero rather
9378 	 * than the uncommitted inode. In either of the COMPLETE cases we
9379 	 * want to immediately free the unwritten and unreferenced inode.
9380 	 */
9381 	if ((dirrem->dm_state & COMPLETE) == 0) {
9382 		dap->da_previous = dirrem;
9383 	} else {
9384 		if (prevdirrem != NULL) {
9385 			dap->da_previous = prevdirrem;
9386 		} else {
9387 			dap->da_state &= ~DIRCHG;
9388 			dap->da_pagedep = pagedep;
9389 		}
9390 		dirrem->dm_dirinum = pagedep->pd_ino;
9391 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9392 			add_to_worklist(&dirrem->dm_list, 0);
9393 	}
9394 	/*
9395 	 * Lookup the jaddref for this journal entry.  We must finish
9396 	 * initializing it and make the diradd write dependent on it.
9397 	 * If we're not journaling, put it on the id_bufwait list if the
9398 	 * inode is not yet written. If it is written, do the post-inode
9399 	 * write processing to put it on the id_pendinghd list.
9400 	 */
9401 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9402 	if (MOUNTEDSUJ(mp)) {
9403 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9404 		    inoreflst);
9405 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9406 		    ("softdep_setup_directory_change: bad jaddref %p",
9407 		    jaddref));
9408 		jaddref->ja_diroff = dp->i_offset;
9409 		jaddref->ja_diradd = dap;
9410 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9411 		    dap, da_pdlist);
9412 		add_to_journal(&jaddref->ja_list);
9413 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9414 		dap->da_state |= COMPLETE;
9415 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9416 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9417 	} else {
9418 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9419 		    dap, da_pdlist);
9420 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9421 	}
9422 	/*
9423 	 * If we're making a new name for a directory that has not been
9424 	 * committed when need to move the dot and dotdot references to
9425 	 * this new name.
9426 	 */
9427 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9428 		merge_diradd(inodedep, dap);
9429 	FREE_LOCK(ump);
9430 }
9431 
9432 /*
9433  * Called whenever the link count on an inode is changed.
9434  * It creates an inode dependency so that the new reference(s)
9435  * to the inode cannot be committed to disk until the updated
9436  * inode has been written.
9437  */
9438 void
9439 softdep_change_linkcnt(ip)
9440 	struct inode *ip;	/* the inode with the increased link count */
9441 {
9442 	struct inodedep *inodedep;
9443 	struct ufsmount *ump;
9444 
9445 	ump = ITOUMP(ip);
9446 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9447 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9448 	ACQUIRE_LOCK(ump);
9449 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9450 	if (ip->i_nlink < ip->i_effnlink)
9451 		panic("softdep_change_linkcnt: bad delta");
9452 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9453 	FREE_LOCK(ump);
9454 }
9455 
9456 /*
9457  * Attach a sbdep dependency to the superblock buf so that we can keep
9458  * track of the head of the linked list of referenced but unlinked inodes.
9459  */
9460 void
9461 softdep_setup_sbupdate(ump, fs, bp)
9462 	struct ufsmount *ump;
9463 	struct fs *fs;
9464 	struct buf *bp;
9465 {
9466 	struct sbdep *sbdep;
9467 	struct worklist *wk;
9468 
9469 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9470 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9471 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9472 		if (wk->wk_type == D_SBDEP)
9473 			break;
9474 	if (wk != NULL)
9475 		return;
9476 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9477 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9478 	sbdep->sb_fs = fs;
9479 	sbdep->sb_ump = ump;
9480 	ACQUIRE_LOCK(ump);
9481 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9482 	FREE_LOCK(ump);
9483 }
9484 
9485 /*
9486  * Return the first unlinked inodedep which is ready to be the head of the
9487  * list.  The inodedep and all those after it must have valid next pointers.
9488  */
9489 static struct inodedep *
9490 first_unlinked_inodedep(ump)
9491 	struct ufsmount *ump;
9492 {
9493 	struct inodedep *inodedep;
9494 	struct inodedep *idp;
9495 
9496 	LOCK_OWNED(ump);
9497 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9498 	    inodedep; inodedep = idp) {
9499 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9500 			return (NULL);
9501 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9502 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9503 			break;
9504 		if ((inodedep->id_state & UNLINKPREV) == 0)
9505 			break;
9506 	}
9507 	return (inodedep);
9508 }
9509 
9510 /*
9511  * Set the sujfree unlinked head pointer prior to writing a superblock.
9512  */
9513 static void
9514 initiate_write_sbdep(sbdep)
9515 	struct sbdep *sbdep;
9516 {
9517 	struct inodedep *inodedep;
9518 	struct fs *bpfs;
9519 	struct fs *fs;
9520 
9521 	bpfs = sbdep->sb_fs;
9522 	fs = sbdep->sb_ump->um_fs;
9523 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9524 	if (inodedep) {
9525 		fs->fs_sujfree = inodedep->id_ino;
9526 		inodedep->id_state |= UNLINKPREV;
9527 	} else
9528 		fs->fs_sujfree = 0;
9529 	bpfs->fs_sujfree = fs->fs_sujfree;
9530 }
9531 
9532 /*
9533  * After a superblock is written determine whether it must be written again
9534  * due to a changing unlinked list head.
9535  */
9536 static int
9537 handle_written_sbdep(sbdep, bp)
9538 	struct sbdep *sbdep;
9539 	struct buf *bp;
9540 {
9541 	struct inodedep *inodedep;
9542 	struct fs *fs;
9543 
9544 	LOCK_OWNED(sbdep->sb_ump);
9545 	fs = sbdep->sb_fs;
9546 	/*
9547 	 * If the superblock doesn't match the in-memory list start over.
9548 	 */
9549 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9550 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9551 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9552 		bdirty(bp);
9553 		return (1);
9554 	}
9555 	WORKITEM_FREE(sbdep, D_SBDEP);
9556 	if (fs->fs_sujfree == 0)
9557 		return (0);
9558 	/*
9559 	 * Now that we have a record of this inode in stable store allow it
9560 	 * to be written to free up pending work.  Inodes may see a lot of
9561 	 * write activity after they are unlinked which we must not hold up.
9562 	 */
9563 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9564 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9565 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9566 			    inodedep, inodedep->id_state);
9567 		if (inodedep->id_state & UNLINKONLIST)
9568 			break;
9569 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9570 	}
9571 
9572 	return (0);
9573 }
9574 
9575 /*
9576  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9577  */
9578 static void
9579 unlinked_inodedep(mp, inodedep)
9580 	struct mount *mp;
9581 	struct inodedep *inodedep;
9582 {
9583 	struct ufsmount *ump;
9584 
9585 	ump = VFSTOUFS(mp);
9586 	LOCK_OWNED(ump);
9587 	if (MOUNTEDSUJ(mp) == 0)
9588 		return;
9589 	ump->um_fs->fs_fmod = 1;
9590 	if (inodedep->id_state & UNLINKED)
9591 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9592 	inodedep->id_state |= UNLINKED;
9593 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9594 }
9595 
9596 /*
9597  * Remove an inodedep from the unlinked inodedep list.  This may require
9598  * disk writes if the inode has made it that far.
9599  */
9600 static void
9601 clear_unlinked_inodedep(inodedep)
9602 	struct inodedep *inodedep;
9603 {
9604 	struct ufsmount *ump;
9605 	struct inodedep *idp;
9606 	struct inodedep *idn;
9607 	struct fs *fs;
9608 	struct buf *bp;
9609 	ino_t ino;
9610 	ino_t nino;
9611 	ino_t pino;
9612 	int error;
9613 
9614 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9615 	fs = ump->um_fs;
9616 	ino = inodedep->id_ino;
9617 	error = 0;
9618 	for (;;) {
9619 		LOCK_OWNED(ump);
9620 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9621 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9622 		    inodedep));
9623 		/*
9624 		 * If nothing has yet been written simply remove us from
9625 		 * the in memory list and return.  This is the most common
9626 		 * case where handle_workitem_remove() loses the final
9627 		 * reference.
9628 		 */
9629 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9630 			break;
9631 		/*
9632 		 * If we have a NEXT pointer and no PREV pointer we can simply
9633 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9634 		 * careful not to clear PREV if the superblock points at
9635 		 * next as well.
9636 		 */
9637 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9638 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9639 			if (idn && fs->fs_sujfree != idn->id_ino)
9640 				idn->id_state &= ~UNLINKPREV;
9641 			break;
9642 		}
9643 		/*
9644 		 * Here we have an inodedep which is actually linked into
9645 		 * the list.  We must remove it by forcing a write to the
9646 		 * link before us, whether it be the superblock or an inode.
9647 		 * Unfortunately the list may change while we're waiting
9648 		 * on the buf lock for either resource so we must loop until
9649 		 * we lock the right one.  If both the superblock and an
9650 		 * inode point to this inode we must clear the inode first
9651 		 * followed by the superblock.
9652 		 */
9653 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9654 		pino = 0;
9655 		if (idp && (idp->id_state & UNLINKNEXT))
9656 			pino = idp->id_ino;
9657 		FREE_LOCK(ump);
9658 		if (pino == 0) {
9659 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9660 			    (int)fs->fs_sbsize, 0, 0, 0);
9661 		} else {
9662 			error = bread(ump->um_devvp,
9663 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9664 			    (int)fs->fs_bsize, NOCRED, &bp);
9665 			if (error)
9666 				brelse(bp);
9667 		}
9668 		ACQUIRE_LOCK(ump);
9669 		if (error)
9670 			break;
9671 		/* If the list has changed restart the loop. */
9672 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9673 		nino = 0;
9674 		if (idp && (idp->id_state & UNLINKNEXT))
9675 			nino = idp->id_ino;
9676 		if (nino != pino ||
9677 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9678 			FREE_LOCK(ump);
9679 			brelse(bp);
9680 			ACQUIRE_LOCK(ump);
9681 			continue;
9682 		}
9683 		nino = 0;
9684 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9685 		if (idn)
9686 			nino = idn->id_ino;
9687 		/*
9688 		 * Remove us from the in memory list.  After this we cannot
9689 		 * access the inodedep.
9690 		 */
9691 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9692 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9693 		    inodedep));
9694 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9695 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9696 		FREE_LOCK(ump);
9697 		/*
9698 		 * The predecessor's next pointer is manually updated here
9699 		 * so that the NEXT flag is never cleared for an element
9700 		 * that is in the list.
9701 		 */
9702 		if (pino == 0) {
9703 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9704 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9705 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9706 			    bp);
9707 		} else if (fs->fs_magic == FS_UFS1_MAGIC)
9708 			((struct ufs1_dinode *)bp->b_data +
9709 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9710 		else
9711 			((struct ufs2_dinode *)bp->b_data +
9712 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9713 		/*
9714 		 * If the bwrite fails we have no recourse to recover.  The
9715 		 * filesystem is corrupted already.
9716 		 */
9717 		bwrite(bp);
9718 		ACQUIRE_LOCK(ump);
9719 		/*
9720 		 * If the superblock pointer still needs to be cleared force
9721 		 * a write here.
9722 		 */
9723 		if (fs->fs_sujfree == ino) {
9724 			FREE_LOCK(ump);
9725 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9726 			    (int)fs->fs_sbsize, 0, 0, 0);
9727 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9728 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9729 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9730 			    bp);
9731 			bwrite(bp);
9732 			ACQUIRE_LOCK(ump);
9733 		}
9734 
9735 		if (fs->fs_sujfree != ino)
9736 			return;
9737 		panic("clear_unlinked_inodedep: Failed to clear free head");
9738 	}
9739 	if (inodedep->id_ino == fs->fs_sujfree)
9740 		panic("clear_unlinked_inodedep: Freeing head of free list");
9741 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9742 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9743 	return;
9744 }
9745 
9746 /*
9747  * This workitem decrements the inode's link count.
9748  * If the link count reaches zero, the file is removed.
9749  */
9750 static int
9751 handle_workitem_remove(dirrem, flags)
9752 	struct dirrem *dirrem;
9753 	int flags;
9754 {
9755 	struct inodedep *inodedep;
9756 	struct workhead dotdotwk;
9757 	struct worklist *wk;
9758 	struct ufsmount *ump;
9759 	struct mount *mp;
9760 	struct vnode *vp;
9761 	struct inode *ip;
9762 	ino_t oldinum;
9763 
9764 	if (dirrem->dm_state & ONWORKLIST)
9765 		panic("handle_workitem_remove: dirrem %p still on worklist",
9766 		    dirrem);
9767 	oldinum = dirrem->dm_oldinum;
9768 	mp = dirrem->dm_list.wk_mp;
9769 	ump = VFSTOUFS(mp);
9770 	flags |= LK_EXCLUSIVE;
9771 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9772 		return (EBUSY);
9773 	ip = VTOI(vp);
9774 	ACQUIRE_LOCK(ump);
9775 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9776 		panic("handle_workitem_remove: lost inodedep");
9777 	if (dirrem->dm_state & ONDEPLIST)
9778 		LIST_REMOVE(dirrem, dm_inonext);
9779 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9780 	    ("handle_workitem_remove:  Journal entries not written."));
9781 
9782 	/*
9783 	 * Move all dependencies waiting on the remove to complete
9784 	 * from the dirrem to the inode inowait list to be completed
9785 	 * after the inode has been updated and written to disk.  Any
9786 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9787 	 * is removed.
9788 	 */
9789 	LIST_INIT(&dotdotwk);
9790 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9791 		WORKLIST_REMOVE(wk);
9792 		if (wk->wk_state & MKDIR_PARENT) {
9793 			wk->wk_state &= ~MKDIR_PARENT;
9794 			WORKLIST_INSERT(&dotdotwk, wk);
9795 			continue;
9796 		}
9797 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9798 	}
9799 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9800 	/*
9801 	 * Normal file deletion.
9802 	 */
9803 	if ((dirrem->dm_state & RMDIR) == 0) {
9804 		ip->i_nlink--;
9805 		DIP_SET(ip, i_nlink, ip->i_nlink);
9806 		ip->i_flag |= IN_CHANGE;
9807 		if (ip->i_nlink < ip->i_effnlink)
9808 			panic("handle_workitem_remove: bad file delta");
9809 		if (ip->i_nlink == 0)
9810 			unlinked_inodedep(mp, inodedep);
9811 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9812 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9813 		    ("handle_workitem_remove: worklist not empty. %s",
9814 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9815 		WORKITEM_FREE(dirrem, D_DIRREM);
9816 		FREE_LOCK(ump);
9817 		goto out;
9818 	}
9819 	/*
9820 	 * Directory deletion. Decrement reference count for both the
9821 	 * just deleted parent directory entry and the reference for ".".
9822 	 * Arrange to have the reference count on the parent decremented
9823 	 * to account for the loss of "..".
9824 	 */
9825 	ip->i_nlink -= 2;
9826 	DIP_SET(ip, i_nlink, ip->i_nlink);
9827 	ip->i_flag |= IN_CHANGE;
9828 	if (ip->i_nlink < ip->i_effnlink)
9829 		panic("handle_workitem_remove: bad dir delta");
9830 	if (ip->i_nlink == 0)
9831 		unlinked_inodedep(mp, inodedep);
9832 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9833 	/*
9834 	 * Rename a directory to a new parent. Since, we are both deleting
9835 	 * and creating a new directory entry, the link count on the new
9836 	 * directory should not change. Thus we skip the followup dirrem.
9837 	 */
9838 	if (dirrem->dm_state & DIRCHG) {
9839 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9840 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9841 		WORKITEM_FREE(dirrem, D_DIRREM);
9842 		FREE_LOCK(ump);
9843 		goto out;
9844 	}
9845 	dirrem->dm_state = ONDEPLIST;
9846 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9847 	/*
9848 	 * Place the dirrem on the parent's diremhd list.
9849 	 */
9850 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9851 		panic("handle_workitem_remove: lost dir inodedep");
9852 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9853 	/*
9854 	 * If the allocated inode has never been written to disk, then
9855 	 * the on-disk inode is zero'ed and we can remove the file
9856 	 * immediately.  When journaling if the inode has been marked
9857 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9858 	 */
9859 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9860 	if (inodedep == NULL ||
9861 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9862 	    check_inode_unwritten(inodedep)) {
9863 		FREE_LOCK(ump);
9864 		vput(vp);
9865 		return handle_workitem_remove(dirrem, flags);
9866 	}
9867 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9868 	FREE_LOCK(ump);
9869 	ip->i_flag |= IN_CHANGE;
9870 out:
9871 	ffs_update(vp, 0);
9872 	vput(vp);
9873 	return (0);
9874 }
9875 
9876 /*
9877  * Inode de-allocation dependencies.
9878  *
9879  * When an inode's link count is reduced to zero, it can be de-allocated. We
9880  * found it convenient to postpone de-allocation until after the inode is
9881  * written to disk with its new link count (zero).  At this point, all of the
9882  * on-disk inode's block pointers are nullified and, with careful dependency
9883  * list ordering, all dependencies related to the inode will be satisfied and
9884  * the corresponding dependency structures de-allocated.  So, if/when the
9885  * inode is reused, there will be no mixing of old dependencies with new
9886  * ones.  This artificial dependency is set up by the block de-allocation
9887  * procedure above (softdep_setup_freeblocks) and completed by the
9888  * following procedure.
9889  */
9890 static void
9891 handle_workitem_freefile(freefile)
9892 	struct freefile *freefile;
9893 {
9894 	struct workhead wkhd;
9895 	struct fs *fs;
9896 	struct inodedep *idp;
9897 	struct ufsmount *ump;
9898 	int error;
9899 
9900 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9901 	fs = ump->um_fs;
9902 #ifdef DEBUG
9903 	ACQUIRE_LOCK(ump);
9904 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9905 	FREE_LOCK(ump);
9906 	if (error)
9907 		panic("handle_workitem_freefile: inodedep %p survived", idp);
9908 #endif
9909 	UFS_LOCK(ump);
9910 	fs->fs_pendinginodes -= 1;
9911 	UFS_UNLOCK(ump);
9912 	LIST_INIT(&wkhd);
9913 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9914 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9915 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9916 		softdep_error("handle_workitem_freefile", error);
9917 	ACQUIRE_LOCK(ump);
9918 	WORKITEM_FREE(freefile, D_FREEFILE);
9919 	FREE_LOCK(ump);
9920 }
9921 
9922 
9923 /*
9924  * Helper function which unlinks marker element from work list and returns
9925  * the next element on the list.
9926  */
9927 static __inline struct worklist *
9928 markernext(struct worklist *marker)
9929 {
9930 	struct worklist *next;
9931 
9932 	next = LIST_NEXT(marker, wk_list);
9933 	LIST_REMOVE(marker, wk_list);
9934 	return next;
9935 }
9936 
9937 /*
9938  * Disk writes.
9939  *
9940  * The dependency structures constructed above are most actively used when file
9941  * system blocks are written to disk.  No constraints are placed on when a
9942  * block can be written, but unsatisfied update dependencies are made safe by
9943  * modifying (or replacing) the source memory for the duration of the disk
9944  * write.  When the disk write completes, the memory block is again brought
9945  * up-to-date.
9946  *
9947  * In-core inode structure reclamation.
9948  *
9949  * Because there are a finite number of "in-core" inode structures, they are
9950  * reused regularly.  By transferring all inode-related dependencies to the
9951  * in-memory inode block and indexing them separately (via "inodedep"s), we
9952  * can allow "in-core" inode structures to be reused at any time and avoid
9953  * any increase in contention.
9954  *
9955  * Called just before entering the device driver to initiate a new disk I/O.
9956  * The buffer must be locked, thus, no I/O completion operations can occur
9957  * while we are manipulating its associated dependencies.
9958  */
9959 static void
9960 softdep_disk_io_initiation(bp)
9961 	struct buf *bp;		/* structure describing disk write to occur */
9962 {
9963 	struct worklist *wk;
9964 	struct worklist marker;
9965 	struct inodedep *inodedep;
9966 	struct freeblks *freeblks;
9967 	struct jblkdep *jblkdep;
9968 	struct newblk *newblk;
9969 	struct ufsmount *ump;
9970 
9971 	/*
9972 	 * We only care about write operations. There should never
9973 	 * be dependencies for reads.
9974 	 */
9975 	if (bp->b_iocmd != BIO_WRITE)
9976 		panic("softdep_disk_io_initiation: not write");
9977 
9978 	if (bp->b_vflags & BV_BKGRDINPROG)
9979 		panic("softdep_disk_io_initiation: Writing buffer with "
9980 		    "background write in progress: %p", bp);
9981 
9982 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
9983 		return;
9984 	ump = VFSTOUFS(wk->wk_mp);
9985 
9986 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
9987 	PHOLD(curproc);			/* Don't swap out kernel stack */
9988 	ACQUIRE_LOCK(ump);
9989 	/*
9990 	 * Do any necessary pre-I/O processing.
9991 	 */
9992 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9993 	     wk = markernext(&marker)) {
9994 		LIST_INSERT_AFTER(wk, &marker, wk_list);
9995 		switch (wk->wk_type) {
9996 
9997 		case D_PAGEDEP:
9998 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
9999 			continue;
10000 
10001 		case D_INODEDEP:
10002 			inodedep = WK_INODEDEP(wk);
10003 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10004 				initiate_write_inodeblock_ufs1(inodedep, bp);
10005 			else
10006 				initiate_write_inodeblock_ufs2(inodedep, bp);
10007 			continue;
10008 
10009 		case D_INDIRDEP:
10010 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10011 			continue;
10012 
10013 		case D_BMSAFEMAP:
10014 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10015 			continue;
10016 
10017 		case D_JSEG:
10018 			WK_JSEG(wk)->js_buf = NULL;
10019 			continue;
10020 
10021 		case D_FREEBLKS:
10022 			freeblks = WK_FREEBLKS(wk);
10023 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10024 			/*
10025 			 * We have to wait for the freeblks to be journaled
10026 			 * before we can write an inodeblock with updated
10027 			 * pointers.  Be careful to arrange the marker so
10028 			 * we revisit the freeblks if it's not removed by
10029 			 * the first jwait().
10030 			 */
10031 			if (jblkdep != NULL) {
10032 				LIST_REMOVE(&marker, wk_list);
10033 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10034 				jwait(&jblkdep->jb_list, MNT_WAIT);
10035 			}
10036 			continue;
10037 		case D_ALLOCDIRECT:
10038 		case D_ALLOCINDIR:
10039 			/*
10040 			 * We have to wait for the jnewblk to be journaled
10041 			 * before we can write to a block if the contents
10042 			 * may be confused with an earlier file's indirect
10043 			 * at recovery time.  Handle the marker as described
10044 			 * above.
10045 			 */
10046 			newblk = WK_NEWBLK(wk);
10047 			if (newblk->nb_jnewblk != NULL &&
10048 			    indirblk_lookup(newblk->nb_list.wk_mp,
10049 			    newblk->nb_newblkno)) {
10050 				LIST_REMOVE(&marker, wk_list);
10051 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10052 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10053 			}
10054 			continue;
10055 
10056 		case D_SBDEP:
10057 			initiate_write_sbdep(WK_SBDEP(wk));
10058 			continue;
10059 
10060 		case D_MKDIR:
10061 		case D_FREEWORK:
10062 		case D_FREEDEP:
10063 		case D_JSEGDEP:
10064 			continue;
10065 
10066 		default:
10067 			panic("handle_disk_io_initiation: Unexpected type %s",
10068 			    TYPENAME(wk->wk_type));
10069 			/* NOTREACHED */
10070 		}
10071 	}
10072 	FREE_LOCK(ump);
10073 	PRELE(curproc);			/* Allow swapout of kernel stack */
10074 }
10075 
10076 /*
10077  * Called from within the procedure above to deal with unsatisfied
10078  * allocation dependencies in a directory. The buffer must be locked,
10079  * thus, no I/O completion operations can occur while we are
10080  * manipulating its associated dependencies.
10081  */
10082 static void
10083 initiate_write_filepage(pagedep, bp)
10084 	struct pagedep *pagedep;
10085 	struct buf *bp;
10086 {
10087 	struct jremref *jremref;
10088 	struct jmvref *jmvref;
10089 	struct dirrem *dirrem;
10090 	struct diradd *dap;
10091 	struct direct *ep;
10092 	int i;
10093 
10094 	if (pagedep->pd_state & IOSTARTED) {
10095 		/*
10096 		 * This can only happen if there is a driver that does not
10097 		 * understand chaining. Here biodone will reissue the call
10098 		 * to strategy for the incomplete buffers.
10099 		 */
10100 		printf("initiate_write_filepage: already started\n");
10101 		return;
10102 	}
10103 	pagedep->pd_state |= IOSTARTED;
10104 	/*
10105 	 * Wait for all journal remove dependencies to hit the disk.
10106 	 * We can not allow any potentially conflicting directory adds
10107 	 * to be visible before removes and rollback is too difficult.
10108 	 * The per-filesystem lock may be dropped and re-acquired, however
10109 	 * we hold the buf locked so the dependency can not go away.
10110 	 */
10111 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10112 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10113 			jwait(&jremref->jr_list, MNT_WAIT);
10114 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10115 		jwait(&jmvref->jm_list, MNT_WAIT);
10116 	for (i = 0; i < DAHASHSZ; i++) {
10117 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10118 			ep = (struct direct *)
10119 			    ((char *)bp->b_data + dap->da_offset);
10120 			if (ep->d_ino != dap->da_newinum)
10121 				panic("%s: dir inum %ju != new %ju",
10122 				    "initiate_write_filepage",
10123 				    (uintmax_t)ep->d_ino,
10124 				    (uintmax_t)dap->da_newinum);
10125 			if (dap->da_state & DIRCHG)
10126 				ep->d_ino = dap->da_previous->dm_oldinum;
10127 			else
10128 				ep->d_ino = 0;
10129 			dap->da_state &= ~ATTACHED;
10130 			dap->da_state |= UNDONE;
10131 		}
10132 	}
10133 }
10134 
10135 /*
10136  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10137  * Note that any bug fixes made to this routine must be done in the
10138  * version found below.
10139  *
10140  * Called from within the procedure above to deal with unsatisfied
10141  * allocation dependencies in an inodeblock. The buffer must be
10142  * locked, thus, no I/O completion operations can occur while we
10143  * are manipulating its associated dependencies.
10144  */
10145 static void
10146 initiate_write_inodeblock_ufs1(inodedep, bp)
10147 	struct inodedep *inodedep;
10148 	struct buf *bp;			/* The inode block */
10149 {
10150 	struct allocdirect *adp, *lastadp;
10151 	struct ufs1_dinode *dp;
10152 	struct ufs1_dinode *sip;
10153 	struct inoref *inoref;
10154 	struct ufsmount *ump;
10155 	struct fs *fs;
10156 	ufs_lbn_t i;
10157 #ifdef INVARIANTS
10158 	ufs_lbn_t prevlbn = 0;
10159 #endif
10160 	int deplist;
10161 
10162 	if (inodedep->id_state & IOSTARTED)
10163 		panic("initiate_write_inodeblock_ufs1: already started");
10164 	inodedep->id_state |= IOSTARTED;
10165 	fs = inodedep->id_fs;
10166 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10167 	LOCK_OWNED(ump);
10168 	dp = (struct ufs1_dinode *)bp->b_data +
10169 	    ino_to_fsbo(fs, inodedep->id_ino);
10170 
10171 	/*
10172 	 * If we're on the unlinked list but have not yet written our
10173 	 * next pointer initialize it here.
10174 	 */
10175 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10176 		struct inodedep *inon;
10177 
10178 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10179 		dp->di_freelink = inon ? inon->id_ino : 0;
10180 	}
10181 	/*
10182 	 * If the bitmap is not yet written, then the allocated
10183 	 * inode cannot be written to disk.
10184 	 */
10185 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10186 		if (inodedep->id_savedino1 != NULL)
10187 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10188 		FREE_LOCK(ump);
10189 		sip = malloc(sizeof(struct ufs1_dinode),
10190 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10191 		ACQUIRE_LOCK(ump);
10192 		inodedep->id_savedino1 = sip;
10193 		*inodedep->id_savedino1 = *dp;
10194 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10195 		dp->di_gen = inodedep->id_savedino1->di_gen;
10196 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10197 		return;
10198 	}
10199 	/*
10200 	 * If no dependencies, then there is nothing to roll back.
10201 	 */
10202 	inodedep->id_savedsize = dp->di_size;
10203 	inodedep->id_savedextsize = 0;
10204 	inodedep->id_savednlink = dp->di_nlink;
10205 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10206 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10207 		return;
10208 	/*
10209 	 * Revert the link count to that of the first unwritten journal entry.
10210 	 */
10211 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10212 	if (inoref)
10213 		dp->di_nlink = inoref->if_nlink;
10214 	/*
10215 	 * Set the dependencies to busy.
10216 	 */
10217 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10218 	     adp = TAILQ_NEXT(adp, ad_next)) {
10219 #ifdef INVARIANTS
10220 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10221 			panic("softdep_write_inodeblock: lbn order");
10222 		prevlbn = adp->ad_offset;
10223 		if (adp->ad_offset < UFS_NDADDR &&
10224 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10225 			panic("%s: direct pointer #%jd mismatch %d != %jd",
10226 			    "softdep_write_inodeblock",
10227 			    (intmax_t)adp->ad_offset,
10228 			    dp->di_db[adp->ad_offset],
10229 			    (intmax_t)adp->ad_newblkno);
10230 		if (adp->ad_offset >= UFS_NDADDR &&
10231 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10232 			panic("%s: indirect pointer #%jd mismatch %d != %jd",
10233 			    "softdep_write_inodeblock",
10234 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10235 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10236 			    (intmax_t)adp->ad_newblkno);
10237 		deplist |= 1 << adp->ad_offset;
10238 		if ((adp->ad_state & ATTACHED) == 0)
10239 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10240 			    adp->ad_state);
10241 #endif /* INVARIANTS */
10242 		adp->ad_state &= ~ATTACHED;
10243 		adp->ad_state |= UNDONE;
10244 	}
10245 	/*
10246 	 * The on-disk inode cannot claim to be any larger than the last
10247 	 * fragment that has been written. Otherwise, the on-disk inode
10248 	 * might have fragments that were not the last block in the file
10249 	 * which would corrupt the filesystem.
10250 	 */
10251 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10252 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10253 		if (adp->ad_offset >= UFS_NDADDR)
10254 			break;
10255 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10256 		/* keep going until hitting a rollback to a frag */
10257 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10258 			continue;
10259 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10260 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10261 #ifdef INVARIANTS
10262 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10263 				panic("softdep_write_inodeblock: lost dep1");
10264 #endif /* INVARIANTS */
10265 			dp->di_db[i] = 0;
10266 		}
10267 		for (i = 0; i < UFS_NIADDR; i++) {
10268 #ifdef INVARIANTS
10269 			if (dp->di_ib[i] != 0 &&
10270 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10271 				panic("softdep_write_inodeblock: lost dep2");
10272 #endif /* INVARIANTS */
10273 			dp->di_ib[i] = 0;
10274 		}
10275 		return;
10276 	}
10277 	/*
10278 	 * If we have zero'ed out the last allocated block of the file,
10279 	 * roll back the size to the last currently allocated block.
10280 	 * We know that this last allocated block is a full-sized as
10281 	 * we already checked for fragments in the loop above.
10282 	 */
10283 	if (lastadp != NULL &&
10284 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10285 		for (i = lastadp->ad_offset; i >= 0; i--)
10286 			if (dp->di_db[i] != 0)
10287 				break;
10288 		dp->di_size = (i + 1) * fs->fs_bsize;
10289 	}
10290 	/*
10291 	 * The only dependencies are for indirect blocks.
10292 	 *
10293 	 * The file size for indirect block additions is not guaranteed.
10294 	 * Such a guarantee would be non-trivial to achieve. The conventional
10295 	 * synchronous write implementation also does not make this guarantee.
10296 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10297 	 * can be over-estimated without destroying integrity when the file
10298 	 * moves into the indirect blocks (i.e., is large). If we want to
10299 	 * postpone fsck, we are stuck with this argument.
10300 	 */
10301 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10302 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10303 }
10304 
10305 /*
10306  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10307  * Note that any bug fixes made to this routine must be done in the
10308  * version found above.
10309  *
10310  * Called from within the procedure above to deal with unsatisfied
10311  * allocation dependencies in an inodeblock. The buffer must be
10312  * locked, thus, no I/O completion operations can occur while we
10313  * are manipulating its associated dependencies.
10314  */
10315 static void
10316 initiate_write_inodeblock_ufs2(inodedep, bp)
10317 	struct inodedep *inodedep;
10318 	struct buf *bp;			/* The inode block */
10319 {
10320 	struct allocdirect *adp, *lastadp;
10321 	struct ufs2_dinode *dp;
10322 	struct ufs2_dinode *sip;
10323 	struct inoref *inoref;
10324 	struct ufsmount *ump;
10325 	struct fs *fs;
10326 	ufs_lbn_t i;
10327 #ifdef INVARIANTS
10328 	ufs_lbn_t prevlbn = 0;
10329 #endif
10330 	int deplist;
10331 
10332 	if (inodedep->id_state & IOSTARTED)
10333 		panic("initiate_write_inodeblock_ufs2: already started");
10334 	inodedep->id_state |= IOSTARTED;
10335 	fs = inodedep->id_fs;
10336 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10337 	LOCK_OWNED(ump);
10338 	dp = (struct ufs2_dinode *)bp->b_data +
10339 	    ino_to_fsbo(fs, inodedep->id_ino);
10340 
10341 	/*
10342 	 * If we're on the unlinked list but have not yet written our
10343 	 * next pointer initialize it here.
10344 	 */
10345 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10346 		struct inodedep *inon;
10347 
10348 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10349 		dp->di_freelink = inon ? inon->id_ino : 0;
10350 	}
10351 	/*
10352 	 * If the bitmap is not yet written, then the allocated
10353 	 * inode cannot be written to disk.
10354 	 */
10355 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10356 		if (inodedep->id_savedino2 != NULL)
10357 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10358 		FREE_LOCK(ump);
10359 		sip = malloc(sizeof(struct ufs2_dinode),
10360 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10361 		ACQUIRE_LOCK(ump);
10362 		inodedep->id_savedino2 = sip;
10363 		*inodedep->id_savedino2 = *dp;
10364 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10365 		dp->di_gen = inodedep->id_savedino2->di_gen;
10366 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10367 		return;
10368 	}
10369 	/*
10370 	 * If no dependencies, then there is nothing to roll back.
10371 	 */
10372 	inodedep->id_savedsize = dp->di_size;
10373 	inodedep->id_savedextsize = dp->di_extsize;
10374 	inodedep->id_savednlink = dp->di_nlink;
10375 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10376 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10377 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10378 		return;
10379 	/*
10380 	 * Revert the link count to that of the first unwritten journal entry.
10381 	 */
10382 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10383 	if (inoref)
10384 		dp->di_nlink = inoref->if_nlink;
10385 
10386 	/*
10387 	 * Set the ext data dependencies to busy.
10388 	 */
10389 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10390 	     adp = TAILQ_NEXT(adp, ad_next)) {
10391 #ifdef INVARIANTS
10392 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10393 			panic("softdep_write_inodeblock: lbn order");
10394 		prevlbn = adp->ad_offset;
10395 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10396 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10397 			    "softdep_write_inodeblock",
10398 			    (intmax_t)adp->ad_offset,
10399 			    (intmax_t)dp->di_extb[adp->ad_offset],
10400 			    (intmax_t)adp->ad_newblkno);
10401 		deplist |= 1 << adp->ad_offset;
10402 		if ((adp->ad_state & ATTACHED) == 0)
10403 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10404 			    adp->ad_state);
10405 #endif /* INVARIANTS */
10406 		adp->ad_state &= ~ATTACHED;
10407 		adp->ad_state |= UNDONE;
10408 	}
10409 	/*
10410 	 * The on-disk inode cannot claim to be any larger than the last
10411 	 * fragment that has been written. Otherwise, the on-disk inode
10412 	 * might have fragments that were not the last block in the ext
10413 	 * data which would corrupt the filesystem.
10414 	 */
10415 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10416 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10417 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10418 		/* keep going until hitting a rollback to a frag */
10419 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10420 			continue;
10421 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10422 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10423 #ifdef INVARIANTS
10424 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10425 				panic("softdep_write_inodeblock: lost dep1");
10426 #endif /* INVARIANTS */
10427 			dp->di_extb[i] = 0;
10428 		}
10429 		lastadp = NULL;
10430 		break;
10431 	}
10432 	/*
10433 	 * If we have zero'ed out the last allocated block of the ext
10434 	 * data, roll back the size to the last currently allocated block.
10435 	 * We know that this last allocated block is a full-sized as
10436 	 * we already checked for fragments in the loop above.
10437 	 */
10438 	if (lastadp != NULL &&
10439 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10440 		for (i = lastadp->ad_offset; i >= 0; i--)
10441 			if (dp->di_extb[i] != 0)
10442 				break;
10443 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10444 	}
10445 	/*
10446 	 * Set the file data dependencies to busy.
10447 	 */
10448 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10449 	     adp = TAILQ_NEXT(adp, ad_next)) {
10450 #ifdef INVARIANTS
10451 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10452 			panic("softdep_write_inodeblock: lbn order");
10453 		if ((adp->ad_state & ATTACHED) == 0)
10454 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10455 		prevlbn = adp->ad_offset;
10456 		if (adp->ad_offset < UFS_NDADDR &&
10457 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10458 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10459 			    "softdep_write_inodeblock",
10460 			    (intmax_t)adp->ad_offset,
10461 			    (intmax_t)dp->di_db[adp->ad_offset],
10462 			    (intmax_t)adp->ad_newblkno);
10463 		if (adp->ad_offset >= UFS_NDADDR &&
10464 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10465 			panic("%s indirect pointer #%jd mismatch %jd != %jd",
10466 			    "softdep_write_inodeblock:",
10467 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10468 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10469 			    (intmax_t)adp->ad_newblkno);
10470 		deplist |= 1 << adp->ad_offset;
10471 		if ((adp->ad_state & ATTACHED) == 0)
10472 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10473 			    adp->ad_state);
10474 #endif /* INVARIANTS */
10475 		adp->ad_state &= ~ATTACHED;
10476 		adp->ad_state |= UNDONE;
10477 	}
10478 	/*
10479 	 * The on-disk inode cannot claim to be any larger than the last
10480 	 * fragment that has been written. Otherwise, the on-disk inode
10481 	 * might have fragments that were not the last block in the file
10482 	 * which would corrupt the filesystem.
10483 	 */
10484 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10485 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10486 		if (adp->ad_offset >= UFS_NDADDR)
10487 			break;
10488 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10489 		/* keep going until hitting a rollback to a frag */
10490 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10491 			continue;
10492 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10493 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10494 #ifdef INVARIANTS
10495 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10496 				panic("softdep_write_inodeblock: lost dep2");
10497 #endif /* INVARIANTS */
10498 			dp->di_db[i] = 0;
10499 		}
10500 		for (i = 0; i < UFS_NIADDR; i++) {
10501 #ifdef INVARIANTS
10502 			if (dp->di_ib[i] != 0 &&
10503 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10504 				panic("softdep_write_inodeblock: lost dep3");
10505 #endif /* INVARIANTS */
10506 			dp->di_ib[i] = 0;
10507 		}
10508 		return;
10509 	}
10510 	/*
10511 	 * If we have zero'ed out the last allocated block of the file,
10512 	 * roll back the size to the last currently allocated block.
10513 	 * We know that this last allocated block is a full-sized as
10514 	 * we already checked for fragments in the loop above.
10515 	 */
10516 	if (lastadp != NULL &&
10517 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10518 		for (i = lastadp->ad_offset; i >= 0; i--)
10519 			if (dp->di_db[i] != 0)
10520 				break;
10521 		dp->di_size = (i + 1) * fs->fs_bsize;
10522 	}
10523 	/*
10524 	 * The only dependencies are for indirect blocks.
10525 	 *
10526 	 * The file size for indirect block additions is not guaranteed.
10527 	 * Such a guarantee would be non-trivial to achieve. The conventional
10528 	 * synchronous write implementation also does not make this guarantee.
10529 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10530 	 * can be over-estimated without destroying integrity when the file
10531 	 * moves into the indirect blocks (i.e., is large). If we want to
10532 	 * postpone fsck, we are stuck with this argument.
10533 	 */
10534 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10535 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10536 }
10537 
10538 /*
10539  * Cancel an indirdep as a result of truncation.  Release all of the
10540  * children allocindirs and place their journal work on the appropriate
10541  * list.
10542  */
10543 static void
10544 cancel_indirdep(indirdep, bp, freeblks)
10545 	struct indirdep *indirdep;
10546 	struct buf *bp;
10547 	struct freeblks *freeblks;
10548 {
10549 	struct allocindir *aip;
10550 
10551 	/*
10552 	 * None of the indirect pointers will ever be visible,
10553 	 * so they can simply be tossed. GOINGAWAY ensures
10554 	 * that allocated pointers will be saved in the buffer
10555 	 * cache until they are freed. Note that they will
10556 	 * only be able to be found by their physical address
10557 	 * since the inode mapping the logical address will
10558 	 * be gone. The save buffer used for the safe copy
10559 	 * was allocated in setup_allocindir_phase2 using
10560 	 * the physical address so it could be used for this
10561 	 * purpose. Hence we swap the safe copy with the real
10562 	 * copy, allowing the safe copy to be freed and holding
10563 	 * on to the real copy for later use in indir_trunc.
10564 	 */
10565 	if (indirdep->ir_state & GOINGAWAY)
10566 		panic("cancel_indirdep: already gone");
10567 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10568 		indirdep->ir_state |= DEPCOMPLETE;
10569 		LIST_REMOVE(indirdep, ir_next);
10570 	}
10571 	indirdep->ir_state |= GOINGAWAY;
10572 	/*
10573 	 * Pass in bp for blocks still have journal writes
10574 	 * pending so we can cancel them on their own.
10575 	 */
10576 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10577 		cancel_allocindir(aip, bp, freeblks, 0);
10578 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10579 		cancel_allocindir(aip, NULL, freeblks, 0);
10580 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10581 		cancel_allocindir(aip, NULL, freeblks, 0);
10582 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10583 		cancel_allocindir(aip, NULL, freeblks, 0);
10584 	/*
10585 	 * If there are pending partial truncations we need to keep the
10586 	 * old block copy around until they complete.  This is because
10587 	 * the current b_data is not a perfect superset of the available
10588 	 * blocks.
10589 	 */
10590 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10591 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10592 	else
10593 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10594 	WORKLIST_REMOVE(&indirdep->ir_list);
10595 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10596 	indirdep->ir_bp = NULL;
10597 	indirdep->ir_freeblks = freeblks;
10598 }
10599 
10600 /*
10601  * Free an indirdep once it no longer has new pointers to track.
10602  */
10603 static void
10604 free_indirdep(indirdep)
10605 	struct indirdep *indirdep;
10606 {
10607 
10608 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10609 	    ("free_indirdep: Indir trunc list not empty."));
10610 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10611 	    ("free_indirdep: Complete head not empty."));
10612 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10613 	    ("free_indirdep: write head not empty."));
10614 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10615 	    ("free_indirdep: done head not empty."));
10616 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10617 	    ("free_indirdep: deplist head not empty."));
10618 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10619 	    ("free_indirdep: %p still on newblk list.", indirdep));
10620 	KASSERT(indirdep->ir_saveddata == NULL,
10621 	    ("free_indirdep: %p still has saved data.", indirdep));
10622 	if (indirdep->ir_state & ONWORKLIST)
10623 		WORKLIST_REMOVE(&indirdep->ir_list);
10624 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10625 }
10626 
10627 /*
10628  * Called before a write to an indirdep.  This routine is responsible for
10629  * rolling back pointers to a safe state which includes only those
10630  * allocindirs which have been completed.
10631  */
10632 static void
10633 initiate_write_indirdep(indirdep, bp)
10634 	struct indirdep *indirdep;
10635 	struct buf *bp;
10636 {
10637 	struct ufsmount *ump;
10638 
10639 	indirdep->ir_state |= IOSTARTED;
10640 	if (indirdep->ir_state & GOINGAWAY)
10641 		panic("disk_io_initiation: indirdep gone");
10642 	/*
10643 	 * If there are no remaining dependencies, this will be writing
10644 	 * the real pointers.
10645 	 */
10646 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10647 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10648 		return;
10649 	/*
10650 	 * Replace up-to-date version with safe version.
10651 	 */
10652 	if (indirdep->ir_saveddata == NULL) {
10653 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10654 		LOCK_OWNED(ump);
10655 		FREE_LOCK(ump);
10656 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10657 		    M_SOFTDEP_FLAGS);
10658 		ACQUIRE_LOCK(ump);
10659 	}
10660 	indirdep->ir_state &= ~ATTACHED;
10661 	indirdep->ir_state |= UNDONE;
10662 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10663 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10664 	    bp->b_bcount);
10665 }
10666 
10667 /*
10668  * Called when an inode has been cleared in a cg bitmap.  This finally
10669  * eliminates any canceled jaddrefs
10670  */
10671 void
10672 softdep_setup_inofree(mp, bp, ino, wkhd)
10673 	struct mount *mp;
10674 	struct buf *bp;
10675 	ino_t ino;
10676 	struct workhead *wkhd;
10677 {
10678 	struct worklist *wk, *wkn;
10679 	struct inodedep *inodedep;
10680 	struct ufsmount *ump;
10681 	uint8_t *inosused;
10682 	struct cg *cgp;
10683 	struct fs *fs;
10684 
10685 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10686 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10687 	ump = VFSTOUFS(mp);
10688 	ACQUIRE_LOCK(ump);
10689 	fs = ump->um_fs;
10690 	cgp = (struct cg *)bp->b_data;
10691 	inosused = cg_inosused(cgp);
10692 	if (isset(inosused, ino % fs->fs_ipg))
10693 		panic("softdep_setup_inofree: inode %ju not freed.",
10694 		    (uintmax_t)ino);
10695 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10696 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10697 		    (uintmax_t)ino, inodedep);
10698 	if (wkhd) {
10699 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10700 			if (wk->wk_type != D_JADDREF)
10701 				continue;
10702 			WORKLIST_REMOVE(wk);
10703 			/*
10704 			 * We can free immediately even if the jaddref
10705 			 * isn't attached in a background write as now
10706 			 * the bitmaps are reconciled.
10707 			 */
10708 			wk->wk_state |= COMPLETE | ATTACHED;
10709 			free_jaddref(WK_JADDREF(wk));
10710 		}
10711 		jwork_move(&bp->b_dep, wkhd);
10712 	}
10713 	FREE_LOCK(ump);
10714 }
10715 
10716 
10717 /*
10718  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10719  * map.  Any dependencies waiting for the write to clear are added to the
10720  * buf's list and any jnewblks that are being canceled are discarded
10721  * immediately.
10722  */
10723 void
10724 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10725 	struct mount *mp;
10726 	struct buf *bp;
10727 	ufs2_daddr_t blkno;
10728 	int frags;
10729 	struct workhead *wkhd;
10730 {
10731 	struct bmsafemap *bmsafemap;
10732 	struct jnewblk *jnewblk;
10733 	struct ufsmount *ump;
10734 	struct worklist *wk;
10735 	struct fs *fs;
10736 #ifdef SUJ_DEBUG
10737 	uint8_t *blksfree;
10738 	struct cg *cgp;
10739 	ufs2_daddr_t jstart;
10740 	ufs2_daddr_t jend;
10741 	ufs2_daddr_t end;
10742 	long bno;
10743 	int i;
10744 #endif
10745 
10746 	CTR3(KTR_SUJ,
10747 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10748 	    blkno, frags, wkhd);
10749 
10750 	ump = VFSTOUFS(mp);
10751 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10752 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10753 	ACQUIRE_LOCK(ump);
10754 	/* Lookup the bmsafemap so we track when it is dirty. */
10755 	fs = ump->um_fs;
10756 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10757 	/*
10758 	 * Detach any jnewblks which have been canceled.  They must linger
10759 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10760 	 * an unjournaled allocation from hitting the disk.
10761 	 */
10762 	if (wkhd) {
10763 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10764 			CTR2(KTR_SUJ,
10765 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10766 			    blkno, wk->wk_type);
10767 			WORKLIST_REMOVE(wk);
10768 			if (wk->wk_type != D_JNEWBLK) {
10769 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10770 				continue;
10771 			}
10772 			jnewblk = WK_JNEWBLK(wk);
10773 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10774 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10775 #ifdef SUJ_DEBUG
10776 			/*
10777 			 * Assert that this block is free in the bitmap
10778 			 * before we discard the jnewblk.
10779 			 */
10780 			cgp = (struct cg *)bp->b_data;
10781 			blksfree = cg_blksfree(cgp);
10782 			bno = dtogd(fs, jnewblk->jn_blkno);
10783 			for (i = jnewblk->jn_oldfrags;
10784 			    i < jnewblk->jn_frags; i++) {
10785 				if (isset(blksfree, bno + i))
10786 					continue;
10787 				panic("softdep_setup_blkfree: not free");
10788 			}
10789 #endif
10790 			/*
10791 			 * Even if it's not attached we can free immediately
10792 			 * as the new bitmap is correct.
10793 			 */
10794 			wk->wk_state |= COMPLETE | ATTACHED;
10795 			free_jnewblk(jnewblk);
10796 		}
10797 	}
10798 
10799 #ifdef SUJ_DEBUG
10800 	/*
10801 	 * Assert that we are not freeing a block which has an outstanding
10802 	 * allocation dependency.
10803 	 */
10804 	fs = VFSTOUFS(mp)->um_fs;
10805 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10806 	end = blkno + frags;
10807 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10808 		/*
10809 		 * Don't match against blocks that will be freed when the
10810 		 * background write is done.
10811 		 */
10812 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10813 		    (COMPLETE | DEPCOMPLETE))
10814 			continue;
10815 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10816 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10817 		if ((blkno >= jstart && blkno < jend) ||
10818 		    (end > jstart && end <= jend)) {
10819 			printf("state 0x%X %jd - %d %d dep %p\n",
10820 			    jnewblk->jn_state, jnewblk->jn_blkno,
10821 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10822 			    jnewblk->jn_dep);
10823 			panic("softdep_setup_blkfree: "
10824 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10825 			    blkno, end, frags, jstart, jend);
10826 		}
10827 	}
10828 #endif
10829 	FREE_LOCK(ump);
10830 }
10831 
10832 /*
10833  * Revert a block allocation when the journal record that describes it
10834  * is not yet written.
10835  */
10836 static int
10837 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10838 	struct jnewblk *jnewblk;
10839 	struct fs *fs;
10840 	struct cg *cgp;
10841 	uint8_t *blksfree;
10842 {
10843 	ufs1_daddr_t fragno;
10844 	long cgbno, bbase;
10845 	int frags, blk;
10846 	int i;
10847 
10848 	frags = 0;
10849 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10850 	/*
10851 	 * We have to test which frags need to be rolled back.  We may
10852 	 * be operating on a stale copy when doing background writes.
10853 	 */
10854 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10855 		if (isclr(blksfree, cgbno + i))
10856 			frags++;
10857 	if (frags == 0)
10858 		return (0);
10859 	/*
10860 	 * This is mostly ffs_blkfree() sans some validation and
10861 	 * superblock updates.
10862 	 */
10863 	if (frags == fs->fs_frag) {
10864 		fragno = fragstoblks(fs, cgbno);
10865 		ffs_setblock(fs, blksfree, fragno);
10866 		ffs_clusteracct(fs, cgp, fragno, 1);
10867 		cgp->cg_cs.cs_nbfree++;
10868 	} else {
10869 		cgbno += jnewblk->jn_oldfrags;
10870 		bbase = cgbno - fragnum(fs, cgbno);
10871 		/* Decrement the old frags.  */
10872 		blk = blkmap(fs, blksfree, bbase);
10873 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10874 		/* Deallocate the fragment */
10875 		for (i = 0; i < frags; i++)
10876 			setbit(blksfree, cgbno + i);
10877 		cgp->cg_cs.cs_nffree += frags;
10878 		/* Add back in counts associated with the new frags */
10879 		blk = blkmap(fs, blksfree, bbase);
10880 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10881 		/* If a complete block has been reassembled, account for it. */
10882 		fragno = fragstoblks(fs, bbase);
10883 		if (ffs_isblock(fs, blksfree, fragno)) {
10884 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10885 			ffs_clusteracct(fs, cgp, fragno, 1);
10886 			cgp->cg_cs.cs_nbfree++;
10887 		}
10888 	}
10889 	stat_jnewblk++;
10890 	jnewblk->jn_state &= ~ATTACHED;
10891 	jnewblk->jn_state |= UNDONE;
10892 
10893 	return (frags);
10894 }
10895 
10896 static void
10897 initiate_write_bmsafemap(bmsafemap, bp)
10898 	struct bmsafemap *bmsafemap;
10899 	struct buf *bp;			/* The cg block. */
10900 {
10901 	struct jaddref *jaddref;
10902 	struct jnewblk *jnewblk;
10903 	uint8_t *inosused;
10904 	uint8_t *blksfree;
10905 	struct cg *cgp;
10906 	struct fs *fs;
10907 	ino_t ino;
10908 
10909 	/*
10910 	 * If this is a background write, we did this at the time that
10911 	 * the copy was made, so do not need to do it again.
10912 	 */
10913 	if (bmsafemap->sm_state & IOSTARTED)
10914 		return;
10915 	bmsafemap->sm_state |= IOSTARTED;
10916 	/*
10917 	 * Clear any inode allocations which are pending journal writes.
10918 	 */
10919 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10920 		cgp = (struct cg *)bp->b_data;
10921 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10922 		inosused = cg_inosused(cgp);
10923 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10924 			ino = jaddref->ja_ino % fs->fs_ipg;
10925 			if (isset(inosused, ino)) {
10926 				if ((jaddref->ja_mode & IFMT) == IFDIR)
10927 					cgp->cg_cs.cs_ndir--;
10928 				cgp->cg_cs.cs_nifree++;
10929 				clrbit(inosused, ino);
10930 				jaddref->ja_state &= ~ATTACHED;
10931 				jaddref->ja_state |= UNDONE;
10932 				stat_jaddref++;
10933 			} else
10934 				panic("initiate_write_bmsafemap: inode %ju "
10935 				    "marked free", (uintmax_t)jaddref->ja_ino);
10936 		}
10937 	}
10938 	/*
10939 	 * Clear any block allocations which are pending journal writes.
10940 	 */
10941 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10942 		cgp = (struct cg *)bp->b_data;
10943 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10944 		blksfree = cg_blksfree(cgp);
10945 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10946 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10947 				continue;
10948 			panic("initiate_write_bmsafemap: block %jd "
10949 			    "marked free", jnewblk->jn_blkno);
10950 		}
10951 	}
10952 	/*
10953 	 * Move allocation lists to the written lists so they can be
10954 	 * cleared once the block write is complete.
10955 	 */
10956 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10957 	    inodedep, id_deps);
10958 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10959 	    newblk, nb_deps);
10960 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10961 	    wk_list);
10962 }
10963 
10964 /*
10965  * This routine is called during the completion interrupt
10966  * service routine for a disk write (from the procedure called
10967  * by the device driver to inform the filesystem caches of
10968  * a request completion).  It should be called early in this
10969  * procedure, before the block is made available to other
10970  * processes or other routines are called.
10971  *
10972  */
10973 static void
10974 softdep_disk_write_complete(bp)
10975 	struct buf *bp;		/* describes the completed disk write */
10976 {
10977 	struct worklist *wk;
10978 	struct worklist *owk;
10979 	struct ufsmount *ump;
10980 	struct workhead reattach;
10981 	struct freeblks *freeblks;
10982 	struct buf *sbp;
10983 
10984 	/*
10985 	 * If an error occurred while doing the write, then the data
10986 	 * has not hit the disk and the dependencies cannot be processed.
10987 	 * But we do have to go through and roll forward any dependencies
10988 	 * that were rolled back before the disk write.
10989 	 */
10990 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
10991 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
10992 			switch (wk->wk_type) {
10993 
10994 			case D_PAGEDEP:
10995 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
10996 				continue;
10997 
10998 			case D_INODEDEP:
10999 				handle_written_inodeblock(WK_INODEDEP(wk),
11000 				    bp, 0);
11001 				continue;
11002 
11003 			case D_BMSAFEMAP:
11004 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11005 				    bp, 0);
11006 				continue;
11007 
11008 			case D_INDIRDEP:
11009 				handle_written_indirdep(WK_INDIRDEP(wk),
11010 				    bp, &sbp, 0);
11011 				continue;
11012 			default:
11013 				/* nothing to roll forward */
11014 				continue;
11015 			}
11016 		}
11017 		return;
11018 	}
11019 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
11020 		return;
11021 	ump = VFSTOUFS(wk->wk_mp);
11022 	LIST_INIT(&reattach);
11023 	/*
11024 	 * This lock must not be released anywhere in this code segment.
11025 	 */
11026 	sbp = NULL;
11027 	owk = NULL;
11028 	ACQUIRE_LOCK(ump);
11029 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11030 		WORKLIST_REMOVE(wk);
11031 		atomic_add_long(&dep_write[wk->wk_type], 1);
11032 		if (wk == owk)
11033 			panic("duplicate worklist: %p\n", wk);
11034 		owk = wk;
11035 		switch (wk->wk_type) {
11036 
11037 		case D_PAGEDEP:
11038 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11039 			    WRITESUCCEEDED))
11040 				WORKLIST_INSERT(&reattach, wk);
11041 			continue;
11042 
11043 		case D_INODEDEP:
11044 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11045 			    WRITESUCCEEDED))
11046 				WORKLIST_INSERT(&reattach, wk);
11047 			continue;
11048 
11049 		case D_BMSAFEMAP:
11050 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11051 			    WRITESUCCEEDED))
11052 				WORKLIST_INSERT(&reattach, wk);
11053 			continue;
11054 
11055 		case D_MKDIR:
11056 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11057 			continue;
11058 
11059 		case D_ALLOCDIRECT:
11060 			wk->wk_state |= COMPLETE;
11061 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11062 			continue;
11063 
11064 		case D_ALLOCINDIR:
11065 			wk->wk_state |= COMPLETE;
11066 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11067 			continue;
11068 
11069 		case D_INDIRDEP:
11070 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11071 			    WRITESUCCEEDED))
11072 				WORKLIST_INSERT(&reattach, wk);
11073 			continue;
11074 
11075 		case D_FREEBLKS:
11076 			wk->wk_state |= COMPLETE;
11077 			freeblks = WK_FREEBLKS(wk);
11078 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11079 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11080 				add_to_worklist(wk, WK_NODELAY);
11081 			continue;
11082 
11083 		case D_FREEWORK:
11084 			handle_written_freework(WK_FREEWORK(wk));
11085 			break;
11086 
11087 		case D_JSEGDEP:
11088 			free_jsegdep(WK_JSEGDEP(wk));
11089 			continue;
11090 
11091 		case D_JSEG:
11092 			handle_written_jseg(WK_JSEG(wk), bp);
11093 			continue;
11094 
11095 		case D_SBDEP:
11096 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11097 				WORKLIST_INSERT(&reattach, wk);
11098 			continue;
11099 
11100 		case D_FREEDEP:
11101 			free_freedep(WK_FREEDEP(wk));
11102 			continue;
11103 
11104 		default:
11105 			panic("handle_disk_write_complete: Unknown type %s",
11106 			    TYPENAME(wk->wk_type));
11107 			/* NOTREACHED */
11108 		}
11109 	}
11110 	/*
11111 	 * Reattach any requests that must be redone.
11112 	 */
11113 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11114 		WORKLIST_REMOVE(wk);
11115 		WORKLIST_INSERT(&bp->b_dep, wk);
11116 	}
11117 	FREE_LOCK(ump);
11118 	if (sbp)
11119 		brelse(sbp);
11120 }
11121 
11122 /*
11123  * Called from within softdep_disk_write_complete above. Note that
11124  * this routine is always called from interrupt level with further
11125  * splbio interrupts blocked.
11126  */
11127 static void
11128 handle_allocdirect_partdone(adp, wkhd)
11129 	struct allocdirect *adp;	/* the completed allocdirect */
11130 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11131 {
11132 	struct allocdirectlst *listhead;
11133 	struct allocdirect *listadp;
11134 	struct inodedep *inodedep;
11135 	long bsize;
11136 
11137 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11138 		return;
11139 	/*
11140 	 * The on-disk inode cannot claim to be any larger than the last
11141 	 * fragment that has been written. Otherwise, the on-disk inode
11142 	 * might have fragments that were not the last block in the file
11143 	 * which would corrupt the filesystem. Thus, we cannot free any
11144 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11145 	 * these blocks must be rolled back to zero before writing the inode.
11146 	 * We check the currently active set of allocdirects in id_inoupdt
11147 	 * or id_extupdt as appropriate.
11148 	 */
11149 	inodedep = adp->ad_inodedep;
11150 	bsize = inodedep->id_fs->fs_bsize;
11151 	if (adp->ad_state & EXTDATA)
11152 		listhead = &inodedep->id_extupdt;
11153 	else
11154 		listhead = &inodedep->id_inoupdt;
11155 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11156 		/* found our block */
11157 		if (listadp == adp)
11158 			break;
11159 		/* continue if ad_oldlbn is not a fragment */
11160 		if (listadp->ad_oldsize == 0 ||
11161 		    listadp->ad_oldsize == bsize)
11162 			continue;
11163 		/* hit a fragment */
11164 		return;
11165 	}
11166 	/*
11167 	 * If we have reached the end of the current list without
11168 	 * finding the just finished dependency, then it must be
11169 	 * on the future dependency list. Future dependencies cannot
11170 	 * be freed until they are moved to the current list.
11171 	 */
11172 	if (listadp == NULL) {
11173 #ifdef DEBUG
11174 		if (adp->ad_state & EXTDATA)
11175 			listhead = &inodedep->id_newextupdt;
11176 		else
11177 			listhead = &inodedep->id_newinoupdt;
11178 		TAILQ_FOREACH(listadp, listhead, ad_next)
11179 			/* found our block */
11180 			if (listadp == adp)
11181 				break;
11182 		if (listadp == NULL)
11183 			panic("handle_allocdirect_partdone: lost dep");
11184 #endif /* DEBUG */
11185 		return;
11186 	}
11187 	/*
11188 	 * If we have found the just finished dependency, then queue
11189 	 * it along with anything that follows it that is complete.
11190 	 * Since the pointer has not yet been written in the inode
11191 	 * as the dependency prevents it, place the allocdirect on the
11192 	 * bufwait list where it will be freed once the pointer is
11193 	 * valid.
11194 	 */
11195 	if (wkhd == NULL)
11196 		wkhd = &inodedep->id_bufwait;
11197 	for (; adp; adp = listadp) {
11198 		listadp = TAILQ_NEXT(adp, ad_next);
11199 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11200 			return;
11201 		TAILQ_REMOVE(listhead, adp, ad_next);
11202 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11203 	}
11204 }
11205 
11206 /*
11207  * Called from within softdep_disk_write_complete above.  This routine
11208  * completes successfully written allocindirs.
11209  */
11210 static void
11211 handle_allocindir_partdone(aip)
11212 	struct allocindir *aip;		/* the completed allocindir */
11213 {
11214 	struct indirdep *indirdep;
11215 
11216 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11217 		return;
11218 	indirdep = aip->ai_indirdep;
11219 	LIST_REMOVE(aip, ai_next);
11220 	/*
11221 	 * Don't set a pointer while the buffer is undergoing IO or while
11222 	 * we have active truncations.
11223 	 */
11224 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11225 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11226 		return;
11227 	}
11228 	if (indirdep->ir_state & UFS1FMT)
11229 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11230 		    aip->ai_newblkno;
11231 	else
11232 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11233 		    aip->ai_newblkno;
11234 	/*
11235 	 * Await the pointer write before freeing the allocindir.
11236 	 */
11237 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11238 }
11239 
11240 /*
11241  * Release segments held on a jwork list.
11242  */
11243 static void
11244 handle_jwork(wkhd)
11245 	struct workhead *wkhd;
11246 {
11247 	struct worklist *wk;
11248 
11249 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11250 		WORKLIST_REMOVE(wk);
11251 		switch (wk->wk_type) {
11252 		case D_JSEGDEP:
11253 			free_jsegdep(WK_JSEGDEP(wk));
11254 			continue;
11255 		case D_FREEDEP:
11256 			free_freedep(WK_FREEDEP(wk));
11257 			continue;
11258 		case D_FREEFRAG:
11259 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11260 			WORKITEM_FREE(wk, D_FREEFRAG);
11261 			continue;
11262 		case D_FREEWORK:
11263 			handle_written_freework(WK_FREEWORK(wk));
11264 			continue;
11265 		default:
11266 			panic("handle_jwork: Unknown type %s\n",
11267 			    TYPENAME(wk->wk_type));
11268 		}
11269 	}
11270 }
11271 
11272 /*
11273  * Handle the bufwait list on an inode when it is safe to release items
11274  * held there.  This normally happens after an inode block is written but
11275  * may be delayed and handled later if there are pending journal items that
11276  * are not yet safe to be released.
11277  */
11278 static struct freefile *
11279 handle_bufwait(inodedep, refhd)
11280 	struct inodedep *inodedep;
11281 	struct workhead *refhd;
11282 {
11283 	struct jaddref *jaddref;
11284 	struct freefile *freefile;
11285 	struct worklist *wk;
11286 
11287 	freefile = NULL;
11288 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11289 		WORKLIST_REMOVE(wk);
11290 		switch (wk->wk_type) {
11291 		case D_FREEFILE:
11292 			/*
11293 			 * We defer adding freefile to the worklist
11294 			 * until all other additions have been made to
11295 			 * ensure that it will be done after all the
11296 			 * old blocks have been freed.
11297 			 */
11298 			if (freefile != NULL)
11299 				panic("handle_bufwait: freefile");
11300 			freefile = WK_FREEFILE(wk);
11301 			continue;
11302 
11303 		case D_MKDIR:
11304 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11305 			continue;
11306 
11307 		case D_DIRADD:
11308 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11309 			continue;
11310 
11311 		case D_FREEFRAG:
11312 			wk->wk_state |= COMPLETE;
11313 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11314 				add_to_worklist(wk, 0);
11315 			continue;
11316 
11317 		case D_DIRREM:
11318 			wk->wk_state |= COMPLETE;
11319 			add_to_worklist(wk, 0);
11320 			continue;
11321 
11322 		case D_ALLOCDIRECT:
11323 		case D_ALLOCINDIR:
11324 			free_newblk(WK_NEWBLK(wk));
11325 			continue;
11326 
11327 		case D_JNEWBLK:
11328 			wk->wk_state |= COMPLETE;
11329 			free_jnewblk(WK_JNEWBLK(wk));
11330 			continue;
11331 
11332 		/*
11333 		 * Save freed journal segments and add references on
11334 		 * the supplied list which will delay their release
11335 		 * until the cg bitmap is cleared on disk.
11336 		 */
11337 		case D_JSEGDEP:
11338 			if (refhd == NULL)
11339 				free_jsegdep(WK_JSEGDEP(wk));
11340 			else
11341 				WORKLIST_INSERT(refhd, wk);
11342 			continue;
11343 
11344 		case D_JADDREF:
11345 			jaddref = WK_JADDREF(wk);
11346 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11347 			    if_deps);
11348 			/*
11349 			 * Transfer any jaddrefs to the list to be freed with
11350 			 * the bitmap if we're handling a removed file.
11351 			 */
11352 			if (refhd == NULL) {
11353 				wk->wk_state |= COMPLETE;
11354 				free_jaddref(jaddref);
11355 			} else
11356 				WORKLIST_INSERT(refhd, wk);
11357 			continue;
11358 
11359 		default:
11360 			panic("handle_bufwait: Unknown type %p(%s)",
11361 			    wk, TYPENAME(wk->wk_type));
11362 			/* NOTREACHED */
11363 		}
11364 	}
11365 	return (freefile);
11366 }
11367 /*
11368  * Called from within softdep_disk_write_complete above to restore
11369  * in-memory inode block contents to their most up-to-date state. Note
11370  * that this routine is always called from interrupt level with further
11371  * interrupts from this device blocked.
11372  *
11373  * If the write did not succeed, we will do all the roll-forward
11374  * operations, but we will not take the actions that will allow its
11375  * dependencies to be processed.
11376  */
11377 static int
11378 handle_written_inodeblock(inodedep, bp, flags)
11379 	struct inodedep *inodedep;
11380 	struct buf *bp;		/* buffer containing the inode block */
11381 	int flags;
11382 {
11383 	struct freefile *freefile;
11384 	struct allocdirect *adp, *nextadp;
11385 	struct ufs1_dinode *dp1 = NULL;
11386 	struct ufs2_dinode *dp2 = NULL;
11387 	struct workhead wkhd;
11388 	int hadchanges, fstype;
11389 	ino_t freelink;
11390 
11391 	LIST_INIT(&wkhd);
11392 	hadchanges = 0;
11393 	freefile = NULL;
11394 	if ((inodedep->id_state & IOSTARTED) == 0)
11395 		panic("handle_written_inodeblock: not started");
11396 	inodedep->id_state &= ~IOSTARTED;
11397 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11398 		fstype = UFS1;
11399 		dp1 = (struct ufs1_dinode *)bp->b_data +
11400 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11401 		freelink = dp1->di_freelink;
11402 	} else {
11403 		fstype = UFS2;
11404 		dp2 = (struct ufs2_dinode *)bp->b_data +
11405 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11406 		freelink = dp2->di_freelink;
11407 	}
11408 	/*
11409 	 * Leave this inodeblock dirty until it's in the list.
11410 	 */
11411 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11412 	    (flags & WRITESUCCEEDED)) {
11413 		struct inodedep *inon;
11414 
11415 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11416 		if ((inon == NULL && freelink == 0) ||
11417 		    (inon && inon->id_ino == freelink)) {
11418 			if (inon)
11419 				inon->id_state |= UNLINKPREV;
11420 			inodedep->id_state |= UNLINKNEXT;
11421 		}
11422 		hadchanges = 1;
11423 	}
11424 	/*
11425 	 * If we had to rollback the inode allocation because of
11426 	 * bitmaps being incomplete, then simply restore it.
11427 	 * Keep the block dirty so that it will not be reclaimed until
11428 	 * all associated dependencies have been cleared and the
11429 	 * corresponding updates written to disk.
11430 	 */
11431 	if (inodedep->id_savedino1 != NULL) {
11432 		hadchanges = 1;
11433 		if (fstype == UFS1)
11434 			*dp1 = *inodedep->id_savedino1;
11435 		else
11436 			*dp2 = *inodedep->id_savedino2;
11437 		free(inodedep->id_savedino1, M_SAVEDINO);
11438 		inodedep->id_savedino1 = NULL;
11439 		if ((bp->b_flags & B_DELWRI) == 0)
11440 			stat_inode_bitmap++;
11441 		bdirty(bp);
11442 		/*
11443 		 * If the inode is clear here and GOINGAWAY it will never
11444 		 * be written.  Process the bufwait and clear any pending
11445 		 * work which may include the freefile.
11446 		 */
11447 		if (inodedep->id_state & GOINGAWAY)
11448 			goto bufwait;
11449 		return (1);
11450 	}
11451 	if (flags & WRITESUCCEEDED)
11452 		inodedep->id_state |= COMPLETE;
11453 	/*
11454 	 * Roll forward anything that had to be rolled back before
11455 	 * the inode could be updated.
11456 	 */
11457 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11458 		nextadp = TAILQ_NEXT(adp, ad_next);
11459 		if (adp->ad_state & ATTACHED)
11460 			panic("handle_written_inodeblock: new entry");
11461 		if (fstype == UFS1) {
11462 			if (adp->ad_offset < UFS_NDADDR) {
11463 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11464 					panic("%s %s #%jd mismatch %d != %jd",
11465 					    "handle_written_inodeblock:",
11466 					    "direct pointer",
11467 					    (intmax_t)adp->ad_offset,
11468 					    dp1->di_db[adp->ad_offset],
11469 					    (intmax_t)adp->ad_oldblkno);
11470 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11471 			} else {
11472 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11473 				    0)
11474 					panic("%s: %s #%jd allocated as %d",
11475 					    "handle_written_inodeblock",
11476 					    "indirect pointer",
11477 					    (intmax_t)adp->ad_offset -
11478 					    UFS_NDADDR,
11479 					    dp1->di_ib[adp->ad_offset -
11480 					    UFS_NDADDR]);
11481 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11482 				    adp->ad_newblkno;
11483 			}
11484 		} else {
11485 			if (adp->ad_offset < UFS_NDADDR) {
11486 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11487 					panic("%s: %s #%jd %s %jd != %jd",
11488 					    "handle_written_inodeblock",
11489 					    "direct pointer",
11490 					    (intmax_t)adp->ad_offset, "mismatch",
11491 					    (intmax_t)dp2->di_db[adp->ad_offset],
11492 					    (intmax_t)adp->ad_oldblkno);
11493 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11494 			} else {
11495 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11496 				    0)
11497 					panic("%s: %s #%jd allocated as %jd",
11498 					    "handle_written_inodeblock",
11499 					    "indirect pointer",
11500 					    (intmax_t)adp->ad_offset -
11501 					    UFS_NDADDR,
11502 					    (intmax_t)
11503 					    dp2->di_ib[adp->ad_offset -
11504 					    UFS_NDADDR]);
11505 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11506 				    adp->ad_newblkno;
11507 			}
11508 		}
11509 		adp->ad_state &= ~UNDONE;
11510 		adp->ad_state |= ATTACHED;
11511 		hadchanges = 1;
11512 	}
11513 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11514 		nextadp = TAILQ_NEXT(adp, ad_next);
11515 		if (adp->ad_state & ATTACHED)
11516 			panic("handle_written_inodeblock: new entry");
11517 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11518 			panic("%s: direct pointers #%jd %s %jd != %jd",
11519 			    "handle_written_inodeblock",
11520 			    (intmax_t)adp->ad_offset, "mismatch",
11521 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11522 			    (intmax_t)adp->ad_oldblkno);
11523 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11524 		adp->ad_state &= ~UNDONE;
11525 		adp->ad_state |= ATTACHED;
11526 		hadchanges = 1;
11527 	}
11528 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11529 		stat_direct_blk_ptrs++;
11530 	/*
11531 	 * Reset the file size to its most up-to-date value.
11532 	 */
11533 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11534 		panic("handle_written_inodeblock: bad size");
11535 	if (inodedep->id_savednlink > LINK_MAX)
11536 		panic("handle_written_inodeblock: Invalid link count "
11537 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11538 		    inodedep);
11539 	if (fstype == UFS1) {
11540 		if (dp1->di_nlink != inodedep->id_savednlink) {
11541 			dp1->di_nlink = inodedep->id_savednlink;
11542 			hadchanges = 1;
11543 		}
11544 		if (dp1->di_size != inodedep->id_savedsize) {
11545 			dp1->di_size = inodedep->id_savedsize;
11546 			hadchanges = 1;
11547 		}
11548 	} else {
11549 		if (dp2->di_nlink != inodedep->id_savednlink) {
11550 			dp2->di_nlink = inodedep->id_savednlink;
11551 			hadchanges = 1;
11552 		}
11553 		if (dp2->di_size != inodedep->id_savedsize) {
11554 			dp2->di_size = inodedep->id_savedsize;
11555 			hadchanges = 1;
11556 		}
11557 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11558 			dp2->di_extsize = inodedep->id_savedextsize;
11559 			hadchanges = 1;
11560 		}
11561 	}
11562 	inodedep->id_savedsize = -1;
11563 	inodedep->id_savedextsize = -1;
11564 	inodedep->id_savednlink = -1;
11565 	/*
11566 	 * If there were any rollbacks in the inode block, then it must be
11567 	 * marked dirty so that its will eventually get written back in
11568 	 * its correct form.
11569 	 */
11570 	if (hadchanges)
11571 		bdirty(bp);
11572 bufwait:
11573 	/*
11574 	 * If the write did not succeed, we have done all the roll-forward
11575 	 * operations, but we cannot take the actions that will allow its
11576 	 * dependencies to be processed.
11577 	 */
11578 	if ((flags & WRITESUCCEEDED) == 0)
11579 		return (hadchanges);
11580 	/*
11581 	 * Process any allocdirects that completed during the update.
11582 	 */
11583 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11584 		handle_allocdirect_partdone(adp, &wkhd);
11585 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11586 		handle_allocdirect_partdone(adp, &wkhd);
11587 	/*
11588 	 * Process deallocations that were held pending until the
11589 	 * inode had been written to disk. Freeing of the inode
11590 	 * is delayed until after all blocks have been freed to
11591 	 * avoid creation of new <vfsid, inum, lbn> triples
11592 	 * before the old ones have been deleted.  Completely
11593 	 * unlinked inodes are not processed until the unlinked
11594 	 * inode list is written or the last reference is removed.
11595 	 */
11596 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11597 		freefile = handle_bufwait(inodedep, NULL);
11598 		if (freefile && !LIST_EMPTY(&wkhd)) {
11599 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11600 			freefile = NULL;
11601 		}
11602 	}
11603 	/*
11604 	 * Move rolled forward dependency completions to the bufwait list
11605 	 * now that those that were already written have been processed.
11606 	 */
11607 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11608 		panic("handle_written_inodeblock: bufwait but no changes");
11609 	jwork_move(&inodedep->id_bufwait, &wkhd);
11610 
11611 	if (freefile != NULL) {
11612 		/*
11613 		 * If the inode is goingaway it was never written.  Fake up
11614 		 * the state here so free_inodedep() can succeed.
11615 		 */
11616 		if (inodedep->id_state & GOINGAWAY)
11617 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11618 		if (free_inodedep(inodedep) == 0)
11619 			panic("handle_written_inodeblock: live inodedep %p",
11620 			    inodedep);
11621 		add_to_worklist(&freefile->fx_list, 0);
11622 		return (0);
11623 	}
11624 
11625 	/*
11626 	 * If no outstanding dependencies, free it.
11627 	 */
11628 	if (free_inodedep(inodedep) ||
11629 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11630 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11631 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11632 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11633 		return (0);
11634 	return (hadchanges);
11635 }
11636 
11637 /*
11638  * Perform needed roll-forwards and kick off any dependencies that
11639  * can now be processed.
11640  *
11641  * If the write did not succeed, we will do all the roll-forward
11642  * operations, but we will not take the actions that will allow its
11643  * dependencies to be processed.
11644  */
11645 static int
11646 handle_written_indirdep(indirdep, bp, bpp, flags)
11647 	struct indirdep *indirdep;
11648 	struct buf *bp;
11649 	struct buf **bpp;
11650 	int flags;
11651 {
11652 	struct allocindir *aip;
11653 	struct buf *sbp;
11654 	int chgs;
11655 
11656 	if (indirdep->ir_state & GOINGAWAY)
11657 		panic("handle_written_indirdep: indirdep gone");
11658 	if ((indirdep->ir_state & IOSTARTED) == 0)
11659 		panic("handle_written_indirdep: IO not started");
11660 	chgs = 0;
11661 	/*
11662 	 * If there were rollbacks revert them here.
11663 	 */
11664 	if (indirdep->ir_saveddata) {
11665 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11666 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11667 			free(indirdep->ir_saveddata, M_INDIRDEP);
11668 			indirdep->ir_saveddata = NULL;
11669 		}
11670 		chgs = 1;
11671 	}
11672 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11673 	indirdep->ir_state |= ATTACHED;
11674 	/*
11675 	 * If the write did not succeed, we have done all the roll-forward
11676 	 * operations, but we cannot take the actions that will allow its
11677 	 * dependencies to be processed.
11678 	 */
11679 	if ((flags & WRITESUCCEEDED) == 0) {
11680 		stat_indir_blk_ptrs++;
11681 		bdirty(bp);
11682 		return (1);
11683 	}
11684 	/*
11685 	 * Move allocindirs with written pointers to the completehd if
11686 	 * the indirdep's pointer is not yet written.  Otherwise
11687 	 * free them here.
11688 	 */
11689 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11690 		LIST_REMOVE(aip, ai_next);
11691 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11692 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11693 			    ai_next);
11694 			newblk_freefrag(&aip->ai_block);
11695 			continue;
11696 		}
11697 		free_newblk(&aip->ai_block);
11698 	}
11699 	/*
11700 	 * Move allocindirs that have finished dependency processing from
11701 	 * the done list to the write list after updating the pointers.
11702 	 */
11703 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11704 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11705 			handle_allocindir_partdone(aip);
11706 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11707 				panic("disk_write_complete: not gone");
11708 			chgs = 1;
11709 		}
11710 	}
11711 	/*
11712 	 * Preserve the indirdep if there were any changes or if it is not
11713 	 * yet valid on disk.
11714 	 */
11715 	if (chgs) {
11716 		stat_indir_blk_ptrs++;
11717 		bdirty(bp);
11718 		return (1);
11719 	}
11720 	/*
11721 	 * If there were no changes we can discard the savedbp and detach
11722 	 * ourselves from the buf.  We are only carrying completed pointers
11723 	 * in this case.
11724 	 */
11725 	sbp = indirdep->ir_savebp;
11726 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11727 	indirdep->ir_savebp = NULL;
11728 	indirdep->ir_bp = NULL;
11729 	if (*bpp != NULL)
11730 		panic("handle_written_indirdep: bp already exists.");
11731 	*bpp = sbp;
11732 	/*
11733 	 * The indirdep may not be freed until its parent points at it.
11734 	 */
11735 	if (indirdep->ir_state & DEPCOMPLETE)
11736 		free_indirdep(indirdep);
11737 
11738 	return (0);
11739 }
11740 
11741 /*
11742  * Process a diradd entry after its dependent inode has been written.
11743  * This routine must be called with splbio interrupts blocked.
11744  */
11745 static void
11746 diradd_inode_written(dap, inodedep)
11747 	struct diradd *dap;
11748 	struct inodedep *inodedep;
11749 {
11750 
11751 	dap->da_state |= COMPLETE;
11752 	complete_diradd(dap);
11753 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11754 }
11755 
11756 /*
11757  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11758  * be called with the per-filesystem lock and the buf lock on the cg held.
11759  */
11760 static int
11761 bmsafemap_backgroundwrite(bmsafemap, bp)
11762 	struct bmsafemap *bmsafemap;
11763 	struct buf *bp;
11764 {
11765 	int dirty;
11766 
11767 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11768 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11769 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11770 	/*
11771 	 * If we're initiating a background write we need to process the
11772 	 * rollbacks as they exist now, not as they exist when IO starts.
11773 	 * No other consumers will look at the contents of the shadowed
11774 	 * buf so this is safe to do here.
11775 	 */
11776 	if (bp->b_xflags & BX_BKGRDMARKER)
11777 		initiate_write_bmsafemap(bmsafemap, bp);
11778 
11779 	return (dirty);
11780 }
11781 
11782 /*
11783  * Re-apply an allocation when a cg write is complete.
11784  */
11785 static int
11786 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11787 	struct jnewblk *jnewblk;
11788 	struct fs *fs;
11789 	struct cg *cgp;
11790 	uint8_t *blksfree;
11791 {
11792 	ufs1_daddr_t fragno;
11793 	ufs2_daddr_t blkno;
11794 	long cgbno, bbase;
11795 	int frags, blk;
11796 	int i;
11797 
11798 	frags = 0;
11799 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11800 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11801 		if (isclr(blksfree, cgbno + i))
11802 			panic("jnewblk_rollforward: re-allocated fragment");
11803 		frags++;
11804 	}
11805 	if (frags == fs->fs_frag) {
11806 		blkno = fragstoblks(fs, cgbno);
11807 		ffs_clrblock(fs, blksfree, (long)blkno);
11808 		ffs_clusteracct(fs, cgp, blkno, -1);
11809 		cgp->cg_cs.cs_nbfree--;
11810 	} else {
11811 		bbase = cgbno - fragnum(fs, cgbno);
11812 		cgbno += jnewblk->jn_oldfrags;
11813                 /* If a complete block had been reassembled, account for it. */
11814 		fragno = fragstoblks(fs, bbase);
11815 		if (ffs_isblock(fs, blksfree, fragno)) {
11816 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11817 			ffs_clusteracct(fs, cgp, fragno, -1);
11818 			cgp->cg_cs.cs_nbfree--;
11819 		}
11820 		/* Decrement the old frags.  */
11821 		blk = blkmap(fs, blksfree, bbase);
11822 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11823 		/* Allocate the fragment */
11824 		for (i = 0; i < frags; i++)
11825 			clrbit(blksfree, cgbno + i);
11826 		cgp->cg_cs.cs_nffree -= frags;
11827 		/* Add back in counts associated with the new frags */
11828 		blk = blkmap(fs, blksfree, bbase);
11829 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11830 	}
11831 	return (frags);
11832 }
11833 
11834 /*
11835  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11836  * changes if it's not a background write.  Set all written dependencies
11837  * to DEPCOMPLETE and free the structure if possible.
11838  *
11839  * If the write did not succeed, we will do all the roll-forward
11840  * operations, but we will not take the actions that will allow its
11841  * dependencies to be processed.
11842  */
11843 static int
11844 handle_written_bmsafemap(bmsafemap, bp, flags)
11845 	struct bmsafemap *bmsafemap;
11846 	struct buf *bp;
11847 	int flags;
11848 {
11849 	struct newblk *newblk;
11850 	struct inodedep *inodedep;
11851 	struct jaddref *jaddref, *jatmp;
11852 	struct jnewblk *jnewblk, *jntmp;
11853 	struct ufsmount *ump;
11854 	uint8_t *inosused;
11855 	uint8_t *blksfree;
11856 	struct cg *cgp;
11857 	struct fs *fs;
11858 	ino_t ino;
11859 	int foreground;
11860 	int chgs;
11861 
11862 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11863 		panic("handle_written_bmsafemap: Not started\n");
11864 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11865 	chgs = 0;
11866 	bmsafemap->sm_state &= ~IOSTARTED;
11867 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11868 	/*
11869 	 * If write was successful, release journal work that was waiting
11870 	 * on the write. Otherwise move the work back.
11871 	 */
11872 	if (flags & WRITESUCCEEDED)
11873 		handle_jwork(&bmsafemap->sm_freewr);
11874 	else
11875 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11876 		    worklist, wk_list);
11877 
11878 	/*
11879 	 * Restore unwritten inode allocation pending jaddref writes.
11880 	 */
11881 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11882 		cgp = (struct cg *)bp->b_data;
11883 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11884 		inosused = cg_inosused(cgp);
11885 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11886 		    ja_bmdeps, jatmp) {
11887 			if ((jaddref->ja_state & UNDONE) == 0)
11888 				continue;
11889 			ino = jaddref->ja_ino % fs->fs_ipg;
11890 			if (isset(inosused, ino))
11891 				panic("handle_written_bmsafemap: "
11892 				    "re-allocated inode");
11893 			/* Do the roll-forward only if it's a real copy. */
11894 			if (foreground) {
11895 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11896 					cgp->cg_cs.cs_ndir++;
11897 				cgp->cg_cs.cs_nifree--;
11898 				setbit(inosused, ino);
11899 				chgs = 1;
11900 			}
11901 			jaddref->ja_state &= ~UNDONE;
11902 			jaddref->ja_state |= ATTACHED;
11903 			free_jaddref(jaddref);
11904 		}
11905 	}
11906 	/*
11907 	 * Restore any block allocations which are pending journal writes.
11908 	 */
11909 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11910 		cgp = (struct cg *)bp->b_data;
11911 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11912 		blksfree = cg_blksfree(cgp);
11913 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11914 		    jntmp) {
11915 			if ((jnewblk->jn_state & UNDONE) == 0)
11916 				continue;
11917 			/* Do the roll-forward only if it's a real copy. */
11918 			if (foreground &&
11919 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11920 				chgs = 1;
11921 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11922 			jnewblk->jn_state |= ATTACHED;
11923 			free_jnewblk(jnewblk);
11924 		}
11925 	}
11926 	/*
11927 	 * If the write did not succeed, we have done all the roll-forward
11928 	 * operations, but we cannot take the actions that will allow its
11929 	 * dependencies to be processed.
11930 	 */
11931 	if ((flags & WRITESUCCEEDED) == 0) {
11932 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11933 		    newblk, nb_deps);
11934 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11935 		    worklist, wk_list);
11936 		if (foreground)
11937 			bdirty(bp);
11938 		return (1);
11939 	}
11940 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11941 		newblk->nb_state |= DEPCOMPLETE;
11942 		newblk->nb_state &= ~ONDEPLIST;
11943 		newblk->nb_bmsafemap = NULL;
11944 		LIST_REMOVE(newblk, nb_deps);
11945 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11946 			handle_allocdirect_partdone(
11947 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11948 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11949 			handle_allocindir_partdone(
11950 			    WK_ALLOCINDIR(&newblk->nb_list));
11951 		else if (newblk->nb_list.wk_type != D_NEWBLK)
11952 			panic("handle_written_bmsafemap: Unexpected type: %s",
11953 			    TYPENAME(newblk->nb_list.wk_type));
11954 	}
11955 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11956 		inodedep->id_state |= DEPCOMPLETE;
11957 		inodedep->id_state &= ~ONDEPLIST;
11958 		LIST_REMOVE(inodedep, id_deps);
11959 		inodedep->id_bmsafemap = NULL;
11960 	}
11961 	LIST_REMOVE(bmsafemap, sm_next);
11962 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11963 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11964 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11965 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11966 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
11967 		LIST_REMOVE(bmsafemap, sm_hash);
11968 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11969 		return (0);
11970 	}
11971 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11972 	if (foreground)
11973 		bdirty(bp);
11974 	return (1);
11975 }
11976 
11977 /*
11978  * Try to free a mkdir dependency.
11979  */
11980 static void
11981 complete_mkdir(mkdir)
11982 	struct mkdir *mkdir;
11983 {
11984 	struct diradd *dap;
11985 
11986 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11987 		return;
11988 	LIST_REMOVE(mkdir, md_mkdirs);
11989 	dap = mkdir->md_diradd;
11990 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11991 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11992 		dap->da_state |= DEPCOMPLETE;
11993 		complete_diradd(dap);
11994 	}
11995 	WORKITEM_FREE(mkdir, D_MKDIR);
11996 }
11997 
11998 /*
11999  * Handle the completion of a mkdir dependency.
12000  */
12001 static void
12002 handle_written_mkdir(mkdir, type)
12003 	struct mkdir *mkdir;
12004 	int type;
12005 {
12006 
12007 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12008 		panic("handle_written_mkdir: bad type");
12009 	mkdir->md_state |= COMPLETE;
12010 	complete_mkdir(mkdir);
12011 }
12012 
12013 static int
12014 free_pagedep(pagedep)
12015 	struct pagedep *pagedep;
12016 {
12017 	int i;
12018 
12019 	if (pagedep->pd_state & NEWBLOCK)
12020 		return (0);
12021 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12022 		return (0);
12023 	for (i = 0; i < DAHASHSZ; i++)
12024 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12025 			return (0);
12026 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12027 		return (0);
12028 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12029 		return (0);
12030 	if (pagedep->pd_state & ONWORKLIST)
12031 		WORKLIST_REMOVE(&pagedep->pd_list);
12032 	LIST_REMOVE(pagedep, pd_hash);
12033 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12034 
12035 	return (1);
12036 }
12037 
12038 /*
12039  * Called from within softdep_disk_write_complete above.
12040  * A write operation was just completed. Removed inodes can
12041  * now be freed and associated block pointers may be committed.
12042  * Note that this routine is always called from interrupt level
12043  * with further interrupts from this device blocked.
12044  *
12045  * If the write did not succeed, we will do all the roll-forward
12046  * operations, but we will not take the actions that will allow its
12047  * dependencies to be processed.
12048  */
12049 static int
12050 handle_written_filepage(pagedep, bp, flags)
12051 	struct pagedep *pagedep;
12052 	struct buf *bp;		/* buffer containing the written page */
12053 	int flags;
12054 {
12055 	struct dirrem *dirrem;
12056 	struct diradd *dap, *nextdap;
12057 	struct direct *ep;
12058 	int i, chgs;
12059 
12060 	if ((pagedep->pd_state & IOSTARTED) == 0)
12061 		panic("handle_written_filepage: not started");
12062 	pagedep->pd_state &= ~IOSTARTED;
12063 	if ((flags & WRITESUCCEEDED) == 0)
12064 		goto rollforward;
12065 	/*
12066 	 * Process any directory removals that have been committed.
12067 	 */
12068 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12069 		LIST_REMOVE(dirrem, dm_next);
12070 		dirrem->dm_state |= COMPLETE;
12071 		dirrem->dm_dirinum = pagedep->pd_ino;
12072 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12073 		    ("handle_written_filepage: Journal entries not written."));
12074 		add_to_worklist(&dirrem->dm_list, 0);
12075 	}
12076 	/*
12077 	 * Free any directory additions that have been committed.
12078 	 * If it is a newly allocated block, we have to wait until
12079 	 * the on-disk directory inode claims the new block.
12080 	 */
12081 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12082 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12083 			free_diradd(dap, NULL);
12084 rollforward:
12085 	/*
12086 	 * Uncommitted directory entries must be restored.
12087 	 */
12088 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12089 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12090 		     dap = nextdap) {
12091 			nextdap = LIST_NEXT(dap, da_pdlist);
12092 			if (dap->da_state & ATTACHED)
12093 				panic("handle_written_filepage: attached");
12094 			ep = (struct direct *)
12095 			    ((char *)bp->b_data + dap->da_offset);
12096 			ep->d_ino = dap->da_newinum;
12097 			dap->da_state &= ~UNDONE;
12098 			dap->da_state |= ATTACHED;
12099 			chgs = 1;
12100 			/*
12101 			 * If the inode referenced by the directory has
12102 			 * been written out, then the dependency can be
12103 			 * moved to the pending list.
12104 			 */
12105 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12106 				LIST_REMOVE(dap, da_pdlist);
12107 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12108 				    da_pdlist);
12109 			}
12110 		}
12111 	}
12112 	/*
12113 	 * If there were any rollbacks in the directory, then it must be
12114 	 * marked dirty so that its will eventually get written back in
12115 	 * its correct form.
12116 	 */
12117 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12118 		if ((bp->b_flags & B_DELWRI) == 0)
12119 			stat_dir_entry++;
12120 		bdirty(bp);
12121 		return (1);
12122 	}
12123 	/*
12124 	 * If we are not waiting for a new directory block to be
12125 	 * claimed by its inode, then the pagedep will be freed.
12126 	 * Otherwise it will remain to track any new entries on
12127 	 * the page in case they are fsync'ed.
12128 	 */
12129 	free_pagedep(pagedep);
12130 	return (0);
12131 }
12132 
12133 /*
12134  * Writing back in-core inode structures.
12135  *
12136  * The filesystem only accesses an inode's contents when it occupies an
12137  * "in-core" inode structure.  These "in-core" structures are separate from
12138  * the page frames used to cache inode blocks.  Only the latter are
12139  * transferred to/from the disk.  So, when the updated contents of the
12140  * "in-core" inode structure are copied to the corresponding in-memory inode
12141  * block, the dependencies are also transferred.  The following procedure is
12142  * called when copying a dirty "in-core" inode to a cached inode block.
12143  */
12144 
12145 /*
12146  * Called when an inode is loaded from disk. If the effective link count
12147  * differed from the actual link count when it was last flushed, then we
12148  * need to ensure that the correct effective link count is put back.
12149  */
12150 void
12151 softdep_load_inodeblock(ip)
12152 	struct inode *ip;	/* the "in_core" copy of the inode */
12153 {
12154 	struct inodedep *inodedep;
12155 	struct ufsmount *ump;
12156 
12157 	ump = ITOUMP(ip);
12158 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12159 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12160 	/*
12161 	 * Check for alternate nlink count.
12162 	 */
12163 	ip->i_effnlink = ip->i_nlink;
12164 	ACQUIRE_LOCK(ump);
12165 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12166 		FREE_LOCK(ump);
12167 		return;
12168 	}
12169 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12170 	FREE_LOCK(ump);
12171 }
12172 
12173 /*
12174  * This routine is called just before the "in-core" inode
12175  * information is to be copied to the in-memory inode block.
12176  * Recall that an inode block contains several inodes. If
12177  * the force flag is set, then the dependencies will be
12178  * cleared so that the update can always be made. Note that
12179  * the buffer is locked when this routine is called, so we
12180  * will never be in the middle of writing the inode block
12181  * to disk.
12182  */
12183 void
12184 softdep_update_inodeblock(ip, bp, waitfor)
12185 	struct inode *ip;	/* the "in_core" copy of the inode */
12186 	struct buf *bp;		/* the buffer containing the inode block */
12187 	int waitfor;		/* nonzero => update must be allowed */
12188 {
12189 	struct inodedep *inodedep;
12190 	struct inoref *inoref;
12191 	struct ufsmount *ump;
12192 	struct worklist *wk;
12193 	struct mount *mp;
12194 	struct buf *ibp;
12195 	struct fs *fs;
12196 	int error;
12197 
12198 	ump = ITOUMP(ip);
12199 	mp = UFSTOVFS(ump);
12200 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12201 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12202 	fs = ump->um_fs;
12203 	/*
12204 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12205 	 * does not have access to the in-core ip so must write directly into
12206 	 * the inode block buffer when setting freelink.
12207 	 */
12208 	if (fs->fs_magic == FS_UFS1_MAGIC)
12209 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12210 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12211 	else
12212 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12213 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12214 	/*
12215 	 * If the effective link count is not equal to the actual link
12216 	 * count, then we must track the difference in an inodedep while
12217 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12218 	 * if there is no existing inodedep, then there are no dependencies
12219 	 * to track.
12220 	 */
12221 	ACQUIRE_LOCK(ump);
12222 again:
12223 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12224 		FREE_LOCK(ump);
12225 		if (ip->i_effnlink != ip->i_nlink)
12226 			panic("softdep_update_inodeblock: bad link count");
12227 		return;
12228 	}
12229 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12230 		panic("softdep_update_inodeblock: bad delta");
12231 	/*
12232 	 * If we're flushing all dependencies we must also move any waiting
12233 	 * for journal writes onto the bufwait list prior to I/O.
12234 	 */
12235 	if (waitfor) {
12236 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12237 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12238 			    == DEPCOMPLETE) {
12239 				jwait(&inoref->if_list, MNT_WAIT);
12240 				goto again;
12241 			}
12242 		}
12243 	}
12244 	/*
12245 	 * Changes have been initiated. Anything depending on these
12246 	 * changes cannot occur until this inode has been written.
12247 	 */
12248 	inodedep->id_state &= ~COMPLETE;
12249 	if ((inodedep->id_state & ONWORKLIST) == 0)
12250 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12251 	/*
12252 	 * Any new dependencies associated with the incore inode must
12253 	 * now be moved to the list associated with the buffer holding
12254 	 * the in-memory copy of the inode. Once merged process any
12255 	 * allocdirects that are completed by the merger.
12256 	 */
12257 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12258 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12259 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12260 		    NULL);
12261 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12262 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12263 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12264 		    NULL);
12265 	/*
12266 	 * Now that the inode has been pushed into the buffer, the
12267 	 * operations dependent on the inode being written to disk
12268 	 * can be moved to the id_bufwait so that they will be
12269 	 * processed when the buffer I/O completes.
12270 	 */
12271 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12272 		WORKLIST_REMOVE(wk);
12273 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12274 	}
12275 	/*
12276 	 * Newly allocated inodes cannot be written until the bitmap
12277 	 * that allocates them have been written (indicated by
12278 	 * DEPCOMPLETE being set in id_state). If we are doing a
12279 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12280 	 * to be written so that the update can be done.
12281 	 */
12282 	if (waitfor == 0) {
12283 		FREE_LOCK(ump);
12284 		return;
12285 	}
12286 retry:
12287 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12288 		FREE_LOCK(ump);
12289 		return;
12290 	}
12291 	ibp = inodedep->id_bmsafemap->sm_buf;
12292 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12293 	if (ibp == NULL) {
12294 		/*
12295 		 * If ibp came back as NULL, the dependency could have been
12296 		 * freed while we slept.  Look it up again, and check to see
12297 		 * that it has completed.
12298 		 */
12299 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12300 			goto retry;
12301 		FREE_LOCK(ump);
12302 		return;
12303 	}
12304 	FREE_LOCK(ump);
12305 	if ((error = bwrite(ibp)) != 0)
12306 		softdep_error("softdep_update_inodeblock: bwrite", error);
12307 }
12308 
12309 /*
12310  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12311  * old inode dependency list (such as id_inoupdt). This routine must be
12312  * called with splbio interrupts blocked.
12313  */
12314 static void
12315 merge_inode_lists(newlisthead, oldlisthead)
12316 	struct allocdirectlst *newlisthead;
12317 	struct allocdirectlst *oldlisthead;
12318 {
12319 	struct allocdirect *listadp, *newadp;
12320 
12321 	newadp = TAILQ_FIRST(newlisthead);
12322 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12323 		if (listadp->ad_offset < newadp->ad_offset) {
12324 			listadp = TAILQ_NEXT(listadp, ad_next);
12325 			continue;
12326 		}
12327 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12328 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12329 		if (listadp->ad_offset == newadp->ad_offset) {
12330 			allocdirect_merge(oldlisthead, newadp,
12331 			    listadp);
12332 			listadp = newadp;
12333 		}
12334 		newadp = TAILQ_FIRST(newlisthead);
12335 	}
12336 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12337 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12338 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12339 	}
12340 }
12341 
12342 /*
12343  * If we are doing an fsync, then we must ensure that any directory
12344  * entries for the inode have been written after the inode gets to disk.
12345  */
12346 int
12347 softdep_fsync(vp)
12348 	struct vnode *vp;	/* the "in_core" copy of the inode */
12349 {
12350 	struct inodedep *inodedep;
12351 	struct pagedep *pagedep;
12352 	struct inoref *inoref;
12353 	struct ufsmount *ump;
12354 	struct worklist *wk;
12355 	struct diradd *dap;
12356 	struct mount *mp;
12357 	struct vnode *pvp;
12358 	struct inode *ip;
12359 	struct buf *bp;
12360 	struct fs *fs;
12361 	struct thread *td = curthread;
12362 	int error, flushparent, pagedep_new_block;
12363 	ino_t parentino;
12364 	ufs_lbn_t lbn;
12365 
12366 	ip = VTOI(vp);
12367 	mp = vp->v_mount;
12368 	ump = VFSTOUFS(mp);
12369 	fs = ump->um_fs;
12370 	if (MOUNTEDSOFTDEP(mp) == 0)
12371 		return (0);
12372 	ACQUIRE_LOCK(ump);
12373 restart:
12374 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12375 		FREE_LOCK(ump);
12376 		return (0);
12377 	}
12378 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12379 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12380 		    == DEPCOMPLETE) {
12381 			jwait(&inoref->if_list, MNT_WAIT);
12382 			goto restart;
12383 		}
12384 	}
12385 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12386 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12387 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12388 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12389 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12390 		panic("softdep_fsync: pending ops %p", inodedep);
12391 	for (error = 0, flushparent = 0; ; ) {
12392 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12393 			break;
12394 		if (wk->wk_type != D_DIRADD)
12395 			panic("softdep_fsync: Unexpected type %s",
12396 			    TYPENAME(wk->wk_type));
12397 		dap = WK_DIRADD(wk);
12398 		/*
12399 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12400 		 * dependency or is contained in a newly allocated block.
12401 		 */
12402 		if (dap->da_state & DIRCHG)
12403 			pagedep = dap->da_previous->dm_pagedep;
12404 		else
12405 			pagedep = dap->da_pagedep;
12406 		parentino = pagedep->pd_ino;
12407 		lbn = pagedep->pd_lbn;
12408 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12409 			panic("softdep_fsync: dirty");
12410 		if ((dap->da_state & MKDIR_PARENT) ||
12411 		    (pagedep->pd_state & NEWBLOCK))
12412 			flushparent = 1;
12413 		else
12414 			flushparent = 0;
12415 		/*
12416 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12417 		 * then we will not be able to release and recover the
12418 		 * vnode below, so we just have to give up on writing its
12419 		 * directory entry out. It will eventually be written, just
12420 		 * not now, but then the user was not asking to have it
12421 		 * written, so we are not breaking any promises.
12422 		 */
12423 		if (vp->v_iflag & VI_DOOMED)
12424 			break;
12425 		/*
12426 		 * We prevent deadlock by always fetching inodes from the
12427 		 * root, moving down the directory tree. Thus, when fetching
12428 		 * our parent directory, we first try to get the lock. If
12429 		 * that fails, we must unlock ourselves before requesting
12430 		 * the lock on our parent. See the comment in ufs_lookup
12431 		 * for details on possible races.
12432 		 */
12433 		FREE_LOCK(ump);
12434 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12435 		    FFSV_FORCEINSMQ)) {
12436 			error = vfs_busy(mp, MBF_NOWAIT);
12437 			if (error != 0) {
12438 				vfs_ref(mp);
12439 				VOP_UNLOCK(vp, 0);
12440 				error = vfs_busy(mp, 0);
12441 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12442 				vfs_rel(mp);
12443 				if (error != 0)
12444 					return (ENOENT);
12445 				if (vp->v_iflag & VI_DOOMED) {
12446 					vfs_unbusy(mp);
12447 					return (ENOENT);
12448 				}
12449 			}
12450 			VOP_UNLOCK(vp, 0);
12451 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12452 			    &pvp, FFSV_FORCEINSMQ);
12453 			vfs_unbusy(mp);
12454 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12455 			if (vp->v_iflag & VI_DOOMED) {
12456 				if (error == 0)
12457 					vput(pvp);
12458 				error = ENOENT;
12459 			}
12460 			if (error != 0)
12461 				return (error);
12462 		}
12463 		/*
12464 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12465 		 * that are contained in direct blocks will be resolved by
12466 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12467 		 * may require a complete sync'ing of the directory. So, we
12468 		 * try the cheap and fast ffs_update first, and if that fails,
12469 		 * then we do the slower ffs_syncvnode of the directory.
12470 		 */
12471 		if (flushparent) {
12472 			int locked;
12473 
12474 			if ((error = ffs_update(pvp, 1)) != 0) {
12475 				vput(pvp);
12476 				return (error);
12477 			}
12478 			ACQUIRE_LOCK(ump);
12479 			locked = 1;
12480 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12481 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12482 					if (wk->wk_type != D_DIRADD)
12483 						panic("softdep_fsync: Unexpected type %s",
12484 						      TYPENAME(wk->wk_type));
12485 					dap = WK_DIRADD(wk);
12486 					if (dap->da_state & DIRCHG)
12487 						pagedep = dap->da_previous->dm_pagedep;
12488 					else
12489 						pagedep = dap->da_pagedep;
12490 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12491 					FREE_LOCK(ump);
12492 					locked = 0;
12493 					if (pagedep_new_block && (error =
12494 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12495 						vput(pvp);
12496 						return (error);
12497 					}
12498 				}
12499 			}
12500 			if (locked)
12501 				FREE_LOCK(ump);
12502 		}
12503 		/*
12504 		 * Flush directory page containing the inode's name.
12505 		 */
12506 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12507 		    &bp);
12508 		if (error == 0)
12509 			error = bwrite(bp);
12510 		else
12511 			brelse(bp);
12512 		vput(pvp);
12513 		if (error != 0)
12514 			return (error);
12515 		ACQUIRE_LOCK(ump);
12516 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12517 			break;
12518 	}
12519 	FREE_LOCK(ump);
12520 	return (0);
12521 }
12522 
12523 /*
12524  * Flush all the dirty bitmaps associated with the block device
12525  * before flushing the rest of the dirty blocks so as to reduce
12526  * the number of dependencies that will have to be rolled back.
12527  *
12528  * XXX Unused?
12529  */
12530 void
12531 softdep_fsync_mountdev(vp)
12532 	struct vnode *vp;
12533 {
12534 	struct buf *bp, *nbp;
12535 	struct worklist *wk;
12536 	struct bufobj *bo;
12537 
12538 	if (!vn_isdisk(vp, NULL))
12539 		panic("softdep_fsync_mountdev: vnode not a disk");
12540 	bo = &vp->v_bufobj;
12541 restart:
12542 	BO_LOCK(bo);
12543 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12544 		/*
12545 		 * If it is already scheduled, skip to the next buffer.
12546 		 */
12547 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12548 			continue;
12549 
12550 		if ((bp->b_flags & B_DELWRI) == 0)
12551 			panic("softdep_fsync_mountdev: not dirty");
12552 		/*
12553 		 * We are only interested in bitmaps with outstanding
12554 		 * dependencies.
12555 		 */
12556 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12557 		    wk->wk_type != D_BMSAFEMAP ||
12558 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12559 			BUF_UNLOCK(bp);
12560 			continue;
12561 		}
12562 		BO_UNLOCK(bo);
12563 		bremfree(bp);
12564 		(void) bawrite(bp);
12565 		goto restart;
12566 	}
12567 	drain_output(vp);
12568 	BO_UNLOCK(bo);
12569 }
12570 
12571 /*
12572  * Sync all cylinder groups that were dirty at the time this function is
12573  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12574  * is used to flush freedep activity that may be holding up writes to a
12575  * indirect block.
12576  */
12577 static int
12578 sync_cgs(mp, waitfor)
12579 	struct mount *mp;
12580 	int waitfor;
12581 {
12582 	struct bmsafemap *bmsafemap;
12583 	struct bmsafemap *sentinel;
12584 	struct ufsmount *ump;
12585 	struct buf *bp;
12586 	int error;
12587 
12588 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12589 	sentinel->sm_cg = -1;
12590 	ump = VFSTOUFS(mp);
12591 	error = 0;
12592 	ACQUIRE_LOCK(ump);
12593 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12594 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12595 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12596 		/* Skip sentinels and cgs with no work to release. */
12597 		if (bmsafemap->sm_cg == -1 ||
12598 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12599 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12600 			LIST_REMOVE(sentinel, sm_next);
12601 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12602 			continue;
12603 		}
12604 		/*
12605 		 * If we don't get the lock and we're waiting try again, if
12606 		 * not move on to the next buf and try to sync it.
12607 		 */
12608 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12609 		if (bp == NULL && waitfor == MNT_WAIT)
12610 			continue;
12611 		LIST_REMOVE(sentinel, sm_next);
12612 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12613 		if (bp == NULL)
12614 			continue;
12615 		FREE_LOCK(ump);
12616 		if (waitfor == MNT_NOWAIT)
12617 			bawrite(bp);
12618 		else
12619 			error = bwrite(bp);
12620 		ACQUIRE_LOCK(ump);
12621 		if (error)
12622 			break;
12623 	}
12624 	LIST_REMOVE(sentinel, sm_next);
12625 	FREE_LOCK(ump);
12626 	free(sentinel, M_BMSAFEMAP);
12627 	return (error);
12628 }
12629 
12630 /*
12631  * This routine is called when we are trying to synchronously flush a
12632  * file. This routine must eliminate any filesystem metadata dependencies
12633  * so that the syncing routine can succeed.
12634  */
12635 int
12636 softdep_sync_metadata(struct vnode *vp)
12637 {
12638 	struct inode *ip;
12639 	int error;
12640 
12641 	ip = VTOI(vp);
12642 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12643 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12644 	/*
12645 	 * Ensure that any direct block dependencies have been cleared,
12646 	 * truncations are started, and inode references are journaled.
12647 	 */
12648 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12649 	/*
12650 	 * Write all journal records to prevent rollbacks on devvp.
12651 	 */
12652 	if (vp->v_type == VCHR)
12653 		softdep_flushjournal(vp->v_mount);
12654 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12655 	/*
12656 	 * Ensure that all truncates are written so we won't find deps on
12657 	 * indirect blocks.
12658 	 */
12659 	process_truncates(vp);
12660 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12661 
12662 	return (error);
12663 }
12664 
12665 /*
12666  * This routine is called when we are attempting to sync a buf with
12667  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12668  * other IO it can but returns EBUSY if the buffer is not yet able to
12669  * be written.  Dependencies which will not cause rollbacks will always
12670  * return 0.
12671  */
12672 int
12673 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12674 {
12675 	struct indirdep *indirdep;
12676 	struct pagedep *pagedep;
12677 	struct allocindir *aip;
12678 	struct newblk *newblk;
12679 	struct ufsmount *ump;
12680 	struct buf *nbp;
12681 	struct worklist *wk;
12682 	int i, error;
12683 
12684 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12685 	    ("softdep_sync_buf called on non-softdep filesystem"));
12686 	/*
12687 	 * For VCHR we just don't want to force flush any dependencies that
12688 	 * will cause rollbacks.
12689 	 */
12690 	if (vp->v_type == VCHR) {
12691 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12692 			return (EBUSY);
12693 		return (0);
12694 	}
12695 	ump = VFSTOUFS(vp->v_mount);
12696 	ACQUIRE_LOCK(ump);
12697 	/*
12698 	 * As we hold the buffer locked, none of its dependencies
12699 	 * will disappear.
12700 	 */
12701 	error = 0;
12702 top:
12703 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12704 		switch (wk->wk_type) {
12705 
12706 		case D_ALLOCDIRECT:
12707 		case D_ALLOCINDIR:
12708 			newblk = WK_NEWBLK(wk);
12709 			if (newblk->nb_jnewblk != NULL) {
12710 				if (waitfor == MNT_NOWAIT) {
12711 					error = EBUSY;
12712 					goto out_unlock;
12713 				}
12714 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12715 				goto top;
12716 			}
12717 			if (newblk->nb_state & DEPCOMPLETE ||
12718 			    waitfor == MNT_NOWAIT)
12719 				continue;
12720 			nbp = newblk->nb_bmsafemap->sm_buf;
12721 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12722 			if (nbp == NULL)
12723 				goto top;
12724 			FREE_LOCK(ump);
12725 			if ((error = bwrite(nbp)) != 0)
12726 				goto out;
12727 			ACQUIRE_LOCK(ump);
12728 			continue;
12729 
12730 		case D_INDIRDEP:
12731 			indirdep = WK_INDIRDEP(wk);
12732 			if (waitfor == MNT_NOWAIT) {
12733 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12734 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12735 					error = EBUSY;
12736 					goto out_unlock;
12737 				}
12738 			}
12739 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12740 				panic("softdep_sync_buf: truncation pending.");
12741 		restart:
12742 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12743 				newblk = (struct newblk *)aip;
12744 				if (newblk->nb_jnewblk != NULL) {
12745 					jwait(&newblk->nb_jnewblk->jn_list,
12746 					    waitfor);
12747 					goto restart;
12748 				}
12749 				if (newblk->nb_state & DEPCOMPLETE)
12750 					continue;
12751 				nbp = newblk->nb_bmsafemap->sm_buf;
12752 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12753 				if (nbp == NULL)
12754 					goto restart;
12755 				FREE_LOCK(ump);
12756 				if ((error = bwrite(nbp)) != 0)
12757 					goto out;
12758 				ACQUIRE_LOCK(ump);
12759 				goto restart;
12760 			}
12761 			continue;
12762 
12763 		case D_PAGEDEP:
12764 			/*
12765 			 * Only flush directory entries in synchronous passes.
12766 			 */
12767 			if (waitfor != MNT_WAIT) {
12768 				error = EBUSY;
12769 				goto out_unlock;
12770 			}
12771 			/*
12772 			 * While syncing snapshots, we must allow recursive
12773 			 * lookups.
12774 			 */
12775 			BUF_AREC(bp);
12776 			/*
12777 			 * We are trying to sync a directory that may
12778 			 * have dependencies on both its own metadata
12779 			 * and/or dependencies on the inodes of any
12780 			 * recently allocated files. We walk its diradd
12781 			 * lists pushing out the associated inode.
12782 			 */
12783 			pagedep = WK_PAGEDEP(wk);
12784 			for (i = 0; i < DAHASHSZ; i++) {
12785 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12786 					continue;
12787 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12788 				    &pagedep->pd_diraddhd[i]))) {
12789 					BUF_NOREC(bp);
12790 					goto out_unlock;
12791 				}
12792 			}
12793 			BUF_NOREC(bp);
12794 			continue;
12795 
12796 		case D_FREEWORK:
12797 		case D_FREEDEP:
12798 		case D_JSEGDEP:
12799 		case D_JNEWBLK:
12800 			continue;
12801 
12802 		default:
12803 			panic("softdep_sync_buf: Unknown type %s",
12804 			    TYPENAME(wk->wk_type));
12805 			/* NOTREACHED */
12806 		}
12807 	}
12808 out_unlock:
12809 	FREE_LOCK(ump);
12810 out:
12811 	return (error);
12812 }
12813 
12814 /*
12815  * Flush the dependencies associated with an inodedep.
12816  * Called with splbio blocked.
12817  */
12818 static int
12819 flush_inodedep_deps(vp, mp, ino)
12820 	struct vnode *vp;
12821 	struct mount *mp;
12822 	ino_t ino;
12823 {
12824 	struct inodedep *inodedep;
12825 	struct inoref *inoref;
12826 	struct ufsmount *ump;
12827 	int error, waitfor;
12828 
12829 	/*
12830 	 * This work is done in two passes. The first pass grabs most
12831 	 * of the buffers and begins asynchronously writing them. The
12832 	 * only way to wait for these asynchronous writes is to sleep
12833 	 * on the filesystem vnode which may stay busy for a long time
12834 	 * if the filesystem is active. So, instead, we make a second
12835 	 * pass over the dependencies blocking on each write. In the
12836 	 * usual case we will be blocking against a write that we
12837 	 * initiated, so when it is done the dependency will have been
12838 	 * resolved. Thus the second pass is expected to end quickly.
12839 	 * We give a brief window at the top of the loop to allow
12840 	 * any pending I/O to complete.
12841 	 */
12842 	ump = VFSTOUFS(mp);
12843 	LOCK_OWNED(ump);
12844 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12845 		if (error)
12846 			return (error);
12847 		FREE_LOCK(ump);
12848 		ACQUIRE_LOCK(ump);
12849 restart:
12850 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12851 			return (0);
12852 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12853 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12854 			    == DEPCOMPLETE) {
12855 				jwait(&inoref->if_list, MNT_WAIT);
12856 				goto restart;
12857 			}
12858 		}
12859 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12860 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12861 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12862 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12863 			continue;
12864 		/*
12865 		 * If pass2, we are done, otherwise do pass 2.
12866 		 */
12867 		if (waitfor == MNT_WAIT)
12868 			break;
12869 		waitfor = MNT_WAIT;
12870 	}
12871 	/*
12872 	 * Try freeing inodedep in case all dependencies have been removed.
12873 	 */
12874 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12875 		(void) free_inodedep(inodedep);
12876 	return (0);
12877 }
12878 
12879 /*
12880  * Flush an inode dependency list.
12881  * Called with splbio blocked.
12882  */
12883 static int
12884 flush_deplist(listhead, waitfor, errorp)
12885 	struct allocdirectlst *listhead;
12886 	int waitfor;
12887 	int *errorp;
12888 {
12889 	struct allocdirect *adp;
12890 	struct newblk *newblk;
12891 	struct ufsmount *ump;
12892 	struct buf *bp;
12893 
12894 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
12895 		return (0);
12896 	ump = VFSTOUFS(adp->ad_list.wk_mp);
12897 	LOCK_OWNED(ump);
12898 	TAILQ_FOREACH(adp, listhead, ad_next) {
12899 		newblk = (struct newblk *)adp;
12900 		if (newblk->nb_jnewblk != NULL) {
12901 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12902 			return (1);
12903 		}
12904 		if (newblk->nb_state & DEPCOMPLETE)
12905 			continue;
12906 		bp = newblk->nb_bmsafemap->sm_buf;
12907 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12908 		if (bp == NULL) {
12909 			if (waitfor == MNT_NOWAIT)
12910 				continue;
12911 			return (1);
12912 		}
12913 		FREE_LOCK(ump);
12914 		if (waitfor == MNT_NOWAIT)
12915 			bawrite(bp);
12916 		else
12917 			*errorp = bwrite(bp);
12918 		ACQUIRE_LOCK(ump);
12919 		return (1);
12920 	}
12921 	return (0);
12922 }
12923 
12924 /*
12925  * Flush dependencies associated with an allocdirect block.
12926  */
12927 static int
12928 flush_newblk_dep(vp, mp, lbn)
12929 	struct vnode *vp;
12930 	struct mount *mp;
12931 	ufs_lbn_t lbn;
12932 {
12933 	struct newblk *newblk;
12934 	struct ufsmount *ump;
12935 	struct bufobj *bo;
12936 	struct inode *ip;
12937 	struct buf *bp;
12938 	ufs2_daddr_t blkno;
12939 	int error;
12940 
12941 	error = 0;
12942 	bo = &vp->v_bufobj;
12943 	ip = VTOI(vp);
12944 	blkno = DIP(ip, i_db[lbn]);
12945 	if (blkno == 0)
12946 		panic("flush_newblk_dep: Missing block");
12947 	ump = VFSTOUFS(mp);
12948 	ACQUIRE_LOCK(ump);
12949 	/*
12950 	 * Loop until all dependencies related to this block are satisfied.
12951 	 * We must be careful to restart after each sleep in case a write
12952 	 * completes some part of this process for us.
12953 	 */
12954 	for (;;) {
12955 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12956 			FREE_LOCK(ump);
12957 			break;
12958 		}
12959 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12960 			panic("flush_newblk_deps: Bad newblk %p", newblk);
12961 		/*
12962 		 * Flush the journal.
12963 		 */
12964 		if (newblk->nb_jnewblk != NULL) {
12965 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12966 			continue;
12967 		}
12968 		/*
12969 		 * Write the bitmap dependency.
12970 		 */
12971 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12972 			bp = newblk->nb_bmsafemap->sm_buf;
12973 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
12974 			if (bp == NULL)
12975 				continue;
12976 			FREE_LOCK(ump);
12977 			error = bwrite(bp);
12978 			if (error)
12979 				break;
12980 			ACQUIRE_LOCK(ump);
12981 			continue;
12982 		}
12983 		/*
12984 		 * Write the buffer.
12985 		 */
12986 		FREE_LOCK(ump);
12987 		BO_LOCK(bo);
12988 		bp = gbincore(bo, lbn);
12989 		if (bp != NULL) {
12990 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12991 			    LK_INTERLOCK, BO_LOCKPTR(bo));
12992 			if (error == ENOLCK) {
12993 				ACQUIRE_LOCK(ump);
12994 				error = 0;
12995 				continue; /* Slept, retry */
12996 			}
12997 			if (error != 0)
12998 				break;	/* Failed */
12999 			if (bp->b_flags & B_DELWRI) {
13000 				bremfree(bp);
13001 				error = bwrite(bp);
13002 				if (error)
13003 					break;
13004 			} else
13005 				BUF_UNLOCK(bp);
13006 		} else
13007 			BO_UNLOCK(bo);
13008 		/*
13009 		 * We have to wait for the direct pointers to
13010 		 * point at the newdirblk before the dependency
13011 		 * will go away.
13012 		 */
13013 		error = ffs_update(vp, 1);
13014 		if (error)
13015 			break;
13016 		ACQUIRE_LOCK(ump);
13017 	}
13018 	return (error);
13019 }
13020 
13021 /*
13022  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13023  * Called with splbio blocked.
13024  */
13025 static int
13026 flush_pagedep_deps(pvp, mp, diraddhdp)
13027 	struct vnode *pvp;
13028 	struct mount *mp;
13029 	struct diraddhd *diraddhdp;
13030 {
13031 	struct inodedep *inodedep;
13032 	struct inoref *inoref;
13033 	struct ufsmount *ump;
13034 	struct diradd *dap;
13035 	struct vnode *vp;
13036 	int error = 0;
13037 	struct buf *bp;
13038 	ino_t inum;
13039 	struct diraddhd unfinished;
13040 
13041 	LIST_INIT(&unfinished);
13042 	ump = VFSTOUFS(mp);
13043 	LOCK_OWNED(ump);
13044 restart:
13045 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13046 		/*
13047 		 * Flush ourselves if this directory entry
13048 		 * has a MKDIR_PARENT dependency.
13049 		 */
13050 		if (dap->da_state & MKDIR_PARENT) {
13051 			FREE_LOCK(ump);
13052 			if ((error = ffs_update(pvp, 1)) != 0)
13053 				break;
13054 			ACQUIRE_LOCK(ump);
13055 			/*
13056 			 * If that cleared dependencies, go on to next.
13057 			 */
13058 			if (dap != LIST_FIRST(diraddhdp))
13059 				continue;
13060 			/*
13061 			 * All MKDIR_PARENT dependencies and all the
13062 			 * NEWBLOCK pagedeps that are contained in direct
13063 			 * blocks were resolved by doing above ffs_update.
13064 			 * Pagedeps contained in indirect blocks may
13065 			 * require a complete sync'ing of the directory.
13066 			 * We are in the midst of doing a complete sync,
13067 			 * so if they are not resolved in this pass we
13068 			 * defer them for now as they will be sync'ed by
13069 			 * our caller shortly.
13070 			 */
13071 			LIST_REMOVE(dap, da_pdlist);
13072 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13073 			continue;
13074 		}
13075 		/*
13076 		 * A newly allocated directory must have its "." and
13077 		 * ".." entries written out before its name can be
13078 		 * committed in its parent.
13079 		 */
13080 		inum = dap->da_newinum;
13081 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13082 			panic("flush_pagedep_deps: lost inode1");
13083 		/*
13084 		 * Wait for any pending journal adds to complete so we don't
13085 		 * cause rollbacks while syncing.
13086 		 */
13087 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13088 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13089 			    == DEPCOMPLETE) {
13090 				jwait(&inoref->if_list, MNT_WAIT);
13091 				goto restart;
13092 			}
13093 		}
13094 		if (dap->da_state & MKDIR_BODY) {
13095 			FREE_LOCK(ump);
13096 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13097 			    FFSV_FORCEINSMQ)))
13098 				break;
13099 			error = flush_newblk_dep(vp, mp, 0);
13100 			/*
13101 			 * If we still have the dependency we might need to
13102 			 * update the vnode to sync the new link count to
13103 			 * disk.
13104 			 */
13105 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13106 				error = ffs_update(vp, 1);
13107 			vput(vp);
13108 			if (error != 0)
13109 				break;
13110 			ACQUIRE_LOCK(ump);
13111 			/*
13112 			 * If that cleared dependencies, go on to next.
13113 			 */
13114 			if (dap != LIST_FIRST(diraddhdp))
13115 				continue;
13116 			if (dap->da_state & MKDIR_BODY) {
13117 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13118 				    &inodedep);
13119 				panic("flush_pagedep_deps: MKDIR_BODY "
13120 				    "inodedep %p dap %p vp %p",
13121 				    inodedep, dap, vp);
13122 			}
13123 		}
13124 		/*
13125 		 * Flush the inode on which the directory entry depends.
13126 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13127 		 * the only remaining dependency is that the updated inode
13128 		 * count must get pushed to disk. The inode has already
13129 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13130 		 * the time of the reference count change. So we need only
13131 		 * locate that buffer, ensure that there will be no rollback
13132 		 * caused by a bitmap dependency, then write the inode buffer.
13133 		 */
13134 retry:
13135 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13136 			panic("flush_pagedep_deps: lost inode");
13137 		/*
13138 		 * If the inode still has bitmap dependencies,
13139 		 * push them to disk.
13140 		 */
13141 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13142 			bp = inodedep->id_bmsafemap->sm_buf;
13143 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13144 			if (bp == NULL)
13145 				goto retry;
13146 			FREE_LOCK(ump);
13147 			if ((error = bwrite(bp)) != 0)
13148 				break;
13149 			ACQUIRE_LOCK(ump);
13150 			if (dap != LIST_FIRST(diraddhdp))
13151 				continue;
13152 		}
13153 		/*
13154 		 * If the inode is still sitting in a buffer waiting
13155 		 * to be written or waiting for the link count to be
13156 		 * adjusted update it here to flush it to disk.
13157 		 */
13158 		if (dap == LIST_FIRST(diraddhdp)) {
13159 			FREE_LOCK(ump);
13160 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13161 			    FFSV_FORCEINSMQ)))
13162 				break;
13163 			error = ffs_update(vp, 1);
13164 			vput(vp);
13165 			if (error)
13166 				break;
13167 			ACQUIRE_LOCK(ump);
13168 		}
13169 		/*
13170 		 * If we have failed to get rid of all the dependencies
13171 		 * then something is seriously wrong.
13172 		 */
13173 		if (dap == LIST_FIRST(diraddhdp)) {
13174 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13175 			panic("flush_pagedep_deps: failed to flush "
13176 			    "inodedep %p ino %ju dap %p",
13177 			    inodedep, (uintmax_t)inum, dap);
13178 		}
13179 	}
13180 	if (error)
13181 		ACQUIRE_LOCK(ump);
13182 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13183 		LIST_REMOVE(dap, da_pdlist);
13184 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13185 	}
13186 	return (error);
13187 }
13188 
13189 /*
13190  * A large burst of file addition or deletion activity can drive the
13191  * memory load excessively high. First attempt to slow things down
13192  * using the techniques below. If that fails, this routine requests
13193  * the offending operations to fall back to running synchronously
13194  * until the memory load returns to a reasonable level.
13195  */
13196 int
13197 softdep_slowdown(vp)
13198 	struct vnode *vp;
13199 {
13200 	struct ufsmount *ump;
13201 	int jlow;
13202 	int max_softdeps_hard;
13203 
13204 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13205 	    ("softdep_slowdown called on non-softdep filesystem"));
13206 	ump = VFSTOUFS(vp->v_mount);
13207 	ACQUIRE_LOCK(ump);
13208 	jlow = 0;
13209 	/*
13210 	 * Check for journal space if needed.
13211 	 */
13212 	if (DOINGSUJ(vp)) {
13213 		if (journal_space(ump, 0) == 0)
13214 			jlow = 1;
13215 	}
13216 	/*
13217 	 * If the system is under its limits and our filesystem is
13218 	 * not responsible for more than our share of the usage and
13219 	 * we are not low on journal space, then no need to slow down.
13220 	 */
13221 	max_softdeps_hard = max_softdeps * 11 / 10;
13222 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13223 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13224 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13225 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13226 	    ump->softdep_curdeps[D_DIRREM] <
13227 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13228 	    ump->softdep_curdeps[D_INODEDEP] <
13229 	    max_softdeps_hard / stat_flush_threads &&
13230 	    ump->softdep_curdeps[D_INDIRDEP] <
13231 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13232 	    ump->softdep_curdeps[D_FREEBLKS] <
13233 	    max_softdeps_hard / stat_flush_threads) {
13234 		FREE_LOCK(ump);
13235   		return (0);
13236 	}
13237 	/*
13238 	 * If the journal is low or our filesystem is over its limit
13239 	 * then speedup the cleanup.
13240 	 */
13241 	if (ump->softdep_curdeps[D_INDIRDEP] <
13242 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13243 		softdep_speedup(ump);
13244 	stat_sync_limit_hit += 1;
13245 	FREE_LOCK(ump);
13246 	/*
13247 	 * We only slow down the rate at which new dependencies are
13248 	 * generated if we are not using journaling. With journaling,
13249 	 * the cleanup should always be sufficient to keep things
13250 	 * under control.
13251 	 */
13252 	if (DOINGSUJ(vp))
13253 		return (0);
13254 	return (1);
13255 }
13256 
13257 /*
13258  * Called by the allocation routines when they are about to fail
13259  * in the hope that we can free up the requested resource (inodes
13260  * or disk space).
13261  *
13262  * First check to see if the work list has anything on it. If it has,
13263  * clean up entries until we successfully free the requested resource.
13264  * Because this process holds inodes locked, we cannot handle any remove
13265  * requests that might block on a locked inode as that could lead to
13266  * deadlock. If the worklist yields none of the requested resource,
13267  * start syncing out vnodes to free up the needed space.
13268  */
13269 int
13270 softdep_request_cleanup(fs, vp, cred, resource)
13271 	struct fs *fs;
13272 	struct vnode *vp;
13273 	struct ucred *cred;
13274 	int resource;
13275 {
13276 	struct ufsmount *ump;
13277 	struct mount *mp;
13278 	long starttime;
13279 	ufs2_daddr_t needed;
13280 	int error, failed_vnode;
13281 
13282 	/*
13283 	 * If we are being called because of a process doing a
13284 	 * copy-on-write, then it is not safe to process any
13285 	 * worklist items as we will recurse into the copyonwrite
13286 	 * routine.  This will result in an incoherent snapshot.
13287 	 * If the vnode that we hold is a snapshot, we must avoid
13288 	 * handling other resources that could cause deadlock.
13289 	 */
13290 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13291 		return (0);
13292 
13293 	if (resource == FLUSH_BLOCKS_WAIT)
13294 		stat_cleanup_blkrequests += 1;
13295 	else
13296 		stat_cleanup_inorequests += 1;
13297 
13298 	mp = vp->v_mount;
13299 	ump = VFSTOUFS(mp);
13300 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13301 	UFS_UNLOCK(ump);
13302 	error = ffs_update(vp, 1);
13303 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13304 		UFS_LOCK(ump);
13305 		return (0);
13306 	}
13307 	/*
13308 	 * If we are in need of resources, start by cleaning up
13309 	 * any block removals associated with our inode.
13310 	 */
13311 	ACQUIRE_LOCK(ump);
13312 	process_removes(vp);
13313 	process_truncates(vp);
13314 	FREE_LOCK(ump);
13315 	/*
13316 	 * Now clean up at least as many resources as we will need.
13317 	 *
13318 	 * When requested to clean up inodes, the number that are needed
13319 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13320 	 * plus a bit of slop (2) in case some more writers show up while
13321 	 * we are cleaning.
13322 	 *
13323 	 * When requested to free up space, the amount of space that
13324 	 * we need is enough blocks to allocate a full-sized segment
13325 	 * (fs_contigsumsize). The number of such segments that will
13326 	 * be needed is set by the number of simultaneous writers
13327 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13328 	 * writers show up while we are cleaning.
13329 	 *
13330 	 * Additionally, if we are unpriviledged and allocating space,
13331 	 * we need to ensure that we clean up enough blocks to get the
13332 	 * needed number of blocks over the threshold of the minimum
13333 	 * number of blocks required to be kept free by the filesystem
13334 	 * (fs_minfree).
13335 	 */
13336 	if (resource == FLUSH_INODES_WAIT) {
13337 		needed = vp->v_mount->mnt_writeopcount + 2;
13338 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13339 		needed = (vp->v_mount->mnt_writeopcount + 2) *
13340 		    fs->fs_contigsumsize;
13341 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
13342 			needed += fragstoblks(fs,
13343 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13344 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13345 	} else {
13346 		UFS_LOCK(ump);
13347 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13348 		    resource);
13349 		return (0);
13350 	}
13351 	starttime = time_second;
13352 retry:
13353 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13354 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13355 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13356 	    fs->fs_cstotal.cs_nifree <= needed)) {
13357 		ACQUIRE_LOCK(ump);
13358 		if (ump->softdep_on_worklist > 0 &&
13359 		    process_worklist_item(UFSTOVFS(ump),
13360 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13361 			stat_worklist_push += 1;
13362 		FREE_LOCK(ump);
13363 	}
13364 	/*
13365 	 * If we still need resources and there are no more worklist
13366 	 * entries to process to obtain them, we have to start flushing
13367 	 * the dirty vnodes to force the release of additional requests
13368 	 * to the worklist that we can then process to reap addition
13369 	 * resources. We walk the vnodes associated with the mount point
13370 	 * until we get the needed worklist requests that we can reap.
13371 	 *
13372 	 * If there are several threads all needing to clean the same
13373 	 * mount point, only one is allowed to walk the mount list.
13374 	 * When several threads all try to walk the same mount list,
13375 	 * they end up competing with each other and often end up in
13376 	 * livelock. This approach ensures that forward progress is
13377 	 * made at the cost of occational ENOSPC errors being returned
13378 	 * that might otherwise have been avoided.
13379 	 */
13380 	error = 1;
13381 	if ((resource == FLUSH_BLOCKS_WAIT &&
13382 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13383 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13384 	     fs->fs_cstotal.cs_nifree <= needed)) {
13385 		ACQUIRE_LOCK(ump);
13386 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13387 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13388 			FREE_LOCK(ump);
13389 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13390 			ACQUIRE_LOCK(ump);
13391 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13392 			FREE_LOCK(ump);
13393 			if (ump->softdep_on_worklist > 0) {
13394 				stat_cleanup_retries += 1;
13395 				if (!failed_vnode)
13396 					goto retry;
13397 			}
13398 		} else {
13399 			FREE_LOCK(ump);
13400 			error = 0;
13401 		}
13402 		stat_cleanup_failures += 1;
13403 	}
13404 	if (time_second - starttime > stat_cleanup_high_delay)
13405 		stat_cleanup_high_delay = time_second - starttime;
13406 	UFS_LOCK(ump);
13407 	return (error);
13408 }
13409 
13410 /*
13411  * Scan the vnodes for the specified mount point flushing out any
13412  * vnodes that can be locked without waiting. Finally, try to flush
13413  * the device associated with the mount point if it can be locked
13414  * without waiting.
13415  *
13416  * We return 0 if we were able to lock every vnode in our scan.
13417  * If we had to skip one or more vnodes, we return 1.
13418  */
13419 static int
13420 softdep_request_cleanup_flush(mp, ump)
13421 	struct mount *mp;
13422 	struct ufsmount *ump;
13423 {
13424 	struct thread *td;
13425 	struct vnode *lvp, *mvp;
13426 	int failed_vnode;
13427 
13428 	failed_vnode = 0;
13429 	td = curthread;
13430 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13431 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13432 			VI_UNLOCK(lvp);
13433 			continue;
13434 		}
13435 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13436 		    td) != 0) {
13437 			failed_vnode = 1;
13438 			continue;
13439 		}
13440 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13441 			vput(lvp);
13442 			continue;
13443 		}
13444 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13445 		vput(lvp);
13446 	}
13447 	lvp = ump->um_devvp;
13448 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13449 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13450 		VOP_UNLOCK(lvp, 0);
13451 	}
13452 	return (failed_vnode);
13453 }
13454 
13455 static bool
13456 softdep_excess_items(struct ufsmount *ump, int item)
13457 {
13458 
13459 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13460 	return (dep_current[item] > max_softdeps &&
13461 	    ump->softdep_curdeps[item] > max_softdeps /
13462 	    stat_flush_threads);
13463 }
13464 
13465 static void
13466 schedule_cleanup(struct mount *mp)
13467 {
13468 	struct ufsmount *ump;
13469 	struct thread *td;
13470 
13471 	ump = VFSTOUFS(mp);
13472 	LOCK_OWNED(ump);
13473 	FREE_LOCK(ump);
13474 	td = curthread;
13475 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13476 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13477 		/*
13478 		 * No ast is delivered to kernel threads, so nobody
13479 		 * would deref the mp.  Some kernel threads
13480 		 * explicitely check for AST, e.g. NFS daemon does
13481 		 * this in the serving loop.
13482 		 */
13483 		return;
13484 	}
13485 	if (td->td_su != NULL)
13486 		vfs_rel(td->td_su);
13487 	vfs_ref(mp);
13488 	td->td_su = mp;
13489 	thread_lock(td);
13490 	td->td_flags |= TDF_ASTPENDING;
13491 	thread_unlock(td);
13492 }
13493 
13494 static void
13495 softdep_ast_cleanup_proc(struct thread *td)
13496 {
13497 	struct mount *mp;
13498 	struct ufsmount *ump;
13499 	int error;
13500 	bool req;
13501 
13502 	while ((mp = td->td_su) != NULL) {
13503 		td->td_su = NULL;
13504 		error = vfs_busy(mp, MBF_NOWAIT);
13505 		vfs_rel(mp);
13506 		if (error != 0)
13507 			return;
13508 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13509 			ump = VFSTOUFS(mp);
13510 			for (;;) {
13511 				req = false;
13512 				ACQUIRE_LOCK(ump);
13513 				if (softdep_excess_items(ump, D_INODEDEP)) {
13514 					req = true;
13515 					request_cleanup(mp, FLUSH_INODES);
13516 				}
13517 				if (softdep_excess_items(ump, D_DIRREM)) {
13518 					req = true;
13519 					request_cleanup(mp, FLUSH_BLOCKS);
13520 				}
13521 				FREE_LOCK(ump);
13522 				if (softdep_excess_items(ump, D_NEWBLK) ||
13523 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13524 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13525 					error = vn_start_write(NULL, &mp,
13526 					    V_WAIT);
13527 					if (error == 0) {
13528 						req = true;
13529 						VFS_SYNC(mp, MNT_WAIT);
13530 						vn_finished_write(mp);
13531 					}
13532 				}
13533 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13534 					break;
13535 			}
13536 		}
13537 		vfs_unbusy(mp);
13538 	}
13539 	if ((mp = td->td_su) != NULL) {
13540 		td->td_su = NULL;
13541 		vfs_rel(mp);
13542 	}
13543 }
13544 
13545 /*
13546  * If memory utilization has gotten too high, deliberately slow things
13547  * down and speed up the I/O processing.
13548  */
13549 static int
13550 request_cleanup(mp, resource)
13551 	struct mount *mp;
13552 	int resource;
13553 {
13554 	struct thread *td = curthread;
13555 	struct ufsmount *ump;
13556 
13557 	ump = VFSTOUFS(mp);
13558 	LOCK_OWNED(ump);
13559 	/*
13560 	 * We never hold up the filesystem syncer or buf daemon.
13561 	 */
13562 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13563 		return (0);
13564 	/*
13565 	 * First check to see if the work list has gotten backlogged.
13566 	 * If it has, co-opt this process to help clean up two entries.
13567 	 * Because this process may hold inodes locked, we cannot
13568 	 * handle any remove requests that might block on a locked
13569 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13570 	 * to avoid recursively processing the worklist.
13571 	 */
13572 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13573 		td->td_pflags |= TDP_SOFTDEP;
13574 		process_worklist_item(mp, 2, LK_NOWAIT);
13575 		td->td_pflags &= ~TDP_SOFTDEP;
13576 		stat_worklist_push += 2;
13577 		return(1);
13578 	}
13579 	/*
13580 	 * Next, we attempt to speed up the syncer process. If that
13581 	 * is successful, then we allow the process to continue.
13582 	 */
13583 	if (softdep_speedup(ump) &&
13584 	    resource != FLUSH_BLOCKS_WAIT &&
13585 	    resource != FLUSH_INODES_WAIT)
13586 		return(0);
13587 	/*
13588 	 * If we are resource constrained on inode dependencies, try
13589 	 * flushing some dirty inodes. Otherwise, we are constrained
13590 	 * by file deletions, so try accelerating flushes of directories
13591 	 * with removal dependencies. We would like to do the cleanup
13592 	 * here, but we probably hold an inode locked at this point and
13593 	 * that might deadlock against one that we try to clean. So,
13594 	 * the best that we can do is request the syncer daemon to do
13595 	 * the cleanup for us.
13596 	 */
13597 	switch (resource) {
13598 
13599 	case FLUSH_INODES:
13600 	case FLUSH_INODES_WAIT:
13601 		ACQUIRE_GBLLOCK(&lk);
13602 		stat_ino_limit_push += 1;
13603 		req_clear_inodedeps += 1;
13604 		FREE_GBLLOCK(&lk);
13605 		stat_countp = &stat_ino_limit_hit;
13606 		break;
13607 
13608 	case FLUSH_BLOCKS:
13609 	case FLUSH_BLOCKS_WAIT:
13610 		ACQUIRE_GBLLOCK(&lk);
13611 		stat_blk_limit_push += 1;
13612 		req_clear_remove += 1;
13613 		FREE_GBLLOCK(&lk);
13614 		stat_countp = &stat_blk_limit_hit;
13615 		break;
13616 
13617 	default:
13618 		panic("request_cleanup: unknown type");
13619 	}
13620 	/*
13621 	 * Hopefully the syncer daemon will catch up and awaken us.
13622 	 * We wait at most tickdelay before proceeding in any case.
13623 	 */
13624 	ACQUIRE_GBLLOCK(&lk);
13625 	FREE_LOCK(ump);
13626 	proc_waiting += 1;
13627 	if (callout_pending(&softdep_callout) == FALSE)
13628 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13629 		    pause_timer, 0);
13630 
13631 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13632 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13633 	proc_waiting -= 1;
13634 	FREE_GBLLOCK(&lk);
13635 	ACQUIRE_LOCK(ump);
13636 	return (1);
13637 }
13638 
13639 /*
13640  * Awaken processes pausing in request_cleanup and clear proc_waiting
13641  * to indicate that there is no longer a timer running. Pause_timer
13642  * will be called with the global softdep mutex (&lk) locked.
13643  */
13644 static void
13645 pause_timer(arg)
13646 	void *arg;
13647 {
13648 
13649 	GBLLOCK_OWNED(&lk);
13650 	/*
13651 	 * The callout_ API has acquired mtx and will hold it around this
13652 	 * function call.
13653 	 */
13654 	*stat_countp += proc_waiting;
13655 	wakeup(&proc_waiting);
13656 }
13657 
13658 /*
13659  * If requested, try removing inode or removal dependencies.
13660  */
13661 static void
13662 check_clear_deps(mp)
13663 	struct mount *mp;
13664 {
13665 
13666 	/*
13667 	 * If we are suspended, it may be because of our using
13668 	 * too many inodedeps, so help clear them out.
13669 	 */
13670 	if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13671 		clear_inodedeps(mp);
13672 	/*
13673 	 * General requests for cleanup of backed up dependencies
13674 	 */
13675 	ACQUIRE_GBLLOCK(&lk);
13676 	if (req_clear_inodedeps) {
13677 		req_clear_inodedeps -= 1;
13678 		FREE_GBLLOCK(&lk);
13679 		clear_inodedeps(mp);
13680 		ACQUIRE_GBLLOCK(&lk);
13681 		wakeup(&proc_waiting);
13682 	}
13683 	if (req_clear_remove) {
13684 		req_clear_remove -= 1;
13685 		FREE_GBLLOCK(&lk);
13686 		clear_remove(mp);
13687 		ACQUIRE_GBLLOCK(&lk);
13688 		wakeup(&proc_waiting);
13689 	}
13690 	FREE_GBLLOCK(&lk);
13691 }
13692 
13693 /*
13694  * Flush out a directory with at least one removal dependency in an effort to
13695  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13696  */
13697 static void
13698 clear_remove(mp)
13699 	struct mount *mp;
13700 {
13701 	struct pagedep_hashhead *pagedephd;
13702 	struct pagedep *pagedep;
13703 	struct ufsmount *ump;
13704 	struct vnode *vp;
13705 	struct bufobj *bo;
13706 	int error, cnt;
13707 	ino_t ino;
13708 
13709 	ump = VFSTOUFS(mp);
13710 	LOCK_OWNED(ump);
13711 
13712 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13713 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13714 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13715 			ump->pagedep_nextclean = 0;
13716 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13717 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13718 				continue;
13719 			ino = pagedep->pd_ino;
13720 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13721 				continue;
13722 			FREE_LOCK(ump);
13723 
13724 			/*
13725 			 * Let unmount clear deps
13726 			 */
13727 			error = vfs_busy(mp, MBF_NOWAIT);
13728 			if (error != 0)
13729 				goto finish_write;
13730 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13731 			     FFSV_FORCEINSMQ);
13732 			vfs_unbusy(mp);
13733 			if (error != 0) {
13734 				softdep_error("clear_remove: vget", error);
13735 				goto finish_write;
13736 			}
13737 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13738 				softdep_error("clear_remove: fsync", error);
13739 			bo = &vp->v_bufobj;
13740 			BO_LOCK(bo);
13741 			drain_output(vp);
13742 			BO_UNLOCK(bo);
13743 			vput(vp);
13744 		finish_write:
13745 			vn_finished_write(mp);
13746 			ACQUIRE_LOCK(ump);
13747 			return;
13748 		}
13749 	}
13750 }
13751 
13752 /*
13753  * Clear out a block of dirty inodes in an effort to reduce
13754  * the number of inodedep dependency structures.
13755  */
13756 static void
13757 clear_inodedeps(mp)
13758 	struct mount *mp;
13759 {
13760 	struct inodedep_hashhead *inodedephd;
13761 	struct inodedep *inodedep;
13762 	struct ufsmount *ump;
13763 	struct vnode *vp;
13764 	struct fs *fs;
13765 	int error, cnt;
13766 	ino_t firstino, lastino, ino;
13767 
13768 	ump = VFSTOUFS(mp);
13769 	fs = ump->um_fs;
13770 	LOCK_OWNED(ump);
13771 	/*
13772 	 * Pick a random inode dependency to be cleared.
13773 	 * We will then gather up all the inodes in its block
13774 	 * that have dependencies and flush them out.
13775 	 */
13776 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13777 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13778 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13779 			ump->inodedep_nextclean = 0;
13780 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13781 			break;
13782 	}
13783 	if (inodedep == NULL)
13784 		return;
13785 	/*
13786 	 * Find the last inode in the block with dependencies.
13787 	 */
13788 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13789 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13790 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13791 			break;
13792 	/*
13793 	 * Asynchronously push all but the last inode with dependencies.
13794 	 * Synchronously push the last inode with dependencies to ensure
13795 	 * that the inode block gets written to free up the inodedeps.
13796 	 */
13797 	for (ino = firstino; ino <= lastino; ino++) {
13798 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13799 			continue;
13800 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13801 			continue;
13802 		FREE_LOCK(ump);
13803 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13804 		if (error != 0) {
13805 			vn_finished_write(mp);
13806 			ACQUIRE_LOCK(ump);
13807 			return;
13808 		}
13809 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13810 		    FFSV_FORCEINSMQ)) != 0) {
13811 			softdep_error("clear_inodedeps: vget", error);
13812 			vfs_unbusy(mp);
13813 			vn_finished_write(mp);
13814 			ACQUIRE_LOCK(ump);
13815 			return;
13816 		}
13817 		vfs_unbusy(mp);
13818 		if (ino == lastino) {
13819 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13820 				softdep_error("clear_inodedeps: fsync1", error);
13821 		} else {
13822 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13823 				softdep_error("clear_inodedeps: fsync2", error);
13824 			BO_LOCK(&vp->v_bufobj);
13825 			drain_output(vp);
13826 			BO_UNLOCK(&vp->v_bufobj);
13827 		}
13828 		vput(vp);
13829 		vn_finished_write(mp);
13830 		ACQUIRE_LOCK(ump);
13831 	}
13832 }
13833 
13834 void
13835 softdep_buf_append(bp, wkhd)
13836 	struct buf *bp;
13837 	struct workhead *wkhd;
13838 {
13839 	struct worklist *wk;
13840 	struct ufsmount *ump;
13841 
13842 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13843 		return;
13844 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13845 	    ("softdep_buf_append called on non-softdep filesystem"));
13846 	ump = VFSTOUFS(wk->wk_mp);
13847 	ACQUIRE_LOCK(ump);
13848 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13849 		WORKLIST_REMOVE(wk);
13850 		WORKLIST_INSERT(&bp->b_dep, wk);
13851 	}
13852 	FREE_LOCK(ump);
13853 
13854 }
13855 
13856 void
13857 softdep_inode_append(ip, cred, wkhd)
13858 	struct inode *ip;
13859 	struct ucred *cred;
13860 	struct workhead *wkhd;
13861 {
13862 	struct buf *bp;
13863 	struct fs *fs;
13864 	struct ufsmount *ump;
13865 	int error;
13866 
13867 	ump = ITOUMP(ip);
13868 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13869 	    ("softdep_inode_append called on non-softdep filesystem"));
13870 	fs = ump->um_fs;
13871 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13872 	    (int)fs->fs_bsize, cred, &bp);
13873 	if (error) {
13874 		bqrelse(bp);
13875 		softdep_freework(wkhd);
13876 		return;
13877 	}
13878 	softdep_buf_append(bp, wkhd);
13879 	bqrelse(bp);
13880 }
13881 
13882 void
13883 softdep_freework(wkhd)
13884 	struct workhead *wkhd;
13885 {
13886 	struct worklist *wk;
13887 	struct ufsmount *ump;
13888 
13889 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13890 		return;
13891 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13892 	    ("softdep_freework called on non-softdep filesystem"));
13893 	ump = VFSTOUFS(wk->wk_mp);
13894 	ACQUIRE_LOCK(ump);
13895 	handle_jwork(wkhd);
13896 	FREE_LOCK(ump);
13897 }
13898 
13899 /*
13900  * Function to determine if the buffer has outstanding dependencies
13901  * that will cause a roll-back if the buffer is written. If wantcount
13902  * is set, return number of dependencies, otherwise just yes or no.
13903  */
13904 static int
13905 softdep_count_dependencies(bp, wantcount)
13906 	struct buf *bp;
13907 	int wantcount;
13908 {
13909 	struct worklist *wk;
13910 	struct ufsmount *ump;
13911 	struct bmsafemap *bmsafemap;
13912 	struct freework *freework;
13913 	struct inodedep *inodedep;
13914 	struct indirdep *indirdep;
13915 	struct freeblks *freeblks;
13916 	struct allocindir *aip;
13917 	struct pagedep *pagedep;
13918 	struct dirrem *dirrem;
13919 	struct newblk *newblk;
13920 	struct mkdir *mkdir;
13921 	struct diradd *dap;
13922 	int i, retval;
13923 
13924 	retval = 0;
13925 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
13926 		return (0);
13927 	ump = VFSTOUFS(wk->wk_mp);
13928 	ACQUIRE_LOCK(ump);
13929 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13930 		switch (wk->wk_type) {
13931 
13932 		case D_INODEDEP:
13933 			inodedep = WK_INODEDEP(wk);
13934 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13935 				/* bitmap allocation dependency */
13936 				retval += 1;
13937 				if (!wantcount)
13938 					goto out;
13939 			}
13940 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13941 				/* direct block pointer dependency */
13942 				retval += 1;
13943 				if (!wantcount)
13944 					goto out;
13945 			}
13946 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13947 				/* direct block pointer dependency */
13948 				retval += 1;
13949 				if (!wantcount)
13950 					goto out;
13951 			}
13952 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13953 				/* Add reference dependency. */
13954 				retval += 1;
13955 				if (!wantcount)
13956 					goto out;
13957 			}
13958 			continue;
13959 
13960 		case D_INDIRDEP:
13961 			indirdep = WK_INDIRDEP(wk);
13962 
13963 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
13964 				/* indirect truncation dependency */
13965 				retval += 1;
13966 				if (!wantcount)
13967 					goto out;
13968 			}
13969 
13970 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13971 				/* indirect block pointer dependency */
13972 				retval += 1;
13973 				if (!wantcount)
13974 					goto out;
13975 			}
13976 			continue;
13977 
13978 		case D_PAGEDEP:
13979 			pagedep = WK_PAGEDEP(wk);
13980 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
13981 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
13982 					/* Journal remove ref dependency. */
13983 					retval += 1;
13984 					if (!wantcount)
13985 						goto out;
13986 				}
13987 			}
13988 			for (i = 0; i < DAHASHSZ; i++) {
13989 
13990 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
13991 					/* directory entry dependency */
13992 					retval += 1;
13993 					if (!wantcount)
13994 						goto out;
13995 				}
13996 			}
13997 			continue;
13998 
13999 		case D_BMSAFEMAP:
14000 			bmsafemap = WK_BMSAFEMAP(wk);
14001 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14002 				/* Add reference dependency. */
14003 				retval += 1;
14004 				if (!wantcount)
14005 					goto out;
14006 			}
14007 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14008 				/* Allocate block dependency. */
14009 				retval += 1;
14010 				if (!wantcount)
14011 					goto out;
14012 			}
14013 			continue;
14014 
14015 		case D_FREEBLKS:
14016 			freeblks = WK_FREEBLKS(wk);
14017 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14018 				/* Freeblk journal dependency. */
14019 				retval += 1;
14020 				if (!wantcount)
14021 					goto out;
14022 			}
14023 			continue;
14024 
14025 		case D_ALLOCDIRECT:
14026 		case D_ALLOCINDIR:
14027 			newblk = WK_NEWBLK(wk);
14028 			if (newblk->nb_jnewblk) {
14029 				/* Journal allocate dependency. */
14030 				retval += 1;
14031 				if (!wantcount)
14032 					goto out;
14033 			}
14034 			continue;
14035 
14036 		case D_MKDIR:
14037 			mkdir = WK_MKDIR(wk);
14038 			if (mkdir->md_jaddref) {
14039 				/* Journal reference dependency. */
14040 				retval += 1;
14041 				if (!wantcount)
14042 					goto out;
14043 			}
14044 			continue;
14045 
14046 		case D_FREEWORK:
14047 		case D_FREEDEP:
14048 		case D_JSEGDEP:
14049 		case D_JSEG:
14050 		case D_SBDEP:
14051 			/* never a dependency on these blocks */
14052 			continue;
14053 
14054 		default:
14055 			panic("softdep_count_dependencies: Unexpected type %s",
14056 			    TYPENAME(wk->wk_type));
14057 			/* NOTREACHED */
14058 		}
14059 	}
14060 out:
14061 	FREE_LOCK(ump);
14062 	return retval;
14063 }
14064 
14065 /*
14066  * Acquire exclusive access to a buffer.
14067  * Must be called with a locked mtx parameter.
14068  * Return acquired buffer or NULL on failure.
14069  */
14070 static struct buf *
14071 getdirtybuf(bp, lock, waitfor)
14072 	struct buf *bp;
14073 	struct rwlock *lock;
14074 	int waitfor;
14075 {
14076 	int error;
14077 
14078 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14079 		if (waitfor != MNT_WAIT)
14080 			return (NULL);
14081 		error = BUF_LOCK(bp,
14082 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14083 		/*
14084 		 * Even if we successfully acquire bp here, we have dropped
14085 		 * lock, which may violates our guarantee.
14086 		 */
14087 		if (error == 0)
14088 			BUF_UNLOCK(bp);
14089 		else if (error != ENOLCK)
14090 			panic("getdirtybuf: inconsistent lock: %d", error);
14091 		rw_wlock(lock);
14092 		return (NULL);
14093 	}
14094 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14095 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14096 			rw_wunlock(lock);
14097 			BO_LOCK(bp->b_bufobj);
14098 			BUF_UNLOCK(bp);
14099 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14100 				bp->b_vflags |= BV_BKGRDWAIT;
14101 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14102 				       PRIBIO | PDROP, "getbuf", 0);
14103 			} else
14104 				BO_UNLOCK(bp->b_bufobj);
14105 			rw_wlock(lock);
14106 			return (NULL);
14107 		}
14108 		BUF_UNLOCK(bp);
14109 		if (waitfor != MNT_WAIT)
14110 			return (NULL);
14111 		/*
14112 		 * The lock argument must be bp->b_vp's mutex in
14113 		 * this case.
14114 		 */
14115 #ifdef	DEBUG_VFS_LOCKS
14116 		if (bp->b_vp->v_type != VCHR)
14117 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14118 #endif
14119 		bp->b_vflags |= BV_BKGRDWAIT;
14120 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14121 		return (NULL);
14122 	}
14123 	if ((bp->b_flags & B_DELWRI) == 0) {
14124 		BUF_UNLOCK(bp);
14125 		return (NULL);
14126 	}
14127 	bremfree(bp);
14128 	return (bp);
14129 }
14130 
14131 
14132 /*
14133  * Check if it is safe to suspend the file system now.  On entry,
14134  * the vnode interlock for devvp should be held.  Return 0 with
14135  * the mount interlock held if the file system can be suspended now,
14136  * otherwise return EAGAIN with the mount interlock held.
14137  */
14138 int
14139 softdep_check_suspend(struct mount *mp,
14140 		      struct vnode *devvp,
14141 		      int softdep_depcnt,
14142 		      int softdep_accdepcnt,
14143 		      int secondary_writes,
14144 		      int secondary_accwrites)
14145 {
14146 	struct bufobj *bo;
14147 	struct ufsmount *ump;
14148 	struct inodedep *inodedep;
14149 	int error, unlinked;
14150 
14151 	bo = &devvp->v_bufobj;
14152 	ASSERT_BO_WLOCKED(bo);
14153 
14154 	/*
14155 	 * If we are not running with soft updates, then we need only
14156 	 * deal with secondary writes as we try to suspend.
14157 	 */
14158 	if (MOUNTEDSOFTDEP(mp) == 0) {
14159 		MNT_ILOCK(mp);
14160 		while (mp->mnt_secondary_writes != 0) {
14161 			BO_UNLOCK(bo);
14162 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14163 			    (PUSER - 1) | PDROP, "secwr", 0);
14164 			BO_LOCK(bo);
14165 			MNT_ILOCK(mp);
14166 		}
14167 
14168 		/*
14169 		 * Reasons for needing more work before suspend:
14170 		 * - Dirty buffers on devvp.
14171 		 * - Secondary writes occurred after start of vnode sync loop
14172 		 */
14173 		error = 0;
14174 		if (bo->bo_numoutput > 0 ||
14175 		    bo->bo_dirty.bv_cnt > 0 ||
14176 		    secondary_writes != 0 ||
14177 		    mp->mnt_secondary_writes != 0 ||
14178 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14179 			error = EAGAIN;
14180 		BO_UNLOCK(bo);
14181 		return (error);
14182 	}
14183 
14184 	/*
14185 	 * If we are running with soft updates, then we need to coordinate
14186 	 * with them as we try to suspend.
14187 	 */
14188 	ump = VFSTOUFS(mp);
14189 	for (;;) {
14190 		if (!TRY_ACQUIRE_LOCK(ump)) {
14191 			BO_UNLOCK(bo);
14192 			ACQUIRE_LOCK(ump);
14193 			FREE_LOCK(ump);
14194 			BO_LOCK(bo);
14195 			continue;
14196 		}
14197 		MNT_ILOCK(mp);
14198 		if (mp->mnt_secondary_writes != 0) {
14199 			FREE_LOCK(ump);
14200 			BO_UNLOCK(bo);
14201 			msleep(&mp->mnt_secondary_writes,
14202 			       MNT_MTX(mp),
14203 			       (PUSER - 1) | PDROP, "secwr", 0);
14204 			BO_LOCK(bo);
14205 			continue;
14206 		}
14207 		break;
14208 	}
14209 
14210 	unlinked = 0;
14211 	if (MOUNTEDSUJ(mp)) {
14212 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14213 		    inodedep != NULL;
14214 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14215 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14216 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14217 			    UNLINKONLIST) ||
14218 			    !check_inodedep_free(inodedep))
14219 				continue;
14220 			unlinked++;
14221 		}
14222 	}
14223 
14224 	/*
14225 	 * Reasons for needing more work before suspend:
14226 	 * - Dirty buffers on devvp.
14227 	 * - Softdep activity occurred after start of vnode sync loop
14228 	 * - Secondary writes occurred after start of vnode sync loop
14229 	 */
14230 	error = 0;
14231 	if (bo->bo_numoutput > 0 ||
14232 	    bo->bo_dirty.bv_cnt > 0 ||
14233 	    softdep_depcnt != unlinked ||
14234 	    ump->softdep_deps != unlinked ||
14235 	    softdep_accdepcnt != ump->softdep_accdeps ||
14236 	    secondary_writes != 0 ||
14237 	    mp->mnt_secondary_writes != 0 ||
14238 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14239 		error = EAGAIN;
14240 	FREE_LOCK(ump);
14241 	BO_UNLOCK(bo);
14242 	return (error);
14243 }
14244 
14245 
14246 /*
14247  * Get the number of dependency structures for the file system, both
14248  * the current number and the total number allocated.  These will
14249  * later be used to detect that softdep processing has occurred.
14250  */
14251 void
14252 softdep_get_depcounts(struct mount *mp,
14253 		      int *softdep_depsp,
14254 		      int *softdep_accdepsp)
14255 {
14256 	struct ufsmount *ump;
14257 
14258 	if (MOUNTEDSOFTDEP(mp) == 0) {
14259 		*softdep_depsp = 0;
14260 		*softdep_accdepsp = 0;
14261 		return;
14262 	}
14263 	ump = VFSTOUFS(mp);
14264 	ACQUIRE_LOCK(ump);
14265 	*softdep_depsp = ump->softdep_deps;
14266 	*softdep_accdepsp = ump->softdep_accdeps;
14267 	FREE_LOCK(ump);
14268 }
14269 
14270 /*
14271  * Wait for pending output on a vnode to complete.
14272  * Must be called with vnode lock and interlock locked.
14273  *
14274  * XXX: Should just be a call to bufobj_wwait().
14275  */
14276 static void
14277 drain_output(vp)
14278 	struct vnode *vp;
14279 {
14280 	struct bufobj *bo;
14281 
14282 	bo = &vp->v_bufobj;
14283 	ASSERT_VOP_LOCKED(vp, "drain_output");
14284 	ASSERT_BO_WLOCKED(bo);
14285 
14286 	while (bo->bo_numoutput) {
14287 		bo->bo_flag |= BO_WWAIT;
14288 		msleep((caddr_t)&bo->bo_numoutput,
14289 		    BO_LOCKPTR(bo), PRIBIO + 1, "drainvp", 0);
14290 	}
14291 }
14292 
14293 /*
14294  * Called whenever a buffer that is being invalidated or reallocated
14295  * contains dependencies. This should only happen if an I/O error has
14296  * occurred. The routine is called with the buffer locked.
14297  */
14298 static void
14299 softdep_deallocate_dependencies(bp)
14300 	struct buf *bp;
14301 {
14302 
14303 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14304 		panic("softdep_deallocate_dependencies: dangling deps");
14305 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14306 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14307 	else
14308 		printf("softdep_deallocate_dependencies: "
14309 		    "got error %d while accessing filesystem\n", bp->b_error);
14310 	if (bp->b_error != ENXIO)
14311 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14312 }
14313 
14314 /*
14315  * Function to handle asynchronous write errors in the filesystem.
14316  */
14317 static void
14318 softdep_error(func, error)
14319 	char *func;
14320 	int error;
14321 {
14322 
14323 	/* XXX should do something better! */
14324 	printf("%s: got error %d while accessing filesystem\n", func, error);
14325 }
14326 
14327 #ifdef DDB
14328 
14329 static void
14330 inodedep_print(struct inodedep *inodedep, int verbose)
14331 {
14332 	db_printf("%p fs %p st %x ino %jd inoblk %jd delta %jd nlink %jd"
14333 	    " saveino %p\n",
14334 	    inodedep, inodedep->id_fs, inodedep->id_state,
14335 	    (intmax_t)inodedep->id_ino,
14336 	    (intmax_t)fsbtodb(inodedep->id_fs,
14337 	    ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14338 	    (intmax_t)inodedep->id_nlinkdelta,
14339 	    (intmax_t)inodedep->id_savednlink,
14340 	    inodedep->id_savedino1);
14341 
14342 	if (verbose == 0)
14343 		return;
14344 
14345 	db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
14346 	    "mkdiradd %p\n",
14347 	    LIST_FIRST(&inodedep->id_pendinghd),
14348 	    LIST_FIRST(&inodedep->id_bufwait),
14349 	    LIST_FIRST(&inodedep->id_inowait),
14350 	    TAILQ_FIRST(&inodedep->id_inoreflst),
14351 	    inodedep->id_mkdiradd);
14352 	db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
14353 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14354 	    TAILQ_FIRST(&inodedep->id_newinoupdt),
14355 	    TAILQ_FIRST(&inodedep->id_extupdt),
14356 	    TAILQ_FIRST(&inodedep->id_newextupdt));
14357 }
14358 
14359 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
14360 {
14361 
14362 	if (have_addr == 0) {
14363 		db_printf("Address required\n");
14364 		return;
14365 	}
14366 	inodedep_print((struct inodedep*)addr, 1);
14367 }
14368 
14369 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
14370 {
14371 	struct inodedep_hashhead *inodedephd;
14372 	struct inodedep *inodedep;
14373 	struct ufsmount *ump;
14374 	int cnt;
14375 
14376 	if (have_addr == 0) {
14377 		db_printf("Address required\n");
14378 		return;
14379 	}
14380 	ump = (struct ufsmount *)addr;
14381 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14382 		inodedephd = &ump->inodedep_hashtbl[cnt];
14383 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14384 			inodedep_print(inodedep, 0);
14385 		}
14386 	}
14387 }
14388 
14389 DB_SHOW_COMMAND(worklist, db_show_worklist)
14390 {
14391 	struct worklist *wk;
14392 
14393 	if (have_addr == 0) {
14394 		db_printf("Address required\n");
14395 		return;
14396 	}
14397 	wk = (struct worklist *)addr;
14398 	printf("worklist: %p type %s state 0x%X\n",
14399 	    wk, TYPENAME(wk->wk_type), wk->wk_state);
14400 }
14401 
14402 DB_SHOW_COMMAND(workhead, db_show_workhead)
14403 {
14404 	struct workhead *wkhd;
14405 	struct worklist *wk;
14406 	int i;
14407 
14408 	if (have_addr == 0) {
14409 		db_printf("Address required\n");
14410 		return;
14411 	}
14412 	wkhd = (struct workhead *)addr;
14413 	wk = LIST_FIRST(wkhd);
14414 	for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
14415 		db_printf("worklist: %p type %s state 0x%X",
14416 		    wk, TYPENAME(wk->wk_type), wk->wk_state);
14417 	if (i == 100)
14418 		db_printf("workhead overflow");
14419 	printf("\n");
14420 }
14421 
14422 
14423 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
14424 {
14425 	struct mkdirlist *mkdirlisthd;
14426 	struct jaddref *jaddref;
14427 	struct diradd *diradd;
14428 	struct mkdir *mkdir;
14429 
14430 	if (have_addr == 0) {
14431 		db_printf("Address required\n");
14432 		return;
14433 	}
14434 	mkdirlisthd = (struct mkdirlist *)addr;
14435 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14436 		diradd = mkdir->md_diradd;
14437 		db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
14438 		    mkdir, mkdir->md_state, diradd, diradd->da_state);
14439 		if ((jaddref = mkdir->md_jaddref) != NULL)
14440 			db_printf(" jaddref %p jaddref state 0x%X",
14441 			    jaddref, jaddref->ja_state);
14442 		db_printf("\n");
14443 	}
14444 }
14445 
14446 /* exported to ffs_vfsops.c */
14447 extern void db_print_ffs(struct ufsmount *ump);
14448 void
14449 db_print_ffs(struct ufsmount *ump)
14450 {
14451 	db_printf("mp %p %s devvp %p fs %p su_wl %d su_deps %d su_req %d\n",
14452 	    ump->um_mountp, ump->um_mountp->mnt_stat.f_mntonname,
14453 	    ump->um_devvp, ump->um_fs, ump->softdep_on_worklist,
14454 	    ump->softdep_deps, ump->softdep_req);
14455 }
14456 
14457 #endif /* DDB */
14458 
14459 #endif /* SOFTUPDATES */
14460