xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 6486b015fc84e96725fef22b0e3363351399ae83)
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/limits.h>
64 #include <sys/lock.h>
65 #include <sys/malloc.h>
66 #include <sys/mount.h>
67 #include <sys/mutex.h>
68 #include <sys/namei.h>
69 #include <sys/priv.h>
70 #include <sys/proc.h>
71 #include <sys/stat.h>
72 #include <sys/sysctl.h>
73 #include <sys/syslog.h>
74 #include <sys/vnode.h>
75 #include <sys/conf.h>
76 
77 #include <ufs/ufs/dir.h>
78 #include <ufs/ufs/extattr.h>
79 #include <ufs/ufs/quota.h>
80 #include <ufs/ufs/inode.h>
81 #include <ufs/ufs/ufsmount.h>
82 #include <ufs/ffs/fs.h>
83 #include <ufs/ffs/softdep.h>
84 #include <ufs/ffs/ffs_extern.h>
85 #include <ufs/ufs/ufs_extern.h>
86 
87 #include <vm/vm.h>
88 #include <vm/vm_extern.h>
89 #include <vm/vm_object.h>
90 
91 #include <ddb/ddb.h>
92 
93 #ifndef SOFTUPDATES
94 
95 int
96 softdep_flushfiles(oldmnt, flags, td)
97 	struct mount *oldmnt;
98 	int flags;
99 	struct thread *td;
100 {
101 
102 	panic("softdep_flushfiles called");
103 }
104 
105 int
106 softdep_mount(devvp, mp, fs, cred)
107 	struct vnode *devvp;
108 	struct mount *mp;
109 	struct fs *fs;
110 	struct ucred *cred;
111 {
112 
113 	return (0);
114 }
115 
116 void
117 softdep_initialize()
118 {
119 
120 	return;
121 }
122 
123 void
124 softdep_uninitialize()
125 {
126 
127 	return;
128 }
129 
130 void
131 softdep_unmount(mp)
132 	struct mount *mp;
133 {
134 
135 }
136 
137 void
138 softdep_setup_sbupdate(ump, fs, bp)
139 	struct ufsmount *ump;
140 	struct fs *fs;
141 	struct buf *bp;
142 {
143 }
144 
145 void
146 softdep_setup_inomapdep(bp, ip, newinum, mode)
147 	struct buf *bp;
148 	struct inode *ip;
149 	ino_t newinum;
150 	int mode;
151 {
152 
153 	panic("softdep_setup_inomapdep called");
154 }
155 
156 void
157 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
158 	struct buf *bp;
159 	struct mount *mp;
160 	ufs2_daddr_t newblkno;
161 	int frags;
162 	int oldfrags;
163 {
164 
165 	panic("softdep_setup_blkmapdep called");
166 }
167 
168 void
169 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
170 	struct inode *ip;
171 	ufs_lbn_t lbn;
172 	ufs2_daddr_t newblkno;
173 	ufs2_daddr_t oldblkno;
174 	long newsize;
175 	long oldsize;
176 	struct buf *bp;
177 {
178 
179 	panic("softdep_setup_allocdirect called");
180 }
181 
182 void
183 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
184 	struct inode *ip;
185 	ufs_lbn_t lbn;
186 	ufs2_daddr_t newblkno;
187 	ufs2_daddr_t oldblkno;
188 	long newsize;
189 	long oldsize;
190 	struct buf *bp;
191 {
192 
193 	panic("softdep_setup_allocext called");
194 }
195 
196 void
197 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
198 	struct inode *ip;
199 	ufs_lbn_t lbn;
200 	struct buf *bp;
201 	int ptrno;
202 	ufs2_daddr_t newblkno;
203 	ufs2_daddr_t oldblkno;
204 	struct buf *nbp;
205 {
206 
207 	panic("softdep_setup_allocindir_page called");
208 }
209 
210 void
211 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
212 	struct buf *nbp;
213 	struct inode *ip;
214 	struct buf *bp;
215 	int ptrno;
216 	ufs2_daddr_t newblkno;
217 {
218 
219 	panic("softdep_setup_allocindir_meta called");
220 }
221 
222 void
223 softdep_journal_freeblocks(ip, cred, length, flags)
224 	struct inode *ip;
225 	struct ucred *cred;
226 	off_t length;
227 	int flags;
228 {
229 
230 	panic("softdep_journal_freeblocks called");
231 }
232 
233 void
234 softdep_journal_fsync(ip)
235 	struct inode *ip;
236 {
237 
238 	panic("softdep_journal_fsync called");
239 }
240 
241 void
242 softdep_setup_freeblocks(ip, length, flags)
243 	struct inode *ip;
244 	off_t length;
245 	int flags;
246 {
247 
248 	panic("softdep_setup_freeblocks called");
249 }
250 
251 void
252 softdep_freefile(pvp, ino, mode)
253 		struct vnode *pvp;
254 		ino_t ino;
255 		int mode;
256 {
257 
258 	panic("softdep_freefile called");
259 }
260 
261 int
262 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
263 	struct buf *bp;
264 	struct inode *dp;
265 	off_t diroffset;
266 	ino_t newinum;
267 	struct buf *newdirbp;
268 	int isnewblk;
269 {
270 
271 	panic("softdep_setup_directory_add called");
272 }
273 
274 void
275 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
276 	struct buf *bp;
277 	struct inode *dp;
278 	caddr_t base;
279 	caddr_t oldloc;
280 	caddr_t newloc;
281 	int entrysize;
282 {
283 
284 	panic("softdep_change_directoryentry_offset called");
285 }
286 
287 void
288 softdep_setup_remove(bp, dp, ip, isrmdir)
289 	struct buf *bp;
290 	struct inode *dp;
291 	struct inode *ip;
292 	int isrmdir;
293 {
294 
295 	panic("softdep_setup_remove called");
296 }
297 
298 void
299 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
300 	struct buf *bp;
301 	struct inode *dp;
302 	struct inode *ip;
303 	ino_t newinum;
304 	int isrmdir;
305 {
306 
307 	panic("softdep_setup_directory_change called");
308 }
309 
310 void
311 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
312 	struct mount *mp;
313 	struct buf *bp;
314 	ufs2_daddr_t blkno;
315 	int frags;
316 	struct workhead *wkhd;
317 {
318 
319 	panic("%s called", __FUNCTION__);
320 }
321 
322 void
323 softdep_setup_inofree(mp, bp, ino, wkhd)
324 	struct mount *mp;
325 	struct buf *bp;
326 	ino_t ino;
327 	struct workhead *wkhd;
328 {
329 
330 	panic("%s called", __FUNCTION__);
331 }
332 
333 void
334 softdep_setup_unlink(dp, ip)
335 	struct inode *dp;
336 	struct inode *ip;
337 {
338 
339 	panic("%s called", __FUNCTION__);
340 }
341 
342 void
343 softdep_setup_link(dp, ip)
344 	struct inode *dp;
345 	struct inode *ip;
346 {
347 
348 	panic("%s called", __FUNCTION__);
349 }
350 
351 void
352 softdep_revert_link(dp, ip)
353 	struct inode *dp;
354 	struct inode *ip;
355 {
356 
357 	panic("%s called", __FUNCTION__);
358 }
359 
360 void
361 softdep_setup_rmdir(dp, ip)
362 	struct inode *dp;
363 	struct inode *ip;
364 {
365 
366 	panic("%s called", __FUNCTION__);
367 }
368 
369 void
370 softdep_revert_rmdir(dp, ip)
371 	struct inode *dp;
372 	struct inode *ip;
373 {
374 
375 	panic("%s called", __FUNCTION__);
376 }
377 
378 void
379 softdep_setup_create(dp, ip)
380 	struct inode *dp;
381 	struct inode *ip;
382 {
383 
384 	panic("%s called", __FUNCTION__);
385 }
386 
387 void
388 softdep_revert_create(dp, ip)
389 	struct inode *dp;
390 	struct inode *ip;
391 {
392 
393 	panic("%s called", __FUNCTION__);
394 }
395 
396 void
397 softdep_setup_mkdir(dp, ip)
398 	struct inode *dp;
399 	struct inode *ip;
400 {
401 
402 	panic("%s called", __FUNCTION__);
403 }
404 
405 void
406 softdep_revert_mkdir(dp, ip)
407 	struct inode *dp;
408 	struct inode *ip;
409 {
410 
411 	panic("%s called", __FUNCTION__);
412 }
413 
414 void
415 softdep_setup_dotdot_link(dp, ip)
416 	struct inode *dp;
417 	struct inode *ip;
418 {
419 
420 	panic("%s called", __FUNCTION__);
421 }
422 
423 int
424 softdep_prealloc(vp, waitok)
425 	struct vnode *vp;
426 	int waitok;
427 {
428 
429 	panic("%s called", __FUNCTION__);
430 
431 	return (0);
432 }
433 
434 int
435 softdep_journal_lookup(mp, vpp)
436 	struct mount *mp;
437 	struct vnode **vpp;
438 {
439 
440 	return (ENOENT);
441 }
442 
443 void
444 softdep_change_linkcnt(ip)
445 	struct inode *ip;
446 {
447 
448 	panic("softdep_change_linkcnt called");
449 }
450 
451 void
452 softdep_load_inodeblock(ip)
453 	struct inode *ip;
454 {
455 
456 	panic("softdep_load_inodeblock called");
457 }
458 
459 void
460 softdep_update_inodeblock(ip, bp, waitfor)
461 	struct inode *ip;
462 	struct buf *bp;
463 	int waitfor;
464 {
465 
466 	panic("softdep_update_inodeblock called");
467 }
468 
469 int
470 softdep_fsync(vp)
471 	struct vnode *vp;	/* the "in_core" copy of the inode */
472 {
473 
474 	return (0);
475 }
476 
477 void
478 softdep_fsync_mountdev(vp)
479 	struct vnode *vp;
480 {
481 
482 	return;
483 }
484 
485 int
486 softdep_flushworklist(oldmnt, countp, td)
487 	struct mount *oldmnt;
488 	int *countp;
489 	struct thread *td;
490 {
491 
492 	*countp = 0;
493 	return (0);
494 }
495 
496 int
497 softdep_sync_metadata(struct vnode *vp)
498 {
499 
500 	return (0);
501 }
502 
503 int
504 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
505 {
506 
507 	return (0);
508 }
509 
510 int
511 softdep_slowdown(vp)
512 	struct vnode *vp;
513 {
514 
515 	panic("softdep_slowdown called");
516 }
517 
518 void
519 softdep_releasefile(ip)
520 	struct inode *ip;	/* inode with the zero effective link count */
521 {
522 
523 	panic("softdep_releasefile 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_deps,
541 		      int softdep_accdeps,
542 		      int secondary_writes,
543 		      int secondary_accwrites)
544 {
545 	struct bufobj *bo;
546 	int error;
547 
548 	(void) softdep_deps,
549 	(void) softdep_accdeps;
550 
551 	bo = &devvp->v_bufobj;
552 	ASSERT_BO_LOCKED(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 /*
621  * These definitions need to be adapted to the system to which
622  * this file is being ported.
623  */
624 
625 #define M_SOFTDEP_FLAGS	(M_WAITOK)
626 
627 #define	D_PAGEDEP	0
628 #define	D_INODEDEP	1
629 #define	D_BMSAFEMAP	2
630 #define	D_NEWBLK	3
631 #define	D_ALLOCDIRECT	4
632 #define	D_INDIRDEP	5
633 #define	D_ALLOCINDIR	6
634 #define	D_FREEFRAG	7
635 #define	D_FREEBLKS	8
636 #define	D_FREEFILE	9
637 #define	D_DIRADD	10
638 #define	D_MKDIR		11
639 #define	D_DIRREM	12
640 #define	D_NEWDIRBLK	13
641 #define	D_FREEWORK	14
642 #define	D_FREEDEP	15
643 #define	D_JADDREF	16
644 #define	D_JREMREF	17
645 #define	D_JMVREF	18
646 #define	D_JNEWBLK	19
647 #define	D_JFREEBLK	20
648 #define	D_JFREEFRAG	21
649 #define	D_JSEG		22
650 #define	D_JSEGDEP	23
651 #define	D_SBDEP		24
652 #define	D_JTRUNC	25
653 #define	D_JFSYNC	26
654 #define	D_SENTINAL	27
655 #define	D_LAST		D_SENTINAL
656 
657 unsigned long dep_current[D_LAST + 1];
658 unsigned long dep_total[D_LAST + 1];
659 unsigned long dep_write[D_LAST + 1];
660 
661 
662 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
663     "soft updates stats");
664 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
665     "total dependencies allocated");
666 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
667     "current dependencies allocated");
668 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
669     "current dependencies written");
670 
671 #define	SOFTDEP_TYPE(type, str, long)					\
672     static MALLOC_DEFINE(M_ ## type, #str, long);			\
673     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
674 	&dep_total[D_ ## type], 0, "");					\
675     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
676 	&dep_current[D_ ## type], 0, "");				\
677     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
678 	&dep_write[D_ ## type], 0, "");
679 
680 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
681 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
682 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
683     "Block or frag allocated from cyl group map");
684 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
685 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
686 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
687 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
688 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
689 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
690 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
691 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
692 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
693 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
694 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
695 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
696 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
697 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
698 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
699 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
700 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
701 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
702 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
703 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
704 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
705 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
706 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
707 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
708 
709 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
710 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
711 
712 /*
713  * translate from workitem type to memory type
714  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
715  */
716 static struct malloc_type *memtype[] = {
717 	M_PAGEDEP,
718 	M_INODEDEP,
719 	M_BMSAFEMAP,
720 	M_NEWBLK,
721 	M_ALLOCDIRECT,
722 	M_INDIRDEP,
723 	M_ALLOCINDIR,
724 	M_FREEFRAG,
725 	M_FREEBLKS,
726 	M_FREEFILE,
727 	M_DIRADD,
728 	M_MKDIR,
729 	M_DIRREM,
730 	M_NEWDIRBLK,
731 	M_FREEWORK,
732 	M_FREEDEP,
733 	M_JADDREF,
734 	M_JREMREF,
735 	M_JMVREF,
736 	M_JNEWBLK,
737 	M_JFREEBLK,
738 	M_JFREEFRAG,
739 	M_JSEG,
740 	M_JSEGDEP,
741 	M_SBDEP,
742 	M_JTRUNC,
743 	M_JFSYNC
744 };
745 
746 static LIST_HEAD(mkdirlist, mkdir) mkdirlisthd;
747 
748 #define DtoM(type) (memtype[type])
749 
750 /*
751  * Names of malloc types.
752  */
753 #define TYPENAME(type)  \
754 	((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
755 /*
756  * End system adaptation definitions.
757  */
758 
759 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
760 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
761 
762 /*
763  * Forward declarations.
764  */
765 struct inodedep_hashhead;
766 struct newblk_hashhead;
767 struct pagedep_hashhead;
768 struct bmsafemap_hashhead;
769 
770 /*
771  * Internal function prototypes.
772  */
773 static	void softdep_error(char *, int);
774 static	void drain_output(struct vnode *);
775 static	struct buf *getdirtybuf(struct buf *, struct mtx *, int);
776 static	void clear_remove(void);
777 static	void clear_inodedeps(void);
778 static	void unlinked_inodedep(struct mount *, struct inodedep *);
779 static	void clear_unlinked_inodedep(struct inodedep *);
780 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
781 static	int flush_pagedep_deps(struct vnode *, struct mount *,
782 	    struct diraddhd *);
783 static	int free_pagedep(struct pagedep *);
784 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
785 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
786 static	int flush_deplist(struct allocdirectlst *, int, int *);
787 static	int sync_cgs(struct mount *, int);
788 static	int handle_written_filepage(struct pagedep *, struct buf *);
789 static	int handle_written_sbdep(struct sbdep *, struct buf *);
790 static	void initiate_write_sbdep(struct sbdep *);
791 static  void diradd_inode_written(struct diradd *, struct inodedep *);
792 static	int handle_written_indirdep(struct indirdep *, struct buf *,
793 	    struct buf**);
794 static	int handle_written_inodeblock(struct inodedep *, struct buf *);
795 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
796 	    uint8_t *);
797 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *);
798 static	void handle_written_jaddref(struct jaddref *);
799 static	void handle_written_jremref(struct jremref *);
800 static	void handle_written_jseg(struct jseg *, struct buf *);
801 static	void handle_written_jnewblk(struct jnewblk *);
802 static	void handle_written_jblkdep(struct jblkdep *);
803 static	void handle_written_jfreefrag(struct jfreefrag *);
804 static	void complete_jseg(struct jseg *);
805 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
806 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
807 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
808 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
809 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
810 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
811 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
812 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
813 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
814 static	inline void inoref_write(struct inoref *, struct jseg *,
815 	    struct jrefrec *);
816 static	void handle_allocdirect_partdone(struct allocdirect *,
817 	    struct workhead *);
818 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
819 	    struct workhead *);
820 static	void indirdep_complete(struct indirdep *);
821 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
822 static	void indirblk_insert(struct freework *);
823 static	void indirblk_remove(struct freework *);
824 static	void handle_allocindir_partdone(struct allocindir *);
825 static	void initiate_write_filepage(struct pagedep *, struct buf *);
826 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
827 static	void handle_written_mkdir(struct mkdir *, int);
828 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
829 	    uint8_t *);
830 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
831 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
832 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
833 static	void handle_workitem_freefile(struct freefile *);
834 static	int handle_workitem_remove(struct dirrem *, int);
835 static	struct dirrem *newdirrem(struct buf *, struct inode *,
836 	    struct inode *, int, struct dirrem **);
837 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
838 	    struct buf *);
839 static	void cancel_indirdep(struct indirdep *, struct buf *,
840 	    struct freeblks *);
841 static	void free_indirdep(struct indirdep *);
842 static	void free_diradd(struct diradd *, struct workhead *);
843 static	void merge_diradd(struct inodedep *, struct diradd *);
844 static	void complete_diradd(struct diradd *);
845 static	struct diradd *diradd_lookup(struct pagedep *, int);
846 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
847 	    struct jremref *);
848 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
849 	    struct jremref *);
850 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
851 	    struct jremref *, struct jremref *);
852 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
853 	    struct jremref *);
854 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
855 	    struct freeblks *, int);
856 static	int setup_trunc_indir(struct freeblks *, struct inode *,
857 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
858 static	void complete_trunc_indir(struct freework *);
859 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
860 	    int);
861 static	void complete_mkdir(struct mkdir *);
862 static	void free_newdirblk(struct newdirblk *);
863 static	void free_jremref(struct jremref *);
864 static	void free_jaddref(struct jaddref *);
865 static	void free_jsegdep(struct jsegdep *);
866 static	void free_jsegs(struct jblocks *);
867 static	void rele_jseg(struct jseg *);
868 static	void free_jseg(struct jseg *, struct jblocks *);
869 static	void free_jnewblk(struct jnewblk *);
870 static	void free_jblkdep(struct jblkdep *);
871 static	void free_jfreefrag(struct jfreefrag *);
872 static	void free_freedep(struct freedep *);
873 static	void journal_jremref(struct dirrem *, struct jremref *,
874 	    struct inodedep *);
875 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
876 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
877 	    struct workhead *);
878 static	void cancel_jfreefrag(struct jfreefrag *);
879 static	inline void setup_freedirect(struct freeblks *, struct inode *,
880 	    int, int);
881 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
882 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
883 	    ufs_lbn_t, int);
884 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
885 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
886 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
887 ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
888 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
889 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
890 	    int, int);
891 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
892 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
893 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
894 static	void newblk_freefrag(struct newblk*);
895 static	void free_newblk(struct newblk *);
896 static	void cancel_allocdirect(struct allocdirectlst *,
897 	    struct allocdirect *, struct freeblks *);
898 static	int check_inode_unwritten(struct inodedep *);
899 static	int free_inodedep(struct inodedep *);
900 static	void freework_freeblock(struct freework *);
901 static	void freework_enqueue(struct freework *);
902 static	int handle_workitem_freeblocks(struct freeblks *, int);
903 static	int handle_complete_freeblocks(struct freeblks *, int);
904 static	void handle_workitem_indirblk(struct freework *);
905 static	void handle_written_freework(struct freework *);
906 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
907 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
908 	    struct workhead *);
909 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
910 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
911 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
912 	    ufs2_daddr_t, ufs_lbn_t);
913 static	void handle_workitem_freefrag(struct freefrag *);
914 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
915 	    ufs_lbn_t);
916 static	void allocdirect_merge(struct allocdirectlst *,
917 	    struct allocdirect *, struct allocdirect *);
918 static	struct freefrag *allocindir_merge(struct allocindir *,
919 	    struct allocindir *);
920 static	int bmsafemap_find(struct bmsafemap_hashhead *, struct mount *, int,
921 	    struct bmsafemap **);
922 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
923 	    int cg);
924 static	int newblk_find(struct newblk_hashhead *, struct mount *, ufs2_daddr_t,
925 	    int, struct newblk **);
926 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
927 static	int inodedep_find(struct inodedep_hashhead *, struct fs *, ino_t,
928 	    struct inodedep **);
929 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
930 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
931 	    int, struct pagedep **);
932 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
933 	    struct mount *mp, int, struct pagedep **);
934 static	void pause_timer(void *);
935 static	int request_cleanup(struct mount *, int);
936 static	int process_worklist_item(struct mount *, int, int);
937 static	void process_removes(struct vnode *);
938 static	void process_truncates(struct vnode *);
939 static	void jwork_move(struct workhead *, struct workhead *);
940 static	void jwork_insert(struct workhead *, struct jsegdep *);
941 static	void add_to_worklist(struct worklist *, int);
942 static	void wake_worklist(struct worklist *);
943 static	void wait_worklist(struct worklist *, char *);
944 static	void remove_from_worklist(struct worklist *);
945 static	void softdep_flush(void);
946 static	void softdep_flushjournal(struct mount *);
947 static	int softdep_speedup(void);
948 static	void worklist_speedup(void);
949 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
950 static	void journal_unmount(struct mount *);
951 static	int journal_space(struct ufsmount *, int);
952 static	void journal_suspend(struct ufsmount *);
953 static	int journal_unsuspend(struct ufsmount *ump);
954 static	void softdep_prelink(struct vnode *, struct vnode *);
955 static	void add_to_journal(struct worklist *);
956 static	void remove_from_journal(struct worklist *);
957 static	void softdep_process_journal(struct mount *, struct worklist *, int);
958 static	struct jremref *newjremref(struct dirrem *, struct inode *,
959 	    struct inode *ip, off_t, nlink_t);
960 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
961 	    uint16_t);
962 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
963 	    uint16_t);
964 static	inline struct jsegdep *inoref_jseg(struct inoref *);
965 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
966 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
967 	    ufs2_daddr_t, int);
968 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
969 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
970 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
971 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
972 	    ufs2_daddr_t, long, ufs_lbn_t);
973 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
974 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
975 static	int jwait(struct worklist *, int);
976 static	struct inodedep *inodedep_lookup_ip(struct inode *);
977 static	int bmsafemap_rollbacks(struct bmsafemap *);
978 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
979 static	void handle_jwork(struct workhead *);
980 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
981 	    struct mkdir **);
982 static	struct jblocks *jblocks_create(void);
983 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
984 static	void jblocks_free(struct jblocks *, struct mount *, int);
985 static	void jblocks_destroy(struct jblocks *);
986 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
987 
988 /*
989  * Exported softdep operations.
990  */
991 static	void softdep_disk_io_initiation(struct buf *);
992 static	void softdep_disk_write_complete(struct buf *);
993 static	void softdep_deallocate_dependencies(struct buf *);
994 static	int softdep_count_dependencies(struct buf *bp, int);
995 
996 static struct mtx lk;
997 MTX_SYSINIT(softdep_lock, &lk, "Softdep Lock", MTX_DEF);
998 
999 #define TRY_ACQUIRE_LOCK(lk)		mtx_trylock(lk)
1000 #define ACQUIRE_LOCK(lk)		mtx_lock(lk)
1001 #define FREE_LOCK(lk)			mtx_unlock(lk)
1002 
1003 #define	BUF_AREC(bp)			lockallowrecurse(&(bp)->b_lock)
1004 #define	BUF_NOREC(bp)			lockdisablerecurse(&(bp)->b_lock)
1005 
1006 /*
1007  * Worklist queue management.
1008  * These routines require that the lock be held.
1009  */
1010 #ifndef /* NOT */ DEBUG
1011 #define WORKLIST_INSERT(head, item) do {	\
1012 	(item)->wk_state |= ONWORKLIST;		\
1013 	LIST_INSERT_HEAD(head, item, wk_list);	\
1014 } while (0)
1015 #define WORKLIST_REMOVE(item) do {		\
1016 	(item)->wk_state &= ~ONWORKLIST;	\
1017 	LIST_REMOVE(item, wk_list);		\
1018 } while (0)
1019 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1020 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1021 
1022 #else /* DEBUG */
1023 static	void worklist_insert(struct workhead *, struct worklist *, int);
1024 static	void worklist_remove(struct worklist *, int);
1025 
1026 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1027 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1028 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1029 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1030 
1031 static void
1032 worklist_insert(head, item, locked)
1033 	struct workhead *head;
1034 	struct worklist *item;
1035 	int locked;
1036 {
1037 
1038 	if (locked)
1039 		mtx_assert(&lk, MA_OWNED);
1040 	if (item->wk_state & ONWORKLIST)
1041 		panic("worklist_insert: %p %s(0x%X) already on list",
1042 		    item, TYPENAME(item->wk_type), item->wk_state);
1043 	item->wk_state |= ONWORKLIST;
1044 	LIST_INSERT_HEAD(head, item, wk_list);
1045 }
1046 
1047 static void
1048 worklist_remove(item, locked)
1049 	struct worklist *item;
1050 	int locked;
1051 {
1052 
1053 	if (locked)
1054 		mtx_assert(&lk, MA_OWNED);
1055 	if ((item->wk_state & ONWORKLIST) == 0)
1056 		panic("worklist_remove: %p %s(0x%X) not on list",
1057 		    item, TYPENAME(item->wk_type), item->wk_state);
1058 	item->wk_state &= ~ONWORKLIST;
1059 	LIST_REMOVE(item, wk_list);
1060 }
1061 #endif /* DEBUG */
1062 
1063 /*
1064  * Merge two jsegdeps keeping only the oldest one as newer references
1065  * can't be discarded until after older references.
1066  */
1067 static inline struct jsegdep *
1068 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1069 {
1070 	struct jsegdep *swp;
1071 
1072 	if (two == NULL)
1073 		return (one);
1074 
1075 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1076 		swp = one;
1077 		one = two;
1078 		two = swp;
1079 	}
1080 	WORKLIST_REMOVE(&two->jd_list);
1081 	free_jsegdep(two);
1082 
1083 	return (one);
1084 }
1085 
1086 /*
1087  * If two freedeps are compatible free one to reduce list size.
1088  */
1089 static inline struct freedep *
1090 freedep_merge(struct freedep *one, struct freedep *two)
1091 {
1092 	if (two == NULL)
1093 		return (one);
1094 
1095 	if (one->fd_freework == two->fd_freework) {
1096 		WORKLIST_REMOVE(&two->fd_list);
1097 		free_freedep(two);
1098 	}
1099 	return (one);
1100 }
1101 
1102 /*
1103  * Move journal work from one list to another.  Duplicate freedeps and
1104  * jsegdeps are coalesced to keep the lists as small as possible.
1105  */
1106 static void
1107 jwork_move(dst, src)
1108 	struct workhead *dst;
1109 	struct workhead *src;
1110 {
1111 	struct freedep *freedep;
1112 	struct jsegdep *jsegdep;
1113 	struct worklist *wkn;
1114 	struct worklist *wk;
1115 
1116 	KASSERT(dst != src,
1117 	    ("jwork_move: dst == src"));
1118 	freedep = NULL;
1119 	jsegdep = NULL;
1120 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1121 		if (wk->wk_type == D_JSEGDEP)
1122 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1123 		if (wk->wk_type == D_FREEDEP)
1124 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1125 	}
1126 
1127 	mtx_assert(&lk, MA_OWNED);
1128 	while ((wk = LIST_FIRST(src)) != NULL) {
1129 		WORKLIST_REMOVE(wk);
1130 		WORKLIST_INSERT(dst, wk);
1131 		if (wk->wk_type == D_JSEGDEP) {
1132 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1133 			continue;
1134 		}
1135 		if (wk->wk_type == D_FREEDEP)
1136 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1137 	}
1138 }
1139 
1140 static void
1141 jwork_insert(dst, jsegdep)
1142 	struct workhead *dst;
1143 	struct jsegdep *jsegdep;
1144 {
1145 	struct jsegdep *jsegdepn;
1146 	struct worklist *wk;
1147 
1148 	LIST_FOREACH(wk, dst, wk_list)
1149 		if (wk->wk_type == D_JSEGDEP)
1150 			break;
1151 	if (wk == NULL) {
1152 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1153 		return;
1154 	}
1155 	jsegdepn = WK_JSEGDEP(wk);
1156 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1157 		WORKLIST_REMOVE(wk);
1158 		free_jsegdep(jsegdepn);
1159 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1160 	} else
1161 		free_jsegdep(jsegdep);
1162 }
1163 
1164 /*
1165  * Routines for tracking and managing workitems.
1166  */
1167 static	void workitem_free(struct worklist *, int);
1168 static	void workitem_alloc(struct worklist *, int, struct mount *);
1169 
1170 #define	WORKITEM_FREE(item, type) workitem_free((struct worklist *)(item), (type))
1171 
1172 static void
1173 workitem_free(item, type)
1174 	struct worklist *item;
1175 	int type;
1176 {
1177 	struct ufsmount *ump;
1178 	mtx_assert(&lk, MA_OWNED);
1179 
1180 #ifdef DEBUG
1181 	if (item->wk_state & ONWORKLIST)
1182 		panic("workitem_free: %s(0x%X) still on list",
1183 		    TYPENAME(item->wk_type), item->wk_state);
1184 	if (item->wk_type != type)
1185 		panic("workitem_free: type mismatch %s != %s",
1186 		    TYPENAME(item->wk_type), TYPENAME(type));
1187 #endif
1188 	if (item->wk_state & IOWAITING)
1189 		wakeup(item);
1190 	ump = VFSTOUFS(item->wk_mp);
1191 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1192 		wakeup(&ump->softdep_deps);
1193 	dep_current[type]--;
1194 	free(item, DtoM(type));
1195 }
1196 
1197 static void
1198 workitem_alloc(item, type, mp)
1199 	struct worklist *item;
1200 	int type;
1201 	struct mount *mp;
1202 {
1203 	struct ufsmount *ump;
1204 
1205 	item->wk_type = type;
1206 	item->wk_mp = mp;
1207 	item->wk_state = 0;
1208 
1209 	ump = VFSTOUFS(mp);
1210 	ACQUIRE_LOCK(&lk);
1211 	dep_current[type]++;
1212 	dep_total[type]++;
1213 	ump->softdep_deps++;
1214 	ump->softdep_accdeps++;
1215 	FREE_LOCK(&lk);
1216 }
1217 
1218 /*
1219  * Workitem queue management
1220  */
1221 static int max_softdeps;	/* maximum number of structs before slowdown */
1222 static int maxindirdeps = 50;	/* max number of indirdeps before slowdown */
1223 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1224 static int proc_waiting;	/* tracks whether we have a timeout posted */
1225 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1226 static struct callout softdep_callout;
1227 static int req_pending;
1228 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1229 static int req_clear_remove;	/* syncer process flush some freeblks */
1230 
1231 /*
1232  * runtime statistics
1233  */
1234 static int stat_worklist_push;	/* number of worklist cleanups */
1235 static int stat_blk_limit_push;	/* number of times block limit neared */
1236 static int stat_ino_limit_push;	/* number of times inode limit neared */
1237 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1238 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1239 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1240 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1241 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1242 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1243 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1244 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1245 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1246 static int stat_journal_min;	/* Times hit journal min threshold */
1247 static int stat_journal_low;	/* Times hit journal low threshold */
1248 static int stat_journal_wait;	/* Times blocked in jwait(). */
1249 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1250 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1251 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1252 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1253 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1254 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1255 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1256 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1257 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1258 
1259 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1260     &max_softdeps, 0, "");
1261 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1262     &tickdelay, 0, "");
1263 SYSCTL_INT(_debug_softdep, OID_AUTO, maxindirdeps, CTLFLAG_RW,
1264     &maxindirdeps, 0, "");
1265 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1266     &stat_worklist_push, 0,"");
1267 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1268     &stat_blk_limit_push, 0,"");
1269 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1270     &stat_ino_limit_push, 0,"");
1271 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1272     &stat_blk_limit_hit, 0, "");
1273 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1274     &stat_ino_limit_hit, 0, "");
1275 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1276     &stat_sync_limit_hit, 0, "");
1277 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1278     &stat_indir_blk_ptrs, 0, "");
1279 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1280     &stat_inode_bitmap, 0, "");
1281 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1282     &stat_direct_blk_ptrs, 0, "");
1283 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1284     &stat_dir_entry, 0, "");
1285 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1286     &stat_jaddref, 0, "");
1287 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1288     &stat_jnewblk, 0, "");
1289 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1290     &stat_journal_low, 0, "");
1291 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1292     &stat_journal_min, 0, "");
1293 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1294     &stat_journal_wait, 0, "");
1295 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1296     &stat_jwait_filepage, 0, "");
1297 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1298     &stat_jwait_freeblks, 0, "");
1299 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1300     &stat_jwait_inode, 0, "");
1301 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1302     &stat_jwait_newblk, 0, "");
1303 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1304     &stat_cleanup_blkrequests, 0, "");
1305 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1306     &stat_cleanup_inorequests, 0, "");
1307 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1308     &stat_cleanup_high_delay, 0, "");
1309 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1310     &stat_cleanup_retries, 0, "");
1311 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1312     &stat_cleanup_failures, 0, "");
1313 
1314 SYSCTL_DECL(_vfs_ffs);
1315 
1316 LIST_HEAD(bmsafemap_hashhead, bmsafemap) *bmsafemap_hashtbl;
1317 static u_long	bmsafemap_hash;	/* size of hash table - 1 */
1318 
1319 static int compute_summary_at_mount = 0;	/* Whether to recompute the summary at mount time */
1320 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1321 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1322 
1323 static struct proc *softdepproc;
1324 static struct kproc_desc softdep_kp = {
1325 	"softdepflush",
1326 	softdep_flush,
1327 	&softdepproc
1328 };
1329 SYSINIT(sdproc, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start,
1330     &softdep_kp);
1331 
1332 static void
1333 softdep_flush(void)
1334 {
1335 	struct mount *nmp;
1336 	struct mount *mp;
1337 	struct ufsmount *ump;
1338 	struct thread *td;
1339 	int remaining;
1340 	int progress;
1341 	int vfslocked;
1342 
1343 	td = curthread;
1344 	td->td_pflags |= TDP_NORUNNINGBUF;
1345 
1346 	for (;;) {
1347 		kproc_suspend_check(softdepproc);
1348 		vfslocked = VFS_LOCK_GIANT((struct mount *)NULL);
1349 		ACQUIRE_LOCK(&lk);
1350 		/*
1351 		 * If requested, try removing inode or removal dependencies.
1352 		 */
1353 		if (req_clear_inodedeps) {
1354 			clear_inodedeps();
1355 			req_clear_inodedeps -= 1;
1356 			wakeup_one(&proc_waiting);
1357 		}
1358 		if (req_clear_remove) {
1359 			clear_remove();
1360 			req_clear_remove -= 1;
1361 			wakeup_one(&proc_waiting);
1362 		}
1363 		FREE_LOCK(&lk);
1364 		VFS_UNLOCK_GIANT(vfslocked);
1365 		remaining = progress = 0;
1366 		mtx_lock(&mountlist_mtx);
1367 		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp)  {
1368 			nmp = TAILQ_NEXT(mp, mnt_list);
1369 			if (MOUNTEDSOFTDEP(mp) == 0)
1370 				continue;
1371 			if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
1372 				continue;
1373 			vfslocked = VFS_LOCK_GIANT(mp);
1374 			progress += softdep_process_worklist(mp, 0);
1375 			ump = VFSTOUFS(mp);
1376 			remaining += ump->softdep_on_worklist;
1377 			VFS_UNLOCK_GIANT(vfslocked);
1378 			mtx_lock(&mountlist_mtx);
1379 			nmp = TAILQ_NEXT(mp, mnt_list);
1380 			vfs_unbusy(mp);
1381 		}
1382 		mtx_unlock(&mountlist_mtx);
1383 		if (remaining && progress)
1384 			continue;
1385 		ACQUIRE_LOCK(&lk);
1386 		if (!req_pending)
1387 			msleep(&req_pending, &lk, PVM, "sdflush", hz);
1388 		req_pending = 0;
1389 		FREE_LOCK(&lk);
1390 	}
1391 }
1392 
1393 static void
1394 worklist_speedup(void)
1395 {
1396 	mtx_assert(&lk, MA_OWNED);
1397 	if (req_pending == 0) {
1398 		req_pending = 1;
1399 		wakeup(&req_pending);
1400 	}
1401 }
1402 
1403 static int
1404 softdep_speedup(void)
1405 {
1406 
1407 	worklist_speedup();
1408 	bd_speedup();
1409 	return speedup_syncer();
1410 }
1411 
1412 /*
1413  * Add an item to the end of the work queue.
1414  * This routine requires that the lock be held.
1415  * This is the only routine that adds items to the list.
1416  * The following routine is the only one that removes items
1417  * and does so in order from first to last.
1418  */
1419 
1420 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1421 #define	WK_NODELAY	0x0002	/* Process immediately. */
1422 
1423 static void
1424 add_to_worklist(wk, flags)
1425 	struct worklist *wk;
1426 	int flags;
1427 {
1428 	struct ufsmount *ump;
1429 
1430 	mtx_assert(&lk, MA_OWNED);
1431 	ump = VFSTOUFS(wk->wk_mp);
1432 	if (wk->wk_state & ONWORKLIST)
1433 		panic("add_to_worklist: %s(0x%X) already on list",
1434 		    TYPENAME(wk->wk_type), wk->wk_state);
1435 	wk->wk_state |= ONWORKLIST;
1436 	if (ump->softdep_on_worklist == 0) {
1437 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1438 		ump->softdep_worklist_tail = wk;
1439 	} else if (flags & WK_HEAD) {
1440 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1441 	} else {
1442 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1443 		ump->softdep_worklist_tail = wk;
1444 	}
1445 	ump->softdep_on_worklist += 1;
1446 	if (flags & WK_NODELAY)
1447 		worklist_speedup();
1448 }
1449 
1450 /*
1451  * Remove the item to be processed. If we are removing the last
1452  * item on the list, we need to recalculate the tail pointer.
1453  */
1454 static void
1455 remove_from_worklist(wk)
1456 	struct worklist *wk;
1457 {
1458 	struct ufsmount *ump;
1459 
1460 	ump = VFSTOUFS(wk->wk_mp);
1461 	WORKLIST_REMOVE(wk);
1462 	if (ump->softdep_worklist_tail == wk)
1463 		ump->softdep_worklist_tail =
1464 		    (struct worklist *)wk->wk_list.le_prev;
1465 	ump->softdep_on_worklist -= 1;
1466 }
1467 
1468 static void
1469 wake_worklist(wk)
1470 	struct worklist *wk;
1471 {
1472 	if (wk->wk_state & IOWAITING) {
1473 		wk->wk_state &= ~IOWAITING;
1474 		wakeup(wk);
1475 	}
1476 }
1477 
1478 static void
1479 wait_worklist(wk, wmesg)
1480 	struct worklist *wk;
1481 	char *wmesg;
1482 {
1483 
1484 	wk->wk_state |= IOWAITING;
1485 	msleep(wk, &lk, PVM, wmesg, 0);
1486 }
1487 
1488 /*
1489  * Process that runs once per second to handle items in the background queue.
1490  *
1491  * Note that we ensure that everything is done in the order in which they
1492  * appear in the queue. The code below depends on this property to ensure
1493  * that blocks of a file are freed before the inode itself is freed. This
1494  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1495  * until all the old ones have been purged from the dependency lists.
1496  */
1497 int
1498 softdep_process_worklist(mp, full)
1499 	struct mount *mp;
1500 	int full;
1501 {
1502 	int cnt, matchcnt;
1503 	struct ufsmount *ump;
1504 	long starttime;
1505 
1506 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1507 	/*
1508 	 * Record the process identifier of our caller so that we can give
1509 	 * this process preferential treatment in request_cleanup below.
1510 	 */
1511 	matchcnt = 0;
1512 	ump = VFSTOUFS(mp);
1513 	ACQUIRE_LOCK(&lk);
1514 	starttime = time_second;
1515 	softdep_process_journal(mp, NULL, full?MNT_WAIT:0);
1516 	while (ump->softdep_on_worklist > 0) {
1517 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1518 			break;
1519 		else
1520 			matchcnt += cnt;
1521 		/*
1522 		 * If requested, try removing inode or removal dependencies.
1523 		 */
1524 		if (req_clear_inodedeps) {
1525 			clear_inodedeps();
1526 			req_clear_inodedeps -= 1;
1527 			wakeup_one(&proc_waiting);
1528 		}
1529 		if (req_clear_remove) {
1530 			clear_remove();
1531 			req_clear_remove -= 1;
1532 			wakeup_one(&proc_waiting);
1533 		}
1534 		/*
1535 		 * We do not generally want to stop for buffer space, but if
1536 		 * we are really being a buffer hog, we will stop and wait.
1537 		 */
1538 		if (should_yield()) {
1539 			FREE_LOCK(&lk);
1540 			kern_yield(PRI_UNCHANGED);
1541 			bwillwrite();
1542 			ACQUIRE_LOCK(&lk);
1543 		}
1544 		/*
1545 		 * Never allow processing to run for more than one
1546 		 * second. Otherwise the other mountpoints may get
1547 		 * excessively backlogged.
1548 		 */
1549 		if (!full && starttime != time_second)
1550 			break;
1551 	}
1552 	if (full == 0)
1553 		journal_unsuspend(ump);
1554 	FREE_LOCK(&lk);
1555 	return (matchcnt);
1556 }
1557 
1558 /*
1559  * Process all removes associated with a vnode if we are running out of
1560  * journal space.  Any other process which attempts to flush these will
1561  * be unable as we have the vnodes locked.
1562  */
1563 static void
1564 process_removes(vp)
1565 	struct vnode *vp;
1566 {
1567 	struct inodedep *inodedep;
1568 	struct dirrem *dirrem;
1569 	struct mount *mp;
1570 	ino_t inum;
1571 
1572 	mtx_assert(&lk, MA_OWNED);
1573 
1574 	mp = vp->v_mount;
1575 	inum = VTOI(vp)->i_number;
1576 	for (;;) {
1577 top:
1578 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1579 			return;
1580 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1581 			/*
1582 			 * If another thread is trying to lock this vnode
1583 			 * it will fail but we must wait for it to do so
1584 			 * before we can proceed.
1585 			 */
1586 			if (dirrem->dm_state & INPROGRESS) {
1587 				wait_worklist(&dirrem->dm_list, "pwrwait");
1588 				goto top;
1589 			}
1590 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1591 			    (COMPLETE | ONWORKLIST))
1592 				break;
1593 		}
1594 		if (dirrem == NULL)
1595 			return;
1596 		remove_from_worklist(&dirrem->dm_list);
1597 		FREE_LOCK(&lk);
1598 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1599 			panic("process_removes: suspended filesystem");
1600 		handle_workitem_remove(dirrem, 0);
1601 		vn_finished_secondary_write(mp);
1602 		ACQUIRE_LOCK(&lk);
1603 	}
1604 }
1605 
1606 /*
1607  * Process all truncations associated with a vnode if we are running out
1608  * of journal space.  This is called when the vnode lock is already held
1609  * and no other process can clear the truncation.  This function returns
1610  * a value greater than zero if it did any work.
1611  */
1612 static void
1613 process_truncates(vp)
1614 	struct vnode *vp;
1615 {
1616 	struct inodedep *inodedep;
1617 	struct freeblks *freeblks;
1618 	struct mount *mp;
1619 	ino_t inum;
1620 	int cgwait;
1621 
1622 	mtx_assert(&lk, MA_OWNED);
1623 
1624 	mp = vp->v_mount;
1625 	inum = VTOI(vp)->i_number;
1626 	for (;;) {
1627 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1628 			return;
1629 		cgwait = 0;
1630 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1631 			/* Journal entries not yet written.  */
1632 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1633 				jwait(&LIST_FIRST(
1634 				    &freeblks->fb_jblkdephd)->jb_list,
1635 				    MNT_WAIT);
1636 				break;
1637 			}
1638 			/* Another thread is executing this item. */
1639 			if (freeblks->fb_state & INPROGRESS) {
1640 				wait_worklist(&freeblks->fb_list, "ptrwait");
1641 				break;
1642 			}
1643 			/* Freeblks is waiting on a inode write. */
1644 			if ((freeblks->fb_state & COMPLETE) == 0) {
1645 				FREE_LOCK(&lk);
1646 				ffs_update(vp, 1);
1647 				ACQUIRE_LOCK(&lk);
1648 				break;
1649 			}
1650 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1651 			    (ALLCOMPLETE | ONWORKLIST)) {
1652 				remove_from_worklist(&freeblks->fb_list);
1653 				freeblks->fb_state |= INPROGRESS;
1654 				FREE_LOCK(&lk);
1655 				if (vn_start_secondary_write(NULL, &mp,
1656 				    V_NOWAIT))
1657 					panic("process_truncates: "
1658 					    "suspended filesystem");
1659 				handle_workitem_freeblocks(freeblks, 0);
1660 				vn_finished_secondary_write(mp);
1661 				ACQUIRE_LOCK(&lk);
1662 				break;
1663 			}
1664 			if (freeblks->fb_cgwait)
1665 				cgwait++;
1666 		}
1667 		if (cgwait) {
1668 			FREE_LOCK(&lk);
1669 			sync_cgs(mp, MNT_WAIT);
1670 			ffs_sync_snap(mp, MNT_WAIT);
1671 			ACQUIRE_LOCK(&lk);
1672 			continue;
1673 		}
1674 		if (freeblks == NULL)
1675 			break;
1676 	}
1677 	return;
1678 }
1679 
1680 /*
1681  * Process one item on the worklist.
1682  */
1683 static int
1684 process_worklist_item(mp, target, flags)
1685 	struct mount *mp;
1686 	int target;
1687 	int flags;
1688 {
1689 	struct worklist sintenel;
1690 	struct worklist *wk;
1691 	struct ufsmount *ump;
1692 	int matchcnt;
1693 	int error;
1694 
1695 	mtx_assert(&lk, MA_OWNED);
1696 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1697 	/*
1698 	 * If we are being called because of a process doing a
1699 	 * copy-on-write, then it is not safe to write as we may
1700 	 * recurse into the copy-on-write routine.
1701 	 */
1702 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1703 		return (-1);
1704 	PHOLD(curproc);	/* Don't let the stack go away. */
1705 	ump = VFSTOUFS(mp);
1706 	matchcnt = 0;
1707 	sintenel.wk_mp = NULL;
1708 	sintenel.wk_type = D_SENTINAL;
1709 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sintenel, wk_list);
1710 	for (wk = LIST_NEXT(&sintenel, wk_list); wk != NULL;
1711 	    wk = LIST_NEXT(&sintenel, wk_list)) {
1712 		if (wk->wk_type == D_SENTINAL) {
1713 			LIST_REMOVE(&sintenel, wk_list);
1714 			LIST_INSERT_AFTER(wk, &sintenel, wk_list);
1715 			continue;
1716 		}
1717 		if (wk->wk_state & INPROGRESS)
1718 			panic("process_worklist_item: %p already in progress.",
1719 			    wk);
1720 		wk->wk_state |= INPROGRESS;
1721 		remove_from_worklist(wk);
1722 		FREE_LOCK(&lk);
1723 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1724 			panic("process_worklist_item: suspended filesystem");
1725 		switch (wk->wk_type) {
1726 		case D_DIRREM:
1727 			/* removal of a directory entry */
1728 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1729 			break;
1730 
1731 		case D_FREEBLKS:
1732 			/* releasing blocks and/or fragments from a file */
1733 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1734 			    flags);
1735 			break;
1736 
1737 		case D_FREEFRAG:
1738 			/* releasing a fragment when replaced as a file grows */
1739 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1740 			error = 0;
1741 			break;
1742 
1743 		case D_FREEFILE:
1744 			/* releasing an inode when its link count drops to 0 */
1745 			handle_workitem_freefile(WK_FREEFILE(wk));
1746 			error = 0;
1747 			break;
1748 
1749 		default:
1750 			panic("%s_process_worklist: Unknown type %s",
1751 			    "softdep", TYPENAME(wk->wk_type));
1752 			/* NOTREACHED */
1753 		}
1754 		vn_finished_secondary_write(mp);
1755 		ACQUIRE_LOCK(&lk);
1756 		if (error == 0) {
1757 			if (++matchcnt == target)
1758 				break;
1759 			continue;
1760 		}
1761 		/*
1762 		 * We have to retry the worklist item later.  Wake up any
1763 		 * waiters who may be able to complete it immediately and
1764 		 * add the item back to the head so we don't try to execute
1765 		 * it again.
1766 		 */
1767 		wk->wk_state &= ~INPROGRESS;
1768 		wake_worklist(wk);
1769 		add_to_worklist(wk, WK_HEAD);
1770 	}
1771 	LIST_REMOVE(&sintenel, wk_list);
1772 	/* Sentinal could've become the tail from remove_from_worklist. */
1773 	if (ump->softdep_worklist_tail == &sintenel)
1774 		ump->softdep_worklist_tail =
1775 		    (struct worklist *)sintenel.wk_list.le_prev;
1776 	PRELE(curproc);
1777 	return (matchcnt);
1778 }
1779 
1780 /*
1781  * Move dependencies from one buffer to another.
1782  */
1783 int
1784 softdep_move_dependencies(oldbp, newbp)
1785 	struct buf *oldbp;
1786 	struct buf *newbp;
1787 {
1788 	struct worklist *wk, *wktail;
1789 	int dirty;
1790 
1791 	dirty = 0;
1792 	wktail = NULL;
1793 	ACQUIRE_LOCK(&lk);
1794 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1795 		LIST_REMOVE(wk, wk_list);
1796 		if (wk->wk_type == D_BMSAFEMAP &&
1797 		    bmsafemap_rollbacks(WK_BMSAFEMAP(wk)))
1798 			dirty = 1;
1799 		if (wktail == 0)
1800 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1801 		else
1802 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1803 		wktail = wk;
1804 	}
1805 	FREE_LOCK(&lk);
1806 
1807 	return (dirty);
1808 }
1809 
1810 /*
1811  * Purge the work list of all items associated with a particular mount point.
1812  */
1813 int
1814 softdep_flushworklist(oldmnt, countp, td)
1815 	struct mount *oldmnt;
1816 	int *countp;
1817 	struct thread *td;
1818 {
1819 	struct vnode *devvp;
1820 	int count, error = 0;
1821 	struct ufsmount *ump;
1822 
1823 	/*
1824 	 * Alternately flush the block device associated with the mount
1825 	 * point and process any dependencies that the flushing
1826 	 * creates. We continue until no more worklist dependencies
1827 	 * are found.
1828 	 */
1829 	*countp = 0;
1830 	ump = VFSTOUFS(oldmnt);
1831 	devvp = ump->um_devvp;
1832 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1833 		*countp += count;
1834 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1835 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1836 		VOP_UNLOCK(devvp, 0);
1837 		if (error)
1838 			break;
1839 	}
1840 	return (error);
1841 }
1842 
1843 int
1844 softdep_waitidle(struct mount *mp)
1845 {
1846 	struct ufsmount *ump;
1847 	int error;
1848 	int i;
1849 
1850 	ump = VFSTOUFS(mp);
1851 	ACQUIRE_LOCK(&lk);
1852 	for (i = 0; i < 10 && ump->softdep_deps; i++) {
1853 		ump->softdep_req = 1;
1854 		if (ump->softdep_on_worklist)
1855 			panic("softdep_waitidle: work added after flush.");
1856 		msleep(&ump->softdep_deps, &lk, PVM, "softdeps", 1);
1857 	}
1858 	ump->softdep_req = 0;
1859 	FREE_LOCK(&lk);
1860 	error = 0;
1861 	if (i == 10) {
1862 		error = EBUSY;
1863 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1864 		    mp);
1865 	}
1866 
1867 	return (error);
1868 }
1869 
1870 /*
1871  * Flush all vnodes and worklist items associated with a specified mount point.
1872  */
1873 int
1874 softdep_flushfiles(oldmnt, flags, td)
1875 	struct mount *oldmnt;
1876 	int flags;
1877 	struct thread *td;
1878 {
1879 	int error, depcount, loopcnt, retry_flush_count, retry;
1880 
1881 	loopcnt = 10;
1882 	retry_flush_count = 3;
1883 retry_flush:
1884 	error = 0;
1885 
1886 	/*
1887 	 * Alternately flush the vnodes associated with the mount
1888 	 * point and process any dependencies that the flushing
1889 	 * creates. In theory, this loop can happen at most twice,
1890 	 * but we give it a few extra just to be sure.
1891 	 */
1892 	for (; loopcnt > 0; loopcnt--) {
1893 		/*
1894 		 * Do another flush in case any vnodes were brought in
1895 		 * as part of the cleanup operations.
1896 		 */
1897 		if ((error = ffs_flushfiles(oldmnt, flags, td)) != 0)
1898 			break;
1899 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1900 		    depcount == 0)
1901 			break;
1902 	}
1903 	/*
1904 	 * If we are unmounting then it is an error to fail. If we
1905 	 * are simply trying to downgrade to read-only, then filesystem
1906 	 * activity can keep us busy forever, so we just fail with EBUSY.
1907 	 */
1908 	if (loopcnt == 0) {
1909 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
1910 			panic("softdep_flushfiles: looping");
1911 		error = EBUSY;
1912 	}
1913 	if (!error)
1914 		error = softdep_waitidle(oldmnt);
1915 	if (!error) {
1916 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
1917 			retry = 0;
1918 			MNT_ILOCK(oldmnt);
1919 			KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
1920 			    ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
1921 			if (oldmnt->mnt_nvnodelistsize > 0) {
1922 				if (--retry_flush_count > 0) {
1923 					retry = 1;
1924 					loopcnt = 3;
1925 				} else
1926 					error = EBUSY;
1927 			}
1928 			MNT_IUNLOCK(oldmnt);
1929 			if (retry)
1930 				goto retry_flush;
1931 		}
1932 	}
1933 	return (error);
1934 }
1935 
1936 /*
1937  * Structure hashing.
1938  *
1939  * There are three types of structures that can be looked up:
1940  *	1) pagedep structures identified by mount point, inode number,
1941  *	   and logical block.
1942  *	2) inodedep structures identified by mount point and inode number.
1943  *	3) newblk structures identified by mount point and
1944  *	   physical block number.
1945  *
1946  * The "pagedep" and "inodedep" dependency structures are hashed
1947  * separately from the file blocks and inodes to which they correspond.
1948  * This separation helps when the in-memory copy of an inode or
1949  * file block must be replaced. It also obviates the need to access
1950  * an inode or file page when simply updating (or de-allocating)
1951  * dependency structures. Lookup of newblk structures is needed to
1952  * find newly allocated blocks when trying to associate them with
1953  * their allocdirect or allocindir structure.
1954  *
1955  * The lookup routines optionally create and hash a new instance when
1956  * an existing entry is not found.
1957  */
1958 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
1959 #define NODELAY		0x0002	/* cannot do background work */
1960 
1961 /*
1962  * Structures and routines associated with pagedep caching.
1963  */
1964 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
1965 u_long	pagedep_hash;		/* size of hash table - 1 */
1966 #define	PAGEDEP_HASH(mp, inum, lbn) \
1967 	(&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
1968 	    pagedep_hash])
1969 
1970 static int
1971 pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp)
1972 	struct pagedep_hashhead *pagedephd;
1973 	ino_t ino;
1974 	ufs_lbn_t lbn;
1975 	struct mount *mp;
1976 	int flags;
1977 	struct pagedep **pagedeppp;
1978 {
1979 	struct pagedep *pagedep;
1980 
1981 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
1982 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn &&
1983 		    mp == pagedep->pd_list.wk_mp) {
1984 			*pagedeppp = pagedep;
1985 			return (1);
1986 		}
1987 	}
1988 	*pagedeppp = NULL;
1989 	return (0);
1990 }
1991 /*
1992  * Look up a pagedep. Return 1 if found, 0 otherwise.
1993  * If not found, allocate if DEPALLOC flag is passed.
1994  * Found or allocated entry is returned in pagedeppp.
1995  * This routine must be called with splbio interrupts blocked.
1996  */
1997 static int
1998 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
1999 	struct mount *mp;
2000 	struct buf *bp;
2001 	ino_t ino;
2002 	ufs_lbn_t lbn;
2003 	int flags;
2004 	struct pagedep **pagedeppp;
2005 {
2006 	struct pagedep *pagedep;
2007 	struct pagedep_hashhead *pagedephd;
2008 	struct worklist *wk;
2009 	int ret;
2010 	int i;
2011 
2012 	mtx_assert(&lk, MA_OWNED);
2013 	if (bp) {
2014 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2015 			if (wk->wk_type == D_PAGEDEP) {
2016 				*pagedeppp = WK_PAGEDEP(wk);
2017 				return (1);
2018 			}
2019 		}
2020 	}
2021 	pagedephd = PAGEDEP_HASH(mp, ino, lbn);
2022 	ret = pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp);
2023 	if (ret) {
2024 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2025 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2026 		return (1);
2027 	}
2028 	if ((flags & DEPALLOC) == 0)
2029 		return (0);
2030 	FREE_LOCK(&lk);
2031 	pagedep = malloc(sizeof(struct pagedep),
2032 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2033 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2034 	ACQUIRE_LOCK(&lk);
2035 	ret = pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp);
2036 	if (*pagedeppp) {
2037 		/*
2038 		 * This should never happen since we only create pagedeps
2039 		 * with the vnode lock held.  Could be an assert.
2040 		 */
2041 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2042 		return (ret);
2043 	}
2044 	pagedep->pd_ino = ino;
2045 	pagedep->pd_lbn = lbn;
2046 	LIST_INIT(&pagedep->pd_dirremhd);
2047 	LIST_INIT(&pagedep->pd_pendinghd);
2048 	for (i = 0; i < DAHASHSZ; i++)
2049 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2050 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2051 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2052 	*pagedeppp = pagedep;
2053 	return (0);
2054 }
2055 
2056 /*
2057  * Structures and routines associated with inodedep caching.
2058  */
2059 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
2060 static u_long	inodedep_hash;	/* size of hash table - 1 */
2061 #define	INODEDEP_HASH(fs, inum) \
2062       (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
2063 
2064 static int
2065 inodedep_find(inodedephd, fs, inum, inodedeppp)
2066 	struct inodedep_hashhead *inodedephd;
2067 	struct fs *fs;
2068 	ino_t inum;
2069 	struct inodedep **inodedeppp;
2070 {
2071 	struct inodedep *inodedep;
2072 
2073 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2074 		if (inum == inodedep->id_ino && fs == inodedep->id_fs)
2075 			break;
2076 	if (inodedep) {
2077 		*inodedeppp = inodedep;
2078 		return (1);
2079 	}
2080 	*inodedeppp = NULL;
2081 
2082 	return (0);
2083 }
2084 /*
2085  * Look up an inodedep. Return 1 if found, 0 if not found.
2086  * If not found, allocate if DEPALLOC flag is passed.
2087  * Found or allocated entry is returned in inodedeppp.
2088  * This routine must be called with splbio interrupts blocked.
2089  */
2090 static int
2091 inodedep_lookup(mp, inum, flags, inodedeppp)
2092 	struct mount *mp;
2093 	ino_t inum;
2094 	int flags;
2095 	struct inodedep **inodedeppp;
2096 {
2097 	struct inodedep *inodedep;
2098 	struct inodedep_hashhead *inodedephd;
2099 	struct fs *fs;
2100 
2101 	mtx_assert(&lk, MA_OWNED);
2102 	fs = VFSTOUFS(mp)->um_fs;
2103 	inodedephd = INODEDEP_HASH(fs, inum);
2104 
2105 	if (inodedep_find(inodedephd, fs, inum, inodedeppp))
2106 		return (1);
2107 	if ((flags & DEPALLOC) == 0)
2108 		return (0);
2109 	/*
2110 	 * If we are over our limit, try to improve the situation.
2111 	 */
2112 	if (dep_current[D_INODEDEP] > max_softdeps && (flags & NODELAY) == 0)
2113 		request_cleanup(mp, FLUSH_INODES);
2114 	FREE_LOCK(&lk);
2115 	inodedep = malloc(sizeof(struct inodedep),
2116 		M_INODEDEP, M_SOFTDEP_FLAGS);
2117 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2118 	ACQUIRE_LOCK(&lk);
2119 	if (inodedep_find(inodedephd, fs, inum, inodedeppp)) {
2120 		WORKITEM_FREE(inodedep, D_INODEDEP);
2121 		return (1);
2122 	}
2123 	inodedep->id_fs = fs;
2124 	inodedep->id_ino = inum;
2125 	inodedep->id_state = ALLCOMPLETE;
2126 	inodedep->id_nlinkdelta = 0;
2127 	inodedep->id_savedino1 = NULL;
2128 	inodedep->id_savedsize = -1;
2129 	inodedep->id_savedextsize = -1;
2130 	inodedep->id_savednlink = -1;
2131 	inodedep->id_bmsafemap = NULL;
2132 	inodedep->id_mkdiradd = NULL;
2133 	LIST_INIT(&inodedep->id_dirremhd);
2134 	LIST_INIT(&inodedep->id_pendinghd);
2135 	LIST_INIT(&inodedep->id_inowait);
2136 	LIST_INIT(&inodedep->id_bufwait);
2137 	TAILQ_INIT(&inodedep->id_inoreflst);
2138 	TAILQ_INIT(&inodedep->id_inoupdt);
2139 	TAILQ_INIT(&inodedep->id_newinoupdt);
2140 	TAILQ_INIT(&inodedep->id_extupdt);
2141 	TAILQ_INIT(&inodedep->id_newextupdt);
2142 	TAILQ_INIT(&inodedep->id_freeblklst);
2143 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2144 	*inodedeppp = inodedep;
2145 	return (0);
2146 }
2147 
2148 /*
2149  * Structures and routines associated with newblk caching.
2150  */
2151 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
2152 u_long	newblk_hash;		/* size of hash table - 1 */
2153 #define	NEWBLK_HASH(fs, inum) \
2154 	(&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
2155 
2156 static int
2157 newblk_find(newblkhd, mp, newblkno, flags, newblkpp)
2158 	struct newblk_hashhead *newblkhd;
2159 	struct mount *mp;
2160 	ufs2_daddr_t newblkno;
2161 	int flags;
2162 	struct newblk **newblkpp;
2163 {
2164 	struct newblk *newblk;
2165 
2166 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2167 		if (newblkno != newblk->nb_newblkno)
2168 			continue;
2169 		if (mp != newblk->nb_list.wk_mp)
2170 			continue;
2171 		/*
2172 		 * If we're creating a new dependency don't match those that
2173 		 * have already been converted to allocdirects.  This is for
2174 		 * a frag extend.
2175 		 */
2176 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2177 			continue;
2178 		break;
2179 	}
2180 	if (newblk) {
2181 		*newblkpp = newblk;
2182 		return (1);
2183 	}
2184 	*newblkpp = NULL;
2185 	return (0);
2186 }
2187 
2188 /*
2189  * Look up a newblk. Return 1 if found, 0 if not found.
2190  * If not found, allocate if DEPALLOC flag is passed.
2191  * Found or allocated entry is returned in newblkpp.
2192  */
2193 static int
2194 newblk_lookup(mp, newblkno, flags, newblkpp)
2195 	struct mount *mp;
2196 	ufs2_daddr_t newblkno;
2197 	int flags;
2198 	struct newblk **newblkpp;
2199 {
2200 	struct newblk *newblk;
2201 	struct newblk_hashhead *newblkhd;
2202 
2203 	newblkhd = NEWBLK_HASH(VFSTOUFS(mp)->um_fs, newblkno);
2204 	if (newblk_find(newblkhd, mp, newblkno, flags, newblkpp))
2205 		return (1);
2206 	if ((flags & DEPALLOC) == 0)
2207 		return (0);
2208 	FREE_LOCK(&lk);
2209 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2210 	    M_SOFTDEP_FLAGS | M_ZERO);
2211 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2212 	ACQUIRE_LOCK(&lk);
2213 	if (newblk_find(newblkhd, mp, newblkno, flags, newblkpp)) {
2214 		WORKITEM_FREE(newblk, D_NEWBLK);
2215 		return (1);
2216 	}
2217 	newblk->nb_freefrag = NULL;
2218 	LIST_INIT(&newblk->nb_indirdeps);
2219 	LIST_INIT(&newblk->nb_newdirblk);
2220 	LIST_INIT(&newblk->nb_jwork);
2221 	newblk->nb_state = ATTACHED;
2222 	newblk->nb_newblkno = newblkno;
2223 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2224 	*newblkpp = newblk;
2225 	return (0);
2226 }
2227 
2228 /*
2229  * Structures and routines associated with freed indirect block caching.
2230  */
2231 struct freeworklst *indir_hashtbl;
2232 u_long	indir_hash;		/* size of hash table - 1 */
2233 #define	INDIR_HASH(mp, blkno) \
2234 	(&indir_hashtbl[((((register_t)(mp)) >> 13) + (blkno)) & indir_hash])
2235 
2236 /*
2237  * Lookup an indirect block in the indir hash table.  The freework is
2238  * removed and potentially freed.  The caller must do a blocking journal
2239  * write before writing to the blkno.
2240  */
2241 static int
2242 indirblk_lookup(mp, blkno)
2243 	struct mount *mp;
2244 	ufs2_daddr_t blkno;
2245 {
2246 	struct freework *freework;
2247 	struct freeworklst *wkhd;
2248 
2249 	wkhd = INDIR_HASH(mp, blkno);
2250 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2251 		if (freework->fw_blkno != blkno)
2252 			continue;
2253 		if (freework->fw_list.wk_mp != mp)
2254 			continue;
2255 		indirblk_remove(freework);
2256 		return (1);
2257 	}
2258 	return (0);
2259 }
2260 
2261 /*
2262  * Insert an indirect block represented by freework into the indirblk
2263  * hash table so that it may prevent the block from being re-used prior
2264  * to the journal being written.
2265  */
2266 static void
2267 indirblk_insert(freework)
2268 	struct freework *freework;
2269 {
2270 	struct freeblks *freeblks;
2271 	struct jsegdep *jsegdep;
2272 	struct worklist *wk;
2273 
2274 	freeblks = freework->fw_freeblks;
2275 	LIST_FOREACH(wk, &freeblks->fb_jwork, wk_list)
2276 		if (wk->wk_type == D_JSEGDEP)
2277 			break;
2278 	if (wk == NULL)
2279 		return;
2280 
2281 	jsegdep = WK_JSEGDEP(wk);
2282 	LIST_INSERT_HEAD(&jsegdep->jd_seg->js_indirs, freework, fw_segs);
2283 	TAILQ_INSERT_HEAD(INDIR_HASH(freework->fw_list.wk_mp,
2284 	    freework->fw_blkno), freework, fw_next);
2285 	freework->fw_state &= ~DEPCOMPLETE;
2286 }
2287 
2288 static void
2289 indirblk_remove(freework)
2290 	struct freework *freework;
2291 {
2292 
2293 	LIST_REMOVE(freework, fw_segs);
2294 	TAILQ_REMOVE(INDIR_HASH(freework->fw_list.wk_mp,
2295 	    freework->fw_blkno), freework, fw_next);
2296 	freework->fw_state |= DEPCOMPLETE;
2297 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2298 		WORKITEM_FREE(freework, D_FREEWORK);
2299 }
2300 
2301 /*
2302  * Executed during filesystem system initialization before
2303  * mounting any filesystems.
2304  */
2305 void
2306 softdep_initialize()
2307 {
2308 	int i;
2309 
2310 	LIST_INIT(&mkdirlisthd);
2311 	max_softdeps = desiredvnodes * 4;
2312 	pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP, &pagedep_hash);
2313 	inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
2314 	newblk_hashtbl = hashinit(desiredvnodes / 5,  M_NEWBLK, &newblk_hash);
2315 	bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP, &bmsafemap_hash);
2316 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2317 	indir_hashtbl = malloc(i * sizeof(indir_hashtbl[0]), M_FREEWORK,
2318 	    M_WAITOK);
2319 	indir_hash = i - 1;
2320 	for (i = 0; i <= indir_hash; i++)
2321 		TAILQ_INIT(&indir_hashtbl[i]);
2322 
2323 	/* initialise bioops hack */
2324 	bioops.io_start = softdep_disk_io_initiation;
2325 	bioops.io_complete = softdep_disk_write_complete;
2326 	bioops.io_deallocate = softdep_deallocate_dependencies;
2327 	bioops.io_countdeps = softdep_count_dependencies;
2328 
2329 	/* Initialize the callout with an mtx. */
2330 	callout_init_mtx(&softdep_callout, &lk, 0);
2331 }
2332 
2333 /*
2334  * Executed after all filesystems have been unmounted during
2335  * filesystem module unload.
2336  */
2337 void
2338 softdep_uninitialize()
2339 {
2340 
2341 	callout_drain(&softdep_callout);
2342 	hashdestroy(pagedep_hashtbl, M_PAGEDEP, pagedep_hash);
2343 	hashdestroy(inodedep_hashtbl, M_INODEDEP, inodedep_hash);
2344 	hashdestroy(newblk_hashtbl, M_NEWBLK, newblk_hash);
2345 	hashdestroy(bmsafemap_hashtbl, M_BMSAFEMAP, bmsafemap_hash);
2346 	free(indir_hashtbl, M_FREEWORK);
2347 }
2348 
2349 /*
2350  * Called at mount time to notify the dependency code that a
2351  * filesystem wishes to use it.
2352  */
2353 int
2354 softdep_mount(devvp, mp, fs, cred)
2355 	struct vnode *devvp;
2356 	struct mount *mp;
2357 	struct fs *fs;
2358 	struct ucred *cred;
2359 {
2360 	struct csum_total cstotal;
2361 	struct ufsmount *ump;
2362 	struct cg *cgp;
2363 	struct buf *bp;
2364 	int error, cyl;
2365 
2366 	MNT_ILOCK(mp);
2367 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2368 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2369 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2370 			MNTK_SOFTDEP | MNTK_NOASYNC;
2371 	}
2372 	MNT_IUNLOCK(mp);
2373 	ump = VFSTOUFS(mp);
2374 	LIST_INIT(&ump->softdep_workitem_pending);
2375 	LIST_INIT(&ump->softdep_journal_pending);
2376 	TAILQ_INIT(&ump->softdep_unlinked);
2377 	LIST_INIT(&ump->softdep_dirtycg);
2378 	ump->softdep_worklist_tail = NULL;
2379 	ump->softdep_on_worklist = 0;
2380 	ump->softdep_deps = 0;
2381 	if ((fs->fs_flags & FS_SUJ) &&
2382 	    (error = journal_mount(mp, fs, cred)) != 0) {
2383 		printf("Failed to start journal: %d\n", error);
2384 		return (error);
2385 	}
2386 	/*
2387 	 * When doing soft updates, the counters in the
2388 	 * superblock may have gotten out of sync. Recomputation
2389 	 * can take a long time and can be deferred for background
2390 	 * fsck.  However, the old behavior of scanning the cylinder
2391 	 * groups and recalculating them at mount time is available
2392 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2393 	 */
2394 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2395 		return (0);
2396 	bzero(&cstotal, sizeof cstotal);
2397 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2398 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2399 		    fs->fs_cgsize, cred, &bp)) != 0) {
2400 			brelse(bp);
2401 			return (error);
2402 		}
2403 		cgp = (struct cg *)bp->b_data;
2404 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2405 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2406 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2407 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2408 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2409 		brelse(bp);
2410 	}
2411 #ifdef DEBUG
2412 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2413 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2414 #endif
2415 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2416 	return (0);
2417 }
2418 
2419 void
2420 softdep_unmount(mp)
2421 	struct mount *mp;
2422 {
2423 
2424 	MNT_ILOCK(mp);
2425 	mp->mnt_flag &= ~MNT_SOFTDEP;
2426 	if (MOUNTEDSUJ(mp) == 0) {
2427 		MNT_IUNLOCK(mp);
2428 		return;
2429 	}
2430 	mp->mnt_flag &= ~MNT_SUJ;
2431 	MNT_IUNLOCK(mp);
2432 	journal_unmount(mp);
2433 }
2434 
2435 struct jblocks {
2436 	struct jseglst	jb_segs;	/* TAILQ of current segments. */
2437 	struct jseg	*jb_writeseg;	/* Next write to complete. */
2438 	struct jseg	*jb_oldestseg;	/* Oldest segment with valid entries. */
2439 	struct jextent	*jb_extent;	/* Extent array. */
2440 	uint64_t	jb_nextseq;	/* Next sequence number. */
2441 	uint64_t	jb_oldestwrseq;	/* Oldest written sequence number. */
2442 	uint8_t		jb_needseg;	/* Need a forced segment. */
2443 	uint8_t		jb_suspended;	/* Did journal suspend writes? */
2444 	int		jb_avail;	/* Available extents. */
2445 	int		jb_used;	/* Last used extent. */
2446 	int		jb_head;	/* Allocator head. */
2447 	int		jb_off;		/* Allocator extent offset. */
2448 	int		jb_blocks;	/* Total disk blocks covered. */
2449 	int		jb_free;	/* Total disk blocks free. */
2450 	int		jb_min;		/* Minimum free space. */
2451 	int		jb_low;		/* Low on space. */
2452 	int		jb_age;		/* Insertion time of oldest rec. */
2453 };
2454 
2455 struct jextent {
2456 	ufs2_daddr_t	je_daddr;	/* Disk block address. */
2457 	int		je_blocks;	/* Disk block count. */
2458 };
2459 
2460 static struct jblocks *
2461 jblocks_create(void)
2462 {
2463 	struct jblocks *jblocks;
2464 
2465 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2466 	TAILQ_INIT(&jblocks->jb_segs);
2467 	jblocks->jb_avail = 10;
2468 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2469 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2470 
2471 	return (jblocks);
2472 }
2473 
2474 static ufs2_daddr_t
2475 jblocks_alloc(jblocks, bytes, actual)
2476 	struct jblocks *jblocks;
2477 	int bytes;
2478 	int *actual;
2479 {
2480 	ufs2_daddr_t daddr;
2481 	struct jextent *jext;
2482 	int freecnt;
2483 	int blocks;
2484 
2485 	blocks = bytes / DEV_BSIZE;
2486 	jext = &jblocks->jb_extent[jblocks->jb_head];
2487 	freecnt = jext->je_blocks - jblocks->jb_off;
2488 	if (freecnt == 0) {
2489 		jblocks->jb_off = 0;
2490 		if (++jblocks->jb_head > jblocks->jb_used)
2491 			jblocks->jb_head = 0;
2492 		jext = &jblocks->jb_extent[jblocks->jb_head];
2493 		freecnt = jext->je_blocks;
2494 	}
2495 	if (freecnt > blocks)
2496 		freecnt = blocks;
2497 	*actual = freecnt * DEV_BSIZE;
2498 	daddr = jext->je_daddr + jblocks->jb_off;
2499 	jblocks->jb_off += freecnt;
2500 	jblocks->jb_free -= freecnt;
2501 
2502 	return (daddr);
2503 }
2504 
2505 static void
2506 jblocks_free(jblocks, mp, bytes)
2507 	struct jblocks *jblocks;
2508 	struct mount *mp;
2509 	int bytes;
2510 {
2511 
2512 	jblocks->jb_free += bytes / DEV_BSIZE;
2513 	if (jblocks->jb_suspended)
2514 		worklist_speedup();
2515 	wakeup(jblocks);
2516 }
2517 
2518 static void
2519 jblocks_destroy(jblocks)
2520 	struct jblocks *jblocks;
2521 {
2522 
2523 	if (jblocks->jb_extent)
2524 		free(jblocks->jb_extent, M_JBLOCKS);
2525 	free(jblocks, M_JBLOCKS);
2526 }
2527 
2528 static void
2529 jblocks_add(jblocks, daddr, blocks)
2530 	struct jblocks *jblocks;
2531 	ufs2_daddr_t daddr;
2532 	int blocks;
2533 {
2534 	struct jextent *jext;
2535 
2536 	jblocks->jb_blocks += blocks;
2537 	jblocks->jb_free += blocks;
2538 	jext = &jblocks->jb_extent[jblocks->jb_used];
2539 	/* Adding the first block. */
2540 	if (jext->je_daddr == 0) {
2541 		jext->je_daddr = daddr;
2542 		jext->je_blocks = blocks;
2543 		return;
2544 	}
2545 	/* Extending the last extent. */
2546 	if (jext->je_daddr + jext->je_blocks == daddr) {
2547 		jext->je_blocks += blocks;
2548 		return;
2549 	}
2550 	/* Adding a new extent. */
2551 	if (++jblocks->jb_used == jblocks->jb_avail) {
2552 		jblocks->jb_avail *= 2;
2553 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2554 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2555 		memcpy(jext, jblocks->jb_extent,
2556 		    sizeof(struct jextent) * jblocks->jb_used);
2557 		free(jblocks->jb_extent, M_JBLOCKS);
2558 		jblocks->jb_extent = jext;
2559 	}
2560 	jext = &jblocks->jb_extent[jblocks->jb_used];
2561 	jext->je_daddr = daddr;
2562 	jext->je_blocks = blocks;
2563 	return;
2564 }
2565 
2566 int
2567 softdep_journal_lookup(mp, vpp)
2568 	struct mount *mp;
2569 	struct vnode **vpp;
2570 {
2571 	struct componentname cnp;
2572 	struct vnode *dvp;
2573 	ino_t sujournal;
2574 	int error;
2575 
2576 	error = VFS_VGET(mp, ROOTINO, LK_EXCLUSIVE, &dvp);
2577 	if (error)
2578 		return (error);
2579 	bzero(&cnp, sizeof(cnp));
2580 	cnp.cn_nameiop = LOOKUP;
2581 	cnp.cn_flags = ISLASTCN;
2582 	cnp.cn_thread = curthread;
2583 	cnp.cn_cred = curthread->td_ucred;
2584 	cnp.cn_pnbuf = SUJ_FILE;
2585 	cnp.cn_nameptr = SUJ_FILE;
2586 	cnp.cn_namelen = strlen(SUJ_FILE);
2587 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2588 	vput(dvp);
2589 	if (error != 0)
2590 		return (error);
2591 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2592 	return (error);
2593 }
2594 
2595 /*
2596  * Open and verify the journal file.
2597  */
2598 static int
2599 journal_mount(mp, fs, cred)
2600 	struct mount *mp;
2601 	struct fs *fs;
2602 	struct ucred *cred;
2603 {
2604 	struct jblocks *jblocks;
2605 	struct vnode *vp;
2606 	struct inode *ip;
2607 	ufs2_daddr_t blkno;
2608 	int bcount;
2609 	int error;
2610 	int i;
2611 
2612 	error = softdep_journal_lookup(mp, &vp);
2613 	if (error != 0) {
2614 		printf("Failed to find journal.  Use tunefs to create one\n");
2615 		return (error);
2616 	}
2617 	ip = VTOI(vp);
2618 	if (ip->i_size < SUJ_MIN) {
2619 		error = ENOSPC;
2620 		goto out;
2621 	}
2622 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2623 	jblocks = jblocks_create();
2624 	for (i = 0; i < bcount; i++) {
2625 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2626 		if (error)
2627 			break;
2628 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2629 	}
2630 	if (error) {
2631 		jblocks_destroy(jblocks);
2632 		goto out;
2633 	}
2634 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2635 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2636 	VFSTOUFS(mp)->softdep_jblocks = jblocks;
2637 out:
2638 	if (error == 0) {
2639 		MNT_ILOCK(mp);
2640 		mp->mnt_flag |= MNT_SUJ;
2641 		mp->mnt_flag &= ~MNT_SOFTDEP;
2642 		MNT_IUNLOCK(mp);
2643 		/*
2644 		 * Only validate the journal contents if the
2645 		 * filesystem is clean, otherwise we write the logs
2646 		 * but they'll never be used.  If the filesystem was
2647 		 * still dirty when we mounted it the journal is
2648 		 * invalid and a new journal can only be valid if it
2649 		 * starts from a clean mount.
2650 		 */
2651 		if (fs->fs_clean) {
2652 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2653 			ip->i_flags |= IN_MODIFIED;
2654 			ffs_update(vp, 1);
2655 		}
2656 	}
2657 	vput(vp);
2658 	return (error);
2659 }
2660 
2661 static void
2662 journal_unmount(mp)
2663 	struct mount *mp;
2664 {
2665 	struct ufsmount *ump;
2666 
2667 	ump = VFSTOUFS(mp);
2668 	if (ump->softdep_jblocks)
2669 		jblocks_destroy(ump->softdep_jblocks);
2670 	ump->softdep_jblocks = NULL;
2671 }
2672 
2673 /*
2674  * Called when a journal record is ready to be written.  Space is allocated
2675  * and the journal entry is created when the journal is flushed to stable
2676  * store.
2677  */
2678 static void
2679 add_to_journal(wk)
2680 	struct worklist *wk;
2681 {
2682 	struct ufsmount *ump;
2683 
2684 	mtx_assert(&lk, MA_OWNED);
2685 	ump = VFSTOUFS(wk->wk_mp);
2686 	if (wk->wk_state & ONWORKLIST)
2687 		panic("add_to_journal: %s(0x%X) already on list",
2688 		    TYPENAME(wk->wk_type), wk->wk_state);
2689 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2690 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2691 		ump->softdep_jblocks->jb_age = ticks;
2692 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2693 	} else
2694 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2695 	ump->softdep_journal_tail = wk;
2696 	ump->softdep_on_journal += 1;
2697 }
2698 
2699 /*
2700  * Remove an arbitrary item for the journal worklist maintain the tail
2701  * pointer.  This happens when a new operation obviates the need to
2702  * journal an old operation.
2703  */
2704 static void
2705 remove_from_journal(wk)
2706 	struct worklist *wk;
2707 {
2708 	struct ufsmount *ump;
2709 
2710 	mtx_assert(&lk, MA_OWNED);
2711 	ump = VFSTOUFS(wk->wk_mp);
2712 #ifdef SUJ_DEBUG
2713 	{
2714 		struct worklist *wkn;
2715 
2716 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2717 			if (wkn == wk)
2718 				break;
2719 		if (wkn == NULL)
2720 			panic("remove_from_journal: %p is not in journal", wk);
2721 	}
2722 #endif
2723 	/*
2724 	 * We emulate a TAILQ to save space in most structures which do not
2725 	 * require TAILQ semantics.  Here we must update the tail position
2726 	 * when removing the tail which is not the final entry. This works
2727 	 * only if the worklist linkage are at the beginning of the structure.
2728 	 */
2729 	if (ump->softdep_journal_tail == wk)
2730 		ump->softdep_journal_tail =
2731 		    (struct worklist *)wk->wk_list.le_prev;
2732 
2733 	WORKLIST_REMOVE(wk);
2734 	ump->softdep_on_journal -= 1;
2735 }
2736 
2737 /*
2738  * Check for journal space as well as dependency limits so the prelink
2739  * code can throttle both journaled and non-journaled filesystems.
2740  * Threshold is 0 for low and 1 for min.
2741  */
2742 static int
2743 journal_space(ump, thresh)
2744 	struct ufsmount *ump;
2745 	int thresh;
2746 {
2747 	struct jblocks *jblocks;
2748 	int avail;
2749 
2750 	jblocks = ump->softdep_jblocks;
2751 	if (jblocks == NULL)
2752 		return (1);
2753 	/*
2754 	 * We use a tighter restriction here to prevent request_cleanup()
2755 	 * running in threads from running into locks we currently hold.
2756 	 */
2757 	if (dep_current[D_INODEDEP] > (max_softdeps / 10) * 9)
2758 		return (0);
2759 	if (thresh)
2760 		thresh = jblocks->jb_min;
2761 	else
2762 		thresh = jblocks->jb_low;
2763 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2764 	avail = jblocks->jb_free - avail;
2765 
2766 	return (avail > thresh);
2767 }
2768 
2769 static void
2770 journal_suspend(ump)
2771 	struct ufsmount *ump;
2772 {
2773 	struct jblocks *jblocks;
2774 	struct mount *mp;
2775 
2776 	mp = UFSTOVFS(ump);
2777 	jblocks = ump->softdep_jblocks;
2778 	MNT_ILOCK(mp);
2779 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2780 		stat_journal_min++;
2781 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2782 		mp->mnt_susp_owner = FIRST_THREAD_IN_PROC(softdepproc);
2783 	}
2784 	jblocks->jb_suspended = 1;
2785 	MNT_IUNLOCK(mp);
2786 }
2787 
2788 static int
2789 journal_unsuspend(struct ufsmount *ump)
2790 {
2791 	struct jblocks *jblocks;
2792 	struct mount *mp;
2793 
2794 	mp = UFSTOVFS(ump);
2795 	jblocks = ump->softdep_jblocks;
2796 
2797 	if (jblocks != NULL && jblocks->jb_suspended &&
2798 	    journal_space(ump, jblocks->jb_min)) {
2799 		jblocks->jb_suspended = 0;
2800 		FREE_LOCK(&lk);
2801 		mp->mnt_susp_owner = curthread;
2802 		vfs_write_resume(mp);
2803 		ACQUIRE_LOCK(&lk);
2804 		return (1);
2805 	}
2806 	return (0);
2807 }
2808 
2809 /*
2810  * Called before any allocation function to be certain that there is
2811  * sufficient space in the journal prior to creating any new records.
2812  * Since in the case of block allocation we may have multiple locked
2813  * buffers at the time of the actual allocation we can not block
2814  * when the journal records are created.  Doing so would create a deadlock
2815  * if any of these buffers needed to be flushed to reclaim space.  Instead
2816  * we require a sufficiently large amount of available space such that
2817  * each thread in the system could have passed this allocation check and
2818  * still have sufficient free space.  With 20% of a minimum journal size
2819  * of 1MB we have 6553 records available.
2820  */
2821 int
2822 softdep_prealloc(vp, waitok)
2823 	struct vnode *vp;
2824 	int waitok;
2825 {
2826 	struct ufsmount *ump;
2827 
2828 	/*
2829 	 * Nothing to do if we are not running journaled soft updates.
2830 	 * If we currently hold the snapshot lock, we must avoid handling
2831 	 * other resources that could cause deadlock.
2832 	 */
2833 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)))
2834 		return (0);
2835 	ump = VFSTOUFS(vp->v_mount);
2836 	ACQUIRE_LOCK(&lk);
2837 	if (journal_space(ump, 0)) {
2838 		FREE_LOCK(&lk);
2839 		return (0);
2840 	}
2841 	stat_journal_low++;
2842 	FREE_LOCK(&lk);
2843 	if (waitok == MNT_NOWAIT)
2844 		return (ENOSPC);
2845 	/*
2846 	 * Attempt to sync this vnode once to flush any journal
2847 	 * work attached to it.
2848 	 */
2849 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
2850 		ffs_syncvnode(vp, waitok, 0);
2851 	ACQUIRE_LOCK(&lk);
2852 	process_removes(vp);
2853 	process_truncates(vp);
2854 	if (journal_space(ump, 0) == 0) {
2855 		softdep_speedup();
2856 		if (journal_space(ump, 1) == 0)
2857 			journal_suspend(ump);
2858 	}
2859 	FREE_LOCK(&lk);
2860 
2861 	return (0);
2862 }
2863 
2864 /*
2865  * Before adjusting a link count on a vnode verify that we have sufficient
2866  * journal space.  If not, process operations that depend on the currently
2867  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
2868  * and softdep flush threads can not acquire these locks to reclaim space.
2869  */
2870 static void
2871 softdep_prelink(dvp, vp)
2872 	struct vnode *dvp;
2873 	struct vnode *vp;
2874 {
2875 	struct ufsmount *ump;
2876 
2877 	ump = VFSTOUFS(dvp->v_mount);
2878 	mtx_assert(&lk, MA_OWNED);
2879 	/*
2880 	 * Nothing to do if we have sufficient journal space.
2881 	 * If we currently hold the snapshot lock, we must avoid
2882 	 * handling other resources that could cause deadlock.
2883 	 */
2884 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
2885 		return;
2886 	stat_journal_low++;
2887 	FREE_LOCK(&lk);
2888 	if (vp)
2889 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
2890 	ffs_syncvnode(dvp, MNT_WAIT, 0);
2891 	ACQUIRE_LOCK(&lk);
2892 	/* Process vp before dvp as it may create .. removes. */
2893 	if (vp) {
2894 		process_removes(vp);
2895 		process_truncates(vp);
2896 	}
2897 	process_removes(dvp);
2898 	process_truncates(dvp);
2899 	softdep_speedup();
2900 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
2901 	if (journal_space(ump, 0) == 0) {
2902 		softdep_speedup();
2903 		if (journal_space(ump, 1) == 0)
2904 			journal_suspend(ump);
2905 	}
2906 }
2907 
2908 static void
2909 jseg_write(ump, jseg, data)
2910 	struct ufsmount *ump;
2911 	struct jseg *jseg;
2912 	uint8_t *data;
2913 {
2914 	struct jsegrec *rec;
2915 
2916 	rec = (struct jsegrec *)data;
2917 	rec->jsr_seq = jseg->js_seq;
2918 	rec->jsr_oldest = jseg->js_oldseq;
2919 	rec->jsr_cnt = jseg->js_cnt;
2920 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
2921 	rec->jsr_crc = 0;
2922 	rec->jsr_time = ump->um_fs->fs_mtime;
2923 }
2924 
2925 static inline void
2926 inoref_write(inoref, jseg, rec)
2927 	struct inoref *inoref;
2928 	struct jseg *jseg;
2929 	struct jrefrec *rec;
2930 {
2931 
2932 	inoref->if_jsegdep->jd_seg = jseg;
2933 	rec->jr_ino = inoref->if_ino;
2934 	rec->jr_parent = inoref->if_parent;
2935 	rec->jr_nlink = inoref->if_nlink;
2936 	rec->jr_mode = inoref->if_mode;
2937 	rec->jr_diroff = inoref->if_diroff;
2938 }
2939 
2940 static void
2941 jaddref_write(jaddref, jseg, data)
2942 	struct jaddref *jaddref;
2943 	struct jseg *jseg;
2944 	uint8_t *data;
2945 {
2946 	struct jrefrec *rec;
2947 
2948 	rec = (struct jrefrec *)data;
2949 	rec->jr_op = JOP_ADDREF;
2950 	inoref_write(&jaddref->ja_ref, jseg, rec);
2951 }
2952 
2953 static void
2954 jremref_write(jremref, jseg, data)
2955 	struct jremref *jremref;
2956 	struct jseg *jseg;
2957 	uint8_t *data;
2958 {
2959 	struct jrefrec *rec;
2960 
2961 	rec = (struct jrefrec *)data;
2962 	rec->jr_op = JOP_REMREF;
2963 	inoref_write(&jremref->jr_ref, jseg, rec);
2964 }
2965 
2966 static void
2967 jmvref_write(jmvref, jseg, data)
2968 	struct jmvref *jmvref;
2969 	struct jseg *jseg;
2970 	uint8_t *data;
2971 {
2972 	struct jmvrec *rec;
2973 
2974 	rec = (struct jmvrec *)data;
2975 	rec->jm_op = JOP_MVREF;
2976 	rec->jm_ino = jmvref->jm_ino;
2977 	rec->jm_parent = jmvref->jm_parent;
2978 	rec->jm_oldoff = jmvref->jm_oldoff;
2979 	rec->jm_newoff = jmvref->jm_newoff;
2980 }
2981 
2982 static void
2983 jnewblk_write(jnewblk, jseg, data)
2984 	struct jnewblk *jnewblk;
2985 	struct jseg *jseg;
2986 	uint8_t *data;
2987 {
2988 	struct jblkrec *rec;
2989 
2990 	jnewblk->jn_jsegdep->jd_seg = jseg;
2991 	rec = (struct jblkrec *)data;
2992 	rec->jb_op = JOP_NEWBLK;
2993 	rec->jb_ino = jnewblk->jn_ino;
2994 	rec->jb_blkno = jnewblk->jn_blkno;
2995 	rec->jb_lbn = jnewblk->jn_lbn;
2996 	rec->jb_frags = jnewblk->jn_frags;
2997 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
2998 }
2999 
3000 static void
3001 jfreeblk_write(jfreeblk, jseg, data)
3002 	struct jfreeblk *jfreeblk;
3003 	struct jseg *jseg;
3004 	uint8_t *data;
3005 {
3006 	struct jblkrec *rec;
3007 
3008 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3009 	rec = (struct jblkrec *)data;
3010 	rec->jb_op = JOP_FREEBLK;
3011 	rec->jb_ino = jfreeblk->jf_ino;
3012 	rec->jb_blkno = jfreeblk->jf_blkno;
3013 	rec->jb_lbn = jfreeblk->jf_lbn;
3014 	rec->jb_frags = jfreeblk->jf_frags;
3015 	rec->jb_oldfrags = 0;
3016 }
3017 
3018 static void
3019 jfreefrag_write(jfreefrag, jseg, data)
3020 	struct jfreefrag *jfreefrag;
3021 	struct jseg *jseg;
3022 	uint8_t *data;
3023 {
3024 	struct jblkrec *rec;
3025 
3026 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3027 	rec = (struct jblkrec *)data;
3028 	rec->jb_op = JOP_FREEBLK;
3029 	rec->jb_ino = jfreefrag->fr_ino;
3030 	rec->jb_blkno = jfreefrag->fr_blkno;
3031 	rec->jb_lbn = jfreefrag->fr_lbn;
3032 	rec->jb_frags = jfreefrag->fr_frags;
3033 	rec->jb_oldfrags = 0;
3034 }
3035 
3036 static void
3037 jtrunc_write(jtrunc, jseg, data)
3038 	struct jtrunc *jtrunc;
3039 	struct jseg *jseg;
3040 	uint8_t *data;
3041 {
3042 	struct jtrncrec *rec;
3043 
3044 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3045 	rec = (struct jtrncrec *)data;
3046 	rec->jt_op = JOP_TRUNC;
3047 	rec->jt_ino = jtrunc->jt_ino;
3048 	rec->jt_size = jtrunc->jt_size;
3049 	rec->jt_extsize = jtrunc->jt_extsize;
3050 }
3051 
3052 static void
3053 jfsync_write(jfsync, jseg, data)
3054 	struct jfsync *jfsync;
3055 	struct jseg *jseg;
3056 	uint8_t *data;
3057 {
3058 	struct jtrncrec *rec;
3059 
3060 	rec = (struct jtrncrec *)data;
3061 	rec->jt_op = JOP_SYNC;
3062 	rec->jt_ino = jfsync->jfs_ino;
3063 	rec->jt_size = jfsync->jfs_size;
3064 	rec->jt_extsize = jfsync->jfs_extsize;
3065 }
3066 
3067 static void
3068 softdep_flushjournal(mp)
3069 	struct mount *mp;
3070 {
3071 	struct jblocks *jblocks;
3072 	struct ufsmount *ump;
3073 
3074 	if (MOUNTEDSUJ(mp) == 0)
3075 		return;
3076 	ump = VFSTOUFS(mp);
3077 	jblocks = ump->softdep_jblocks;
3078 	ACQUIRE_LOCK(&lk);
3079 	while (ump->softdep_on_journal) {
3080 		jblocks->jb_needseg = 1;
3081 		softdep_process_journal(mp, NULL, MNT_WAIT);
3082 	}
3083 	FREE_LOCK(&lk);
3084 }
3085 
3086 /*
3087  * Flush some journal records to disk.
3088  */
3089 static void
3090 softdep_process_journal(mp, needwk, flags)
3091 	struct mount *mp;
3092 	struct worklist *needwk;
3093 	int flags;
3094 {
3095 	struct jblocks *jblocks;
3096 	struct ufsmount *ump;
3097 	struct worklist *wk;
3098 	struct jseg *jseg;
3099 	struct buf *bp;
3100 	uint8_t *data;
3101 	struct fs *fs;
3102 	int segwritten;
3103 	int jrecmin;	/* Minimum records per block. */
3104 	int jrecmax;	/* Maximum records per block. */
3105 	int size;
3106 	int cnt;
3107 	int off;
3108 	int devbsize;
3109 
3110 	if (MOUNTEDSUJ(mp) == 0)
3111 		return;
3112 	ump = VFSTOUFS(mp);
3113 	fs = ump->um_fs;
3114 	jblocks = ump->softdep_jblocks;
3115 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3116 	/*
3117 	 * We write anywhere between a disk block and fs block.  The upper
3118 	 * bound is picked to prevent buffer cache fragmentation and limit
3119 	 * processing time per I/O.
3120 	 */
3121 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3122 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3123 	segwritten = 0;
3124 	for (;;) {
3125 		cnt = ump->softdep_on_journal;
3126 		/*
3127 		 * Criteria for writing a segment:
3128 		 * 1) We have a full block.
3129 		 * 2) We're called from jwait() and haven't found the
3130 		 *    journal item yet.
3131 		 * 3) Always write if needseg is set.
3132 		 * 4) If we are called from process_worklist and have
3133 		 *    not yet written anything we write a partial block
3134 		 *    to enforce a 1 second maximum latency on journal
3135 		 *    entries.
3136 		 */
3137 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3138 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3139 			break;
3140 		cnt++;
3141 		/*
3142 		 * Verify some free journal space.  softdep_prealloc() should
3143 	 	 * guarantee that we don't run out so this is indicative of
3144 		 * a problem with the flow control.  Try to recover
3145 		 * gracefully in any event.
3146 		 */
3147 		while (jblocks->jb_free == 0) {
3148 			if (flags != MNT_WAIT)
3149 				break;
3150 			printf("softdep: Out of journal space!\n");
3151 			softdep_speedup();
3152 			msleep(jblocks, &lk, PRIBIO, "jblocks", hz);
3153 		}
3154 		FREE_LOCK(&lk);
3155 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3156 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3157 		LIST_INIT(&jseg->js_entries);
3158 		LIST_INIT(&jseg->js_indirs);
3159 		jseg->js_state = ATTACHED;
3160 		jseg->js_jblocks = jblocks;
3161 		bp = geteblk(fs->fs_bsize, 0);
3162 		ACQUIRE_LOCK(&lk);
3163 		/*
3164 		 * If there was a race while we were allocating the block
3165 		 * and jseg the entry we care about was likely written.
3166 		 * We bail out in both the WAIT and NOWAIT case and assume
3167 		 * the caller will loop if the entry it cares about is
3168 		 * not written.
3169 		 */
3170 		cnt = ump->softdep_on_journal;
3171 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3172 			bp->b_flags |= B_INVAL | B_NOCACHE;
3173 			WORKITEM_FREE(jseg, D_JSEG);
3174 			FREE_LOCK(&lk);
3175 			brelse(bp);
3176 			ACQUIRE_LOCK(&lk);
3177 			break;
3178 		}
3179 		/*
3180 		 * Calculate the disk block size required for the available
3181 		 * records rounded to the min size.
3182 		 */
3183 		if (cnt == 0)
3184 			size = devbsize;
3185 		else if (cnt < jrecmax)
3186 			size = howmany(cnt, jrecmin) * devbsize;
3187 		else
3188 			size = fs->fs_bsize;
3189 		/*
3190 		 * Allocate a disk block for this journal data and account
3191 		 * for truncation of the requested size if enough contiguous
3192 		 * space was not available.
3193 		 */
3194 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3195 		bp->b_lblkno = bp->b_blkno;
3196 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3197 		bp->b_bcount = size;
3198 		bp->b_bufobj = &ump->um_devvp->v_bufobj;
3199 		bp->b_flags &= ~B_INVAL;
3200 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3201 		/*
3202 		 * Initialize our jseg with cnt records.  Assign the next
3203 		 * sequence number to it and link it in-order.
3204 		 */
3205 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3206 		jseg->js_buf = bp;
3207 		jseg->js_cnt = cnt;
3208 		jseg->js_refs = cnt + 1;	/* Self ref. */
3209 		jseg->js_size = size;
3210 		jseg->js_seq = jblocks->jb_nextseq++;
3211 		if (jblocks->jb_oldestseg == NULL)
3212 			jblocks->jb_oldestseg = jseg;
3213 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3214 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3215 		if (jblocks->jb_writeseg == NULL)
3216 			jblocks->jb_writeseg = jseg;
3217 		/*
3218 		 * Start filling in records from the pending list.
3219 		 */
3220 		data = bp->b_data;
3221 		off = 0;
3222 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3223 		    != NULL) {
3224 			if (cnt == 0)
3225 				break;
3226 			/* Place a segment header on every device block. */
3227 			if ((off % devbsize) == 0) {
3228 				jseg_write(ump, jseg, data);
3229 				off += JREC_SIZE;
3230 				data = bp->b_data + off;
3231 			}
3232 			if (wk == needwk)
3233 				needwk = NULL;
3234 			remove_from_journal(wk);
3235 			wk->wk_state |= INPROGRESS;
3236 			WORKLIST_INSERT(&jseg->js_entries, wk);
3237 			switch (wk->wk_type) {
3238 			case D_JADDREF:
3239 				jaddref_write(WK_JADDREF(wk), jseg, data);
3240 				break;
3241 			case D_JREMREF:
3242 				jremref_write(WK_JREMREF(wk), jseg, data);
3243 				break;
3244 			case D_JMVREF:
3245 				jmvref_write(WK_JMVREF(wk), jseg, data);
3246 				break;
3247 			case D_JNEWBLK:
3248 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3249 				break;
3250 			case D_JFREEBLK:
3251 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3252 				break;
3253 			case D_JFREEFRAG:
3254 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3255 				break;
3256 			case D_JTRUNC:
3257 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3258 				break;
3259 			case D_JFSYNC:
3260 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3261 				break;
3262 			default:
3263 				panic("process_journal: Unknown type %s",
3264 				    TYPENAME(wk->wk_type));
3265 				/* NOTREACHED */
3266 			}
3267 			off += JREC_SIZE;
3268 			data = bp->b_data + off;
3269 			cnt--;
3270 		}
3271 		/*
3272 		 * Write this one buffer and continue.
3273 		 */
3274 		segwritten = 1;
3275 		jblocks->jb_needseg = 0;
3276 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3277 		FREE_LOCK(&lk);
3278 		BO_LOCK(bp->b_bufobj);
3279 		bgetvp(ump->um_devvp, bp);
3280 		BO_UNLOCK(bp->b_bufobj);
3281 		/*
3282 		 * We only do the blocking wait once we find the journal
3283 		 * entry we're looking for.
3284 		 */
3285 		if (needwk == NULL && flags == MNT_WAIT)
3286 			bwrite(bp);
3287 		else
3288 			bawrite(bp);
3289 		ACQUIRE_LOCK(&lk);
3290 	}
3291 	/*
3292 	 * If we've suspended the filesystem because we ran out of journal
3293 	 * space either try to sync it here to make some progress or
3294 	 * unsuspend it if we already have.
3295 	 */
3296 	if (flags == 0 && jblocks->jb_suspended) {
3297 		if (journal_unsuspend(ump))
3298 			return;
3299 		FREE_LOCK(&lk);
3300 		VFS_SYNC(mp, MNT_NOWAIT);
3301 		ffs_sbupdate(ump, MNT_WAIT, 0);
3302 		ACQUIRE_LOCK(&lk);
3303 	}
3304 }
3305 
3306 /*
3307  * Complete a jseg, allowing all dependencies awaiting journal writes
3308  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3309  * structures so that the journal segment can be freed to reclaim space.
3310  */
3311 static void
3312 complete_jseg(jseg)
3313 	struct jseg *jseg;
3314 {
3315 	struct worklist *wk;
3316 	struct jmvref *jmvref;
3317 	int waiting;
3318 #ifdef INVARIANTS
3319 	int i = 0;
3320 #endif
3321 
3322 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3323 		WORKLIST_REMOVE(wk);
3324 		waiting = wk->wk_state & IOWAITING;
3325 		wk->wk_state &= ~(INPROGRESS | IOWAITING);
3326 		wk->wk_state |= COMPLETE;
3327 		KASSERT(i++ < jseg->js_cnt,
3328 		    ("handle_written_jseg: overflow %d >= %d",
3329 		    i - 1, jseg->js_cnt));
3330 		switch (wk->wk_type) {
3331 		case D_JADDREF:
3332 			handle_written_jaddref(WK_JADDREF(wk));
3333 			break;
3334 		case D_JREMREF:
3335 			handle_written_jremref(WK_JREMREF(wk));
3336 			break;
3337 		case D_JMVREF:
3338 			rele_jseg(jseg);	/* No jsegdep. */
3339 			jmvref = WK_JMVREF(wk);
3340 			LIST_REMOVE(jmvref, jm_deps);
3341 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3342 				free_pagedep(jmvref->jm_pagedep);
3343 			WORKITEM_FREE(jmvref, D_JMVREF);
3344 			break;
3345 		case D_JNEWBLK:
3346 			handle_written_jnewblk(WK_JNEWBLK(wk));
3347 			break;
3348 		case D_JFREEBLK:
3349 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3350 			break;
3351 		case D_JTRUNC:
3352 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3353 			break;
3354 		case D_JFSYNC:
3355 			rele_jseg(jseg);	/* No jsegdep. */
3356 			WORKITEM_FREE(wk, D_JFSYNC);
3357 			break;
3358 		case D_JFREEFRAG:
3359 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3360 			break;
3361 		default:
3362 			panic("handle_written_jseg: Unknown type %s",
3363 			    TYPENAME(wk->wk_type));
3364 			/* NOTREACHED */
3365 		}
3366 		if (waiting)
3367 			wakeup(wk);
3368 	}
3369 	/* Release the self reference so the structure may be freed. */
3370 	rele_jseg(jseg);
3371 }
3372 
3373 /*
3374  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Handle jseg
3375  * completions in order only.
3376  */
3377 static void
3378 handle_written_jseg(jseg, bp)
3379 	struct jseg *jseg;
3380 	struct buf *bp;
3381 {
3382 	struct jblocks *jblocks;
3383 	struct jseg *jsegn;
3384 
3385 	if (jseg->js_refs == 0)
3386 		panic("handle_written_jseg: No self-reference on %p", jseg);
3387 	jseg->js_state |= DEPCOMPLETE;
3388 	/*
3389 	 * We'll never need this buffer again, set flags so it will be
3390 	 * discarded.
3391 	 */
3392 	bp->b_flags |= B_INVAL | B_NOCACHE;
3393 	jblocks = jseg->js_jblocks;
3394 	/*
3395 	 * Don't allow out of order completions.  If this isn't the first
3396 	 * block wait for it to write before we're done.
3397 	 */
3398 	if (jseg != jblocks->jb_writeseg)
3399 		return;
3400 	/* Iterate through available jsegs processing their entries. */
3401 	do {
3402 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3403 		jsegn = TAILQ_NEXT(jseg, js_next);
3404 		complete_jseg(jseg);
3405 		jseg = jsegn;
3406 	} while (jseg && jseg->js_state & DEPCOMPLETE);
3407 	jblocks->jb_writeseg = jseg;
3408 	/*
3409 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3410 	 */
3411 	free_jsegs(jblocks);
3412 }
3413 
3414 static inline struct jsegdep *
3415 inoref_jseg(inoref)
3416 	struct inoref *inoref;
3417 {
3418 	struct jsegdep *jsegdep;
3419 
3420 	jsegdep = inoref->if_jsegdep;
3421 	inoref->if_jsegdep = NULL;
3422 
3423 	return (jsegdep);
3424 }
3425 
3426 /*
3427  * Called once a jremref has made it to stable store.  The jremref is marked
3428  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3429  * for the jremref to complete will be awoken by free_jremref.
3430  */
3431 static void
3432 handle_written_jremref(jremref)
3433 	struct jremref *jremref;
3434 {
3435 	struct inodedep *inodedep;
3436 	struct jsegdep *jsegdep;
3437 	struct dirrem *dirrem;
3438 
3439 	/* Grab the jsegdep. */
3440 	jsegdep = inoref_jseg(&jremref->jr_ref);
3441 	/*
3442 	 * Remove us from the inoref list.
3443 	 */
3444 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3445 	    0, &inodedep) == 0)
3446 		panic("handle_written_jremref: Lost inodedep");
3447 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3448 	/*
3449 	 * Complete the dirrem.
3450 	 */
3451 	dirrem = jremref->jr_dirrem;
3452 	jremref->jr_dirrem = NULL;
3453 	LIST_REMOVE(jremref, jr_deps);
3454 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3455 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3456 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3457 	    (dirrem->dm_state & COMPLETE) != 0)
3458 		add_to_worklist(&dirrem->dm_list, 0);
3459 	free_jremref(jremref);
3460 }
3461 
3462 /*
3463  * Called once a jaddref has made it to stable store.  The dependency is
3464  * marked complete and any dependent structures are added to the inode
3465  * bufwait list to be completed as soon as it is written.  If a bitmap write
3466  * depends on this entry we move the inode into the inodedephd of the
3467  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3468  */
3469 static void
3470 handle_written_jaddref(jaddref)
3471 	struct jaddref *jaddref;
3472 {
3473 	struct jsegdep *jsegdep;
3474 	struct inodedep *inodedep;
3475 	struct diradd *diradd;
3476 	struct mkdir *mkdir;
3477 
3478 	/* Grab the jsegdep. */
3479 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3480 	mkdir = NULL;
3481 	diradd = NULL;
3482 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3483 	    0, &inodedep) == 0)
3484 		panic("handle_written_jaddref: Lost inodedep.");
3485 	if (jaddref->ja_diradd == NULL)
3486 		panic("handle_written_jaddref: No dependency");
3487 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3488 		diradd = jaddref->ja_diradd;
3489 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3490 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3491 		mkdir = jaddref->ja_mkdir;
3492 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3493 	} else if (jaddref->ja_state & MKDIR_BODY)
3494 		mkdir = jaddref->ja_mkdir;
3495 	else
3496 		panic("handle_written_jaddref: Unknown dependency %p",
3497 		    jaddref->ja_diradd);
3498 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3499 	/*
3500 	 * Remove us from the inode list.
3501 	 */
3502 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3503 	/*
3504 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3505 	 */
3506 	if (mkdir) {
3507 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3508 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3509 		    TYPENAME(mkdir->md_list.wk_type)));
3510 		mkdir->md_jaddref = NULL;
3511 		diradd = mkdir->md_diradd;
3512 		mkdir->md_state |= DEPCOMPLETE;
3513 		complete_mkdir(mkdir);
3514 	}
3515 	jwork_insert(&diradd->da_jwork, jsegdep);
3516 	if (jaddref->ja_state & NEWBLOCK) {
3517 		inodedep->id_state |= ONDEPLIST;
3518 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3519 		    inodedep, id_deps);
3520 	}
3521 	free_jaddref(jaddref);
3522 }
3523 
3524 /*
3525  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3526  * is placed in the bmsafemap to await notification of a written bitmap.  If
3527  * the operation was canceled we add the segdep to the appropriate
3528  * dependency to free the journal space once the canceling operation
3529  * completes.
3530  */
3531 static void
3532 handle_written_jnewblk(jnewblk)
3533 	struct jnewblk *jnewblk;
3534 {
3535 	struct bmsafemap *bmsafemap;
3536 	struct freefrag *freefrag;
3537 	struct freework *freework;
3538 	struct jsegdep *jsegdep;
3539 	struct newblk *newblk;
3540 
3541 	/* Grab the jsegdep. */
3542 	jsegdep = jnewblk->jn_jsegdep;
3543 	jnewblk->jn_jsegdep = NULL;
3544 	if (jnewblk->jn_dep == NULL)
3545 		panic("handle_written_jnewblk: No dependency for the segdep.");
3546 	switch (jnewblk->jn_dep->wk_type) {
3547 	case D_NEWBLK:
3548 	case D_ALLOCDIRECT:
3549 	case D_ALLOCINDIR:
3550 		/*
3551 		 * Add the written block to the bmsafemap so it can
3552 		 * be notified when the bitmap is on disk.
3553 		 */
3554 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3555 		newblk->nb_jnewblk = NULL;
3556 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3557 			bmsafemap = newblk->nb_bmsafemap;
3558 			newblk->nb_state |= ONDEPLIST;
3559 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3560 			    nb_deps);
3561 		}
3562 		jwork_insert(&newblk->nb_jwork, jsegdep);
3563 		break;
3564 	case D_FREEFRAG:
3565 		/*
3566 		 * A newblock being removed by a freefrag when replaced by
3567 		 * frag extension.
3568 		 */
3569 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3570 		freefrag->ff_jdep = NULL;
3571 		WORKLIST_INSERT(&freefrag->ff_jwork, &jsegdep->jd_list);
3572 		break;
3573 	case D_FREEWORK:
3574 		/*
3575 		 * A direct block was removed by truncate.
3576 		 */
3577 		freework = WK_FREEWORK(jnewblk->jn_dep);
3578 		freework->fw_jnewblk = NULL;
3579 		WORKLIST_INSERT(&freework->fw_freeblks->fb_jwork,
3580 		    &jsegdep->jd_list);
3581 		break;
3582 	default:
3583 		panic("handle_written_jnewblk: Unknown type %d.",
3584 		    jnewblk->jn_dep->wk_type);
3585 	}
3586 	jnewblk->jn_dep = NULL;
3587 	free_jnewblk(jnewblk);
3588 }
3589 
3590 /*
3591  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3592  * an in-flight allocation that has not yet been committed.  Divorce us
3593  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3594  * to the worklist.
3595  */
3596 static void
3597 cancel_jfreefrag(jfreefrag)
3598 	struct jfreefrag *jfreefrag;
3599 {
3600 	struct freefrag *freefrag;
3601 
3602 	if (jfreefrag->fr_jsegdep) {
3603 		free_jsegdep(jfreefrag->fr_jsegdep);
3604 		jfreefrag->fr_jsegdep = NULL;
3605 	}
3606 	freefrag = jfreefrag->fr_freefrag;
3607 	jfreefrag->fr_freefrag = NULL;
3608 	free_jfreefrag(jfreefrag);
3609 	freefrag->ff_state |= DEPCOMPLETE;
3610 }
3611 
3612 /*
3613  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3614  */
3615 static void
3616 free_jfreefrag(jfreefrag)
3617 	struct jfreefrag *jfreefrag;
3618 {
3619 
3620 	if (jfreefrag->fr_state & INPROGRESS)
3621 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3622 	else if (jfreefrag->fr_state & ONWORKLIST)
3623 		remove_from_journal(&jfreefrag->fr_list);
3624 	if (jfreefrag->fr_freefrag != NULL)
3625 		panic("free_jfreefrag:  Still attached to a freefrag.");
3626 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3627 }
3628 
3629 /*
3630  * Called when the journal write for a jfreefrag completes.  The parent
3631  * freefrag is added to the worklist if this completes its dependencies.
3632  */
3633 static void
3634 handle_written_jfreefrag(jfreefrag)
3635 	struct jfreefrag *jfreefrag;
3636 {
3637 	struct jsegdep *jsegdep;
3638 	struct freefrag *freefrag;
3639 
3640 	/* Grab the jsegdep. */
3641 	jsegdep = jfreefrag->fr_jsegdep;
3642 	jfreefrag->fr_jsegdep = NULL;
3643 	freefrag = jfreefrag->fr_freefrag;
3644 	if (freefrag == NULL)
3645 		panic("handle_written_jfreefrag: No freefrag.");
3646 	freefrag->ff_state |= DEPCOMPLETE;
3647 	freefrag->ff_jdep = NULL;
3648 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3649 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3650 		add_to_worklist(&freefrag->ff_list, 0);
3651 	jfreefrag->fr_freefrag = NULL;
3652 	free_jfreefrag(jfreefrag);
3653 }
3654 
3655 /*
3656  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3657  * is removed from the freeblks list of pending journal writes and the
3658  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3659  * have been reclaimed.
3660  */
3661 static void
3662 handle_written_jblkdep(jblkdep)
3663 	struct jblkdep *jblkdep;
3664 {
3665 	struct freeblks *freeblks;
3666 	struct jsegdep *jsegdep;
3667 
3668 	/* Grab the jsegdep. */
3669 	jsegdep = jblkdep->jb_jsegdep;
3670 	jblkdep->jb_jsegdep = NULL;
3671 	freeblks = jblkdep->jb_freeblks;
3672 	LIST_REMOVE(jblkdep, jb_deps);
3673 	WORKLIST_INSERT(&freeblks->fb_jwork, &jsegdep->jd_list);
3674 	/*
3675 	 * If the freeblks is all journaled, we can add it to the worklist.
3676 	 */
3677 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3678 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3679 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3680 
3681 	free_jblkdep(jblkdep);
3682 }
3683 
3684 static struct jsegdep *
3685 newjsegdep(struct worklist *wk)
3686 {
3687 	struct jsegdep *jsegdep;
3688 
3689 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3690 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3691 	jsegdep->jd_seg = NULL;
3692 
3693 	return (jsegdep);
3694 }
3695 
3696 static struct jmvref *
3697 newjmvref(dp, ino, oldoff, newoff)
3698 	struct inode *dp;
3699 	ino_t ino;
3700 	off_t oldoff;
3701 	off_t newoff;
3702 {
3703 	struct jmvref *jmvref;
3704 
3705 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
3706 	workitem_alloc(&jmvref->jm_list, D_JMVREF, UFSTOVFS(dp->i_ump));
3707 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
3708 	jmvref->jm_parent = dp->i_number;
3709 	jmvref->jm_ino = ino;
3710 	jmvref->jm_oldoff = oldoff;
3711 	jmvref->jm_newoff = newoff;
3712 
3713 	return (jmvref);
3714 }
3715 
3716 /*
3717  * Allocate a new jremref that tracks the removal of ip from dp with the
3718  * directory entry offset of diroff.  Mark the entry as ATTACHED and
3719  * DEPCOMPLETE as we have all the information required for the journal write
3720  * and the directory has already been removed from the buffer.  The caller
3721  * is responsible for linking the jremref into the pagedep and adding it
3722  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
3723  * a DOTDOT addition so handle_workitem_remove() can properly assign
3724  * the jsegdep when we're done.
3725  */
3726 static struct jremref *
3727 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
3728     off_t diroff, nlink_t nlink)
3729 {
3730 	struct jremref *jremref;
3731 
3732 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
3733 	workitem_alloc(&jremref->jr_list, D_JREMREF, UFSTOVFS(dp->i_ump));
3734 	jremref->jr_state = ATTACHED;
3735 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
3736 	   nlink, ip->i_mode);
3737 	jremref->jr_dirrem = dirrem;
3738 
3739 	return (jremref);
3740 }
3741 
3742 static inline void
3743 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
3744     nlink_t nlink, uint16_t mode)
3745 {
3746 
3747 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
3748 	inoref->if_diroff = diroff;
3749 	inoref->if_ino = ino;
3750 	inoref->if_parent = parent;
3751 	inoref->if_nlink = nlink;
3752 	inoref->if_mode = mode;
3753 }
3754 
3755 /*
3756  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
3757  * directory offset may not be known until later.  The caller is responsible
3758  * adding the entry to the journal when this information is available.  nlink
3759  * should be the link count prior to the addition and mode is only required
3760  * to have the correct FMT.
3761  */
3762 static struct jaddref *
3763 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
3764     uint16_t mode)
3765 {
3766 	struct jaddref *jaddref;
3767 
3768 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
3769 	workitem_alloc(&jaddref->ja_list, D_JADDREF, UFSTOVFS(dp->i_ump));
3770 	jaddref->ja_state = ATTACHED;
3771 	jaddref->ja_mkdir = NULL;
3772 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
3773 
3774 	return (jaddref);
3775 }
3776 
3777 /*
3778  * Create a new free dependency for a freework.  The caller is responsible
3779  * for adjusting the reference count when it has the lock held.  The freedep
3780  * will track an outstanding bitmap write that will ultimately clear the
3781  * freework to continue.
3782  */
3783 static struct freedep *
3784 newfreedep(struct freework *freework)
3785 {
3786 	struct freedep *freedep;
3787 
3788 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
3789 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
3790 	freedep->fd_freework = freework;
3791 
3792 	return (freedep);
3793 }
3794 
3795 /*
3796  * Free a freedep structure once the buffer it is linked to is written.  If
3797  * this is the last reference to the freework schedule it for completion.
3798  */
3799 static void
3800 free_freedep(freedep)
3801 	struct freedep *freedep;
3802 {
3803 	struct freework *freework;
3804 
3805 	freework = freedep->fd_freework;
3806 	freework->fw_freeblks->fb_cgwait--;
3807 	if (--freework->fw_ref == 0)
3808 		freework_enqueue(freework);
3809 	WORKITEM_FREE(freedep, D_FREEDEP);
3810 }
3811 
3812 /*
3813  * Allocate a new freework structure that may be a level in an indirect
3814  * when parent is not NULL or a top level block when it is.  The top level
3815  * freework structures are allocated without lk held and before the freeblks
3816  * is visible outside of softdep_setup_freeblocks().
3817  */
3818 static struct freework *
3819 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
3820 	struct ufsmount *ump;
3821 	struct freeblks *freeblks;
3822 	struct freework *parent;
3823 	ufs_lbn_t lbn;
3824 	ufs2_daddr_t nb;
3825 	int frags;
3826 	int off;
3827 	int journal;
3828 {
3829 	struct freework *freework;
3830 
3831 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
3832 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
3833 	freework->fw_state = ATTACHED;
3834 	freework->fw_jnewblk = NULL;
3835 	freework->fw_freeblks = freeblks;
3836 	freework->fw_parent = parent;
3837 	freework->fw_lbn = lbn;
3838 	freework->fw_blkno = nb;
3839 	freework->fw_frags = frags;
3840 	freework->fw_indir = NULL;
3841 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 || lbn >= -NXADDR)
3842 		? 0 : NINDIR(ump->um_fs) + 1;
3843 	freework->fw_start = freework->fw_off = off;
3844 	if (journal)
3845 		newjfreeblk(freeblks, lbn, nb, frags);
3846 	if (parent == NULL) {
3847 		ACQUIRE_LOCK(&lk);
3848 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
3849 		freeblks->fb_ref++;
3850 		FREE_LOCK(&lk);
3851 	}
3852 
3853 	return (freework);
3854 }
3855 
3856 /*
3857  * Eliminate a jfreeblk for a block that does not need journaling.
3858  */
3859 static void
3860 cancel_jfreeblk(freeblks, blkno)
3861 	struct freeblks *freeblks;
3862 	ufs2_daddr_t blkno;
3863 {
3864 	struct jfreeblk *jfreeblk;
3865 	struct jblkdep *jblkdep;
3866 
3867 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
3868 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
3869 			continue;
3870 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
3871 		if (jfreeblk->jf_blkno == blkno)
3872 			break;
3873 	}
3874 	if (jblkdep == NULL)
3875 		return;
3876 	free_jsegdep(jblkdep->jb_jsegdep);
3877 	LIST_REMOVE(jblkdep, jb_deps);
3878 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
3879 }
3880 
3881 /*
3882  * Allocate a new jfreeblk to journal top level block pointer when truncating
3883  * a file.  The caller must add this to the worklist when lk is held.
3884  */
3885 static struct jfreeblk *
3886 newjfreeblk(freeblks, lbn, blkno, frags)
3887 	struct freeblks *freeblks;
3888 	ufs_lbn_t lbn;
3889 	ufs2_daddr_t blkno;
3890 	int frags;
3891 {
3892 	struct jfreeblk *jfreeblk;
3893 
3894 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
3895 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
3896 	    freeblks->fb_list.wk_mp);
3897 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
3898 	jfreeblk->jf_dep.jb_freeblks = freeblks;
3899 	jfreeblk->jf_ino = freeblks->fb_inum;
3900 	jfreeblk->jf_lbn = lbn;
3901 	jfreeblk->jf_blkno = blkno;
3902 	jfreeblk->jf_frags = frags;
3903 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
3904 
3905 	return (jfreeblk);
3906 }
3907 
3908 /*
3909  * Allocate a new jtrunc to track a partial truncation.
3910  */
3911 static struct jtrunc *
3912 newjtrunc(freeblks, size, extsize)
3913 	struct freeblks *freeblks;
3914 	off_t size;
3915 	int extsize;
3916 {
3917 	struct jtrunc *jtrunc;
3918 
3919 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
3920 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
3921 	    freeblks->fb_list.wk_mp);
3922 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
3923 	jtrunc->jt_dep.jb_freeblks = freeblks;
3924 	jtrunc->jt_ino = freeblks->fb_inum;
3925 	jtrunc->jt_size = size;
3926 	jtrunc->jt_extsize = extsize;
3927 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
3928 
3929 	return (jtrunc);
3930 }
3931 
3932 /*
3933  * If we're canceling a new bitmap we have to search for another ref
3934  * to move into the bmsafemap dep.  This might be better expressed
3935  * with another structure.
3936  */
3937 static void
3938 move_newblock_dep(jaddref, inodedep)
3939 	struct jaddref *jaddref;
3940 	struct inodedep *inodedep;
3941 {
3942 	struct inoref *inoref;
3943 	struct jaddref *jaddrefn;
3944 
3945 	jaddrefn = NULL;
3946 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
3947 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
3948 		if ((jaddref->ja_state & NEWBLOCK) &&
3949 		    inoref->if_list.wk_type == D_JADDREF) {
3950 			jaddrefn = (struct jaddref *)inoref;
3951 			break;
3952 		}
3953 	}
3954 	if (jaddrefn == NULL)
3955 		return;
3956 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
3957 	jaddrefn->ja_state |= jaddref->ja_state &
3958 	    (ATTACHED | UNDONE | NEWBLOCK);
3959 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
3960 	jaddref->ja_state |= ATTACHED;
3961 	LIST_REMOVE(jaddref, ja_bmdeps);
3962 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
3963 	    ja_bmdeps);
3964 }
3965 
3966 /*
3967  * Cancel a jaddref either before it has been written or while it is being
3968  * written.  This happens when a link is removed before the add reaches
3969  * the disk.  The jaddref dependency is kept linked into the bmsafemap
3970  * and inode to prevent the link count or bitmap from reaching the disk
3971  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
3972  * required.
3973  *
3974  * Returns 1 if the canceled addref requires journaling of the remove and
3975  * 0 otherwise.
3976  */
3977 static int
3978 cancel_jaddref(jaddref, inodedep, wkhd)
3979 	struct jaddref *jaddref;
3980 	struct inodedep *inodedep;
3981 	struct workhead *wkhd;
3982 {
3983 	struct inoref *inoref;
3984 	struct jsegdep *jsegdep;
3985 	int needsj;
3986 
3987 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
3988 	    ("cancel_jaddref: Canceling complete jaddref"));
3989 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
3990 		needsj = 1;
3991 	else
3992 		needsj = 0;
3993 	if (inodedep == NULL)
3994 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3995 		    0, &inodedep) == 0)
3996 			panic("cancel_jaddref: Lost inodedep");
3997 	/*
3998 	 * We must adjust the nlink of any reference operation that follows
3999 	 * us so that it is consistent with the in-memory reference.  This
4000 	 * ensures that inode nlink rollbacks always have the correct link.
4001 	 */
4002 	if (needsj == 0) {
4003 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4004 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4005 			if (inoref->if_state & GOINGAWAY)
4006 				break;
4007 			inoref->if_nlink--;
4008 		}
4009 	}
4010 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4011 	if (jaddref->ja_state & NEWBLOCK)
4012 		move_newblock_dep(jaddref, inodedep);
4013 	wake_worklist(&jaddref->ja_list);
4014 	jaddref->ja_mkdir = NULL;
4015 	if (jaddref->ja_state & INPROGRESS) {
4016 		jaddref->ja_state &= ~INPROGRESS;
4017 		WORKLIST_REMOVE(&jaddref->ja_list);
4018 		jwork_insert(wkhd, jsegdep);
4019 	} else {
4020 		free_jsegdep(jsegdep);
4021 		if (jaddref->ja_state & DEPCOMPLETE)
4022 			remove_from_journal(&jaddref->ja_list);
4023 	}
4024 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4025 	/*
4026 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4027 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4028 	 * no longer need this addref attached to the inoreflst and it
4029 	 * will incorrectly adjust nlink if we leave it.
4030 	 */
4031 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4032 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4033 		    if_deps);
4034 		jaddref->ja_state |= COMPLETE;
4035 		free_jaddref(jaddref);
4036 		return (needsj);
4037 	}
4038 	/*
4039 	 * Leave the head of the list for jsegdeps for fast merging.
4040 	 */
4041 	if (LIST_FIRST(wkhd) != NULL) {
4042 		jaddref->ja_state |= ONWORKLIST;
4043 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4044 	} else
4045 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4046 
4047 	return (needsj);
4048 }
4049 
4050 /*
4051  * Attempt to free a jaddref structure when some work completes.  This
4052  * should only succeed once the entry is written and all dependencies have
4053  * been notified.
4054  */
4055 static void
4056 free_jaddref(jaddref)
4057 	struct jaddref *jaddref;
4058 {
4059 
4060 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4061 		return;
4062 	if (jaddref->ja_ref.if_jsegdep)
4063 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4064 		    jaddref, jaddref->ja_state);
4065 	if (jaddref->ja_state & NEWBLOCK)
4066 		LIST_REMOVE(jaddref, ja_bmdeps);
4067 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4068 		panic("free_jaddref: Bad state %p(0x%X)",
4069 		    jaddref, jaddref->ja_state);
4070 	if (jaddref->ja_mkdir != NULL)
4071 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4072 	WORKITEM_FREE(jaddref, D_JADDREF);
4073 }
4074 
4075 /*
4076  * Free a jremref structure once it has been written or discarded.
4077  */
4078 static void
4079 free_jremref(jremref)
4080 	struct jremref *jremref;
4081 {
4082 
4083 	if (jremref->jr_ref.if_jsegdep)
4084 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4085 	if (jremref->jr_state & INPROGRESS)
4086 		panic("free_jremref: IO still pending");
4087 	WORKITEM_FREE(jremref, D_JREMREF);
4088 }
4089 
4090 /*
4091  * Free a jnewblk structure.
4092  */
4093 static void
4094 free_jnewblk(jnewblk)
4095 	struct jnewblk *jnewblk;
4096 {
4097 
4098 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4099 		return;
4100 	LIST_REMOVE(jnewblk, jn_deps);
4101 	if (jnewblk->jn_dep != NULL)
4102 		panic("free_jnewblk: Dependency still attached.");
4103 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4104 }
4105 
4106 /*
4107  * Cancel a jnewblk which has been been made redundant by frag extension.
4108  */
4109 static void
4110 cancel_jnewblk(jnewblk, wkhd)
4111 	struct jnewblk *jnewblk;
4112 	struct workhead *wkhd;
4113 {
4114 	struct jsegdep *jsegdep;
4115 
4116 	jsegdep = jnewblk->jn_jsegdep;
4117 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4118 		panic("cancel_jnewblk: Invalid state");
4119 	jnewblk->jn_jsegdep  = NULL;
4120 	jnewblk->jn_dep = NULL;
4121 	jnewblk->jn_state |= GOINGAWAY;
4122 	if (jnewblk->jn_state & INPROGRESS) {
4123 		jnewblk->jn_state &= ~INPROGRESS;
4124 		WORKLIST_REMOVE(&jnewblk->jn_list);
4125 		jwork_insert(wkhd, jsegdep);
4126 	} else {
4127 		free_jsegdep(jsegdep);
4128 		remove_from_journal(&jnewblk->jn_list);
4129 	}
4130 	wake_worklist(&jnewblk->jn_list);
4131 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4132 }
4133 
4134 static void
4135 free_jblkdep(jblkdep)
4136 	struct jblkdep *jblkdep;
4137 {
4138 
4139 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4140 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4141 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4142 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4143 	else
4144 		panic("free_jblkdep: Unexpected type %s",
4145 		    TYPENAME(jblkdep->jb_list.wk_type));
4146 }
4147 
4148 /*
4149  * Free a single jseg once it is no longer referenced in memory or on
4150  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4151  * to disappear.
4152  */
4153 static void
4154 free_jseg(jseg, jblocks)
4155 	struct jseg *jseg;
4156 	struct jblocks *jblocks;
4157 {
4158 	struct freework *freework;
4159 
4160 	/*
4161 	 * Free freework structures that were lingering to indicate freed
4162 	 * indirect blocks that forced journal write ordering on reallocate.
4163 	 */
4164 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4165 		indirblk_remove(freework);
4166 	if (jblocks->jb_oldestseg == jseg)
4167 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4168 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4169 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4170 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4171 	    ("free_jseg: Freed jseg has valid entries."));
4172 	WORKITEM_FREE(jseg, D_JSEG);
4173 }
4174 
4175 /*
4176  * Free all jsegs that meet the criteria for being reclaimed and update
4177  * oldestseg.
4178  */
4179 static void
4180 free_jsegs(jblocks)
4181 	struct jblocks *jblocks;
4182 {
4183 	struct jseg *jseg;
4184 
4185 	/*
4186 	 * Free only those jsegs which have none allocated before them to
4187 	 * preserve the journal space ordering.
4188 	 */
4189 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4190 		/*
4191 		 * Only reclaim space when nothing depends on this journal
4192 		 * set and another set has written that it is no longer
4193 		 * valid.
4194 		 */
4195 		if (jseg->js_refs != 0) {
4196 			jblocks->jb_oldestseg = jseg;
4197 			return;
4198 		}
4199 		if (!LIST_EMPTY(&jseg->js_indirs) &&
4200 		    jseg->js_seq >= jblocks->jb_oldestwrseq)
4201 			break;
4202 		free_jseg(jseg, jblocks);
4203 	}
4204 	/*
4205 	 * If we exited the loop above we still must discover the
4206 	 * oldest valid segment.
4207 	 */
4208 	if (jseg)
4209 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4210 		     jseg = TAILQ_NEXT(jseg, js_next))
4211 			if (jseg->js_refs != 0)
4212 				break;
4213 	jblocks->jb_oldestseg = jseg;
4214 	/*
4215 	 * The journal has no valid records but some jsegs may still be
4216 	 * waiting on oldestwrseq to advance.  We force a small record
4217 	 * out to permit these lingering records to be reclaimed.
4218 	 */
4219 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4220 		jblocks->jb_needseg = 1;
4221 }
4222 
4223 /*
4224  * Release one reference to a jseg and free it if the count reaches 0.  This
4225  * should eventually reclaim journal space as well.
4226  */
4227 static void
4228 rele_jseg(jseg)
4229 	struct jseg *jseg;
4230 {
4231 
4232 	KASSERT(jseg->js_refs > 0,
4233 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4234 	if (--jseg->js_refs != 0)
4235 		return;
4236 	free_jsegs(jseg->js_jblocks);
4237 }
4238 
4239 /*
4240  * Release a jsegdep and decrement the jseg count.
4241  */
4242 static void
4243 free_jsegdep(jsegdep)
4244 	struct jsegdep *jsegdep;
4245 {
4246 
4247 	if (jsegdep->jd_seg)
4248 		rele_jseg(jsegdep->jd_seg);
4249 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4250 }
4251 
4252 /*
4253  * Wait for a journal item to make it to disk.  Initiate journal processing
4254  * if required.
4255  */
4256 static int
4257 jwait(wk, waitfor)
4258 	struct worklist *wk;
4259 	int waitfor;
4260 {
4261 
4262 	/*
4263 	 * Blocking journal waits cause slow synchronous behavior.  Record
4264 	 * stats on the frequency of these blocking operations.
4265 	 */
4266 	if (waitfor == MNT_WAIT) {
4267 		stat_journal_wait++;
4268 		switch (wk->wk_type) {
4269 		case D_JREMREF:
4270 		case D_JMVREF:
4271 			stat_jwait_filepage++;
4272 			break;
4273 		case D_JTRUNC:
4274 		case D_JFREEBLK:
4275 			stat_jwait_freeblks++;
4276 			break;
4277 		case D_JNEWBLK:
4278 			stat_jwait_newblk++;
4279 			break;
4280 		case D_JADDREF:
4281 			stat_jwait_inode++;
4282 			break;
4283 		default:
4284 			break;
4285 		}
4286 	}
4287 	/*
4288 	 * If IO has not started we process the journal.  We can't mark the
4289 	 * worklist item as IOWAITING because we drop the lock while
4290 	 * processing the journal and the worklist entry may be freed after
4291 	 * this point.  The caller may call back in and re-issue the request.
4292 	 */
4293 	if ((wk->wk_state & INPROGRESS) == 0) {
4294 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4295 		if (waitfor != MNT_WAIT)
4296 			return (EBUSY);
4297 		return (0);
4298 	}
4299 	if (waitfor != MNT_WAIT)
4300 		return (EBUSY);
4301 	wait_worklist(wk, "jwait");
4302 	return (0);
4303 }
4304 
4305 /*
4306  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4307  * appropriate.  This is a convenience function to reduce duplicate code
4308  * for the setup and revert functions below.
4309  */
4310 static struct inodedep *
4311 inodedep_lookup_ip(ip)
4312 	struct inode *ip;
4313 {
4314 	struct inodedep *inodedep;
4315 	int dflags;
4316 
4317 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4318 	    ("inodedep_lookup_ip: bad delta"));
4319 	dflags = DEPALLOC;
4320 	if (IS_SNAPSHOT(ip))
4321 		dflags |= NODELAY;
4322 	(void) inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags,
4323 	    &inodedep);
4324 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4325 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4326 
4327 	return (inodedep);
4328 }
4329 
4330 /*
4331  * Called prior to creating a new inode and linking it to a directory.  The
4332  * jaddref structure must already be allocated by softdep_setup_inomapdep
4333  * and it is discovered here so we can initialize the mode and update
4334  * nlinkdelta.
4335  */
4336 void
4337 softdep_setup_create(dp, ip)
4338 	struct inode *dp;
4339 	struct inode *ip;
4340 {
4341 	struct inodedep *inodedep;
4342 	struct jaddref *jaddref;
4343 	struct vnode *dvp;
4344 
4345 	KASSERT(ip->i_nlink == 1,
4346 	    ("softdep_setup_create: Invalid link count."));
4347 	dvp = ITOV(dp);
4348 	ACQUIRE_LOCK(&lk);
4349 	inodedep = inodedep_lookup_ip(ip);
4350 	if (DOINGSUJ(dvp)) {
4351 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4352 		    inoreflst);
4353 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4354 		    ("softdep_setup_create: No addref structure present."));
4355 	}
4356 	softdep_prelink(dvp, NULL);
4357 	FREE_LOCK(&lk);
4358 }
4359 
4360 /*
4361  * Create a jaddref structure to track the addition of a DOTDOT link when
4362  * we are reparenting an inode as part of a rename.  This jaddref will be
4363  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4364  * non-journaling softdep.
4365  */
4366 void
4367 softdep_setup_dotdot_link(dp, ip)
4368 	struct inode *dp;
4369 	struct inode *ip;
4370 {
4371 	struct inodedep *inodedep;
4372 	struct jaddref *jaddref;
4373 	struct vnode *dvp;
4374 	struct vnode *vp;
4375 
4376 	dvp = ITOV(dp);
4377 	vp = ITOV(ip);
4378 	jaddref = NULL;
4379 	/*
4380 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4381 	 * is used as a normal link would be.
4382 	 */
4383 	if (DOINGSUJ(dvp))
4384 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4385 		    dp->i_effnlink - 1, dp->i_mode);
4386 	ACQUIRE_LOCK(&lk);
4387 	inodedep = inodedep_lookup_ip(dp);
4388 	if (jaddref)
4389 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4390 		    if_deps);
4391 	softdep_prelink(dvp, ITOV(ip));
4392 	FREE_LOCK(&lk);
4393 }
4394 
4395 /*
4396  * Create a jaddref structure to track a new link to an inode.  The directory
4397  * offset is not known until softdep_setup_directory_add or
4398  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4399  * softdep.
4400  */
4401 void
4402 softdep_setup_link(dp, ip)
4403 	struct inode *dp;
4404 	struct inode *ip;
4405 {
4406 	struct inodedep *inodedep;
4407 	struct jaddref *jaddref;
4408 	struct vnode *dvp;
4409 
4410 	dvp = ITOV(dp);
4411 	jaddref = NULL;
4412 	if (DOINGSUJ(dvp))
4413 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4414 		    ip->i_mode);
4415 	ACQUIRE_LOCK(&lk);
4416 	inodedep = inodedep_lookup_ip(ip);
4417 	if (jaddref)
4418 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4419 		    if_deps);
4420 	softdep_prelink(dvp, ITOV(ip));
4421 	FREE_LOCK(&lk);
4422 }
4423 
4424 /*
4425  * Called to create the jaddref structures to track . and .. references as
4426  * well as lookup and further initialize the incomplete jaddref created
4427  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4428  * nlinkdelta for non-journaling softdep.
4429  */
4430 void
4431 softdep_setup_mkdir(dp, ip)
4432 	struct inode *dp;
4433 	struct inode *ip;
4434 {
4435 	struct inodedep *inodedep;
4436 	struct jaddref *dotdotaddref;
4437 	struct jaddref *dotaddref;
4438 	struct jaddref *jaddref;
4439 	struct vnode *dvp;
4440 
4441 	dvp = ITOV(dp);
4442 	dotaddref = dotdotaddref = NULL;
4443 	if (DOINGSUJ(dvp)) {
4444 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4445 		    ip->i_mode);
4446 		dotaddref->ja_state |= MKDIR_BODY;
4447 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4448 		    dp->i_effnlink - 1, dp->i_mode);
4449 		dotdotaddref->ja_state |= MKDIR_PARENT;
4450 	}
4451 	ACQUIRE_LOCK(&lk);
4452 	inodedep = inodedep_lookup_ip(ip);
4453 	if (DOINGSUJ(dvp)) {
4454 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4455 		    inoreflst);
4456 		KASSERT(jaddref != NULL,
4457 		    ("softdep_setup_mkdir: No addref structure present."));
4458 		KASSERT(jaddref->ja_parent == dp->i_number,
4459 		    ("softdep_setup_mkdir: bad parent %d",
4460 		    jaddref->ja_parent));
4461 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4462 		    if_deps);
4463 	}
4464 	inodedep = inodedep_lookup_ip(dp);
4465 	if (DOINGSUJ(dvp))
4466 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4467 		    &dotdotaddref->ja_ref, if_deps);
4468 	softdep_prelink(ITOV(dp), NULL);
4469 	FREE_LOCK(&lk);
4470 }
4471 
4472 /*
4473  * Called to track nlinkdelta of the inode and parent directories prior to
4474  * unlinking a directory.
4475  */
4476 void
4477 softdep_setup_rmdir(dp, ip)
4478 	struct inode *dp;
4479 	struct inode *ip;
4480 {
4481 	struct vnode *dvp;
4482 
4483 	dvp = ITOV(dp);
4484 	ACQUIRE_LOCK(&lk);
4485 	(void) inodedep_lookup_ip(ip);
4486 	(void) inodedep_lookup_ip(dp);
4487 	softdep_prelink(dvp, ITOV(ip));
4488 	FREE_LOCK(&lk);
4489 }
4490 
4491 /*
4492  * Called to track nlinkdelta of the inode and parent directories prior to
4493  * unlink.
4494  */
4495 void
4496 softdep_setup_unlink(dp, ip)
4497 	struct inode *dp;
4498 	struct inode *ip;
4499 {
4500 	struct vnode *dvp;
4501 
4502 	dvp = ITOV(dp);
4503 	ACQUIRE_LOCK(&lk);
4504 	(void) inodedep_lookup_ip(ip);
4505 	(void) inodedep_lookup_ip(dp);
4506 	softdep_prelink(dvp, ITOV(ip));
4507 	FREE_LOCK(&lk);
4508 }
4509 
4510 /*
4511  * Called to release the journal structures created by a failed non-directory
4512  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4513  */
4514 void
4515 softdep_revert_create(dp, ip)
4516 	struct inode *dp;
4517 	struct inode *ip;
4518 {
4519 	struct inodedep *inodedep;
4520 	struct jaddref *jaddref;
4521 	struct vnode *dvp;
4522 
4523 	dvp = ITOV(dp);
4524 	ACQUIRE_LOCK(&lk);
4525 	inodedep = inodedep_lookup_ip(ip);
4526 	if (DOINGSUJ(dvp)) {
4527 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4528 		    inoreflst);
4529 		KASSERT(jaddref->ja_parent == dp->i_number,
4530 		    ("softdep_revert_create: addref parent mismatch"));
4531 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4532 	}
4533 	FREE_LOCK(&lk);
4534 }
4535 
4536 /*
4537  * Called to release the journal structures created by a failed dotdot link
4538  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4539  */
4540 void
4541 softdep_revert_dotdot_link(dp, ip)
4542 	struct inode *dp;
4543 	struct inode *ip;
4544 {
4545 	struct inodedep *inodedep;
4546 	struct jaddref *jaddref;
4547 	struct vnode *dvp;
4548 
4549 	dvp = ITOV(dp);
4550 	ACQUIRE_LOCK(&lk);
4551 	inodedep = inodedep_lookup_ip(dp);
4552 	if (DOINGSUJ(dvp)) {
4553 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4554 		    inoreflst);
4555 		KASSERT(jaddref->ja_parent == ip->i_number,
4556 		    ("softdep_revert_dotdot_link: addref parent mismatch"));
4557 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4558 	}
4559 	FREE_LOCK(&lk);
4560 }
4561 
4562 /*
4563  * Called to release the journal structures created by a failed link
4564  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4565  */
4566 void
4567 softdep_revert_link(dp, ip)
4568 	struct inode *dp;
4569 	struct inode *ip;
4570 {
4571 	struct inodedep *inodedep;
4572 	struct jaddref *jaddref;
4573 	struct vnode *dvp;
4574 
4575 	dvp = ITOV(dp);
4576 	ACQUIRE_LOCK(&lk);
4577 	inodedep = inodedep_lookup_ip(ip);
4578 	if (DOINGSUJ(dvp)) {
4579 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4580 		    inoreflst);
4581 		KASSERT(jaddref->ja_parent == dp->i_number,
4582 		    ("softdep_revert_link: addref parent mismatch"));
4583 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4584 	}
4585 	FREE_LOCK(&lk);
4586 }
4587 
4588 /*
4589  * Called to release the journal structures created by a failed mkdir
4590  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4591  */
4592 void
4593 softdep_revert_mkdir(dp, ip)
4594 	struct inode *dp;
4595 	struct inode *ip;
4596 {
4597 	struct inodedep *inodedep;
4598 	struct jaddref *jaddref;
4599 	struct jaddref *dotaddref;
4600 	struct vnode *dvp;
4601 
4602 	dvp = ITOV(dp);
4603 
4604 	ACQUIRE_LOCK(&lk);
4605 	inodedep = inodedep_lookup_ip(dp);
4606 	if (DOINGSUJ(dvp)) {
4607 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4608 		    inoreflst);
4609 		KASSERT(jaddref->ja_parent == ip->i_number,
4610 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4611 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4612 	}
4613 	inodedep = inodedep_lookup_ip(ip);
4614 	if (DOINGSUJ(dvp)) {
4615 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4616 		    inoreflst);
4617 		KASSERT(jaddref->ja_parent == dp->i_number,
4618 		    ("softdep_revert_mkdir: addref parent mismatch"));
4619 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4620 		    inoreflst, if_deps);
4621 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4622 		KASSERT(dotaddref->ja_parent == ip->i_number,
4623 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4624 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4625 	}
4626 	FREE_LOCK(&lk);
4627 }
4628 
4629 /*
4630  * Called to correct nlinkdelta after a failed rmdir.
4631  */
4632 void
4633 softdep_revert_rmdir(dp, ip)
4634 	struct inode *dp;
4635 	struct inode *ip;
4636 {
4637 
4638 	ACQUIRE_LOCK(&lk);
4639 	(void) inodedep_lookup_ip(ip);
4640 	(void) inodedep_lookup_ip(dp);
4641 	FREE_LOCK(&lk);
4642 }
4643 
4644 /*
4645  * Protecting the freemaps (or bitmaps).
4646  *
4647  * To eliminate the need to execute fsck before mounting a filesystem
4648  * after a power failure, one must (conservatively) guarantee that the
4649  * on-disk copy of the bitmaps never indicate that a live inode or block is
4650  * free.  So, when a block or inode is allocated, the bitmap should be
4651  * updated (on disk) before any new pointers.  When a block or inode is
4652  * freed, the bitmap should not be updated until all pointers have been
4653  * reset.  The latter dependency is handled by the delayed de-allocation
4654  * approach described below for block and inode de-allocation.  The former
4655  * dependency is handled by calling the following procedure when a block or
4656  * inode is allocated. When an inode is allocated an "inodedep" is created
4657  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4658  * Each "inodedep" is also inserted into the hash indexing structure so
4659  * that any additional link additions can be made dependent on the inode
4660  * allocation.
4661  *
4662  * The ufs filesystem maintains a number of free block counts (e.g., per
4663  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4664  * in addition to the bitmaps.  These counts are used to improve efficiency
4665  * during allocation and therefore must be consistent with the bitmaps.
4666  * There is no convenient way to guarantee post-crash consistency of these
4667  * counts with simple update ordering, for two main reasons: (1) The counts
4668  * and bitmaps for a single cylinder group block are not in the same disk
4669  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4670  * be written and the other not.  (2) Some of the counts are located in the
4671  * superblock rather than the cylinder group block. So, we focus our soft
4672  * updates implementation on protecting the bitmaps. When mounting a
4673  * filesystem, we recompute the auxiliary counts from the bitmaps.
4674  */
4675 
4676 /*
4677  * Called just after updating the cylinder group block to allocate an inode.
4678  */
4679 void
4680 softdep_setup_inomapdep(bp, ip, newinum, mode)
4681 	struct buf *bp;		/* buffer for cylgroup block with inode map */
4682 	struct inode *ip;	/* inode related to allocation */
4683 	ino_t newinum;		/* new inode number being allocated */
4684 	int mode;
4685 {
4686 	struct inodedep *inodedep;
4687 	struct bmsafemap *bmsafemap;
4688 	struct jaddref *jaddref;
4689 	struct mount *mp;
4690 	struct fs *fs;
4691 
4692 	mp = UFSTOVFS(ip->i_ump);
4693 	fs = ip->i_ump->um_fs;
4694 	jaddref = NULL;
4695 
4696 	/*
4697 	 * Allocate the journal reference add structure so that the bitmap
4698 	 * can be dependent on it.
4699 	 */
4700 	if (MOUNTEDSUJ(mp)) {
4701 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
4702 		jaddref->ja_state |= NEWBLOCK;
4703 	}
4704 
4705 	/*
4706 	 * Create a dependency for the newly allocated inode.
4707 	 * Panic if it already exists as something is seriously wrong.
4708 	 * Otherwise add it to the dependency list for the buffer holding
4709 	 * the cylinder group map from which it was allocated.
4710 	 */
4711 	ACQUIRE_LOCK(&lk);
4712 	if ((inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep)))
4713 		panic("softdep_setup_inomapdep: dependency %p for new"
4714 		    "inode already exists", inodedep);
4715 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum));
4716 	if (jaddref) {
4717 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
4718 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4719 		    if_deps);
4720 	} else {
4721 		inodedep->id_state |= ONDEPLIST;
4722 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
4723 	}
4724 	inodedep->id_bmsafemap = bmsafemap;
4725 	inodedep->id_state &= ~DEPCOMPLETE;
4726 	FREE_LOCK(&lk);
4727 }
4728 
4729 /*
4730  * Called just after updating the cylinder group block to
4731  * allocate block or fragment.
4732  */
4733 void
4734 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
4735 	struct buf *bp;		/* buffer for cylgroup block with block map */
4736 	struct mount *mp;	/* filesystem doing allocation */
4737 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
4738 	int frags;		/* Number of fragments. */
4739 	int oldfrags;		/* Previous number of fragments for extend. */
4740 {
4741 	struct newblk *newblk;
4742 	struct bmsafemap *bmsafemap;
4743 	struct jnewblk *jnewblk;
4744 	struct fs *fs;
4745 
4746 	fs = VFSTOUFS(mp)->um_fs;
4747 	jnewblk = NULL;
4748 	/*
4749 	 * Create a dependency for the newly allocated block.
4750 	 * Add it to the dependency list for the buffer holding
4751 	 * the cylinder group map from which it was allocated.
4752 	 */
4753 	if (MOUNTEDSUJ(mp)) {
4754 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
4755 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
4756 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
4757 		jnewblk->jn_state = ATTACHED;
4758 		jnewblk->jn_blkno = newblkno;
4759 		jnewblk->jn_frags = frags;
4760 		jnewblk->jn_oldfrags = oldfrags;
4761 #ifdef SUJ_DEBUG
4762 		{
4763 			struct cg *cgp;
4764 			uint8_t *blksfree;
4765 			long bno;
4766 			int i;
4767 
4768 			cgp = (struct cg *)bp->b_data;
4769 			blksfree = cg_blksfree(cgp);
4770 			bno = dtogd(fs, jnewblk->jn_blkno);
4771 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
4772 			    i++) {
4773 				if (isset(blksfree, bno + i))
4774 					panic("softdep_setup_blkmapdep: "
4775 					    "free fragment %d from %d-%d "
4776 					    "state 0x%X dep %p", i,
4777 					    jnewblk->jn_oldfrags,
4778 					    jnewblk->jn_frags,
4779 					    jnewblk->jn_state,
4780 					    jnewblk->jn_dep);
4781 			}
4782 		}
4783 #endif
4784 	}
4785 	ACQUIRE_LOCK(&lk);
4786 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
4787 		panic("softdep_setup_blkmapdep: found block");
4788 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
4789 	    dtog(fs, newblkno));
4790 	if (jnewblk) {
4791 		jnewblk->jn_dep = (struct worklist *)newblk;
4792 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
4793 	} else {
4794 		newblk->nb_state |= ONDEPLIST;
4795 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
4796 	}
4797 	newblk->nb_bmsafemap = bmsafemap;
4798 	newblk->nb_jnewblk = jnewblk;
4799 	FREE_LOCK(&lk);
4800 }
4801 
4802 #define	BMSAFEMAP_HASH(fs, cg) \
4803       (&bmsafemap_hashtbl[((((register_t)(fs)) >> 13) + (cg)) & bmsafemap_hash])
4804 
4805 static int
4806 bmsafemap_find(bmsafemaphd, mp, cg, bmsafemapp)
4807 	struct bmsafemap_hashhead *bmsafemaphd;
4808 	struct mount *mp;
4809 	int cg;
4810 	struct bmsafemap **bmsafemapp;
4811 {
4812 	struct bmsafemap *bmsafemap;
4813 
4814 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
4815 		if (bmsafemap->sm_list.wk_mp == mp && bmsafemap->sm_cg == cg)
4816 			break;
4817 	if (bmsafemap) {
4818 		*bmsafemapp = bmsafemap;
4819 		return (1);
4820 	}
4821 	*bmsafemapp = NULL;
4822 
4823 	return (0);
4824 }
4825 
4826 /*
4827  * Find the bmsafemap associated with a cylinder group buffer.
4828  * If none exists, create one. The buffer must be locked when
4829  * this routine is called and this routine must be called with
4830  * splbio interrupts blocked.
4831  */
4832 static struct bmsafemap *
4833 bmsafemap_lookup(mp, bp, cg)
4834 	struct mount *mp;
4835 	struct buf *bp;
4836 	int cg;
4837 {
4838 	struct bmsafemap_hashhead *bmsafemaphd;
4839 	struct bmsafemap *bmsafemap, *collision;
4840 	struct worklist *wk;
4841 	struct fs *fs;
4842 
4843 	mtx_assert(&lk, MA_OWNED);
4844 	if (bp)
4845 		LIST_FOREACH(wk, &bp->b_dep, wk_list)
4846 			if (wk->wk_type == D_BMSAFEMAP)
4847 				return (WK_BMSAFEMAP(wk));
4848 	fs = VFSTOUFS(mp)->um_fs;
4849 	bmsafemaphd = BMSAFEMAP_HASH(fs, cg);
4850 	if (bmsafemap_find(bmsafemaphd, mp, cg, &bmsafemap) == 1)
4851 		return (bmsafemap);
4852 	FREE_LOCK(&lk);
4853 	bmsafemap = malloc(sizeof(struct bmsafemap),
4854 		M_BMSAFEMAP, M_SOFTDEP_FLAGS);
4855 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
4856 	bmsafemap->sm_buf = bp;
4857 	LIST_INIT(&bmsafemap->sm_inodedephd);
4858 	LIST_INIT(&bmsafemap->sm_inodedepwr);
4859 	LIST_INIT(&bmsafemap->sm_newblkhd);
4860 	LIST_INIT(&bmsafemap->sm_newblkwr);
4861 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
4862 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
4863 	LIST_INIT(&bmsafemap->sm_freehd);
4864 	LIST_INIT(&bmsafemap->sm_freewr);
4865 	ACQUIRE_LOCK(&lk);
4866 	if (bmsafemap_find(bmsafemaphd, mp, cg, &collision) == 1) {
4867 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
4868 		return (collision);
4869 	}
4870 	bmsafemap->sm_cg = cg;
4871 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
4872 	LIST_INSERT_HEAD(&VFSTOUFS(mp)->softdep_dirtycg, bmsafemap, sm_next);
4873 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
4874 	return (bmsafemap);
4875 }
4876 
4877 /*
4878  * Direct block allocation dependencies.
4879  *
4880  * When a new block is allocated, the corresponding disk locations must be
4881  * initialized (with zeros or new data) before the on-disk inode points to
4882  * them.  Also, the freemap from which the block was allocated must be
4883  * updated (on disk) before the inode's pointer. These two dependencies are
4884  * independent of each other and are needed for all file blocks and indirect
4885  * blocks that are pointed to directly by the inode.  Just before the
4886  * "in-core" version of the inode is updated with a newly allocated block
4887  * number, a procedure (below) is called to setup allocation dependency
4888  * structures.  These structures are removed when the corresponding
4889  * dependencies are satisfied or when the block allocation becomes obsolete
4890  * (i.e., the file is deleted, the block is de-allocated, or the block is a
4891  * fragment that gets upgraded).  All of these cases are handled in
4892  * procedures described later.
4893  *
4894  * When a file extension causes a fragment to be upgraded, either to a larger
4895  * fragment or to a full block, the on-disk location may change (if the
4896  * previous fragment could not simply be extended). In this case, the old
4897  * fragment must be de-allocated, but not until after the inode's pointer has
4898  * been updated. In most cases, this is handled by later procedures, which
4899  * will construct a "freefrag" structure to be added to the workitem queue
4900  * when the inode update is complete (or obsolete).  The main exception to
4901  * this is when an allocation occurs while a pending allocation dependency
4902  * (for the same block pointer) remains.  This case is handled in the main
4903  * allocation dependency setup procedure by immediately freeing the
4904  * unreferenced fragments.
4905  */
4906 void
4907 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
4908 	struct inode *ip;	/* inode to which block is being added */
4909 	ufs_lbn_t off;		/* block pointer within inode */
4910 	ufs2_daddr_t newblkno;	/* disk block number being added */
4911 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
4912 	long newsize;		/* size of new block */
4913 	long oldsize;		/* size of new block */
4914 	struct buf *bp;		/* bp for allocated block */
4915 {
4916 	struct allocdirect *adp, *oldadp;
4917 	struct allocdirectlst *adphead;
4918 	struct freefrag *freefrag;
4919 	struct inodedep *inodedep;
4920 	struct pagedep *pagedep;
4921 	struct jnewblk *jnewblk;
4922 	struct newblk *newblk;
4923 	struct mount *mp;
4924 	ufs_lbn_t lbn;
4925 
4926 	lbn = bp->b_lblkno;
4927 	mp = UFSTOVFS(ip->i_ump);
4928 	if (oldblkno && oldblkno != newblkno)
4929 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
4930 	else
4931 		freefrag = NULL;
4932 
4933 	ACQUIRE_LOCK(&lk);
4934 	if (off >= NDADDR) {
4935 		if (lbn > 0)
4936 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
4937 			    lbn, off);
4938 		/* allocating an indirect block */
4939 		if (oldblkno != 0)
4940 			panic("softdep_setup_allocdirect: non-zero indir");
4941 	} else {
4942 		if (off != lbn)
4943 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
4944 			    lbn, off);
4945 		/*
4946 		 * Allocating a direct block.
4947 		 *
4948 		 * If we are allocating a directory block, then we must
4949 		 * allocate an associated pagedep to track additions and
4950 		 * deletions.
4951 		 */
4952 		if ((ip->i_mode & IFMT) == IFDIR)
4953 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
4954 			    &pagedep);
4955 	}
4956 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
4957 		panic("softdep_setup_allocdirect: lost block");
4958 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
4959 	    ("softdep_setup_allocdirect: newblk already initialized"));
4960 	/*
4961 	 * Convert the newblk to an allocdirect.
4962 	 */
4963 	newblk->nb_list.wk_type = D_ALLOCDIRECT;
4964 	adp = (struct allocdirect *)newblk;
4965 	newblk->nb_freefrag = freefrag;
4966 	adp->ad_offset = off;
4967 	adp->ad_oldblkno = oldblkno;
4968 	adp->ad_newsize = newsize;
4969 	adp->ad_oldsize = oldsize;
4970 
4971 	/*
4972 	 * Finish initializing the journal.
4973 	 */
4974 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
4975 		jnewblk->jn_ino = ip->i_number;
4976 		jnewblk->jn_lbn = lbn;
4977 		add_to_journal(&jnewblk->jn_list);
4978 	}
4979 	if (freefrag && freefrag->ff_jdep != NULL &&
4980 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
4981 		add_to_journal(freefrag->ff_jdep);
4982 	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
4983 	adp->ad_inodedep = inodedep;
4984 
4985 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
4986 	/*
4987 	 * The list of allocdirects must be kept in sorted and ascending
4988 	 * order so that the rollback routines can quickly determine the
4989 	 * first uncommitted block (the size of the file stored on disk
4990 	 * ends at the end of the lowest committed fragment, or if there
4991 	 * are no fragments, at the end of the highest committed block).
4992 	 * Since files generally grow, the typical case is that the new
4993 	 * block is to be added at the end of the list. We speed this
4994 	 * special case by checking against the last allocdirect in the
4995 	 * list before laboriously traversing the list looking for the
4996 	 * insertion point.
4997 	 */
4998 	adphead = &inodedep->id_newinoupdt;
4999 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5000 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5001 		/* insert at end of list */
5002 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5003 		if (oldadp != NULL && oldadp->ad_offset == off)
5004 			allocdirect_merge(adphead, adp, oldadp);
5005 		FREE_LOCK(&lk);
5006 		return;
5007 	}
5008 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5009 		if (oldadp->ad_offset >= off)
5010 			break;
5011 	}
5012 	if (oldadp == NULL)
5013 		panic("softdep_setup_allocdirect: lost entry");
5014 	/* insert in middle of list */
5015 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5016 	if (oldadp->ad_offset == off)
5017 		allocdirect_merge(adphead, adp, oldadp);
5018 
5019 	FREE_LOCK(&lk);
5020 }
5021 
5022 /*
5023  * Merge a newer and older journal record to be stored either in a
5024  * newblock or freefrag.  This handles aggregating journal records for
5025  * fragment allocation into a second record as well as replacing a
5026  * journal free with an aborted journal allocation.  A segment for the
5027  * oldest record will be placed on wkhd if it has been written.  If not
5028  * the segment for the newer record will suffice.
5029  */
5030 static struct worklist *
5031 jnewblk_merge(new, old, wkhd)
5032 	struct worklist *new;
5033 	struct worklist *old;
5034 	struct workhead *wkhd;
5035 {
5036 	struct jnewblk *njnewblk;
5037 	struct jnewblk *jnewblk;
5038 
5039 	/* Handle NULLs to simplify callers. */
5040 	if (new == NULL)
5041 		return (old);
5042 	if (old == NULL)
5043 		return (new);
5044 	/* Replace a jfreefrag with a jnewblk. */
5045 	if (new->wk_type == D_JFREEFRAG) {
5046 		cancel_jfreefrag(WK_JFREEFRAG(new));
5047 		return (old);
5048 	}
5049 	/*
5050 	 * Handle merging of two jnewblk records that describe
5051 	 * different sets of fragments in the same block.
5052 	 */
5053 	jnewblk = WK_JNEWBLK(old);
5054 	njnewblk = WK_JNEWBLK(new);
5055 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5056 		panic("jnewblk_merge: Merging disparate blocks.");
5057 	/*
5058 	 * The record may be rolled back in the cg.
5059 	 */
5060 	if (jnewblk->jn_state & UNDONE) {
5061 		jnewblk->jn_state &= ~UNDONE;
5062 		njnewblk->jn_state |= UNDONE;
5063 		njnewblk->jn_state &= ~ATTACHED;
5064 	}
5065 	/*
5066 	 * We modify the newer addref and free the older so that if neither
5067 	 * has been written the most up-to-date copy will be on disk.  If
5068 	 * both have been written but rolled back we only temporarily need
5069 	 * one of them to fix the bits when the cg write completes.
5070 	 */
5071 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5072 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5073 	cancel_jnewblk(jnewblk, wkhd);
5074 	WORKLIST_REMOVE(&jnewblk->jn_list);
5075 	free_jnewblk(jnewblk);
5076 	return (new);
5077 }
5078 
5079 /*
5080  * Replace an old allocdirect dependency with a newer one.
5081  * This routine must be called with splbio interrupts blocked.
5082  */
5083 static void
5084 allocdirect_merge(adphead, newadp, oldadp)
5085 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5086 	struct allocdirect *newadp;	/* allocdirect being added */
5087 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5088 {
5089 	struct worklist *wk;
5090 	struct freefrag *freefrag;
5091 
5092 	freefrag = NULL;
5093 	mtx_assert(&lk, MA_OWNED);
5094 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5095 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5096 	    newadp->ad_offset >= NDADDR)
5097 		panic("%s %jd != new %jd || old size %ld != new %ld",
5098 		    "allocdirect_merge: old blkno",
5099 		    (intmax_t)newadp->ad_oldblkno,
5100 		    (intmax_t)oldadp->ad_newblkno,
5101 		    newadp->ad_oldsize, oldadp->ad_newsize);
5102 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5103 	newadp->ad_oldsize = oldadp->ad_oldsize;
5104 	/*
5105 	 * If the old dependency had a fragment to free or had never
5106 	 * previously had a block allocated, then the new dependency
5107 	 * can immediately post its freefrag and adopt the old freefrag.
5108 	 * This action is done by swapping the freefrag dependencies.
5109 	 * The new dependency gains the old one's freefrag, and the
5110 	 * old one gets the new one and then immediately puts it on
5111 	 * the worklist when it is freed by free_newblk. It is
5112 	 * not possible to do this swap when the old dependency had a
5113 	 * non-zero size but no previous fragment to free. This condition
5114 	 * arises when the new block is an extension of the old block.
5115 	 * Here, the first part of the fragment allocated to the new
5116 	 * dependency is part of the block currently claimed on disk by
5117 	 * the old dependency, so cannot legitimately be freed until the
5118 	 * conditions for the new dependency are fulfilled.
5119 	 */
5120 	freefrag = newadp->ad_freefrag;
5121 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5122 		newadp->ad_freefrag = oldadp->ad_freefrag;
5123 		oldadp->ad_freefrag = freefrag;
5124 	}
5125 	/*
5126 	 * If we are tracking a new directory-block allocation,
5127 	 * move it from the old allocdirect to the new allocdirect.
5128 	 */
5129 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5130 		WORKLIST_REMOVE(wk);
5131 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5132 			panic("allocdirect_merge: extra newdirblk");
5133 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5134 	}
5135 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5136 	/*
5137 	 * We need to move any journal dependencies over to the freefrag
5138 	 * that releases this block if it exists.  Otherwise we are
5139 	 * extending an existing block and we'll wait until that is
5140 	 * complete to release the journal space and extend the
5141 	 * new journal to cover this old space as well.
5142 	 */
5143 	if (freefrag == NULL) {
5144 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5145 			panic("allocdirect_merge: %jd != %jd",
5146 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5147 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5148 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5149 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5150 		    &newadp->ad_block.nb_jwork);
5151 		oldadp->ad_block.nb_jnewblk = NULL;
5152 		cancel_newblk(&oldadp->ad_block, NULL,
5153 		    &newadp->ad_block.nb_jwork);
5154 	} else {
5155 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5156 		    &freefrag->ff_list, &freefrag->ff_jwork);
5157 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5158 		    &freefrag->ff_jwork);
5159 	}
5160 	free_newblk(&oldadp->ad_block);
5161 }
5162 
5163 /*
5164  * Allocate a jfreefrag structure to journal a single block free.
5165  */
5166 static struct jfreefrag *
5167 newjfreefrag(freefrag, ip, blkno, size, lbn)
5168 	struct freefrag *freefrag;
5169 	struct inode *ip;
5170 	ufs2_daddr_t blkno;
5171 	long size;
5172 	ufs_lbn_t lbn;
5173 {
5174 	struct jfreefrag *jfreefrag;
5175 	struct fs *fs;
5176 
5177 	fs = ip->i_fs;
5178 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5179 	    M_SOFTDEP_FLAGS);
5180 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, UFSTOVFS(ip->i_ump));
5181 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5182 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5183 	jfreefrag->fr_ino = ip->i_number;
5184 	jfreefrag->fr_lbn = lbn;
5185 	jfreefrag->fr_blkno = blkno;
5186 	jfreefrag->fr_frags = numfrags(fs, size);
5187 	jfreefrag->fr_freefrag = freefrag;
5188 
5189 	return (jfreefrag);
5190 }
5191 
5192 /*
5193  * Allocate a new freefrag structure.
5194  */
5195 static struct freefrag *
5196 newfreefrag(ip, blkno, size, lbn)
5197 	struct inode *ip;
5198 	ufs2_daddr_t blkno;
5199 	long size;
5200 	ufs_lbn_t lbn;
5201 {
5202 	struct freefrag *freefrag;
5203 	struct fs *fs;
5204 
5205 	fs = ip->i_fs;
5206 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5207 		panic("newfreefrag: frag size");
5208 	freefrag = malloc(sizeof(struct freefrag),
5209 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5210 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ip->i_ump));
5211 	freefrag->ff_state = ATTACHED;
5212 	LIST_INIT(&freefrag->ff_jwork);
5213 	freefrag->ff_inum = ip->i_number;
5214 	freefrag->ff_vtype = ITOV(ip)->v_type;
5215 	freefrag->ff_blkno = blkno;
5216 	freefrag->ff_fragsize = size;
5217 
5218 	if (MOUNTEDSUJ(UFSTOVFS(ip->i_ump))) {
5219 		freefrag->ff_jdep = (struct worklist *)
5220 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5221 	} else {
5222 		freefrag->ff_state |= DEPCOMPLETE;
5223 		freefrag->ff_jdep = NULL;
5224 	}
5225 
5226 	return (freefrag);
5227 }
5228 
5229 /*
5230  * This workitem de-allocates fragments that were replaced during
5231  * file block allocation.
5232  */
5233 static void
5234 handle_workitem_freefrag(freefrag)
5235 	struct freefrag *freefrag;
5236 {
5237 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5238 	struct workhead wkhd;
5239 
5240 	/*
5241 	 * It would be illegal to add new completion items to the
5242 	 * freefrag after it was schedule to be done so it must be
5243 	 * safe to modify the list head here.
5244 	 */
5245 	LIST_INIT(&wkhd);
5246 	ACQUIRE_LOCK(&lk);
5247 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5248 	/*
5249 	 * If the journal has not been written we must cancel it here.
5250 	 */
5251 	if (freefrag->ff_jdep) {
5252 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5253 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5254 			    freefrag->ff_jdep->wk_type);
5255 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5256 	}
5257 	FREE_LOCK(&lk);
5258 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5259 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5260 	ACQUIRE_LOCK(&lk);
5261 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5262 	FREE_LOCK(&lk);
5263 }
5264 
5265 /*
5266  * Set up a dependency structure for an external attributes data block.
5267  * This routine follows much of the structure of softdep_setup_allocdirect.
5268  * See the description of softdep_setup_allocdirect above for details.
5269  */
5270 void
5271 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5272 	struct inode *ip;
5273 	ufs_lbn_t off;
5274 	ufs2_daddr_t newblkno;
5275 	ufs2_daddr_t oldblkno;
5276 	long newsize;
5277 	long oldsize;
5278 	struct buf *bp;
5279 {
5280 	struct allocdirect *adp, *oldadp;
5281 	struct allocdirectlst *adphead;
5282 	struct freefrag *freefrag;
5283 	struct inodedep *inodedep;
5284 	struct jnewblk *jnewblk;
5285 	struct newblk *newblk;
5286 	struct mount *mp;
5287 	ufs_lbn_t lbn;
5288 
5289 	if (off >= NXADDR)
5290 		panic("softdep_setup_allocext: lbn %lld > NXADDR",
5291 		    (long long)off);
5292 
5293 	lbn = bp->b_lblkno;
5294 	mp = UFSTOVFS(ip->i_ump);
5295 	if (oldblkno && oldblkno != newblkno)
5296 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5297 	else
5298 		freefrag = NULL;
5299 
5300 	ACQUIRE_LOCK(&lk);
5301 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5302 		panic("softdep_setup_allocext: lost block");
5303 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5304 	    ("softdep_setup_allocext: newblk already initialized"));
5305 	/*
5306 	 * Convert the newblk to an allocdirect.
5307 	 */
5308 	newblk->nb_list.wk_type = D_ALLOCDIRECT;
5309 	adp = (struct allocdirect *)newblk;
5310 	newblk->nb_freefrag = freefrag;
5311 	adp->ad_offset = off;
5312 	adp->ad_oldblkno = oldblkno;
5313 	adp->ad_newsize = newsize;
5314 	adp->ad_oldsize = oldsize;
5315 	adp->ad_state |=  EXTDATA;
5316 
5317 	/*
5318 	 * Finish initializing the journal.
5319 	 */
5320 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5321 		jnewblk->jn_ino = ip->i_number;
5322 		jnewblk->jn_lbn = lbn;
5323 		add_to_journal(&jnewblk->jn_list);
5324 	}
5325 	if (freefrag && freefrag->ff_jdep != NULL &&
5326 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5327 		add_to_journal(freefrag->ff_jdep);
5328 	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
5329 	adp->ad_inodedep = inodedep;
5330 
5331 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5332 	/*
5333 	 * The list of allocdirects must be kept in sorted and ascending
5334 	 * order so that the rollback routines can quickly determine the
5335 	 * first uncommitted block (the size of the file stored on disk
5336 	 * ends at the end of the lowest committed fragment, or if there
5337 	 * are no fragments, at the end of the highest committed block).
5338 	 * Since files generally grow, the typical case is that the new
5339 	 * block is to be added at the end of the list. We speed this
5340 	 * special case by checking against the last allocdirect in the
5341 	 * list before laboriously traversing the list looking for the
5342 	 * insertion point.
5343 	 */
5344 	adphead = &inodedep->id_newextupdt;
5345 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5346 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5347 		/* insert at end of list */
5348 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5349 		if (oldadp != NULL && oldadp->ad_offset == off)
5350 			allocdirect_merge(adphead, adp, oldadp);
5351 		FREE_LOCK(&lk);
5352 		return;
5353 	}
5354 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5355 		if (oldadp->ad_offset >= off)
5356 			break;
5357 	}
5358 	if (oldadp == NULL)
5359 		panic("softdep_setup_allocext: lost entry");
5360 	/* insert in middle of list */
5361 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5362 	if (oldadp->ad_offset == off)
5363 		allocdirect_merge(adphead, adp, oldadp);
5364 	FREE_LOCK(&lk);
5365 }
5366 
5367 /*
5368  * Indirect block allocation dependencies.
5369  *
5370  * The same dependencies that exist for a direct block also exist when
5371  * a new block is allocated and pointed to by an entry in a block of
5372  * indirect pointers. The undo/redo states described above are also
5373  * used here. Because an indirect block contains many pointers that
5374  * may have dependencies, a second copy of the entire in-memory indirect
5375  * block is kept. The buffer cache copy is always completely up-to-date.
5376  * The second copy, which is used only as a source for disk writes,
5377  * contains only the safe pointers (i.e., those that have no remaining
5378  * update dependencies). The second copy is freed when all pointers
5379  * are safe. The cache is not allowed to replace indirect blocks with
5380  * pending update dependencies. If a buffer containing an indirect
5381  * block with dependencies is written, these routines will mark it
5382  * dirty again. It can only be successfully written once all the
5383  * dependencies are removed. The ffs_fsync routine in conjunction with
5384  * softdep_sync_metadata work together to get all the dependencies
5385  * removed so that a file can be successfully written to disk. Three
5386  * procedures are used when setting up indirect block pointer
5387  * dependencies. The division is necessary because of the organization
5388  * of the "balloc" routine and because of the distinction between file
5389  * pages and file metadata blocks.
5390  */
5391 
5392 /*
5393  * Allocate a new allocindir structure.
5394  */
5395 static struct allocindir *
5396 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5397 	struct inode *ip;	/* inode for file being extended */
5398 	int ptrno;		/* offset of pointer in indirect block */
5399 	ufs2_daddr_t newblkno;	/* disk block number being added */
5400 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5401 	ufs_lbn_t lbn;
5402 {
5403 	struct newblk *newblk;
5404 	struct allocindir *aip;
5405 	struct freefrag *freefrag;
5406 	struct jnewblk *jnewblk;
5407 
5408 	if (oldblkno)
5409 		freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize, lbn);
5410 	else
5411 		freefrag = NULL;
5412 	ACQUIRE_LOCK(&lk);
5413 	if (newblk_lookup(UFSTOVFS(ip->i_ump), newblkno, 0, &newblk) == 0)
5414 		panic("new_allocindir: lost block");
5415 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5416 	    ("newallocindir: newblk already initialized"));
5417 	newblk->nb_list.wk_type = D_ALLOCINDIR;
5418 	newblk->nb_freefrag = freefrag;
5419 	aip = (struct allocindir *)newblk;
5420 	aip->ai_offset = ptrno;
5421 	aip->ai_oldblkno = oldblkno;
5422 	aip->ai_lbn = lbn;
5423 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5424 		jnewblk->jn_ino = ip->i_number;
5425 		jnewblk->jn_lbn = lbn;
5426 		add_to_journal(&jnewblk->jn_list);
5427 	}
5428 	if (freefrag && freefrag->ff_jdep != NULL &&
5429 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5430 		add_to_journal(freefrag->ff_jdep);
5431 	return (aip);
5432 }
5433 
5434 /*
5435  * Called just before setting an indirect block pointer
5436  * to a newly allocated file page.
5437  */
5438 void
5439 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5440 	struct inode *ip;	/* inode for file being extended */
5441 	ufs_lbn_t lbn;		/* allocated block number within file */
5442 	struct buf *bp;		/* buffer with indirect blk referencing page */
5443 	int ptrno;		/* offset of pointer in indirect block */
5444 	ufs2_daddr_t newblkno;	/* disk block number being added */
5445 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5446 	struct buf *nbp;	/* buffer holding allocated page */
5447 {
5448 	struct inodedep *inodedep;
5449 	struct freefrag *freefrag;
5450 	struct allocindir *aip;
5451 	struct pagedep *pagedep;
5452 	struct mount *mp;
5453 	int dflags;
5454 
5455 	if (lbn != nbp->b_lblkno)
5456 		panic("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5457 		    lbn, bp->b_lblkno);
5458 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5459 	mp = UFSTOVFS(ip->i_ump);
5460 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5461 	dflags = DEPALLOC;
5462 	if (IS_SNAPSHOT(ip))
5463 		dflags |= NODELAY;
5464 	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
5465 	/*
5466 	 * If we are allocating a directory page, then we must
5467 	 * allocate an associated pagedep to track additions and
5468 	 * deletions.
5469 	 */
5470 	if ((ip->i_mode & IFMT) == IFDIR)
5471 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5472 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5473 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5474 	FREE_LOCK(&lk);
5475 	if (freefrag)
5476 		handle_workitem_freefrag(freefrag);
5477 }
5478 
5479 /*
5480  * Called just before setting an indirect block pointer to a
5481  * newly allocated indirect block.
5482  */
5483 void
5484 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5485 	struct buf *nbp;	/* newly allocated indirect block */
5486 	struct inode *ip;	/* inode for file being extended */
5487 	struct buf *bp;		/* indirect block referencing allocated block */
5488 	int ptrno;		/* offset of pointer in indirect block */
5489 	ufs2_daddr_t newblkno;	/* disk block number being added */
5490 {
5491 	struct inodedep *inodedep;
5492 	struct allocindir *aip;
5493 	ufs_lbn_t lbn;
5494 	int dflags;
5495 
5496 	lbn = nbp->b_lblkno;
5497 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5498 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5499 	dflags = DEPALLOC;
5500 	if (IS_SNAPSHOT(ip))
5501 		dflags |= NODELAY;
5502 	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags, &inodedep);
5503 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5504 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5505 		panic("softdep_setup_allocindir_meta: Block already existed");
5506 	FREE_LOCK(&lk);
5507 }
5508 
5509 static void
5510 indirdep_complete(indirdep)
5511 	struct indirdep *indirdep;
5512 {
5513 	struct allocindir *aip;
5514 
5515 	LIST_REMOVE(indirdep, ir_next);
5516 	indirdep->ir_state |= DEPCOMPLETE;
5517 
5518 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5519 		LIST_REMOVE(aip, ai_next);
5520 		free_newblk(&aip->ai_block);
5521 	}
5522 	/*
5523 	 * If this indirdep is not attached to a buf it was simply waiting
5524 	 * on completion to clear completehd.  free_indirdep() asserts
5525 	 * that nothing is dangling.
5526 	 */
5527 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5528 		free_indirdep(indirdep);
5529 }
5530 
5531 static struct indirdep *
5532 indirdep_lookup(mp, ip, bp)
5533 	struct mount *mp;
5534 	struct inode *ip;
5535 	struct buf *bp;
5536 {
5537 	struct indirdep *indirdep, *newindirdep;
5538 	struct newblk *newblk;
5539 	struct worklist *wk;
5540 	struct fs *fs;
5541 	ufs2_daddr_t blkno;
5542 
5543 	mtx_assert(&lk, MA_OWNED);
5544 	indirdep = NULL;
5545 	newindirdep = NULL;
5546 	fs = ip->i_fs;
5547 	for (;;) {
5548 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5549 			if (wk->wk_type != D_INDIRDEP)
5550 				continue;
5551 			indirdep = WK_INDIRDEP(wk);
5552 			break;
5553 		}
5554 		/* Found on the buffer worklist, no new structure to free. */
5555 		if (indirdep != NULL && newindirdep == NULL)
5556 			return (indirdep);
5557 		if (indirdep != NULL && newindirdep != NULL)
5558 			panic("indirdep_lookup: simultaneous create");
5559 		/* None found on the buffer and a new structure is ready. */
5560 		if (indirdep == NULL && newindirdep != NULL)
5561 			break;
5562 		/* None found and no new structure available. */
5563 		FREE_LOCK(&lk);
5564 		newindirdep = malloc(sizeof(struct indirdep),
5565 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
5566 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5567 		newindirdep->ir_state = ATTACHED;
5568 		if (ip->i_ump->um_fstype == UFS1)
5569 			newindirdep->ir_state |= UFS1FMT;
5570 		TAILQ_INIT(&newindirdep->ir_trunc);
5571 		newindirdep->ir_saveddata = NULL;
5572 		LIST_INIT(&newindirdep->ir_deplisthd);
5573 		LIST_INIT(&newindirdep->ir_donehd);
5574 		LIST_INIT(&newindirdep->ir_writehd);
5575 		LIST_INIT(&newindirdep->ir_completehd);
5576 		if (bp->b_blkno == bp->b_lblkno) {
5577 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5578 			    NULL, NULL);
5579 			bp->b_blkno = blkno;
5580 		}
5581 		newindirdep->ir_freeblks = NULL;
5582 		newindirdep->ir_savebp =
5583 		    getblk(ip->i_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5584 		newindirdep->ir_bp = bp;
5585 		BUF_KERNPROC(newindirdep->ir_savebp);
5586 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5587 		ACQUIRE_LOCK(&lk);
5588 	}
5589 	indirdep = newindirdep;
5590 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5591 	/*
5592 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
5593 	 * that we don't free dependencies until the pointers are valid.
5594 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5595 	 * than using the hash.
5596 	 */
5597 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5598 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5599 	else
5600 		indirdep->ir_state |= DEPCOMPLETE;
5601 	return (indirdep);
5602 }
5603 
5604 /*
5605  * Called to finish the allocation of the "aip" allocated
5606  * by one of the two routines above.
5607  */
5608 static struct freefrag *
5609 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
5610 	struct buf *bp;		/* in-memory copy of the indirect block */
5611 	struct inode *ip;	/* inode for file being extended */
5612 	struct inodedep *inodedep; /* Inodedep for ip */
5613 	struct allocindir *aip;	/* allocindir allocated by the above routines */
5614 	ufs_lbn_t lbn;		/* Logical block number for this block. */
5615 {
5616 	struct fs *fs;
5617 	struct indirdep *indirdep;
5618 	struct allocindir *oldaip;
5619 	struct freefrag *freefrag;
5620 	struct mount *mp;
5621 
5622 	mtx_assert(&lk, MA_OWNED);
5623 	mp = UFSTOVFS(ip->i_ump);
5624 	fs = ip->i_fs;
5625 	if (bp->b_lblkno >= 0)
5626 		panic("setup_allocindir_phase2: not indir blk");
5627 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
5628 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
5629 	indirdep = indirdep_lookup(mp, ip, bp);
5630 	KASSERT(indirdep->ir_savebp != NULL,
5631 	    ("setup_allocindir_phase2 NULL ir_savebp"));
5632 	aip->ai_indirdep = indirdep;
5633 	/*
5634 	 * Check for an unwritten dependency for this indirect offset.  If
5635 	 * there is, merge the old dependency into the new one.  This happens
5636 	 * as a result of reallocblk only.
5637 	 */
5638 	freefrag = NULL;
5639 	if (aip->ai_oldblkno != 0) {
5640 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
5641 			if (oldaip->ai_offset == aip->ai_offset) {
5642 				freefrag = allocindir_merge(aip, oldaip);
5643 				goto done;
5644 			}
5645 		}
5646 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
5647 			if (oldaip->ai_offset == aip->ai_offset) {
5648 				freefrag = allocindir_merge(aip, oldaip);
5649 				goto done;
5650 			}
5651 		}
5652 	}
5653 done:
5654 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
5655 	return (freefrag);
5656 }
5657 
5658 /*
5659  * Merge two allocindirs which refer to the same block.  Move newblock
5660  * dependencies and setup the freefrags appropriately.
5661  */
5662 static struct freefrag *
5663 allocindir_merge(aip, oldaip)
5664 	struct allocindir *aip;
5665 	struct allocindir *oldaip;
5666 {
5667 	struct freefrag *freefrag;
5668 	struct worklist *wk;
5669 
5670 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
5671 		panic("allocindir_merge: blkno");
5672 	aip->ai_oldblkno = oldaip->ai_oldblkno;
5673 	freefrag = aip->ai_freefrag;
5674 	aip->ai_freefrag = oldaip->ai_freefrag;
5675 	oldaip->ai_freefrag = NULL;
5676 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
5677 	/*
5678 	 * If we are tracking a new directory-block allocation,
5679 	 * move it from the old allocindir to the new allocindir.
5680 	 */
5681 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
5682 		WORKLIST_REMOVE(wk);
5683 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
5684 			panic("allocindir_merge: extra newdirblk");
5685 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
5686 	}
5687 	/*
5688 	 * We can skip journaling for this freefrag and just complete
5689 	 * any pending journal work for the allocindir that is being
5690 	 * removed after the freefrag completes.
5691 	 */
5692 	if (freefrag->ff_jdep)
5693 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
5694 	LIST_REMOVE(oldaip, ai_next);
5695 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
5696 	    &freefrag->ff_list, &freefrag->ff_jwork);
5697 	free_newblk(&oldaip->ai_block);
5698 
5699 	return (freefrag);
5700 }
5701 
5702 static inline void
5703 setup_freedirect(freeblks, ip, i, needj)
5704 	struct freeblks *freeblks;
5705 	struct inode *ip;
5706 	int i;
5707 	int needj;
5708 {
5709 	ufs2_daddr_t blkno;
5710 	int frags;
5711 
5712 	blkno = DIP(ip, i_db[i]);
5713 	if (blkno == 0)
5714 		return;
5715 	DIP_SET(ip, i_db[i], 0);
5716 	frags = sblksize(ip->i_fs, ip->i_size, i);
5717 	frags = numfrags(ip->i_fs, frags);
5718 	newfreework(ip->i_ump, freeblks, NULL, i, blkno, frags, 0, needj);
5719 }
5720 
5721 static inline void
5722 setup_freeext(freeblks, ip, i, needj)
5723 	struct freeblks *freeblks;
5724 	struct inode *ip;
5725 	int i;
5726 	int needj;
5727 {
5728 	ufs2_daddr_t blkno;
5729 	int frags;
5730 
5731 	blkno = ip->i_din2->di_extb[i];
5732 	if (blkno == 0)
5733 		return;
5734 	ip->i_din2->di_extb[i] = 0;
5735 	frags = sblksize(ip->i_fs, ip->i_din2->di_extsize, i);
5736 	frags = numfrags(ip->i_fs, frags);
5737 	newfreework(ip->i_ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
5738 }
5739 
5740 static inline void
5741 setup_freeindir(freeblks, ip, i, lbn, needj)
5742 	struct freeblks *freeblks;
5743 	struct inode *ip;
5744 	int i;
5745 	ufs_lbn_t lbn;
5746 	int needj;
5747 {
5748 	ufs2_daddr_t blkno;
5749 
5750 	blkno = DIP(ip, i_ib[i]);
5751 	if (blkno == 0)
5752 		return;
5753 	DIP_SET(ip, i_ib[i], 0);
5754 	newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, ip->i_fs->fs_frag,
5755 	    0, needj);
5756 }
5757 
5758 static inline struct freeblks *
5759 newfreeblks(mp, ip)
5760 	struct mount *mp;
5761 	struct inode *ip;
5762 {
5763 	struct freeblks *freeblks;
5764 
5765 	freeblks = malloc(sizeof(struct freeblks),
5766 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
5767 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
5768 	LIST_INIT(&freeblks->fb_jblkdephd);
5769 	LIST_INIT(&freeblks->fb_jwork);
5770 	freeblks->fb_ref = 0;
5771 	freeblks->fb_cgwait = 0;
5772 	freeblks->fb_state = ATTACHED;
5773 	freeblks->fb_uid = ip->i_uid;
5774 	freeblks->fb_inum = ip->i_number;
5775 	freeblks->fb_vtype = ITOV(ip)->v_type;
5776 	freeblks->fb_modrev = DIP(ip, i_modrev);
5777 	freeblks->fb_devvp = ip->i_devvp;
5778 	freeblks->fb_chkcnt = 0;
5779 	freeblks->fb_len = 0;
5780 
5781 	return (freeblks);
5782 }
5783 
5784 static void
5785 trunc_indirdep(indirdep, freeblks, bp, off)
5786 	struct indirdep *indirdep;
5787 	struct freeblks *freeblks;
5788 	struct buf *bp;
5789 	int off;
5790 {
5791 	struct allocindir *aip, *aipn;
5792 
5793 	/*
5794 	 * The first set of allocindirs won't be in savedbp.
5795 	 */
5796 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
5797 		if (aip->ai_offset > off)
5798 			cancel_allocindir(aip, bp, freeblks, 1);
5799 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
5800 		if (aip->ai_offset > off)
5801 			cancel_allocindir(aip, bp, freeblks, 1);
5802 	/*
5803 	 * These will exist in savedbp.
5804 	 */
5805 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
5806 		if (aip->ai_offset > off)
5807 			cancel_allocindir(aip, NULL, freeblks, 0);
5808 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
5809 		if (aip->ai_offset > off)
5810 			cancel_allocindir(aip, NULL, freeblks, 0);
5811 }
5812 
5813 /*
5814  * Follow the chain of indirects down to lastlbn creating a freework
5815  * structure for each.  This will be used to start indir_trunc() at
5816  * the right offset and create the journal records for the parrtial
5817  * truncation.  A second step will handle the truncated dependencies.
5818  */
5819 static int
5820 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
5821 	struct freeblks *freeblks;
5822 	struct inode *ip;
5823 	ufs_lbn_t lbn;
5824 	ufs_lbn_t lastlbn;
5825 	ufs2_daddr_t blkno;
5826 {
5827 	struct indirdep *indirdep;
5828 	struct indirdep *indirn;
5829 	struct freework *freework;
5830 	struct newblk *newblk;
5831 	struct mount *mp;
5832 	struct buf *bp;
5833 	uint8_t *start;
5834 	uint8_t *end;
5835 	ufs_lbn_t lbnadd;
5836 	int level;
5837 	int error;
5838 	int off;
5839 
5840 
5841 	freework = NULL;
5842 	if (blkno == 0)
5843 		return (0);
5844 	mp = freeblks->fb_list.wk_mp;
5845 	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
5846 	if ((bp->b_flags & B_CACHE) == 0) {
5847 		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
5848 		bp->b_iocmd = BIO_READ;
5849 		bp->b_flags &= ~B_INVAL;
5850 		bp->b_ioflags &= ~BIO_ERROR;
5851 		vfs_busy_pages(bp, 0);
5852 		bp->b_iooffset = dbtob(bp->b_blkno);
5853 		bstrategy(bp);
5854 		curthread->td_ru.ru_inblock++;
5855 		error = bufwait(bp);
5856 		if (error) {
5857 			brelse(bp);
5858 			return (error);
5859 		}
5860 	}
5861 	level = lbn_level(lbn);
5862 	lbnadd = lbn_offset(ip->i_fs, level);
5863 	/*
5864 	 * Compute the offset of the last block we want to keep.  Store
5865 	 * in the freework the first block we want to completely free.
5866 	 */
5867 	off = (lastlbn - -(lbn + level)) / lbnadd;
5868 	if (off + 1 == NINDIR(ip->i_fs))
5869 		goto nowork;
5870 	freework = newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, 0, off+1,
5871 	    0);
5872 	/*
5873 	 * Link the freework into the indirdep.  This will prevent any new
5874 	 * allocations from proceeding until we are finished with the
5875 	 * truncate and the block is written.
5876 	 */
5877 	ACQUIRE_LOCK(&lk);
5878 	indirdep = indirdep_lookup(mp, ip, bp);
5879 	if (indirdep->ir_freeblks)
5880 		panic("setup_trunc_indir: indirdep already truncated.");
5881 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
5882 	freework->fw_indir = indirdep;
5883 	/*
5884 	 * Cancel any allocindirs that will not make it to disk.
5885 	 * We have to do this for all copies of the indirdep that
5886 	 * live on this newblk.
5887 	 */
5888 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
5889 		newblk_lookup(mp, dbtofsb(ip->i_fs, bp->b_blkno), 0, &newblk);
5890 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
5891 			trunc_indirdep(indirn, freeblks, bp, off);
5892 	} else
5893 		trunc_indirdep(indirdep, freeblks, bp, off);
5894 	FREE_LOCK(&lk);
5895 	/*
5896 	 * Creation is protected by the buf lock. The saveddata is only
5897 	 * needed if a full truncation follows a partial truncation but it
5898 	 * is difficult to allocate in that case so we fetch it anyway.
5899 	 */
5900 	if (indirdep->ir_saveddata == NULL)
5901 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
5902 		    M_SOFTDEP_FLAGS);
5903 nowork:
5904 	/* Fetch the blkno of the child and the zero start offset. */
5905 	if (ip->i_ump->um_fstype == UFS1) {
5906 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
5907 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
5908 	} else {
5909 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
5910 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
5911 	}
5912 	if (freework) {
5913 		/* Zero the truncated pointers. */
5914 		end = bp->b_data + bp->b_bcount;
5915 		bzero(start, end - start);
5916 		bdwrite(bp);
5917 	} else
5918 		bqrelse(bp);
5919 	if (level == 0)
5920 		return (0);
5921 	lbn++; /* adjust level */
5922 	lbn -= (off * lbnadd);
5923 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
5924 }
5925 
5926 /*
5927  * Complete the partial truncation of an indirect block setup by
5928  * setup_trunc_indir().  This zeros the truncated pointers in the saved
5929  * copy and writes them to disk before the freeblks is allowed to complete.
5930  */
5931 static void
5932 complete_trunc_indir(freework)
5933 	struct freework *freework;
5934 {
5935 	struct freework *fwn;
5936 	struct indirdep *indirdep;
5937 	struct buf *bp;
5938 	uintptr_t start;
5939 	int count;
5940 
5941 	indirdep = freework->fw_indir;
5942 	for (;;) {
5943 		bp = indirdep->ir_bp;
5944 		/* See if the block was discarded. */
5945 		if (bp == NULL)
5946 			break;
5947 		/* Inline part of getdirtybuf().  We dont want bremfree. */
5948 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
5949 			break;
5950 		if (BUF_LOCK(bp,
5951 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, &lk) == 0)
5952 			BUF_UNLOCK(bp);
5953 		ACQUIRE_LOCK(&lk);
5954 	}
5955 	mtx_assert(&lk, MA_OWNED);
5956 	freework->fw_state |= DEPCOMPLETE;
5957 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
5958 	/*
5959 	 * Zero the pointers in the saved copy.
5960 	 */
5961 	if (indirdep->ir_state & UFS1FMT)
5962 		start = sizeof(ufs1_daddr_t);
5963 	else
5964 		start = sizeof(ufs2_daddr_t);
5965 	start *= freework->fw_start;
5966 	count = indirdep->ir_savebp->b_bcount - start;
5967 	start += (uintptr_t)indirdep->ir_savebp->b_data;
5968 	bzero((char *)start, count);
5969 	/*
5970 	 * We need to start the next truncation in the list if it has not
5971 	 * been started yet.
5972 	 */
5973 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
5974 	if (fwn != NULL) {
5975 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
5976 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
5977 		if ((fwn->fw_state & ONWORKLIST) == 0)
5978 			freework_enqueue(fwn);
5979 	}
5980 	/*
5981 	 * If bp is NULL the block was fully truncated, restore
5982 	 * the saved block list otherwise free it if it is no
5983 	 * longer needed.
5984 	 */
5985 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
5986 		if (bp == NULL)
5987 			bcopy(indirdep->ir_saveddata,
5988 			    indirdep->ir_savebp->b_data,
5989 			    indirdep->ir_savebp->b_bcount);
5990 		free(indirdep->ir_saveddata, M_INDIRDEP);
5991 		indirdep->ir_saveddata = NULL;
5992 	}
5993 	/*
5994 	 * When bp is NULL there is a full truncation pending.  We
5995 	 * must wait for this full truncation to be journaled before
5996 	 * we can release this freework because the disk pointers will
5997 	 * never be written as zero.
5998 	 */
5999 	if (bp == NULL)  {
6000 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6001 			handle_written_freework(freework);
6002 		else
6003 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6004 			   &freework->fw_list);
6005 	} else {
6006 		/* Complete when the real copy is written. */
6007 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6008 		BUF_UNLOCK(bp);
6009 	}
6010 }
6011 
6012 /*
6013  * Calculate the number of blocks we are going to release where datablocks
6014  * is the current total and length is the new file size.
6015  */
6016 ufs2_daddr_t
6017 blkcount(fs, datablocks, length)
6018 	struct fs *fs;
6019 	ufs2_daddr_t datablocks;
6020 	off_t length;
6021 {
6022 	off_t totblks, numblks;
6023 
6024 	totblks = 0;
6025 	numblks = howmany(length, fs->fs_bsize);
6026 	if (numblks <= NDADDR) {
6027 		totblks = howmany(length, fs->fs_fsize);
6028 		goto out;
6029 	}
6030         totblks = blkstofrags(fs, numblks);
6031 	numblks -= NDADDR;
6032 	/*
6033 	 * Count all single, then double, then triple indirects required.
6034 	 * Subtracting one indirects worth of blocks for each pass
6035 	 * acknowledges one of each pointed to by the inode.
6036 	 */
6037 	for (;;) {
6038 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6039 		numblks -= NINDIR(fs);
6040 		if (numblks <= 0)
6041 			break;
6042 		numblks = howmany(numblks, NINDIR(fs));
6043 	}
6044 out:
6045 	totblks = fsbtodb(fs, totblks);
6046 	/*
6047 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6048 	 * references.  We will correct it later in handle_complete_freeblks()
6049 	 * when we know the real count.
6050 	 */
6051 	if (totblks > datablocks)
6052 		return (0);
6053 	return (datablocks - totblks);
6054 }
6055 
6056 /*
6057  * Handle freeblocks for journaled softupdate filesystems.
6058  *
6059  * Contrary to normal softupdates, we must preserve the block pointers in
6060  * indirects until their subordinates are free.  This is to avoid journaling
6061  * every block that is freed which may consume more space than the journal
6062  * itself.  The recovery program will see the free block journals at the
6063  * base of the truncated area and traverse them to reclaim space.  The
6064  * pointers in the inode may be cleared immediately after the journal
6065  * records are written because each direct and indirect pointer in the
6066  * inode is recorded in a journal.  This permits full truncation to proceed
6067  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6068  *
6069  * The algorithm is as follows:
6070  * 1) Traverse the in-memory state and create journal entries to release
6071  *    the relevant blocks and full indirect trees.
6072  * 2) Traverse the indirect block chain adding partial truncation freework
6073  *    records to indirects in the path to lastlbn.  The freework will
6074  *    prevent new allocation dependencies from being satisfied in this
6075  *    indirect until the truncation completes.
6076  * 3) Read and lock the inode block, performing an update with the new size
6077  *    and pointers.  This prevents truncated data from becoming valid on
6078  *    disk through step 4.
6079  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6080  *    eliminate journal work for those records that do not require it.
6081  * 5) Schedule the journal records to be written followed by the inode block.
6082  * 6) Allocate any necessary frags for the end of file.
6083  * 7) Zero any partially truncated blocks.
6084  *
6085  * From this truncation proceeds asynchronously using the freework and
6086  * indir_trunc machinery.  The file will not be extended again into a
6087  * partially truncated indirect block until all work is completed but
6088  * the normal dependency mechanism ensures that it is rolled back/forward
6089  * as appropriate.  Further truncation may occur without delay and is
6090  * serialized in indir_trunc().
6091  */
6092 void
6093 softdep_journal_freeblocks(ip, cred, length, flags)
6094 	struct inode *ip;	/* The inode whose length is to be reduced */
6095 	struct ucred *cred;
6096 	off_t length;		/* The new length for the file */
6097 	int flags;		/* IO_EXT and/or IO_NORMAL */
6098 {
6099 	struct freeblks *freeblks, *fbn;
6100 	struct inodedep *inodedep;
6101 	struct jblkdep *jblkdep;
6102 	struct allocdirect *adp, *adpn;
6103 	struct fs *fs;
6104 	struct buf *bp;
6105 	struct vnode *vp;
6106 	struct mount *mp;
6107 	ufs2_daddr_t extblocks, datablocks;
6108 	ufs_lbn_t tmpval, lbn, lastlbn;
6109 	int frags, lastoff, iboff, allocblock, needj, dflags, error, i;
6110 
6111 	fs = ip->i_fs;
6112 	mp = UFSTOVFS(ip->i_ump);
6113 	vp = ITOV(ip);
6114 	needj = 1;
6115 	iboff = -1;
6116 	allocblock = 0;
6117 	extblocks = 0;
6118 	datablocks = 0;
6119 	frags = 0;
6120 	freeblks = newfreeblks(mp, ip);
6121 	ACQUIRE_LOCK(&lk);
6122 	/*
6123 	 * If we're truncating a removed file that will never be written
6124 	 * we don't need to journal the block frees.  The canceled journals
6125 	 * for the allocations will suffice.
6126 	 */
6127 	dflags = DEPALLOC;
6128 	if (IS_SNAPSHOT(ip))
6129 		dflags |= NODELAY;
6130 	inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6131 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6132 	    length == 0)
6133 		needj = 0;
6134 	FREE_LOCK(&lk);
6135 	/*
6136 	 * Calculate the lbn that we are truncating to.  This results in -1
6137 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6138 	 * to keep, not the first lbn we want to truncate.
6139 	 */
6140 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6141 	lastoff = blkoff(fs, length);
6142 	/*
6143 	 * Compute frags we are keeping in lastlbn.  0 means all.
6144 	 */
6145 	if (lastlbn >= 0 && lastlbn < NDADDR) {
6146 		frags = fragroundup(fs, lastoff);
6147 		/* adp offset of last valid allocdirect. */
6148 		iboff = lastlbn;
6149 	} else if (lastlbn > 0)
6150 		iboff = NDADDR;
6151 	if (fs->fs_magic == FS_UFS2_MAGIC)
6152 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6153 	/*
6154 	 * Handle normal data blocks and indirects.  This section saves
6155 	 * values used after the inode update to complete frag and indirect
6156 	 * truncation.
6157 	 */
6158 	if ((flags & IO_NORMAL) != 0) {
6159 		/*
6160 		 * Handle truncation of whole direct and indirect blocks.
6161 		 */
6162 		for (i = iboff + 1; i < NDADDR; i++)
6163 			setup_freedirect(freeblks, ip, i, needj);
6164 		for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6165 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6166 			/* Release a whole indirect tree. */
6167 			if (lbn > lastlbn) {
6168 				setup_freeindir(freeblks, ip, i, -lbn -i,
6169 				    needj);
6170 				continue;
6171 			}
6172 			iboff = i + NDADDR;
6173 			/*
6174 			 * Traverse partially truncated indirect tree.
6175 			 */
6176 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6177 				setup_trunc_indir(freeblks, ip, -lbn - i,
6178 				    lastlbn, DIP(ip, i_ib[i]));
6179 		}
6180 		/*
6181 		 * Handle partial truncation to a frag boundary.
6182 		 */
6183 		if (frags) {
6184 			ufs2_daddr_t blkno;
6185 			long oldfrags;
6186 
6187 			oldfrags = blksize(fs, ip, lastlbn);
6188 			blkno = DIP(ip, i_db[lastlbn]);
6189 			if (blkno && oldfrags != frags) {
6190 				oldfrags -= frags;
6191 				oldfrags = numfrags(ip->i_fs, oldfrags);
6192 				blkno += numfrags(ip->i_fs, frags);
6193 				newfreework(ip->i_ump, freeblks, NULL, lastlbn,
6194 				    blkno, oldfrags, 0, needj);
6195 			} else if (blkno == 0)
6196 				allocblock = 1;
6197 		}
6198 		/*
6199 		 * Add a journal record for partial truncate if we are
6200 		 * handling indirect blocks.  Non-indirects need no extra
6201 		 * journaling.
6202 		 */
6203 		if (length != 0 && lastlbn >= NDADDR) {
6204 			ip->i_flag |= IN_TRUNCATED;
6205 			newjtrunc(freeblks, length, 0);
6206 		}
6207 		ip->i_size = length;
6208 		DIP_SET(ip, i_size, ip->i_size);
6209 		datablocks = DIP(ip, i_blocks) - extblocks;
6210 		if (length != 0)
6211 			datablocks = blkcount(ip->i_fs, datablocks, length);
6212 		freeblks->fb_len = length;
6213 	}
6214 	if ((flags & IO_EXT) != 0) {
6215 		for (i = 0; i < NXADDR; i++)
6216 			setup_freeext(freeblks, ip, i, needj);
6217 		ip->i_din2->di_extsize = 0;
6218 		datablocks += extblocks;
6219 	}
6220 #ifdef QUOTA
6221 	/* Reference the quotas in case the block count is wrong in the end. */
6222 	quotaref(vp, freeblks->fb_quota);
6223 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6224 #endif
6225 	freeblks->fb_chkcnt = -datablocks;
6226 	UFS_LOCK(ip->i_ump);
6227 	fs->fs_pendingblocks += datablocks;
6228 	UFS_UNLOCK(ip->i_ump);
6229 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6230 	/*
6231 	 * Handle truncation of incomplete alloc direct dependencies.  We
6232 	 * hold the inode block locked to prevent incomplete dependencies
6233 	 * from reaching the disk while we are eliminating those that
6234 	 * have been truncated.  This is a partially inlined ffs_update().
6235 	 */
6236 	ufs_itimes(vp);
6237 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6238 	error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6239 	    (int)fs->fs_bsize, cred, &bp);
6240 	if (error) {
6241 		brelse(bp);
6242 		softdep_error("softdep_journal_freeblocks", error);
6243 		return;
6244 	}
6245 	if (bp->b_bufsize == fs->fs_bsize)
6246 		bp->b_flags |= B_CLUSTEROK;
6247 	softdep_update_inodeblock(ip, bp, 0);
6248 	if (ip->i_ump->um_fstype == UFS1)
6249 		*((struct ufs1_dinode *)bp->b_data +
6250 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6251 	else
6252 		*((struct ufs2_dinode *)bp->b_data +
6253 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6254 	ACQUIRE_LOCK(&lk);
6255 	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6256 	if ((inodedep->id_state & IOSTARTED) != 0)
6257 		panic("softdep_setup_freeblocks: inode busy");
6258 	/*
6259 	 * Add the freeblks structure to the list of operations that
6260 	 * must await the zero'ed inode being written to disk. If we
6261 	 * still have a bitmap dependency (needj), then the inode
6262 	 * has never been written to disk, so we can process the
6263 	 * freeblks below once we have deleted the dependencies.
6264 	 */
6265 	if (needj)
6266 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6267 	else
6268 		freeblks->fb_state |= COMPLETE;
6269 	if ((flags & IO_NORMAL) != 0) {
6270 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6271 			if (adp->ad_offset > iboff)
6272 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6273 				    freeblks);
6274 			/*
6275 			 * Truncate the allocdirect.  We could eliminate
6276 			 * or modify journal records as well.
6277 			 */
6278 			else if (adp->ad_offset == iboff && frags)
6279 				adp->ad_newsize = frags;
6280 		}
6281 	}
6282 	if ((flags & IO_EXT) != 0)
6283 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6284 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6285 			    freeblks);
6286 	/*
6287 	 * Add journal work.
6288 	 */
6289 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6290 		add_to_journal(&jblkdep->jb_list);
6291 	FREE_LOCK(&lk);
6292 	bdwrite(bp);
6293 	/*
6294 	 * Truncate dependency structures beyond length.
6295 	 */
6296 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6297 	/*
6298 	 * This is only set when we need to allocate a fragment because
6299 	 * none existed at the end of a frag-sized file.  It handles only
6300 	 * allocating a new, zero filled block.
6301 	 */
6302 	if (allocblock) {
6303 		ip->i_size = length - lastoff;
6304 		DIP_SET(ip, i_size, ip->i_size);
6305 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6306 		if (error != 0) {
6307 			softdep_error("softdep_journal_freeblks", error);
6308 			return;
6309 		}
6310 		ip->i_size = length;
6311 		DIP_SET(ip, i_size, length);
6312 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6313 		allocbuf(bp, frags);
6314 		ffs_update(vp, 0);
6315 		bawrite(bp);
6316 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6317 		int size;
6318 
6319 		/*
6320 		 * Zero the end of a truncated frag or block.
6321 		 */
6322 		size = sblksize(fs, length, lastlbn);
6323 		error = bread(vp, lastlbn, size, cred, &bp);
6324 		if (error) {
6325 			softdep_error("softdep_journal_freeblks", error);
6326 			return;
6327 		}
6328 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6329 		bawrite(bp);
6330 
6331 	}
6332 	ACQUIRE_LOCK(&lk);
6333 	inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6334 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6335 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6336 	/*
6337 	 * We zero earlier truncations so they don't erroneously
6338 	 * update i_blocks.
6339 	 */
6340 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6341 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6342 			fbn->fb_len = 0;
6343 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6344 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6345 		freeblks->fb_state |= INPROGRESS;
6346 	else
6347 		freeblks = NULL;
6348 	FREE_LOCK(&lk);
6349 	if (freeblks)
6350 		handle_workitem_freeblocks(freeblks, 0);
6351 	trunc_pages(ip, length, extblocks, flags);
6352 
6353 }
6354 
6355 /*
6356  * Flush a JOP_SYNC to the journal.
6357  */
6358 void
6359 softdep_journal_fsync(ip)
6360 	struct inode *ip;
6361 {
6362 	struct jfsync *jfsync;
6363 
6364 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6365 		return;
6366 	ip->i_flag &= ~IN_TRUNCATED;
6367 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6368 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ip->i_ump));
6369 	jfsync->jfs_size = ip->i_size;
6370 	jfsync->jfs_ino = ip->i_number;
6371 	ACQUIRE_LOCK(&lk);
6372 	add_to_journal(&jfsync->jfs_list);
6373 	jwait(&jfsync->jfs_list, MNT_WAIT);
6374 	FREE_LOCK(&lk);
6375 }
6376 
6377 /*
6378  * Block de-allocation dependencies.
6379  *
6380  * When blocks are de-allocated, the on-disk pointers must be nullified before
6381  * the blocks are made available for use by other files.  (The true
6382  * requirement is that old pointers must be nullified before new on-disk
6383  * pointers are set.  We chose this slightly more stringent requirement to
6384  * reduce complexity.) Our implementation handles this dependency by updating
6385  * the inode (or indirect block) appropriately but delaying the actual block
6386  * de-allocation (i.e., freemap and free space count manipulation) until
6387  * after the updated versions reach stable storage.  After the disk is
6388  * updated, the blocks can be safely de-allocated whenever it is convenient.
6389  * This implementation handles only the common case of reducing a file's
6390  * length to zero. Other cases are handled by the conventional synchronous
6391  * write approach.
6392  *
6393  * The ffs implementation with which we worked double-checks
6394  * the state of the block pointers and file size as it reduces
6395  * a file's length.  Some of this code is replicated here in our
6396  * soft updates implementation.  The freeblks->fb_chkcnt field is
6397  * used to transfer a part of this information to the procedure
6398  * that eventually de-allocates the blocks.
6399  *
6400  * This routine should be called from the routine that shortens
6401  * a file's length, before the inode's size or block pointers
6402  * are modified. It will save the block pointer information for
6403  * later release and zero the inode so that the calling routine
6404  * can release it.
6405  */
6406 void
6407 softdep_setup_freeblocks(ip, length, flags)
6408 	struct inode *ip;	/* The inode whose length is to be reduced */
6409 	off_t length;		/* The new length for the file */
6410 	int flags;		/* IO_EXT and/or IO_NORMAL */
6411 {
6412 	struct ufs1_dinode *dp1;
6413 	struct ufs2_dinode *dp2;
6414 	struct freeblks *freeblks;
6415 	struct inodedep *inodedep;
6416 	struct allocdirect *adp;
6417 	struct buf *bp;
6418 	struct fs *fs;
6419 	ufs2_daddr_t extblocks, datablocks;
6420 	struct mount *mp;
6421 	int i, delay, error, dflags;
6422 	ufs_lbn_t tmpval;
6423 	ufs_lbn_t lbn;
6424 
6425 	fs = ip->i_fs;
6426 	mp = UFSTOVFS(ip->i_ump);
6427 	if (length != 0)
6428 		panic("softdep_setup_freeblocks: non-zero length");
6429 	freeblks = newfreeblks(mp, ip);
6430 	extblocks = 0;
6431 	datablocks = 0;
6432 	if (fs->fs_magic == FS_UFS2_MAGIC)
6433 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6434 	if ((flags & IO_NORMAL) != 0) {
6435 		for (i = 0; i < NDADDR; i++)
6436 			setup_freedirect(freeblks, ip, i, 0);
6437 		for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6438 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6439 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6440 		ip->i_size = 0;
6441 		DIP_SET(ip, i_size, 0);
6442 		datablocks = DIP(ip, i_blocks) - extblocks;
6443 	}
6444 	if ((flags & IO_EXT) != 0) {
6445 		for (i = 0; i < NXADDR; i++)
6446 			setup_freeext(freeblks, ip, i, 0);
6447 		ip->i_din2->di_extsize = 0;
6448 		datablocks += extblocks;
6449 	}
6450 #ifdef QUOTA
6451 	/* Reference the quotas in case the block count is wrong in the end. */
6452 	quotaref(ITOV(ip), freeblks->fb_quota);
6453 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6454 #endif
6455 	freeblks->fb_chkcnt = -datablocks;
6456 	UFS_LOCK(ip->i_ump);
6457 	fs->fs_pendingblocks += datablocks;
6458 	UFS_UNLOCK(ip->i_ump);
6459 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6460 	/*
6461 	 * Push the zero'ed inode to to its disk buffer so that we are free
6462 	 * to delete its dependencies below. Once the dependencies are gone
6463 	 * the buffer can be safely released.
6464 	 */
6465 	if ((error = bread(ip->i_devvp,
6466 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6467 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6468 		brelse(bp);
6469 		softdep_error("softdep_setup_freeblocks", error);
6470 	}
6471 	if (ip->i_ump->um_fstype == UFS1) {
6472 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6473 		    ino_to_fsbo(fs, ip->i_number));
6474 		ip->i_din1->di_freelink = dp1->di_freelink;
6475 		*dp1 = *ip->i_din1;
6476 	} else {
6477 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6478 		    ino_to_fsbo(fs, ip->i_number));
6479 		ip->i_din2->di_freelink = dp2->di_freelink;
6480 		*dp2 = *ip->i_din2;
6481 	}
6482 	/*
6483 	 * Find and eliminate any inode dependencies.
6484 	 */
6485 	ACQUIRE_LOCK(&lk);
6486 	dflags = DEPALLOC;
6487 	if (IS_SNAPSHOT(ip))
6488 		dflags |= NODELAY;
6489 	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6490 	if ((inodedep->id_state & IOSTARTED) != 0)
6491 		panic("softdep_setup_freeblocks: inode busy");
6492 	/*
6493 	 * Add the freeblks structure to the list of operations that
6494 	 * must await the zero'ed inode being written to disk. If we
6495 	 * still have a bitmap dependency (delay == 0), then the inode
6496 	 * has never been written to disk, so we can process the
6497 	 * freeblks below once we have deleted the dependencies.
6498 	 */
6499 	delay = (inodedep->id_state & DEPCOMPLETE);
6500 	if (delay)
6501 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6502 	else
6503 		freeblks->fb_state |= COMPLETE;
6504 	/*
6505 	 * Because the file length has been truncated to zero, any
6506 	 * pending block allocation dependency structures associated
6507 	 * with this inode are obsolete and can simply be de-allocated.
6508 	 * We must first merge the two dependency lists to get rid of
6509 	 * any duplicate freefrag structures, then purge the merged list.
6510 	 * If we still have a bitmap dependency, then the inode has never
6511 	 * been written to disk, so we can free any fragments without delay.
6512 	 */
6513 	if (flags & IO_NORMAL) {
6514 		merge_inode_lists(&inodedep->id_newinoupdt,
6515 		    &inodedep->id_inoupdt);
6516 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
6517 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
6518 			    freeblks);
6519 	}
6520 	if (flags & IO_EXT) {
6521 		merge_inode_lists(&inodedep->id_newextupdt,
6522 		    &inodedep->id_extupdt);
6523 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6524 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6525 			    freeblks);
6526 	}
6527 	FREE_LOCK(&lk);
6528 	bdwrite(bp);
6529 	trunc_dependencies(ip, freeblks, -1, 0, flags);
6530 	ACQUIRE_LOCK(&lk);
6531 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6532 		(void) free_inodedep(inodedep);
6533 	freeblks->fb_state |= DEPCOMPLETE;
6534 	/*
6535 	 * If the inode with zeroed block pointers is now on disk
6536 	 * we can start freeing blocks.
6537 	 */
6538 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6539 		freeblks->fb_state |= INPROGRESS;
6540 	else
6541 		freeblks = NULL;
6542 	FREE_LOCK(&lk);
6543 	if (freeblks)
6544 		handle_workitem_freeblocks(freeblks, 0);
6545 	trunc_pages(ip, length, extblocks, flags);
6546 }
6547 
6548 /*
6549  * Eliminate pages from the page cache that back parts of this inode and
6550  * adjust the vnode pager's idea of our size.  This prevents stale data
6551  * from hanging around in the page cache.
6552  */
6553 static void
6554 trunc_pages(ip, length, extblocks, flags)
6555 	struct inode *ip;
6556 	off_t length;
6557 	ufs2_daddr_t extblocks;
6558 	int flags;
6559 {
6560 	struct vnode *vp;
6561 	struct fs *fs;
6562 	ufs_lbn_t lbn;
6563 	off_t end, extend;
6564 
6565 	vp = ITOV(ip);
6566 	fs = ip->i_fs;
6567 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
6568 	if ((flags & IO_EXT) != 0)
6569 		vn_pages_remove(vp, extend, 0);
6570 	if ((flags & IO_NORMAL) == 0)
6571 		return;
6572 	BO_LOCK(&vp->v_bufobj);
6573 	drain_output(vp);
6574 	BO_UNLOCK(&vp->v_bufobj);
6575 	/*
6576 	 * The vnode pager eliminates file pages we eliminate indirects
6577 	 * below.
6578 	 */
6579 	vnode_pager_setsize(vp, length);
6580 	/*
6581 	 * Calculate the end based on the last indirect we want to keep.  If
6582 	 * the block extends into indirects we can just use the negative of
6583 	 * its lbn.  Doubles and triples exist at lower numbers so we must
6584 	 * be careful not to remove those, if they exist.  double and triple
6585 	 * indirect lbns do not overlap with others so it is not important
6586 	 * to verify how many levels are required.
6587 	 */
6588 	lbn = lblkno(fs, length);
6589 	if (lbn >= NDADDR) {
6590 		/* Calculate the virtual lbn of the triple indirect. */
6591 		lbn = -lbn - (NIADDR - 1);
6592 		end = OFF_TO_IDX(lblktosize(fs, lbn));
6593 	} else
6594 		end = extend;
6595 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
6596 }
6597 
6598 /*
6599  * See if the buf bp is in the range eliminated by truncation.
6600  */
6601 static int
6602 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
6603 	struct buf *bp;
6604 	int *blkoffp;
6605 	ufs_lbn_t lastlbn;
6606 	int lastoff;
6607 	int flags;
6608 {
6609 	ufs_lbn_t lbn;
6610 
6611 	*blkoffp = 0;
6612 	/* Only match ext/normal blocks as appropriate. */
6613 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
6614 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
6615 		return (0);
6616 	/* ALTDATA is always a full truncation. */
6617 	if ((bp->b_xflags & BX_ALTDATA) != 0)
6618 		return (1);
6619 	/* -1 is full truncation. */
6620 	if (lastlbn == -1)
6621 		return (1);
6622 	/*
6623 	 * If this is a partial truncate we only want those
6624 	 * blocks and indirect blocks that cover the range
6625 	 * we're after.
6626 	 */
6627 	lbn = bp->b_lblkno;
6628 	if (lbn < 0)
6629 		lbn = -(lbn + lbn_level(lbn));
6630 	if (lbn < lastlbn)
6631 		return (0);
6632 	/* Here we only truncate lblkno if it's partial. */
6633 	if (lbn == lastlbn) {
6634 		if (lastoff == 0)
6635 			return (0);
6636 		*blkoffp = lastoff;
6637 	}
6638 	return (1);
6639 }
6640 
6641 /*
6642  * Eliminate any dependencies that exist in memory beyond lblkno:off
6643  */
6644 static void
6645 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
6646 	struct inode *ip;
6647 	struct freeblks *freeblks;
6648 	ufs_lbn_t lastlbn;
6649 	int lastoff;
6650 	int flags;
6651 {
6652 	struct bufobj *bo;
6653 	struct vnode *vp;
6654 	struct buf *bp;
6655 	struct fs *fs;
6656 	int blkoff;
6657 
6658 	/*
6659 	 * We must wait for any I/O in progress to finish so that
6660 	 * all potential buffers on the dirty list will be visible.
6661 	 * Once they are all there, walk the list and get rid of
6662 	 * any dependencies.
6663 	 */
6664 	fs = ip->i_fs;
6665 	vp = ITOV(ip);
6666 	bo = &vp->v_bufobj;
6667 	BO_LOCK(bo);
6668 	drain_output(vp);
6669 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
6670 		bp->b_vflags &= ~BV_SCANNED;
6671 restart:
6672 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
6673 		if (bp->b_vflags & BV_SCANNED)
6674 			continue;
6675 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
6676 			bp->b_vflags |= BV_SCANNED;
6677 			continue;
6678 		}
6679 		if ((bp = getdirtybuf(bp, BO_MTX(bo), MNT_WAIT)) == NULL)
6680 			goto restart;
6681 		BO_UNLOCK(bo);
6682 		if (deallocate_dependencies(bp, freeblks, blkoff))
6683 			bqrelse(bp);
6684 		else
6685 			brelse(bp);
6686 		BO_LOCK(bo);
6687 		goto restart;
6688 	}
6689 	/*
6690 	 * Now do the work of vtruncbuf while also matching indirect blocks.
6691 	 */
6692 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
6693 		bp->b_vflags &= ~BV_SCANNED;
6694 cleanrestart:
6695 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
6696 		if (bp->b_vflags & BV_SCANNED)
6697 			continue;
6698 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
6699 			bp->b_vflags |= BV_SCANNED;
6700 			continue;
6701 		}
6702 		if (BUF_LOCK(bp,
6703 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6704 		    BO_MTX(bo)) == ENOLCK) {
6705 			BO_LOCK(bo);
6706 			goto cleanrestart;
6707 		}
6708 		bp->b_vflags |= BV_SCANNED;
6709 		BO_LOCK(bo);
6710 		bremfree(bp);
6711 		BO_UNLOCK(bo);
6712 		if (blkoff != 0) {
6713 			allocbuf(bp, blkoff);
6714 			bqrelse(bp);
6715 		} else {
6716 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
6717 			brelse(bp);
6718 		}
6719 		BO_LOCK(bo);
6720 		goto cleanrestart;
6721 	}
6722 	drain_output(vp);
6723 	BO_UNLOCK(bo);
6724 }
6725 
6726 static int
6727 cancel_pagedep(pagedep, freeblks, blkoff)
6728 	struct pagedep *pagedep;
6729 	struct freeblks *freeblks;
6730 	int blkoff;
6731 {
6732 	struct jremref *jremref;
6733 	struct jmvref *jmvref;
6734 	struct dirrem *dirrem, *tmp;
6735 	int i;
6736 
6737 	/*
6738 	 * Copy any directory remove dependencies to the list
6739 	 * to be processed after the freeblks proceeds.  If
6740 	 * directory entry never made it to disk they
6741 	 * can be dumped directly onto the work list.
6742 	 */
6743 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
6744 		/* Skip this directory removal if it is intended to remain. */
6745 		if (dirrem->dm_offset < blkoff)
6746 			continue;
6747 		/*
6748 		 * If there are any dirrems we wait for the journal write
6749 		 * to complete and then restart the buf scan as the lock
6750 		 * has been dropped.
6751 		 */
6752 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
6753 			jwait(&jremref->jr_list, MNT_WAIT);
6754 			return (ERESTART);
6755 		}
6756 		LIST_REMOVE(dirrem, dm_next);
6757 		dirrem->dm_dirinum = pagedep->pd_ino;
6758 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
6759 	}
6760 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
6761 		jwait(&jmvref->jm_list, MNT_WAIT);
6762 		return (ERESTART);
6763 	}
6764 	/*
6765 	 * When we're partially truncating a pagedep we just want to flush
6766 	 * journal entries and return.  There can not be any adds in the
6767 	 * truncated portion of the directory and newblk must remain if
6768 	 * part of the block remains.
6769 	 */
6770 	if (blkoff != 0) {
6771 		struct diradd *dap;
6772 
6773 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
6774 			if (dap->da_offset > blkoff)
6775 				panic("cancel_pagedep: diradd %p off %d > %d",
6776 				    dap, dap->da_offset, blkoff);
6777 		for (i = 0; i < DAHASHSZ; i++)
6778 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
6779 				if (dap->da_offset > blkoff)
6780 					panic("cancel_pagedep: diradd %p off %d > %d",
6781 					    dap, dap->da_offset, blkoff);
6782 		return (0);
6783 	}
6784 	/*
6785 	 * There should be no directory add dependencies present
6786 	 * as the directory could not be truncated until all
6787 	 * children were removed.
6788 	 */
6789 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
6790 	    ("deallocate_dependencies: pendinghd != NULL"));
6791 	for (i = 0; i < DAHASHSZ; i++)
6792 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
6793 		    ("deallocate_dependencies: diraddhd != NULL"));
6794 	if ((pagedep->pd_state & NEWBLOCK) != 0)
6795 		free_newdirblk(pagedep->pd_newdirblk);
6796 	if (free_pagedep(pagedep) == 0)
6797 		panic("Failed to free pagedep %p", pagedep);
6798 	return (0);
6799 }
6800 
6801 /*
6802  * Reclaim any dependency structures from a buffer that is about to
6803  * be reallocated to a new vnode. The buffer must be locked, thus,
6804  * no I/O completion operations can occur while we are manipulating
6805  * its associated dependencies. The mutex is held so that other I/O's
6806  * associated with related dependencies do not occur.
6807  */
6808 static int
6809 deallocate_dependencies(bp, freeblks, off)
6810 	struct buf *bp;
6811 	struct freeblks *freeblks;
6812 	int off;
6813 {
6814 	struct indirdep *indirdep;
6815 	struct pagedep *pagedep;
6816 	struct allocdirect *adp;
6817 	struct worklist *wk, *wkn;
6818 
6819 	ACQUIRE_LOCK(&lk);
6820 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
6821 		switch (wk->wk_type) {
6822 		case D_INDIRDEP:
6823 			indirdep = WK_INDIRDEP(wk);
6824 			if (bp->b_lblkno >= 0 ||
6825 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
6826 				panic("deallocate_dependencies: not indir");
6827 			cancel_indirdep(indirdep, bp, freeblks);
6828 			continue;
6829 
6830 		case D_PAGEDEP:
6831 			pagedep = WK_PAGEDEP(wk);
6832 			if (cancel_pagedep(pagedep, freeblks, off)) {
6833 				FREE_LOCK(&lk);
6834 				return (ERESTART);
6835 			}
6836 			continue;
6837 
6838 		case D_ALLOCINDIR:
6839 			/*
6840 			 * Simply remove the allocindir, we'll find it via
6841 			 * the indirdep where we can clear pointers if
6842 			 * needed.
6843 			 */
6844 			WORKLIST_REMOVE(wk);
6845 			continue;
6846 
6847 		case D_FREEWORK:
6848 			/*
6849 			 * A truncation is waiting for the zero'd pointers
6850 			 * to be written.  It can be freed when the freeblks
6851 			 * is journaled.
6852 			 */
6853 			WORKLIST_REMOVE(wk);
6854 			wk->wk_state |= ONDEPLIST;
6855 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6856 			break;
6857 
6858 		case D_ALLOCDIRECT:
6859 			adp = WK_ALLOCDIRECT(wk);
6860 			if (off != 0)
6861 				continue;
6862 			/* FALLTHROUGH */
6863 		default:
6864 			panic("deallocate_dependencies: Unexpected type %s",
6865 			    TYPENAME(wk->wk_type));
6866 			/* NOTREACHED */
6867 		}
6868 	}
6869 	FREE_LOCK(&lk);
6870 	/*
6871 	 * Don't throw away this buf, we were partially truncating and
6872 	 * some deps may always remain.
6873 	 */
6874 	if (off) {
6875 		allocbuf(bp, off);
6876 		bp->b_vflags |= BV_SCANNED;
6877 		return (EBUSY);
6878 	}
6879 	bp->b_flags |= B_INVAL | B_NOCACHE;
6880 
6881 	return (0);
6882 }
6883 
6884 /*
6885  * An allocdirect is being canceled due to a truncate.  We must make sure
6886  * the journal entry is released in concert with the blkfree that releases
6887  * the storage.  Completed journal entries must not be released until the
6888  * space is no longer pointed to by the inode or in the bitmap.
6889  */
6890 static void
6891 cancel_allocdirect(adphead, adp, freeblks)
6892 	struct allocdirectlst *adphead;
6893 	struct allocdirect *adp;
6894 	struct freeblks *freeblks;
6895 {
6896 	struct freework *freework;
6897 	struct newblk *newblk;
6898 	struct worklist *wk;
6899 
6900 	TAILQ_REMOVE(adphead, adp, ad_next);
6901 	newblk = (struct newblk *)adp;
6902 	freework = NULL;
6903 	/*
6904 	 * Find the correct freework structure.
6905 	 */
6906 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
6907 		if (wk->wk_type != D_FREEWORK)
6908 			continue;
6909 		freework = WK_FREEWORK(wk);
6910 		if (freework->fw_blkno == newblk->nb_newblkno)
6911 			break;
6912 	}
6913 	if (freework == NULL)
6914 		panic("cancel_allocdirect: Freework not found");
6915 	/*
6916 	 * If a newblk exists at all we still have the journal entry that
6917 	 * initiated the allocation so we do not need to journal the free.
6918 	 */
6919 	cancel_jfreeblk(freeblks, freework->fw_blkno);
6920 	/*
6921 	 * If the journal hasn't been written the jnewblk must be passed
6922 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
6923 	 * this by linking the journal dependency into the freework to be
6924 	 * freed when freework_freeblock() is called.  If the journal has
6925 	 * been written we can simply reclaim the journal space when the
6926 	 * freeblks work is complete.
6927 	 */
6928 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
6929 	    &freeblks->fb_jwork);
6930 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
6931 }
6932 
6933 
6934 /*
6935  * Cancel a new block allocation.  May be an indirect or direct block.  We
6936  * remove it from various lists and return any journal record that needs to
6937  * be resolved by the caller.
6938  *
6939  * A special consideration is made for indirects which were never pointed
6940  * at on disk and will never be found once this block is released.
6941  */
6942 static struct jnewblk *
6943 cancel_newblk(newblk, wk, wkhd)
6944 	struct newblk *newblk;
6945 	struct worklist *wk;
6946 	struct workhead *wkhd;
6947 {
6948 	struct jnewblk *jnewblk;
6949 
6950 	newblk->nb_state |= GOINGAWAY;
6951 	/*
6952 	 * Previously we traversed the completedhd on each indirdep
6953 	 * attached to this newblk to cancel them and gather journal
6954 	 * work.  Since we need only the oldest journal segment and
6955 	 * the lowest point on the tree will always have the oldest
6956 	 * journal segment we are free to release the segments
6957 	 * of any subordinates and may leave the indirdep list to
6958 	 * indirdep_complete() when this newblk is freed.
6959 	 */
6960 	if (newblk->nb_state & ONDEPLIST) {
6961 		newblk->nb_state &= ~ONDEPLIST;
6962 		LIST_REMOVE(newblk, nb_deps);
6963 	}
6964 	if (newblk->nb_state & ONWORKLIST)
6965 		WORKLIST_REMOVE(&newblk->nb_list);
6966 	/*
6967 	 * If the journal entry hasn't been written we save a pointer to
6968 	 * the dependency that frees it until it is written or the
6969 	 * superseding operation completes.
6970 	 */
6971 	jnewblk = newblk->nb_jnewblk;
6972 	if (jnewblk != NULL && wk != NULL) {
6973 		newblk->nb_jnewblk = NULL;
6974 		jnewblk->jn_dep = wk;
6975 	}
6976 	if (!LIST_EMPTY(&newblk->nb_jwork))
6977 		jwork_move(wkhd, &newblk->nb_jwork);
6978 	/*
6979 	 * When truncating we must free the newdirblk early to remove
6980 	 * the pagedep from the hash before returning.
6981 	 */
6982 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
6983 		free_newdirblk(WK_NEWDIRBLK(wk));
6984 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
6985 		panic("cancel_newblk: extra newdirblk");
6986 
6987 	return (jnewblk);
6988 }
6989 
6990 /*
6991  * Schedule the freefrag associated with a newblk to be released once
6992  * the pointers are written and the previous block is no longer needed.
6993  */
6994 static void
6995 newblk_freefrag(newblk)
6996 	struct newblk *newblk;
6997 {
6998 	struct freefrag *freefrag;
6999 
7000 	if (newblk->nb_freefrag == NULL)
7001 		return;
7002 	freefrag = newblk->nb_freefrag;
7003 	newblk->nb_freefrag = NULL;
7004 	freefrag->ff_state |= COMPLETE;
7005 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7006 		add_to_worklist(&freefrag->ff_list, 0);
7007 }
7008 
7009 /*
7010  * Free a newblk. Generate a new freefrag work request if appropriate.
7011  * This must be called after the inode pointer and any direct block pointers
7012  * are valid or fully removed via truncate or frag extension.
7013  */
7014 static void
7015 free_newblk(newblk)
7016 	struct newblk *newblk;
7017 {
7018 	struct indirdep *indirdep;
7019 	struct worklist *wk;
7020 
7021 	KASSERT(newblk->nb_jnewblk == NULL,
7022 	    ("free_newblk; jnewblk %p still attached", newblk->nb_jnewblk));
7023 	mtx_assert(&lk, MA_OWNED);
7024 	newblk_freefrag(newblk);
7025 	if (newblk->nb_state & ONDEPLIST)
7026 		LIST_REMOVE(newblk, nb_deps);
7027 	if (newblk->nb_state & ONWORKLIST)
7028 		WORKLIST_REMOVE(&newblk->nb_list);
7029 	LIST_REMOVE(newblk, nb_hash);
7030 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7031 		free_newdirblk(WK_NEWDIRBLK(wk));
7032 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7033 		panic("free_newblk: extra newdirblk");
7034 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7035 		indirdep_complete(indirdep);
7036 	handle_jwork(&newblk->nb_jwork);
7037 	newblk->nb_list.wk_type = D_NEWBLK;
7038 	WORKITEM_FREE(newblk, D_NEWBLK);
7039 }
7040 
7041 /*
7042  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7043  * This routine must be called with splbio interrupts blocked.
7044  */
7045 static void
7046 free_newdirblk(newdirblk)
7047 	struct newdirblk *newdirblk;
7048 {
7049 	struct pagedep *pagedep;
7050 	struct diradd *dap;
7051 	struct worklist *wk;
7052 
7053 	mtx_assert(&lk, MA_OWNED);
7054 	WORKLIST_REMOVE(&newdirblk->db_list);
7055 	/*
7056 	 * If the pagedep is still linked onto the directory buffer
7057 	 * dependency chain, then some of the entries on the
7058 	 * pd_pendinghd list may not be committed to disk yet. In
7059 	 * this case, we will simply clear the NEWBLOCK flag and
7060 	 * let the pd_pendinghd list be processed when the pagedep
7061 	 * is next written. If the pagedep is no longer on the buffer
7062 	 * dependency chain, then all the entries on the pd_pending
7063 	 * list are committed to disk and we can free them here.
7064 	 */
7065 	pagedep = newdirblk->db_pagedep;
7066 	pagedep->pd_state &= ~NEWBLOCK;
7067 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7068 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7069 			free_diradd(dap, NULL);
7070 		/*
7071 		 * If no dependencies remain, the pagedep will be freed.
7072 		 */
7073 		free_pagedep(pagedep);
7074 	}
7075 	/* Should only ever be one item in the list. */
7076 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7077 		WORKLIST_REMOVE(wk);
7078 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7079 	}
7080 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7081 }
7082 
7083 /*
7084  * Prepare an inode to be freed. The actual free operation is not
7085  * done until the zero'ed inode has been written to disk.
7086  */
7087 void
7088 softdep_freefile(pvp, ino, mode)
7089 	struct vnode *pvp;
7090 	ino_t ino;
7091 	int mode;
7092 {
7093 	struct inode *ip = VTOI(pvp);
7094 	struct inodedep *inodedep;
7095 	struct freefile *freefile;
7096 	struct freeblks *freeblks;
7097 
7098 	/*
7099 	 * This sets up the inode de-allocation dependency.
7100 	 */
7101 	freefile = malloc(sizeof(struct freefile),
7102 		M_FREEFILE, M_SOFTDEP_FLAGS);
7103 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7104 	freefile->fx_mode = mode;
7105 	freefile->fx_oldinum = ino;
7106 	freefile->fx_devvp = ip->i_devvp;
7107 	LIST_INIT(&freefile->fx_jwork);
7108 	UFS_LOCK(ip->i_ump);
7109 	ip->i_fs->fs_pendinginodes += 1;
7110 	UFS_UNLOCK(ip->i_ump);
7111 
7112 	/*
7113 	 * If the inodedep does not exist, then the zero'ed inode has
7114 	 * been written to disk. If the allocated inode has never been
7115 	 * written to disk, then the on-disk inode is zero'ed. In either
7116 	 * case we can free the file immediately.  If the journal was
7117 	 * canceled before being written the inode will never make it to
7118 	 * disk and we must send the canceled journal entrys to
7119 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7120 	 * Any blocks waiting on the inode to write can be safely freed
7121 	 * here as it will never been written.
7122 	 */
7123 	ACQUIRE_LOCK(&lk);
7124 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7125 	if (inodedep) {
7126 		/*
7127 		 * Clear out freeblks that no longer need to reference
7128 		 * this inode.
7129 		 */
7130 		while ((freeblks =
7131 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7132 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7133 			    fb_next);
7134 			freeblks->fb_state &= ~ONDEPLIST;
7135 		}
7136 		/*
7137 		 * Remove this inode from the unlinked list.
7138 		 */
7139 		if (inodedep->id_state & UNLINKED) {
7140 			/*
7141 			 * Save the journal work to be freed with the bitmap
7142 			 * before we clear UNLINKED.  Otherwise it can be lost
7143 			 * if the inode block is written.
7144 			 */
7145 			handle_bufwait(inodedep, &freefile->fx_jwork);
7146 			clear_unlinked_inodedep(inodedep);
7147 			/* Re-acquire inodedep as we've dropped lk. */
7148 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7149 		}
7150 	}
7151 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7152 		FREE_LOCK(&lk);
7153 		handle_workitem_freefile(freefile);
7154 		return;
7155 	}
7156 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7157 		inodedep->id_state |= GOINGAWAY;
7158 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7159 	FREE_LOCK(&lk);
7160 	if (ip->i_number == ino)
7161 		ip->i_flag |= IN_MODIFIED;
7162 }
7163 
7164 /*
7165  * Check to see if an inode has never been written to disk. If
7166  * so free the inodedep and return success, otherwise return failure.
7167  * This routine must be called with splbio interrupts blocked.
7168  *
7169  * If we still have a bitmap dependency, then the inode has never
7170  * been written to disk. Drop the dependency as it is no longer
7171  * necessary since the inode is being deallocated. We set the
7172  * ALLCOMPLETE flags since the bitmap now properly shows that the
7173  * inode is not allocated. Even if the inode is actively being
7174  * written, it has been rolled back to its zero'ed state, so we
7175  * are ensured that a zero inode is what is on the disk. For short
7176  * lived files, this change will usually result in removing all the
7177  * dependencies from the inode so that it can be freed immediately.
7178  */
7179 static int
7180 check_inode_unwritten(inodedep)
7181 	struct inodedep *inodedep;
7182 {
7183 
7184 	mtx_assert(&lk, MA_OWNED);
7185 
7186 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7187 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7188 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7189 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7190 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7191 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7192 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7193 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7194 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7195 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7196 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7197 	    inodedep->id_mkdiradd != NULL ||
7198 	    inodedep->id_nlinkdelta != 0)
7199 		return (0);
7200 	/*
7201 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7202 	 * trying to allocate memory without holding "Softdep Lock".
7203 	 */
7204 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7205 	    inodedep->id_savedino1 == NULL)
7206 		return (0);
7207 
7208 	if (inodedep->id_state & ONDEPLIST)
7209 		LIST_REMOVE(inodedep, id_deps);
7210 	inodedep->id_state &= ~ONDEPLIST;
7211 	inodedep->id_state |= ALLCOMPLETE;
7212 	inodedep->id_bmsafemap = NULL;
7213 	if (inodedep->id_state & ONWORKLIST)
7214 		WORKLIST_REMOVE(&inodedep->id_list);
7215 	if (inodedep->id_savedino1 != NULL) {
7216 		free(inodedep->id_savedino1, M_SAVEDINO);
7217 		inodedep->id_savedino1 = NULL;
7218 	}
7219 	if (free_inodedep(inodedep) == 0)
7220 		panic("check_inode_unwritten: busy inode");
7221 	return (1);
7222 }
7223 
7224 /*
7225  * Try to free an inodedep structure. Return 1 if it could be freed.
7226  */
7227 static int
7228 free_inodedep(inodedep)
7229 	struct inodedep *inodedep;
7230 {
7231 
7232 	mtx_assert(&lk, MA_OWNED);
7233 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7234 	    (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7235 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7236 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7237 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7238 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7239 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7240 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7241 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7242 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7243 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7244 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7245 	    inodedep->id_mkdiradd != NULL ||
7246 	    inodedep->id_nlinkdelta != 0 ||
7247 	    inodedep->id_savedino1 != NULL)
7248 		return (0);
7249 	if (inodedep->id_state & ONDEPLIST)
7250 		LIST_REMOVE(inodedep, id_deps);
7251 	LIST_REMOVE(inodedep, id_hash);
7252 	WORKITEM_FREE(inodedep, D_INODEDEP);
7253 	return (1);
7254 }
7255 
7256 /*
7257  * Free the block referenced by a freework structure.  The parent freeblks
7258  * structure is released and completed when the final cg bitmap reaches
7259  * the disk.  This routine may be freeing a jnewblk which never made it to
7260  * disk in which case we do not have to wait as the operation is undone
7261  * in memory immediately.
7262  */
7263 static void
7264 freework_freeblock(freework)
7265 	struct freework *freework;
7266 {
7267 	struct freeblks *freeblks;
7268 	struct jnewblk *jnewblk;
7269 	struct ufsmount *ump;
7270 	struct workhead wkhd;
7271 	struct fs *fs;
7272 	int bsize;
7273 	int needj;
7274 
7275 	mtx_assert(&lk, MA_OWNED);
7276 	/*
7277 	 * Handle partial truncate separately.
7278 	 */
7279 	if (freework->fw_indir) {
7280 		complete_trunc_indir(freework);
7281 		return;
7282 	}
7283 	freeblks = freework->fw_freeblks;
7284 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7285 	fs = ump->um_fs;
7286 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7287 	bsize = lfragtosize(fs, freework->fw_frags);
7288 	LIST_INIT(&wkhd);
7289 	/*
7290 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7291 	 * on the indirblk hashtable and prevents premature freeing.
7292 	 */
7293 	freework->fw_state |= DEPCOMPLETE;
7294 	/*
7295 	 * SUJ needs to wait for the segment referencing freed indirect
7296 	 * blocks to expire so that we know the checker will not confuse
7297 	 * a re-allocated indirect block with its old contents.
7298 	 */
7299 	if (needj && freework->fw_lbn <= -NDADDR)
7300 		indirblk_insert(freework);
7301 	/*
7302 	 * If we are canceling an existing jnewblk pass it to the free
7303 	 * routine, otherwise pass the freeblk which will ultimately
7304 	 * release the freeblks.  If we're not journaling, we can just
7305 	 * free the freeblks immediately.
7306 	 */
7307 	jnewblk = freework->fw_jnewblk;
7308 	if (jnewblk != NULL) {
7309 		cancel_jnewblk(jnewblk, &wkhd);
7310 		needj = 0;
7311 	} else if (needj) {
7312 		freework->fw_state |= DELAYEDFREE;
7313 		freeblks->fb_cgwait++;
7314 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7315 	}
7316 	FREE_LOCK(&lk);
7317 	freeblks_free(ump, freeblks, btodb(bsize));
7318 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7319 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7320 	ACQUIRE_LOCK(&lk);
7321 	/*
7322 	 * The jnewblk will be discarded and the bits in the map never
7323 	 * made it to disk.  We can immediately free the freeblk.
7324 	 */
7325 	if (needj == 0)
7326 		handle_written_freework(freework);
7327 }
7328 
7329 /*
7330  * We enqueue freework items that need processing back on the freeblks and
7331  * add the freeblks to the worklist.  This makes it easier to find all work
7332  * required to flush a truncation in process_truncates().
7333  */
7334 static void
7335 freework_enqueue(freework)
7336 	struct freework *freework;
7337 {
7338 	struct freeblks *freeblks;
7339 
7340 	freeblks = freework->fw_freeblks;
7341 	if ((freework->fw_state & INPROGRESS) == 0)
7342 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7343 	if ((freeblks->fb_state &
7344 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7345 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7346 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7347 }
7348 
7349 /*
7350  * Start, continue, or finish the process of freeing an indirect block tree.
7351  * The free operation may be paused at any point with fw_off containing the
7352  * offset to restart from.  This enables us to implement some flow control
7353  * for large truncates which may fan out and generate a huge number of
7354  * dependencies.
7355  */
7356 static void
7357 handle_workitem_indirblk(freework)
7358 	struct freework *freework;
7359 {
7360 	struct freeblks *freeblks;
7361 	struct ufsmount *ump;
7362 	struct fs *fs;
7363 
7364 	freeblks = freework->fw_freeblks;
7365 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7366 	fs = ump->um_fs;
7367 	if (freework->fw_state & DEPCOMPLETE) {
7368 		handle_written_freework(freework);
7369 		return;
7370 	}
7371 	if (freework->fw_off == NINDIR(fs)) {
7372 		freework_freeblock(freework);
7373 		return;
7374 	}
7375 	freework->fw_state |= INPROGRESS;
7376 	FREE_LOCK(&lk);
7377 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7378 	    freework->fw_lbn);
7379 	ACQUIRE_LOCK(&lk);
7380 }
7381 
7382 /*
7383  * Called when a freework structure attached to a cg buf is written.  The
7384  * ref on either the parent or the freeblks structure is released and
7385  * the freeblks is added back to the worklist if there is more work to do.
7386  */
7387 static void
7388 handle_written_freework(freework)
7389 	struct freework *freework;
7390 {
7391 	struct freeblks *freeblks;
7392 	struct freework *parent;
7393 
7394 	freeblks = freework->fw_freeblks;
7395 	parent = freework->fw_parent;
7396 	if (freework->fw_state & DELAYEDFREE)
7397 		freeblks->fb_cgwait--;
7398 	freework->fw_state |= COMPLETE;
7399 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7400 		WORKITEM_FREE(freework, D_FREEWORK);
7401 	if (parent) {
7402 		if (--parent->fw_ref == 0)
7403 			freework_enqueue(parent);
7404 		return;
7405 	}
7406 	if (--freeblks->fb_ref != 0)
7407 		return;
7408 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7409 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7410 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7411 }
7412 
7413 /*
7414  * This workitem routine performs the block de-allocation.
7415  * The workitem is added to the pending list after the updated
7416  * inode block has been written to disk.  As mentioned above,
7417  * checks regarding the number of blocks de-allocated (compared
7418  * to the number of blocks allocated for the file) are also
7419  * performed in this function.
7420  */
7421 static int
7422 handle_workitem_freeblocks(freeblks, flags)
7423 	struct freeblks *freeblks;
7424 	int flags;
7425 {
7426 	struct freework *freework;
7427 	struct newblk *newblk;
7428 	struct allocindir *aip;
7429 	struct ufsmount *ump;
7430 	struct worklist *wk;
7431 
7432 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7433 	    ("handle_workitem_freeblocks: Journal entries not written."));
7434 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7435 	ACQUIRE_LOCK(&lk);
7436 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7437 		WORKLIST_REMOVE(wk);
7438 		switch (wk->wk_type) {
7439 		case D_DIRREM:
7440 			wk->wk_state |= COMPLETE;
7441 			add_to_worklist(wk, 0);
7442 			continue;
7443 
7444 		case D_ALLOCDIRECT:
7445 			free_newblk(WK_NEWBLK(wk));
7446 			continue;
7447 
7448 		case D_ALLOCINDIR:
7449 			aip = WK_ALLOCINDIR(wk);
7450 			freework = NULL;
7451 			if (aip->ai_state & DELAYEDFREE) {
7452 				FREE_LOCK(&lk);
7453 				freework = newfreework(ump, freeblks, NULL,
7454 				    aip->ai_lbn, aip->ai_newblkno,
7455 				    ump->um_fs->fs_frag, 0, 0);
7456 				ACQUIRE_LOCK(&lk);
7457 			}
7458 			newblk = WK_NEWBLK(wk);
7459 			if (newblk->nb_jnewblk) {
7460 				freework->fw_jnewblk = newblk->nb_jnewblk;
7461 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7462 				newblk->nb_jnewblk = NULL;
7463 			}
7464 			free_newblk(newblk);
7465 			continue;
7466 
7467 		case D_FREEWORK:
7468 			freework = WK_FREEWORK(wk);
7469 			if (freework->fw_lbn <= -NDADDR)
7470 				handle_workitem_indirblk(freework);
7471 			else
7472 				freework_freeblock(freework);
7473 			continue;
7474 		default:
7475 			panic("handle_workitem_freeblocks: Unknown type %s",
7476 			    TYPENAME(wk->wk_type));
7477 		}
7478 	}
7479 	if (freeblks->fb_ref != 0) {
7480 		freeblks->fb_state &= ~INPROGRESS;
7481 		wake_worklist(&freeblks->fb_list);
7482 		freeblks = NULL;
7483 	}
7484 	FREE_LOCK(&lk);
7485 	if (freeblks)
7486 		return handle_complete_freeblocks(freeblks, flags);
7487 	return (0);
7488 }
7489 
7490 /*
7491  * Handle completion of block free via truncate.  This allows fs_pending
7492  * to track the actual free block count more closely than if we only updated
7493  * it at the end.  We must be careful to handle cases where the block count
7494  * on free was incorrect.
7495  */
7496 static void
7497 freeblks_free(ump, freeblks, blocks)
7498 	struct ufsmount *ump;
7499 	struct freeblks *freeblks;
7500 	int blocks;
7501 {
7502 	struct fs *fs;
7503 	ufs2_daddr_t remain;
7504 
7505 	UFS_LOCK(ump);
7506 	remain = -freeblks->fb_chkcnt;
7507 	freeblks->fb_chkcnt += blocks;
7508 	if (remain > 0) {
7509 		if (remain < blocks)
7510 			blocks = remain;
7511 		fs = ump->um_fs;
7512 		fs->fs_pendingblocks -= blocks;
7513 	}
7514 	UFS_UNLOCK(ump);
7515 }
7516 
7517 /*
7518  * Once all of the freework workitems are complete we can retire the
7519  * freeblocks dependency and any journal work awaiting completion.  This
7520  * can not be called until all other dependencies are stable on disk.
7521  */
7522 static int
7523 handle_complete_freeblocks(freeblks, flags)
7524 	struct freeblks *freeblks;
7525 	int flags;
7526 {
7527 	struct inodedep *inodedep;
7528 	struct inode *ip;
7529 	struct vnode *vp;
7530 	struct fs *fs;
7531 	struct ufsmount *ump;
7532 	ufs2_daddr_t spare;
7533 
7534 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7535 	fs = ump->um_fs;
7536 	flags = LK_EXCLUSIVE | flags;
7537 	spare = freeblks->fb_chkcnt;
7538 
7539 	/*
7540 	 * If we did not release the expected number of blocks we may have
7541 	 * to adjust the inode block count here.  Only do so if it wasn't
7542 	 * a truncation to zero and the modrev still matches.
7543 	 */
7544 	if (spare && freeblks->fb_len != 0) {
7545 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7546 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
7547 			return (EBUSY);
7548 		ip = VTOI(vp);
7549 		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
7550 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
7551 			ip->i_flag |= IN_CHANGE;
7552 			/*
7553 			 * We must wait so this happens before the
7554 			 * journal is reclaimed.
7555 			 */
7556 			ffs_update(vp, 1);
7557 		}
7558 		vput(vp);
7559 	}
7560 	if (spare < 0) {
7561 		UFS_LOCK(ump);
7562 		fs->fs_pendingblocks += spare;
7563 		UFS_UNLOCK(ump);
7564 	}
7565 #ifdef QUOTA
7566 	/* Handle spare. */
7567 	if (spare)
7568 		quotaadj(freeblks->fb_quota, ump, -spare);
7569 	quotarele(freeblks->fb_quota);
7570 #endif
7571 	ACQUIRE_LOCK(&lk);
7572 	if (freeblks->fb_state & ONDEPLIST) {
7573 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7574 		    0, &inodedep);
7575 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
7576 		freeblks->fb_state &= ~ONDEPLIST;
7577 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
7578 			free_inodedep(inodedep);
7579 	}
7580 	/*
7581 	 * All of the freeblock deps must be complete prior to this call
7582 	 * so it's now safe to complete earlier outstanding journal entries.
7583 	 */
7584 	handle_jwork(&freeblks->fb_jwork);
7585 	WORKITEM_FREE(freeblks, D_FREEBLKS);
7586 	FREE_LOCK(&lk);
7587 	return (0);
7588 }
7589 
7590 /*
7591  * Release blocks associated with the freeblks and stored in the indirect
7592  * block dbn. If level is greater than SINGLE, the block is an indirect block
7593  * and recursive calls to indirtrunc must be used to cleanse other indirect
7594  * blocks.
7595  *
7596  * This handles partial and complete truncation of blocks.  Partial is noted
7597  * with goingaway == 0.  In this case the freework is completed after the
7598  * zero'd indirects are written to disk.  For full truncation the freework
7599  * is completed after the block is freed.
7600  */
7601 static void
7602 indir_trunc(freework, dbn, lbn)
7603 	struct freework *freework;
7604 	ufs2_daddr_t dbn;
7605 	ufs_lbn_t lbn;
7606 {
7607 	struct freework *nfreework;
7608 	struct workhead wkhd;
7609 	struct freeblks *freeblks;
7610 	struct buf *bp;
7611 	struct fs *fs;
7612 	struct indirdep *indirdep;
7613 	struct ufsmount *ump;
7614 	ufs1_daddr_t *bap1 = 0;
7615 	ufs2_daddr_t nb, nnb, *bap2 = 0;
7616 	ufs_lbn_t lbnadd, nlbn;
7617 	int i, nblocks, ufs1fmt;
7618 	int freedblocks;
7619 	int goingaway;
7620 	int freedeps;
7621 	int needj;
7622 	int level;
7623 	int cnt;
7624 
7625 	freeblks = freework->fw_freeblks;
7626 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7627 	fs = ump->um_fs;
7628 	/*
7629 	 * Get buffer of block pointers to be freed.  There are three cases:
7630 	 *
7631 	 * 1) Partial truncate caches the indirdep pointer in the freework
7632 	 *    which provides us a back copy to the save bp which holds the
7633 	 *    pointers we want to clear.  When this completes the zero
7634 	 *    pointers are written to the real copy.
7635 	 * 2) The indirect is being completely truncated, cancel_indirdep()
7636 	 *    eliminated the real copy and placed the indirdep on the saved
7637 	 *    copy.  The indirdep and buf are discarded when this completes.
7638 	 * 3) The indirect was not in memory, we read a copy off of the disk
7639 	 *    using the devvp and drop and invalidate the buffer when we're
7640 	 *    done.
7641 	 */
7642 	goingaway = 1;
7643 	indirdep = NULL;
7644 	if (freework->fw_indir != NULL) {
7645 		goingaway = 0;
7646 		indirdep = freework->fw_indir;
7647 		bp = indirdep->ir_savebp;
7648 		if (bp == NULL || bp->b_blkno != dbn)
7649 			panic("indir_trunc: Bad saved buf %p blkno %jd",
7650 			    bp, (intmax_t)dbn);
7651 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
7652 		/*
7653 		 * The lock prevents the buf dep list from changing and
7654 	 	 * indirects on devvp should only ever have one dependency.
7655 		 */
7656 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
7657 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
7658 			panic("indir_trunc: Bad indirdep %p from buf %p",
7659 			    indirdep, bp);
7660 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
7661 	    NOCRED, &bp) != 0) {
7662 		brelse(bp);
7663 		return;
7664 	}
7665 	ACQUIRE_LOCK(&lk);
7666 	/* Protects against a race with complete_trunc_indir(). */
7667 	freework->fw_state &= ~INPROGRESS;
7668 	/*
7669 	 * If we have an indirdep we need to enforce the truncation order
7670 	 * and discard it when it is complete.
7671 	 */
7672 	if (indirdep) {
7673 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
7674 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
7675 			/*
7676 			 * Add the complete truncate to the list on the
7677 			 * indirdep to enforce in-order processing.
7678 			 */
7679 			if (freework->fw_indir == NULL)
7680 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
7681 				    freework, fw_next);
7682 			FREE_LOCK(&lk);
7683 			return;
7684 		}
7685 		/*
7686 		 * If we're goingaway, free the indirdep.  Otherwise it will
7687 		 * linger until the write completes.
7688 		 */
7689 		if (goingaway) {
7690 			free_indirdep(indirdep);
7691 			ump->um_numindirdeps -= 1;
7692 		}
7693 	}
7694 	FREE_LOCK(&lk);
7695 	/* Initialize pointers depending on block size. */
7696 	if (ump->um_fstype == UFS1) {
7697 		bap1 = (ufs1_daddr_t *)bp->b_data;
7698 		nb = bap1[freework->fw_off];
7699 		ufs1fmt = 1;
7700 	} else {
7701 		bap2 = (ufs2_daddr_t *)bp->b_data;
7702 		nb = bap2[freework->fw_off];
7703 		ufs1fmt = 0;
7704 	}
7705 	level = lbn_level(lbn);
7706 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
7707 	lbnadd = lbn_offset(fs, level);
7708 	nblocks = btodb(fs->fs_bsize);
7709 	nfreework = freework;
7710 	freedeps = 0;
7711 	cnt = 0;
7712 	/*
7713 	 * Reclaim blocks.  Traverses into nested indirect levels and
7714 	 * arranges for the current level to be freed when subordinates
7715 	 * are free when journaling.
7716 	 */
7717 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
7718 		if (i != NINDIR(fs) - 1) {
7719 			if (ufs1fmt)
7720 				nnb = bap1[i+1];
7721 			else
7722 				nnb = bap2[i+1];
7723 		} else
7724 			nnb = 0;
7725 		if (nb == 0)
7726 			continue;
7727 		cnt++;
7728 		if (level != 0) {
7729 			nlbn = (lbn + 1) - (i * lbnadd);
7730 			if (needj != 0) {
7731 				nfreework = newfreework(ump, freeblks, freework,
7732 				    nlbn, nb, fs->fs_frag, 0, 0);
7733 				freedeps++;
7734 			}
7735 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
7736 		} else {
7737 			struct freedep *freedep;
7738 
7739 			/*
7740 			 * Attempt to aggregate freedep dependencies for
7741 			 * all blocks being released to the same CG.
7742 			 */
7743 			LIST_INIT(&wkhd);
7744 			if (needj != 0 &&
7745 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
7746 				freedep = newfreedep(freework);
7747 				WORKLIST_INSERT_UNLOCKED(&wkhd,
7748 				    &freedep->fd_list);
7749 				freedeps++;
7750 			}
7751 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
7752 			    fs->fs_bsize, freeblks->fb_inum,
7753 			    freeblks->fb_vtype, &wkhd);
7754 		}
7755 	}
7756 	if (goingaway) {
7757 		bp->b_flags |= B_INVAL | B_NOCACHE;
7758 		brelse(bp);
7759 	}
7760 	freedblocks = 0;
7761 	if (level == 0)
7762 		freedblocks = (nblocks * cnt);
7763 	if (needj == 0)
7764 		freedblocks += nblocks;
7765 	freeblks_free(ump, freeblks, freedblocks);
7766 	/*
7767 	 * If we are journaling set up the ref counts and offset so this
7768 	 * indirect can be completed when its children are free.
7769 	 */
7770 	if (needj) {
7771 		ACQUIRE_LOCK(&lk);
7772 		freework->fw_off = i;
7773 		freework->fw_ref += freedeps;
7774 		freework->fw_ref -= NINDIR(fs) + 1;
7775 		if (level == 0)
7776 			freeblks->fb_cgwait += freedeps;
7777 		if (freework->fw_ref == 0)
7778 			freework_freeblock(freework);
7779 		FREE_LOCK(&lk);
7780 		return;
7781 	}
7782 	/*
7783 	 * If we're not journaling we can free the indirect now.
7784 	 */
7785 	dbn = dbtofsb(fs, dbn);
7786 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
7787 	    freeblks->fb_inum, freeblks->fb_vtype, NULL);
7788 	/* Non SUJ softdep does single-threaded truncations. */
7789 	if (freework->fw_blkno == dbn) {
7790 		freework->fw_state |= ALLCOMPLETE;
7791 		ACQUIRE_LOCK(&lk);
7792 		handle_written_freework(freework);
7793 		FREE_LOCK(&lk);
7794 	}
7795 	return;
7796 }
7797 
7798 /*
7799  * Cancel an allocindir when it is removed via truncation.  When bp is not
7800  * NULL the indirect never appeared on disk and is scheduled to be freed
7801  * independently of the indir so we can more easily track journal work.
7802  */
7803 static void
7804 cancel_allocindir(aip, bp, freeblks, trunc)
7805 	struct allocindir *aip;
7806 	struct buf *bp;
7807 	struct freeblks *freeblks;
7808 	int trunc;
7809 {
7810 	struct indirdep *indirdep;
7811 	struct freefrag *freefrag;
7812 	struct newblk *newblk;
7813 
7814 	newblk = (struct newblk *)aip;
7815 	LIST_REMOVE(aip, ai_next);
7816 	/*
7817 	 * We must eliminate the pointer in bp if it must be freed on its
7818 	 * own due to partial truncate or pending journal work.
7819 	 */
7820 	if (bp && (trunc || newblk->nb_jnewblk)) {
7821 		/*
7822 		 * Clear the pointer and mark the aip to be freed
7823 		 * directly if it never existed on disk.
7824 		 */
7825 		aip->ai_state |= DELAYEDFREE;
7826 		indirdep = aip->ai_indirdep;
7827 		if (indirdep->ir_state & UFS1FMT)
7828 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
7829 		else
7830 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
7831 	}
7832 	/*
7833 	 * When truncating the previous pointer will be freed via
7834 	 * savedbp.  Eliminate the freefrag which would dup free.
7835 	 */
7836 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
7837 		newblk->nb_freefrag = NULL;
7838 		if (freefrag->ff_jdep)
7839 			cancel_jfreefrag(
7840 			    WK_JFREEFRAG(freefrag->ff_jdep));
7841 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
7842 		WORKITEM_FREE(freefrag, D_FREEFRAG);
7843 	}
7844 	/*
7845 	 * If the journal hasn't been written the jnewblk must be passed
7846 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7847 	 * this by leaving the journal dependency on the newblk to be freed
7848 	 * when a freework is created in handle_workitem_freeblocks().
7849 	 */
7850 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
7851 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7852 }
7853 
7854 /*
7855  * Create the mkdir dependencies for . and .. in a new directory.  Link them
7856  * in to a newdirblk so any subsequent additions are tracked properly.  The
7857  * caller is responsible for adding the mkdir1 dependency to the journal
7858  * and updating id_mkdiradd.  This function returns with lk held.
7859  */
7860 static struct mkdir *
7861 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
7862 	struct diradd *dap;
7863 	ino_t newinum;
7864 	ino_t dinum;
7865 	struct buf *newdirbp;
7866 	struct mkdir **mkdirp;
7867 {
7868 	struct newblk *newblk;
7869 	struct pagedep *pagedep;
7870 	struct inodedep *inodedep;
7871 	struct newdirblk *newdirblk = 0;
7872 	struct mkdir *mkdir1, *mkdir2;
7873 	struct worklist *wk;
7874 	struct jaddref *jaddref;
7875 	struct mount *mp;
7876 
7877 	mp = dap->da_list.wk_mp;
7878 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
7879 	    M_SOFTDEP_FLAGS);
7880 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
7881 	LIST_INIT(&newdirblk->db_mkdir);
7882 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
7883 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
7884 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
7885 	mkdir1->md_diradd = dap;
7886 	mkdir1->md_jaddref = NULL;
7887 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
7888 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
7889 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
7890 	mkdir2->md_diradd = dap;
7891 	mkdir2->md_jaddref = NULL;
7892 	if (MOUNTEDSUJ(mp) == 0) {
7893 		mkdir1->md_state |= DEPCOMPLETE;
7894 		mkdir2->md_state |= DEPCOMPLETE;
7895 	}
7896 	/*
7897 	 * Dependency on "." and ".." being written to disk.
7898 	 */
7899 	mkdir1->md_buf = newdirbp;
7900 	ACQUIRE_LOCK(&lk);
7901 	LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
7902 	/*
7903 	 * We must link the pagedep, allocdirect, and newdirblk for
7904 	 * the initial file page so the pointer to the new directory
7905 	 * is not written until the directory contents are live and
7906 	 * any subsequent additions are not marked live until the
7907 	 * block is reachable via the inode.
7908 	 */
7909 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
7910 		panic("setup_newdir: lost pagedep");
7911 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
7912 		if (wk->wk_type == D_ALLOCDIRECT)
7913 			break;
7914 	if (wk == NULL)
7915 		panic("setup_newdir: lost allocdirect");
7916 	if (pagedep->pd_state & NEWBLOCK)
7917 		panic("setup_newdir: NEWBLOCK already set");
7918 	newblk = WK_NEWBLK(wk);
7919 	pagedep->pd_state |= NEWBLOCK;
7920 	pagedep->pd_newdirblk = newdirblk;
7921 	newdirblk->db_pagedep = pagedep;
7922 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
7923 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
7924 	/*
7925 	 * Look up the inodedep for the parent directory so that we
7926 	 * can link mkdir2 into the pending dotdot jaddref or
7927 	 * the inode write if there is none.  If the inode is
7928 	 * ALLCOMPLETE and no jaddref is present all dependencies have
7929 	 * been satisfied and mkdir2 can be freed.
7930 	 */
7931 	inodedep_lookup(mp, dinum, 0, &inodedep);
7932 	if (MOUNTEDSUJ(mp)) {
7933 		if (inodedep == NULL)
7934 			panic("setup_newdir: Lost parent.");
7935 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
7936 		    inoreflst);
7937 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
7938 		    (jaddref->ja_state & MKDIR_PARENT),
7939 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
7940 		LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
7941 		mkdir2->md_jaddref = jaddref;
7942 		jaddref->ja_mkdir = mkdir2;
7943 	} else if (inodedep == NULL ||
7944 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
7945 		dap->da_state &= ~MKDIR_PARENT;
7946 		WORKITEM_FREE(mkdir2, D_MKDIR);
7947 	} else {
7948 		LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
7949 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
7950 	}
7951 	*mkdirp = mkdir2;
7952 
7953 	return (mkdir1);
7954 }
7955 
7956 /*
7957  * Directory entry addition dependencies.
7958  *
7959  * When adding a new directory entry, the inode (with its incremented link
7960  * count) must be written to disk before the directory entry's pointer to it.
7961  * Also, if the inode is newly allocated, the corresponding freemap must be
7962  * updated (on disk) before the directory entry's pointer. These requirements
7963  * are met via undo/redo on the directory entry's pointer, which consists
7964  * simply of the inode number.
7965  *
7966  * As directory entries are added and deleted, the free space within a
7967  * directory block can become fragmented.  The ufs filesystem will compact
7968  * a fragmented directory block to make space for a new entry. When this
7969  * occurs, the offsets of previously added entries change. Any "diradd"
7970  * dependency structures corresponding to these entries must be updated with
7971  * the new offsets.
7972  */
7973 
7974 /*
7975  * This routine is called after the in-memory inode's link
7976  * count has been incremented, but before the directory entry's
7977  * pointer to the inode has been set.
7978  */
7979 int
7980 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
7981 	struct buf *bp;		/* buffer containing directory block */
7982 	struct inode *dp;	/* inode for directory */
7983 	off_t diroffset;	/* offset of new entry in directory */
7984 	ino_t newinum;		/* inode referenced by new directory entry */
7985 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
7986 	int isnewblk;		/* entry is in a newly allocated block */
7987 {
7988 	int offset;		/* offset of new entry within directory block */
7989 	ufs_lbn_t lbn;		/* block in directory containing new entry */
7990 	struct fs *fs;
7991 	struct diradd *dap;
7992 	struct newblk *newblk;
7993 	struct pagedep *pagedep;
7994 	struct inodedep *inodedep;
7995 	struct newdirblk *newdirblk = 0;
7996 	struct mkdir *mkdir1, *mkdir2;
7997 	struct jaddref *jaddref;
7998 	struct mount *mp;
7999 	int isindir;
8000 
8001 	/*
8002 	 * Whiteouts have no dependencies.
8003 	 */
8004 	if (newinum == WINO) {
8005 		if (newdirbp != NULL)
8006 			bdwrite(newdirbp);
8007 		return (0);
8008 	}
8009 	jaddref = NULL;
8010 	mkdir1 = mkdir2 = NULL;
8011 	mp = UFSTOVFS(dp->i_ump);
8012 	fs = dp->i_fs;
8013 	lbn = lblkno(fs, diroffset);
8014 	offset = blkoff(fs, diroffset);
8015 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8016 		M_SOFTDEP_FLAGS|M_ZERO);
8017 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8018 	dap->da_offset = offset;
8019 	dap->da_newinum = newinum;
8020 	dap->da_state = ATTACHED;
8021 	LIST_INIT(&dap->da_jwork);
8022 	isindir = bp->b_lblkno >= NDADDR;
8023 	if (isnewblk &&
8024 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8025 		newdirblk = malloc(sizeof(struct newdirblk),
8026 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8027 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8028 		LIST_INIT(&newdirblk->db_mkdir);
8029 	}
8030 	/*
8031 	 * If we're creating a new directory setup the dependencies and set
8032 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8033 	 * we can move on.
8034 	 */
8035 	if (newdirbp == NULL) {
8036 		dap->da_state |= DEPCOMPLETE;
8037 		ACQUIRE_LOCK(&lk);
8038 	} else {
8039 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8040 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8041 		    &mkdir2);
8042 	}
8043 	/*
8044 	 * Link into parent directory pagedep to await its being written.
8045 	 */
8046 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8047 #ifdef DEBUG
8048 	if (diradd_lookup(pagedep, offset) != NULL)
8049 		panic("softdep_setup_directory_add: %p already at off %d\n",
8050 		    diradd_lookup(pagedep, offset), offset);
8051 #endif
8052 	dap->da_pagedep = pagedep;
8053 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8054 	    da_pdlist);
8055 	inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep);
8056 	/*
8057 	 * If we're journaling, link the diradd into the jaddref so it
8058 	 * may be completed after the journal entry is written.  Otherwise,
8059 	 * link the diradd into its inodedep.  If the inode is not yet
8060 	 * written place it on the bufwait list, otherwise do the post-inode
8061 	 * write processing to put it on the id_pendinghd list.
8062 	 */
8063 	if (MOUNTEDSUJ(mp)) {
8064 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8065 		    inoreflst);
8066 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8067 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8068 		jaddref->ja_diroff = diroffset;
8069 		jaddref->ja_diradd = dap;
8070 		add_to_journal(&jaddref->ja_list);
8071 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8072 		diradd_inode_written(dap, inodedep);
8073 	else
8074 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8075 	/*
8076 	 * Add the journal entries for . and .. links now that the primary
8077 	 * link is written.
8078 	 */
8079 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8080 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8081 		    inoreflst, if_deps);
8082 		KASSERT(jaddref != NULL &&
8083 		    jaddref->ja_ino == jaddref->ja_parent &&
8084 		    (jaddref->ja_state & MKDIR_BODY),
8085 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8086 		    jaddref));
8087 		mkdir1->md_jaddref = jaddref;
8088 		jaddref->ja_mkdir = mkdir1;
8089 		/*
8090 		 * It is important that the dotdot journal entry
8091 		 * is added prior to the dot entry since dot writes
8092 		 * both the dot and dotdot links.  These both must
8093 		 * be added after the primary link for the journal
8094 		 * to remain consistent.
8095 		 */
8096 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8097 		add_to_journal(&jaddref->ja_list);
8098 	}
8099 	/*
8100 	 * If we are adding a new directory remember this diradd so that if
8101 	 * we rename it we can keep the dot and dotdot dependencies.  If
8102 	 * we are adding a new name for an inode that has a mkdiradd we
8103 	 * must be in rename and we have to move the dot and dotdot
8104 	 * dependencies to this new name.  The old name is being orphaned
8105 	 * soon.
8106 	 */
8107 	if (mkdir1 != NULL) {
8108 		if (inodedep->id_mkdiradd != NULL)
8109 			panic("softdep_setup_directory_add: Existing mkdir");
8110 		inodedep->id_mkdiradd = dap;
8111 	} else if (inodedep->id_mkdiradd)
8112 		merge_diradd(inodedep, dap);
8113 	if (newdirblk) {
8114 		/*
8115 		 * There is nothing to do if we are already tracking
8116 		 * this block.
8117 		 */
8118 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8119 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8120 			FREE_LOCK(&lk);
8121 			return (0);
8122 		}
8123 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8124 		    == 0)
8125 			panic("softdep_setup_directory_add: lost entry");
8126 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8127 		pagedep->pd_state |= NEWBLOCK;
8128 		pagedep->pd_newdirblk = newdirblk;
8129 		newdirblk->db_pagedep = pagedep;
8130 		FREE_LOCK(&lk);
8131 		/*
8132 		 * If we extended into an indirect signal direnter to sync.
8133 		 */
8134 		if (isindir)
8135 			return (1);
8136 		return (0);
8137 	}
8138 	FREE_LOCK(&lk);
8139 	return (0);
8140 }
8141 
8142 /*
8143  * This procedure is called to change the offset of a directory
8144  * entry when compacting a directory block which must be owned
8145  * exclusively by the caller. Note that the actual entry movement
8146  * must be done in this procedure to ensure that no I/O completions
8147  * occur while the move is in progress.
8148  */
8149 void
8150 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8151 	struct buf *bp;		/* Buffer holding directory block. */
8152 	struct inode *dp;	/* inode for directory */
8153 	caddr_t base;		/* address of dp->i_offset */
8154 	caddr_t oldloc;		/* address of old directory location */
8155 	caddr_t newloc;		/* address of new directory location */
8156 	int entrysize;		/* size of directory entry */
8157 {
8158 	int offset, oldoffset, newoffset;
8159 	struct pagedep *pagedep;
8160 	struct jmvref *jmvref;
8161 	struct diradd *dap;
8162 	struct direct *de;
8163 	struct mount *mp;
8164 	ufs_lbn_t lbn;
8165 	int flags;
8166 
8167 	mp = UFSTOVFS(dp->i_ump);
8168 	de = (struct direct *)oldloc;
8169 	jmvref = NULL;
8170 	flags = 0;
8171 	/*
8172 	 * Moves are always journaled as it would be too complex to
8173 	 * determine if any affected adds or removes are present in the
8174 	 * journal.
8175 	 */
8176 	if (MOUNTEDSUJ(mp)) {
8177 		flags = DEPALLOC;
8178 		jmvref = newjmvref(dp, de->d_ino,
8179 		    dp->i_offset + (oldloc - base),
8180 		    dp->i_offset + (newloc - base));
8181 	}
8182 	lbn = lblkno(dp->i_fs, dp->i_offset);
8183 	offset = blkoff(dp->i_fs, dp->i_offset);
8184 	oldoffset = offset + (oldloc - base);
8185 	newoffset = offset + (newloc - base);
8186 	ACQUIRE_LOCK(&lk);
8187 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8188 		goto done;
8189 	dap = diradd_lookup(pagedep, oldoffset);
8190 	if (dap) {
8191 		dap->da_offset = newoffset;
8192 		newoffset = DIRADDHASH(newoffset);
8193 		oldoffset = DIRADDHASH(oldoffset);
8194 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8195 		    newoffset != oldoffset) {
8196 			LIST_REMOVE(dap, da_pdlist);
8197 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8198 			    dap, da_pdlist);
8199 		}
8200 	}
8201 done:
8202 	if (jmvref) {
8203 		jmvref->jm_pagedep = pagedep;
8204 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8205 		add_to_journal(&jmvref->jm_list);
8206 	}
8207 	bcopy(oldloc, newloc, entrysize);
8208 	FREE_LOCK(&lk);
8209 }
8210 
8211 /*
8212  * Move the mkdir dependencies and journal work from one diradd to another
8213  * when renaming a directory.  The new name must depend on the mkdir deps
8214  * completing as the old name did.  Directories can only have one valid link
8215  * at a time so one must be canonical.
8216  */
8217 static void
8218 merge_diradd(inodedep, newdap)
8219 	struct inodedep *inodedep;
8220 	struct diradd *newdap;
8221 {
8222 	struct diradd *olddap;
8223 	struct mkdir *mkdir, *nextmd;
8224 	short state;
8225 
8226 	olddap = inodedep->id_mkdiradd;
8227 	inodedep->id_mkdiradd = newdap;
8228 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8229 		newdap->da_state &= ~DEPCOMPLETE;
8230 		for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
8231 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8232 			if (mkdir->md_diradd != olddap)
8233 				continue;
8234 			mkdir->md_diradd = newdap;
8235 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8236 			newdap->da_state |= state;
8237 			olddap->da_state &= ~state;
8238 			if ((olddap->da_state &
8239 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8240 				break;
8241 		}
8242 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8243 			panic("merge_diradd: unfound ref");
8244 	}
8245 	/*
8246 	 * Any mkdir related journal items are not safe to be freed until
8247 	 * the new name is stable.
8248 	 */
8249 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8250 	olddap->da_state |= DEPCOMPLETE;
8251 	complete_diradd(olddap);
8252 }
8253 
8254 /*
8255  * Move the diradd to the pending list when all diradd dependencies are
8256  * complete.
8257  */
8258 static void
8259 complete_diradd(dap)
8260 	struct diradd *dap;
8261 {
8262 	struct pagedep *pagedep;
8263 
8264 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8265 		if (dap->da_state & DIRCHG)
8266 			pagedep = dap->da_previous->dm_pagedep;
8267 		else
8268 			pagedep = dap->da_pagedep;
8269 		LIST_REMOVE(dap, da_pdlist);
8270 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8271 	}
8272 }
8273 
8274 /*
8275  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8276  * add entries and conditonally journal the remove.
8277  */
8278 static void
8279 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8280 	struct diradd *dap;
8281 	struct dirrem *dirrem;
8282 	struct jremref *jremref;
8283 	struct jremref *dotremref;
8284 	struct jremref *dotdotremref;
8285 {
8286 	struct inodedep *inodedep;
8287 	struct jaddref *jaddref;
8288 	struct inoref *inoref;
8289 	struct mkdir *mkdir;
8290 
8291 	/*
8292 	 * If no remove references were allocated we're on a non-journaled
8293 	 * filesystem and can skip the cancel step.
8294 	 */
8295 	if (jremref == NULL) {
8296 		free_diradd(dap, NULL);
8297 		return;
8298 	}
8299 	/*
8300 	 * Cancel the primary name an free it if it does not require
8301 	 * journaling.
8302 	 */
8303 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8304 	    0, &inodedep) != 0) {
8305 		/* Abort the addref that reference this diradd.  */
8306 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8307 			if (inoref->if_list.wk_type != D_JADDREF)
8308 				continue;
8309 			jaddref = (struct jaddref *)inoref;
8310 			if (jaddref->ja_diradd != dap)
8311 				continue;
8312 			if (cancel_jaddref(jaddref, inodedep,
8313 			    &dirrem->dm_jwork) == 0) {
8314 				free_jremref(jremref);
8315 				jremref = NULL;
8316 			}
8317 			break;
8318 		}
8319 	}
8320 	/*
8321 	 * Cancel subordinate names and free them if they do not require
8322 	 * journaling.
8323 	 */
8324 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8325 		LIST_FOREACH(mkdir, &mkdirlisthd, md_mkdirs) {
8326 			if (mkdir->md_diradd != dap)
8327 				continue;
8328 			if ((jaddref = mkdir->md_jaddref) == NULL)
8329 				continue;
8330 			mkdir->md_jaddref = NULL;
8331 			if (mkdir->md_state & MKDIR_PARENT) {
8332 				if (cancel_jaddref(jaddref, NULL,
8333 				    &dirrem->dm_jwork) == 0) {
8334 					free_jremref(dotdotremref);
8335 					dotdotremref = NULL;
8336 				}
8337 			} else {
8338 				if (cancel_jaddref(jaddref, inodedep,
8339 				    &dirrem->dm_jwork) == 0) {
8340 					free_jremref(dotremref);
8341 					dotremref = NULL;
8342 				}
8343 			}
8344 		}
8345 	}
8346 
8347 	if (jremref)
8348 		journal_jremref(dirrem, jremref, inodedep);
8349 	if (dotremref)
8350 		journal_jremref(dirrem, dotremref, inodedep);
8351 	if (dotdotremref)
8352 		journal_jremref(dirrem, dotdotremref, NULL);
8353 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8354 	free_diradd(dap, &dirrem->dm_jwork);
8355 }
8356 
8357 /*
8358  * Free a diradd dependency structure. This routine must be called
8359  * with splbio interrupts blocked.
8360  */
8361 static void
8362 free_diradd(dap, wkhd)
8363 	struct diradd *dap;
8364 	struct workhead *wkhd;
8365 {
8366 	struct dirrem *dirrem;
8367 	struct pagedep *pagedep;
8368 	struct inodedep *inodedep;
8369 	struct mkdir *mkdir, *nextmd;
8370 
8371 	mtx_assert(&lk, MA_OWNED);
8372 	LIST_REMOVE(dap, da_pdlist);
8373 	if (dap->da_state & ONWORKLIST)
8374 		WORKLIST_REMOVE(&dap->da_list);
8375 	if ((dap->da_state & DIRCHG) == 0) {
8376 		pagedep = dap->da_pagedep;
8377 	} else {
8378 		dirrem = dap->da_previous;
8379 		pagedep = dirrem->dm_pagedep;
8380 		dirrem->dm_dirinum = pagedep->pd_ino;
8381 		dirrem->dm_state |= COMPLETE;
8382 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8383 			add_to_worklist(&dirrem->dm_list, 0);
8384 	}
8385 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8386 	    0, &inodedep) != 0)
8387 		if (inodedep->id_mkdiradd == dap)
8388 			inodedep->id_mkdiradd = NULL;
8389 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8390 		for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
8391 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8392 			if (mkdir->md_diradd != dap)
8393 				continue;
8394 			dap->da_state &=
8395 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8396 			LIST_REMOVE(mkdir, md_mkdirs);
8397 			if (mkdir->md_state & ONWORKLIST)
8398 				WORKLIST_REMOVE(&mkdir->md_list);
8399 			if (mkdir->md_jaddref != NULL)
8400 				panic("free_diradd: Unexpected jaddref");
8401 			WORKITEM_FREE(mkdir, D_MKDIR);
8402 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8403 				break;
8404 		}
8405 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8406 			panic("free_diradd: unfound ref");
8407 	}
8408 	if (inodedep)
8409 		free_inodedep(inodedep);
8410 	/*
8411 	 * Free any journal segments waiting for the directory write.
8412 	 */
8413 	handle_jwork(&dap->da_jwork);
8414 	WORKITEM_FREE(dap, D_DIRADD);
8415 }
8416 
8417 /*
8418  * Directory entry removal dependencies.
8419  *
8420  * When removing a directory entry, the entry's inode pointer must be
8421  * zero'ed on disk before the corresponding inode's link count is decremented
8422  * (possibly freeing the inode for re-use). This dependency is handled by
8423  * updating the directory entry but delaying the inode count reduction until
8424  * after the directory block has been written to disk. After this point, the
8425  * inode count can be decremented whenever it is convenient.
8426  */
8427 
8428 /*
8429  * This routine should be called immediately after removing
8430  * a directory entry.  The inode's link count should not be
8431  * decremented by the calling procedure -- the soft updates
8432  * code will do this task when it is safe.
8433  */
8434 void
8435 softdep_setup_remove(bp, dp, ip, isrmdir)
8436 	struct buf *bp;		/* buffer containing directory block */
8437 	struct inode *dp;	/* inode for the directory being modified */
8438 	struct inode *ip;	/* inode for directory entry being removed */
8439 	int isrmdir;		/* indicates if doing RMDIR */
8440 {
8441 	struct dirrem *dirrem, *prevdirrem;
8442 	struct inodedep *inodedep;
8443 	int direct;
8444 
8445 	/*
8446 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8447 	 * newdirrem() to setup the full directory remove which requires
8448 	 * isrmdir > 1.
8449 	 */
8450 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8451 	/*
8452 	 * Add the dirrem to the inodedep's pending remove list for quick
8453 	 * discovery later.
8454 	 */
8455 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8456 	    &inodedep) == 0)
8457 		panic("softdep_setup_remove: Lost inodedep.");
8458 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8459 	dirrem->dm_state |= ONDEPLIST;
8460 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8461 
8462 	/*
8463 	 * If the COMPLETE flag is clear, then there were no active
8464 	 * entries and we want to roll back to a zeroed entry until
8465 	 * the new inode is committed to disk. If the COMPLETE flag is
8466 	 * set then we have deleted an entry that never made it to
8467 	 * disk. If the entry we deleted resulted from a name change,
8468 	 * then the old name still resides on disk. We cannot delete
8469 	 * its inode (returned to us in prevdirrem) until the zeroed
8470 	 * directory entry gets to disk. The new inode has never been
8471 	 * referenced on the disk, so can be deleted immediately.
8472 	 */
8473 	if ((dirrem->dm_state & COMPLETE) == 0) {
8474 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8475 		    dm_next);
8476 		FREE_LOCK(&lk);
8477 	} else {
8478 		if (prevdirrem != NULL)
8479 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8480 			    prevdirrem, dm_next);
8481 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8482 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8483 		FREE_LOCK(&lk);
8484 		if (direct)
8485 			handle_workitem_remove(dirrem, 0);
8486 	}
8487 }
8488 
8489 /*
8490  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8491  * pd_pendinghd list of a pagedep.
8492  */
8493 static struct diradd *
8494 diradd_lookup(pagedep, offset)
8495 	struct pagedep *pagedep;
8496 	int offset;
8497 {
8498 	struct diradd *dap;
8499 
8500 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8501 		if (dap->da_offset == offset)
8502 			return (dap);
8503 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8504 		if (dap->da_offset == offset)
8505 			return (dap);
8506 	return (NULL);
8507 }
8508 
8509 /*
8510  * Search for a .. diradd dependency in a directory that is being removed.
8511  * If the directory was renamed to a new parent we have a diradd rather
8512  * than a mkdir for the .. entry.  We need to cancel it now before
8513  * it is found in truncate().
8514  */
8515 static struct jremref *
8516 cancel_diradd_dotdot(ip, dirrem, jremref)
8517 	struct inode *ip;
8518 	struct dirrem *dirrem;
8519 	struct jremref *jremref;
8520 {
8521 	struct pagedep *pagedep;
8522 	struct diradd *dap;
8523 	struct worklist *wk;
8524 
8525 	if (pagedep_lookup(UFSTOVFS(ip->i_ump), NULL, ip->i_number, 0, 0,
8526 	    &pagedep) == 0)
8527 		return (jremref);
8528 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
8529 	if (dap == NULL)
8530 		return (jremref);
8531 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
8532 	/*
8533 	 * Mark any journal work as belonging to the parent so it is freed
8534 	 * with the .. reference.
8535 	 */
8536 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
8537 		wk->wk_state |= MKDIR_PARENT;
8538 	return (NULL);
8539 }
8540 
8541 /*
8542  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
8543  * replace it with a dirrem/diradd pair as a result of re-parenting a
8544  * directory.  This ensures that we don't simultaneously have a mkdir and
8545  * a diradd for the same .. entry.
8546  */
8547 static struct jremref *
8548 cancel_mkdir_dotdot(ip, dirrem, jremref)
8549 	struct inode *ip;
8550 	struct dirrem *dirrem;
8551 	struct jremref *jremref;
8552 {
8553 	struct inodedep *inodedep;
8554 	struct jaddref *jaddref;
8555 	struct mkdir *mkdir;
8556 	struct diradd *dap;
8557 
8558 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8559 	    &inodedep) == 0)
8560 		panic("cancel_mkdir_dotdot: Lost inodedep");
8561 	dap = inodedep->id_mkdiradd;
8562 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
8563 		return (jremref);
8564 	for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir;
8565 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
8566 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
8567 			break;
8568 	if (mkdir == NULL)
8569 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
8570 	if ((jaddref = mkdir->md_jaddref) != NULL) {
8571 		mkdir->md_jaddref = NULL;
8572 		jaddref->ja_state &= ~MKDIR_PARENT;
8573 		if (inodedep_lookup(UFSTOVFS(ip->i_ump), jaddref->ja_ino, 0,
8574 		    &inodedep) == 0)
8575 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
8576 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
8577 			journal_jremref(dirrem, jremref, inodedep);
8578 			jremref = NULL;
8579 		}
8580 	}
8581 	if (mkdir->md_state & ONWORKLIST)
8582 		WORKLIST_REMOVE(&mkdir->md_list);
8583 	mkdir->md_state |= ALLCOMPLETE;
8584 	complete_mkdir(mkdir);
8585 	return (jremref);
8586 }
8587 
8588 static void
8589 journal_jremref(dirrem, jremref, inodedep)
8590 	struct dirrem *dirrem;
8591 	struct jremref *jremref;
8592 	struct inodedep *inodedep;
8593 {
8594 
8595 	if (inodedep == NULL)
8596 		if (inodedep_lookup(jremref->jr_list.wk_mp,
8597 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
8598 			panic("journal_jremref: Lost inodedep");
8599 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
8600 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
8601 	add_to_journal(&jremref->jr_list);
8602 }
8603 
8604 static void
8605 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
8606 	struct dirrem *dirrem;
8607 	struct jremref *jremref;
8608 	struct jremref *dotremref;
8609 	struct jremref *dotdotremref;
8610 {
8611 	struct inodedep *inodedep;
8612 
8613 
8614 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
8615 	    &inodedep) == 0)
8616 		panic("dirrem_journal: Lost inodedep");
8617 	journal_jremref(dirrem, jremref, inodedep);
8618 	if (dotremref)
8619 		journal_jremref(dirrem, dotremref, inodedep);
8620 	if (dotdotremref)
8621 		journal_jremref(dirrem, dotdotremref, NULL);
8622 }
8623 
8624 /*
8625  * Allocate a new dirrem if appropriate and return it along with
8626  * its associated pagedep. Called without a lock, returns with lock.
8627  */
8628 static struct dirrem *
8629 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
8630 	struct buf *bp;		/* buffer containing directory block */
8631 	struct inode *dp;	/* inode for the directory being modified */
8632 	struct inode *ip;	/* inode for directory entry being removed */
8633 	int isrmdir;		/* indicates if doing RMDIR */
8634 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
8635 {
8636 	int offset;
8637 	ufs_lbn_t lbn;
8638 	struct diradd *dap;
8639 	struct dirrem *dirrem;
8640 	struct pagedep *pagedep;
8641 	struct jremref *jremref;
8642 	struct jremref *dotremref;
8643 	struct jremref *dotdotremref;
8644 	struct vnode *dvp;
8645 
8646 	/*
8647 	 * Whiteouts have no deletion dependencies.
8648 	 */
8649 	if (ip == NULL)
8650 		panic("newdirrem: whiteout");
8651 	dvp = ITOV(dp);
8652 	/*
8653 	 * If we are over our limit, try to improve the situation.
8654 	 * Limiting the number of dirrem structures will also limit
8655 	 * the number of freefile and freeblks structures.
8656 	 */
8657 	ACQUIRE_LOCK(&lk);
8658 	if (!IS_SNAPSHOT(ip) && dep_current[D_DIRREM] > max_softdeps / 2)
8659 		(void) request_cleanup(ITOV(dp)->v_mount, FLUSH_BLOCKS);
8660 	FREE_LOCK(&lk);
8661 	dirrem = malloc(sizeof(struct dirrem),
8662 		M_DIRREM, M_SOFTDEP_FLAGS|M_ZERO);
8663 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
8664 	LIST_INIT(&dirrem->dm_jremrefhd);
8665 	LIST_INIT(&dirrem->dm_jwork);
8666 	dirrem->dm_state = isrmdir ? RMDIR : 0;
8667 	dirrem->dm_oldinum = ip->i_number;
8668 	*prevdirremp = NULL;
8669 	/*
8670 	 * Allocate remove reference structures to track journal write
8671 	 * dependencies.  We will always have one for the link and
8672 	 * when doing directories we will always have one more for dot.
8673 	 * When renaming a directory we skip the dotdot link change so
8674 	 * this is not needed.
8675 	 */
8676 	jremref = dotremref = dotdotremref = NULL;
8677 	if (DOINGSUJ(dvp)) {
8678 		if (isrmdir) {
8679 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
8680 			    ip->i_effnlink + 2);
8681 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
8682 			    ip->i_effnlink + 1);
8683 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
8684 			    dp->i_effnlink + 1);
8685 			dotdotremref->jr_state |= MKDIR_PARENT;
8686 		} else
8687 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
8688 			    ip->i_effnlink + 1);
8689 	}
8690 	ACQUIRE_LOCK(&lk);
8691 	lbn = lblkno(dp->i_fs, dp->i_offset);
8692 	offset = blkoff(dp->i_fs, dp->i_offset);
8693 	pagedep_lookup(UFSTOVFS(dp->i_ump), bp, dp->i_number, lbn, DEPALLOC,
8694 	    &pagedep);
8695 	dirrem->dm_pagedep = pagedep;
8696 	dirrem->dm_offset = offset;
8697 	/*
8698 	 * If we're renaming a .. link to a new directory, cancel any
8699 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
8700 	 * the jremref is preserved for any potential diradd in this
8701 	 * location.  This can not coincide with a rmdir.
8702 	 */
8703 	if (dp->i_offset == DOTDOT_OFFSET) {
8704 		if (isrmdir)
8705 			panic("newdirrem: .. directory change during remove?");
8706 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
8707 	}
8708 	/*
8709 	 * If we're removing a directory search for the .. dependency now and
8710 	 * cancel it.  Any pending journal work will be added to the dirrem
8711 	 * to be completed when the workitem remove completes.
8712 	 */
8713 	if (isrmdir)
8714 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
8715 	/*
8716 	 * Check for a diradd dependency for the same directory entry.
8717 	 * If present, then both dependencies become obsolete and can
8718 	 * be de-allocated.
8719 	 */
8720 	dap = diradd_lookup(pagedep, offset);
8721 	if (dap == NULL) {
8722 		/*
8723 		 * Link the jremref structures into the dirrem so they are
8724 		 * written prior to the pagedep.
8725 		 */
8726 		if (jremref)
8727 			dirrem_journal(dirrem, jremref, dotremref,
8728 			    dotdotremref);
8729 		return (dirrem);
8730 	}
8731 	/*
8732 	 * Must be ATTACHED at this point.
8733 	 */
8734 	if ((dap->da_state & ATTACHED) == 0)
8735 		panic("newdirrem: not ATTACHED");
8736 	if (dap->da_newinum != ip->i_number)
8737 		panic("newdirrem: inum %d should be %d",
8738 		    ip->i_number, dap->da_newinum);
8739 	/*
8740 	 * If we are deleting a changed name that never made it to disk,
8741 	 * then return the dirrem describing the previous inode (which
8742 	 * represents the inode currently referenced from this entry on disk).
8743 	 */
8744 	if ((dap->da_state & DIRCHG) != 0) {
8745 		*prevdirremp = dap->da_previous;
8746 		dap->da_state &= ~DIRCHG;
8747 		dap->da_pagedep = pagedep;
8748 	}
8749 	/*
8750 	 * We are deleting an entry that never made it to disk.
8751 	 * Mark it COMPLETE so we can delete its inode immediately.
8752 	 */
8753 	dirrem->dm_state |= COMPLETE;
8754 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
8755 #ifdef SUJ_DEBUG
8756 	if (isrmdir == 0) {
8757 		struct worklist *wk;
8758 
8759 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
8760 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
8761 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
8762 	}
8763 #endif
8764 
8765 	return (dirrem);
8766 }
8767 
8768 /*
8769  * Directory entry change dependencies.
8770  *
8771  * Changing an existing directory entry requires that an add operation
8772  * be completed first followed by a deletion. The semantics for the addition
8773  * are identical to the description of adding a new entry above except
8774  * that the rollback is to the old inode number rather than zero. Once
8775  * the addition dependency is completed, the removal is done as described
8776  * in the removal routine above.
8777  */
8778 
8779 /*
8780  * This routine should be called immediately after changing
8781  * a directory entry.  The inode's link count should not be
8782  * decremented by the calling procedure -- the soft updates
8783  * code will perform this task when it is safe.
8784  */
8785 void
8786 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
8787 	struct buf *bp;		/* buffer containing directory block */
8788 	struct inode *dp;	/* inode for the directory being modified */
8789 	struct inode *ip;	/* inode for directory entry being removed */
8790 	ino_t newinum;		/* new inode number for changed entry */
8791 	int isrmdir;		/* indicates if doing RMDIR */
8792 {
8793 	int offset;
8794 	struct diradd *dap = NULL;
8795 	struct dirrem *dirrem, *prevdirrem;
8796 	struct pagedep *pagedep;
8797 	struct inodedep *inodedep;
8798 	struct jaddref *jaddref;
8799 	struct mount *mp;
8800 
8801 	offset = blkoff(dp->i_fs, dp->i_offset);
8802 	mp = UFSTOVFS(dp->i_ump);
8803 
8804 	/*
8805 	 * Whiteouts do not need diradd dependencies.
8806 	 */
8807 	if (newinum != WINO) {
8808 		dap = malloc(sizeof(struct diradd),
8809 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
8810 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
8811 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
8812 		dap->da_offset = offset;
8813 		dap->da_newinum = newinum;
8814 		LIST_INIT(&dap->da_jwork);
8815 	}
8816 
8817 	/*
8818 	 * Allocate a new dirrem and ACQUIRE_LOCK.
8819 	 */
8820 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8821 	pagedep = dirrem->dm_pagedep;
8822 	/*
8823 	 * The possible values for isrmdir:
8824 	 *	0 - non-directory file rename
8825 	 *	1 - directory rename within same directory
8826 	 *   inum - directory rename to new directory of given inode number
8827 	 * When renaming to a new directory, we are both deleting and
8828 	 * creating a new directory entry, so the link count on the new
8829 	 * directory should not change. Thus we do not need the followup
8830 	 * dirrem which is usually done in handle_workitem_remove. We set
8831 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
8832 	 * followup dirrem.
8833 	 */
8834 	if (isrmdir > 1)
8835 		dirrem->dm_state |= DIRCHG;
8836 
8837 	/*
8838 	 * Whiteouts have no additional dependencies,
8839 	 * so just put the dirrem on the correct list.
8840 	 */
8841 	if (newinum == WINO) {
8842 		if ((dirrem->dm_state & COMPLETE) == 0) {
8843 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
8844 			    dm_next);
8845 		} else {
8846 			dirrem->dm_dirinum = pagedep->pd_ino;
8847 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8848 				add_to_worklist(&dirrem->dm_list, 0);
8849 		}
8850 		FREE_LOCK(&lk);
8851 		return;
8852 	}
8853 	/*
8854 	 * Add the dirrem to the inodedep's pending remove list for quick
8855 	 * discovery later.  A valid nlinkdelta ensures that this lookup
8856 	 * will not fail.
8857 	 */
8858 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
8859 		panic("softdep_setup_directory_change: Lost inodedep.");
8860 	dirrem->dm_state |= ONDEPLIST;
8861 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8862 
8863 	/*
8864 	 * If the COMPLETE flag is clear, then there were no active
8865 	 * entries and we want to roll back to the previous inode until
8866 	 * the new inode is committed to disk. If the COMPLETE flag is
8867 	 * set, then we have deleted an entry that never made it to disk.
8868 	 * If the entry we deleted resulted from a name change, then the old
8869 	 * inode reference still resides on disk. Any rollback that we do
8870 	 * needs to be to that old inode (returned to us in prevdirrem). If
8871 	 * the entry we deleted resulted from a create, then there is
8872 	 * no entry on the disk, so we want to roll back to zero rather
8873 	 * than the uncommitted inode. In either of the COMPLETE cases we
8874 	 * want to immediately free the unwritten and unreferenced inode.
8875 	 */
8876 	if ((dirrem->dm_state & COMPLETE) == 0) {
8877 		dap->da_previous = dirrem;
8878 	} else {
8879 		if (prevdirrem != NULL) {
8880 			dap->da_previous = prevdirrem;
8881 		} else {
8882 			dap->da_state &= ~DIRCHG;
8883 			dap->da_pagedep = pagedep;
8884 		}
8885 		dirrem->dm_dirinum = pagedep->pd_ino;
8886 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8887 			add_to_worklist(&dirrem->dm_list, 0);
8888 	}
8889 	/*
8890 	 * Lookup the jaddref for this journal entry.  We must finish
8891 	 * initializing it and make the diradd write dependent on it.
8892 	 * If we're not journaling, put it on the id_bufwait list if the
8893 	 * inode is not yet written. If it is written, do the post-inode
8894 	 * write processing to put it on the id_pendinghd list.
8895 	 */
8896 	inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep);
8897 	if (MOUNTEDSUJ(mp)) {
8898 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8899 		    inoreflst);
8900 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8901 		    ("softdep_setup_directory_change: bad jaddref %p",
8902 		    jaddref));
8903 		jaddref->ja_diroff = dp->i_offset;
8904 		jaddref->ja_diradd = dap;
8905 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
8906 		    dap, da_pdlist);
8907 		add_to_journal(&jaddref->ja_list);
8908 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8909 		dap->da_state |= COMPLETE;
8910 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8911 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
8912 	} else {
8913 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
8914 		    dap, da_pdlist);
8915 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8916 	}
8917 	/*
8918 	 * If we're making a new name for a directory that has not been
8919 	 * committed when need to move the dot and dotdot references to
8920 	 * this new name.
8921 	 */
8922 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
8923 		merge_diradd(inodedep, dap);
8924 	FREE_LOCK(&lk);
8925 }
8926 
8927 /*
8928  * Called whenever the link count on an inode is changed.
8929  * It creates an inode dependency so that the new reference(s)
8930  * to the inode cannot be committed to disk until the updated
8931  * inode has been written.
8932  */
8933 void
8934 softdep_change_linkcnt(ip)
8935 	struct inode *ip;	/* the inode with the increased link count */
8936 {
8937 	struct inodedep *inodedep;
8938 	int dflags;
8939 
8940 	ACQUIRE_LOCK(&lk);
8941 	dflags = DEPALLOC;
8942 	if (IS_SNAPSHOT(ip))
8943 		dflags |= NODELAY;
8944 	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags, &inodedep);
8945 	if (ip->i_nlink < ip->i_effnlink)
8946 		panic("softdep_change_linkcnt: bad delta");
8947 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
8948 	FREE_LOCK(&lk);
8949 }
8950 
8951 /*
8952  * Attach a sbdep dependency to the superblock buf so that we can keep
8953  * track of the head of the linked list of referenced but unlinked inodes.
8954  */
8955 void
8956 softdep_setup_sbupdate(ump, fs, bp)
8957 	struct ufsmount *ump;
8958 	struct fs *fs;
8959 	struct buf *bp;
8960 {
8961 	struct sbdep *sbdep;
8962 	struct worklist *wk;
8963 
8964 	if (MOUNTEDSUJ(UFSTOVFS(ump)) == 0)
8965 		return;
8966 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
8967 		if (wk->wk_type == D_SBDEP)
8968 			break;
8969 	if (wk != NULL)
8970 		return;
8971 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
8972 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
8973 	sbdep->sb_fs = fs;
8974 	sbdep->sb_ump = ump;
8975 	ACQUIRE_LOCK(&lk);
8976 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
8977 	FREE_LOCK(&lk);
8978 }
8979 
8980 /*
8981  * Return the first unlinked inodedep which is ready to be the head of the
8982  * list.  The inodedep and all those after it must have valid next pointers.
8983  */
8984 static struct inodedep *
8985 first_unlinked_inodedep(ump)
8986 	struct ufsmount *ump;
8987 {
8988 	struct inodedep *inodedep;
8989 	struct inodedep *idp;
8990 
8991 	mtx_assert(&lk, MA_OWNED);
8992 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
8993 	    inodedep; inodedep = idp) {
8994 		if ((inodedep->id_state & UNLINKNEXT) == 0)
8995 			return (NULL);
8996 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
8997 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
8998 			break;
8999 		if ((inodedep->id_state & UNLINKPREV) == 0)
9000 			break;
9001 	}
9002 	return (inodedep);
9003 }
9004 
9005 /*
9006  * Set the sujfree unlinked head pointer prior to writing a superblock.
9007  */
9008 static void
9009 initiate_write_sbdep(sbdep)
9010 	struct sbdep *sbdep;
9011 {
9012 	struct inodedep *inodedep;
9013 	struct fs *bpfs;
9014 	struct fs *fs;
9015 
9016 	bpfs = sbdep->sb_fs;
9017 	fs = sbdep->sb_ump->um_fs;
9018 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9019 	if (inodedep) {
9020 		fs->fs_sujfree = inodedep->id_ino;
9021 		inodedep->id_state |= UNLINKPREV;
9022 	} else
9023 		fs->fs_sujfree = 0;
9024 	bpfs->fs_sujfree = fs->fs_sujfree;
9025 }
9026 
9027 /*
9028  * After a superblock is written determine whether it must be written again
9029  * due to a changing unlinked list head.
9030  */
9031 static int
9032 handle_written_sbdep(sbdep, bp)
9033 	struct sbdep *sbdep;
9034 	struct buf *bp;
9035 {
9036 	struct inodedep *inodedep;
9037 	struct mount *mp;
9038 	struct fs *fs;
9039 
9040 	mtx_assert(&lk, MA_OWNED);
9041 	fs = sbdep->sb_fs;
9042 	mp = UFSTOVFS(sbdep->sb_ump);
9043 	/*
9044 	 * If the superblock doesn't match the in-memory list start over.
9045 	 */
9046 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9047 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9048 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9049 		bdirty(bp);
9050 		return (1);
9051 	}
9052 	WORKITEM_FREE(sbdep, D_SBDEP);
9053 	if (fs->fs_sujfree == 0)
9054 		return (0);
9055 	/*
9056 	 * Now that we have a record of this inode in stable store allow it
9057 	 * to be written to free up pending work.  Inodes may see a lot of
9058 	 * write activity after they are unlinked which we must not hold up.
9059 	 */
9060 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9061 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9062 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9063 			    inodedep, inodedep->id_state);
9064 		if (inodedep->id_state & UNLINKONLIST)
9065 			break;
9066 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9067 	}
9068 
9069 	return (0);
9070 }
9071 
9072 /*
9073  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9074  */
9075 static void
9076 unlinked_inodedep(mp, inodedep)
9077 	struct mount *mp;
9078 	struct inodedep *inodedep;
9079 {
9080 	struct ufsmount *ump;
9081 
9082 	mtx_assert(&lk, MA_OWNED);
9083 	if (MOUNTEDSUJ(mp) == 0)
9084 		return;
9085 	ump = VFSTOUFS(mp);
9086 	ump->um_fs->fs_fmod = 1;
9087 	if (inodedep->id_state & UNLINKED)
9088 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9089 	inodedep->id_state |= UNLINKED;
9090 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9091 }
9092 
9093 /*
9094  * Remove an inodedep from the unlinked inodedep list.  This may require
9095  * disk writes if the inode has made it that far.
9096  */
9097 static void
9098 clear_unlinked_inodedep(inodedep)
9099 	struct inodedep *inodedep;
9100 {
9101 	struct ufsmount *ump;
9102 	struct inodedep *idp;
9103 	struct inodedep *idn;
9104 	struct fs *fs;
9105 	struct buf *bp;
9106 	ino_t ino;
9107 	ino_t nino;
9108 	ino_t pino;
9109 	int error;
9110 
9111 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9112 	fs = ump->um_fs;
9113 	ino = inodedep->id_ino;
9114 	error = 0;
9115 	for (;;) {
9116 		mtx_assert(&lk, MA_OWNED);
9117 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9118 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9119 		    inodedep));
9120 		/*
9121 		 * If nothing has yet been written simply remove us from
9122 		 * the in memory list and return.  This is the most common
9123 		 * case where handle_workitem_remove() loses the final
9124 		 * reference.
9125 		 */
9126 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9127 			break;
9128 		/*
9129 		 * If we have a NEXT pointer and no PREV pointer we can simply
9130 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9131 		 * careful not to clear PREV if the superblock points at
9132 		 * next as well.
9133 		 */
9134 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9135 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9136 			if (idn && fs->fs_sujfree != idn->id_ino)
9137 				idn->id_state &= ~UNLINKPREV;
9138 			break;
9139 		}
9140 		/*
9141 		 * Here we have an inodedep which is actually linked into
9142 		 * the list.  We must remove it by forcing a write to the
9143 		 * link before us, whether it be the superblock or an inode.
9144 		 * Unfortunately the list may change while we're waiting
9145 		 * on the buf lock for either resource so we must loop until
9146 		 * we lock the right one.  If both the superblock and an
9147 		 * inode point to this inode we must clear the inode first
9148 		 * followed by the superblock.
9149 		 */
9150 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9151 		pino = 0;
9152 		if (idp && (idp->id_state & UNLINKNEXT))
9153 			pino = idp->id_ino;
9154 		FREE_LOCK(&lk);
9155 		if (pino == 0)
9156 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9157 			    (int)fs->fs_sbsize, 0, 0, 0);
9158 		else
9159 			error = bread(ump->um_devvp,
9160 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9161 			    (int)fs->fs_bsize, NOCRED, &bp);
9162 		ACQUIRE_LOCK(&lk);
9163 		if (error)
9164 			break;
9165 		/* If the list has changed restart the loop. */
9166 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9167 		nino = 0;
9168 		if (idp && (idp->id_state & UNLINKNEXT))
9169 			nino = idp->id_ino;
9170 		if (nino != pino ||
9171 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9172 			FREE_LOCK(&lk);
9173 			brelse(bp);
9174 			ACQUIRE_LOCK(&lk);
9175 			continue;
9176 		}
9177 		nino = 0;
9178 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9179 		if (idn)
9180 			nino = idn->id_ino;
9181 		/*
9182 		 * Remove us from the in memory list.  After this we cannot
9183 		 * access the inodedep.
9184 		 */
9185 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9186 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9187 		    inodedep));
9188 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9189 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9190 		FREE_LOCK(&lk);
9191 		/*
9192 		 * The predecessor's next pointer is manually updated here
9193 		 * so that the NEXT flag is never cleared for an element
9194 		 * that is in the list.
9195 		 */
9196 		if (pino == 0) {
9197 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9198 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9199 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9200 			    bp);
9201 		} else if (fs->fs_magic == FS_UFS1_MAGIC)
9202 			((struct ufs1_dinode *)bp->b_data +
9203 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9204 		else
9205 			((struct ufs2_dinode *)bp->b_data +
9206 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9207 		/*
9208 		 * If the bwrite fails we have no recourse to recover.  The
9209 		 * filesystem is corrupted already.
9210 		 */
9211 		bwrite(bp);
9212 		ACQUIRE_LOCK(&lk);
9213 		/*
9214 		 * If the superblock pointer still needs to be cleared force
9215 		 * a write here.
9216 		 */
9217 		if (fs->fs_sujfree == ino) {
9218 			FREE_LOCK(&lk);
9219 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9220 			    (int)fs->fs_sbsize, 0, 0, 0);
9221 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9222 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9223 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9224 			    bp);
9225 			bwrite(bp);
9226 			ACQUIRE_LOCK(&lk);
9227 		}
9228 
9229 		if (fs->fs_sujfree != ino)
9230 			return;
9231 		panic("clear_unlinked_inodedep: Failed to clear free head");
9232 	}
9233 	if (inodedep->id_ino == fs->fs_sujfree)
9234 		panic("clear_unlinked_inodedep: Freeing head of free list");
9235 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9236 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9237 	return;
9238 }
9239 
9240 /*
9241  * This workitem decrements the inode's link count.
9242  * If the link count reaches zero, the file is removed.
9243  */
9244 static int
9245 handle_workitem_remove(dirrem, flags)
9246 	struct dirrem *dirrem;
9247 	int flags;
9248 {
9249 	struct inodedep *inodedep;
9250 	struct workhead dotdotwk;
9251 	struct worklist *wk;
9252 	struct ufsmount *ump;
9253 	struct mount *mp;
9254 	struct vnode *vp;
9255 	struct inode *ip;
9256 	ino_t oldinum;
9257 
9258 	if (dirrem->dm_state & ONWORKLIST)
9259 		panic("handle_workitem_remove: dirrem %p still on worklist",
9260 		    dirrem);
9261 	oldinum = dirrem->dm_oldinum;
9262 	mp = dirrem->dm_list.wk_mp;
9263 	ump = VFSTOUFS(mp);
9264 	flags |= LK_EXCLUSIVE;
9265 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9266 		return (EBUSY);
9267 	ip = VTOI(vp);
9268 	ACQUIRE_LOCK(&lk);
9269 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9270 		panic("handle_workitem_remove: lost inodedep");
9271 	if (dirrem->dm_state & ONDEPLIST)
9272 		LIST_REMOVE(dirrem, dm_inonext);
9273 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9274 	    ("handle_workitem_remove:  Journal entries not written."));
9275 
9276 	/*
9277 	 * Move all dependencies waiting on the remove to complete
9278 	 * from the dirrem to the inode inowait list to be completed
9279 	 * after the inode has been updated and written to disk.  Any
9280 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9281 	 * is removed.
9282 	 */
9283 	LIST_INIT(&dotdotwk);
9284 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9285 		WORKLIST_REMOVE(wk);
9286 		if (wk->wk_state & MKDIR_PARENT) {
9287 			wk->wk_state &= ~MKDIR_PARENT;
9288 			WORKLIST_INSERT(&dotdotwk, wk);
9289 			continue;
9290 		}
9291 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9292 	}
9293 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9294 	/*
9295 	 * Normal file deletion.
9296 	 */
9297 	if ((dirrem->dm_state & RMDIR) == 0) {
9298 		ip->i_nlink--;
9299 		DIP_SET(ip, i_nlink, ip->i_nlink);
9300 		ip->i_flag |= IN_CHANGE;
9301 		if (ip->i_nlink < ip->i_effnlink)
9302 			panic("handle_workitem_remove: bad file delta");
9303 		if (ip->i_nlink == 0)
9304 			unlinked_inodedep(mp, inodedep);
9305 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9306 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9307 		    ("handle_workitem_remove: worklist not empty. %s",
9308 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9309 		WORKITEM_FREE(dirrem, D_DIRREM);
9310 		FREE_LOCK(&lk);
9311 		goto out;
9312 	}
9313 	/*
9314 	 * Directory deletion. Decrement reference count for both the
9315 	 * just deleted parent directory entry and the reference for ".".
9316 	 * Arrange to have the reference count on the parent decremented
9317 	 * to account for the loss of "..".
9318 	 */
9319 	ip->i_nlink -= 2;
9320 	DIP_SET(ip, i_nlink, ip->i_nlink);
9321 	ip->i_flag |= IN_CHANGE;
9322 	if (ip->i_nlink < ip->i_effnlink)
9323 		panic("handle_workitem_remove: bad dir delta");
9324 	if (ip->i_nlink == 0)
9325 		unlinked_inodedep(mp, inodedep);
9326 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9327 	/*
9328 	 * Rename a directory to a new parent. Since, we are both deleting
9329 	 * and creating a new directory entry, the link count on the new
9330 	 * directory should not change. Thus we skip the followup dirrem.
9331 	 */
9332 	if (dirrem->dm_state & DIRCHG) {
9333 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9334 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9335 		WORKITEM_FREE(dirrem, D_DIRREM);
9336 		FREE_LOCK(&lk);
9337 		goto out;
9338 	}
9339 	dirrem->dm_state = ONDEPLIST;
9340 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9341 	/*
9342 	 * Place the dirrem on the parent's diremhd list.
9343 	 */
9344 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9345 		panic("handle_workitem_remove: lost dir inodedep");
9346 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9347 	/*
9348 	 * If the allocated inode has never been written to disk, then
9349 	 * the on-disk inode is zero'ed and we can remove the file
9350 	 * immediately.  When journaling if the inode has been marked
9351 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9352 	 */
9353 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9354 	if (inodedep == NULL ||
9355 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9356 	    check_inode_unwritten(inodedep)) {
9357 		FREE_LOCK(&lk);
9358 		vput(vp);
9359 		return handle_workitem_remove(dirrem, flags);
9360 	}
9361 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9362 	FREE_LOCK(&lk);
9363 	ip->i_flag |= IN_CHANGE;
9364 out:
9365 	ffs_update(vp, 0);
9366 	vput(vp);
9367 	return (0);
9368 }
9369 
9370 /*
9371  * Inode de-allocation dependencies.
9372  *
9373  * When an inode's link count is reduced to zero, it can be de-allocated. We
9374  * found it convenient to postpone de-allocation until after the inode is
9375  * written to disk with its new link count (zero).  At this point, all of the
9376  * on-disk inode's block pointers are nullified and, with careful dependency
9377  * list ordering, all dependencies related to the inode will be satisfied and
9378  * the corresponding dependency structures de-allocated.  So, if/when the
9379  * inode is reused, there will be no mixing of old dependencies with new
9380  * ones.  This artificial dependency is set up by the block de-allocation
9381  * procedure above (softdep_setup_freeblocks) and completed by the
9382  * following procedure.
9383  */
9384 static void
9385 handle_workitem_freefile(freefile)
9386 	struct freefile *freefile;
9387 {
9388 	struct workhead wkhd;
9389 	struct fs *fs;
9390 	struct inodedep *idp;
9391 	struct ufsmount *ump;
9392 	int error;
9393 
9394 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9395 	fs = ump->um_fs;
9396 #ifdef DEBUG
9397 	ACQUIRE_LOCK(&lk);
9398 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9399 	FREE_LOCK(&lk);
9400 	if (error)
9401 		panic("handle_workitem_freefile: inodedep %p survived", idp);
9402 #endif
9403 	UFS_LOCK(ump);
9404 	fs->fs_pendinginodes -= 1;
9405 	UFS_UNLOCK(ump);
9406 	LIST_INIT(&wkhd);
9407 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9408 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9409 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9410 		softdep_error("handle_workitem_freefile", error);
9411 	ACQUIRE_LOCK(&lk);
9412 	WORKITEM_FREE(freefile, D_FREEFILE);
9413 	FREE_LOCK(&lk);
9414 }
9415 
9416 
9417 /*
9418  * Helper function which unlinks marker element from work list and returns
9419  * the next element on the list.
9420  */
9421 static __inline struct worklist *
9422 markernext(struct worklist *marker)
9423 {
9424 	struct worklist *next;
9425 
9426 	next = LIST_NEXT(marker, wk_list);
9427 	LIST_REMOVE(marker, wk_list);
9428 	return next;
9429 }
9430 
9431 /*
9432  * Disk writes.
9433  *
9434  * The dependency structures constructed above are most actively used when file
9435  * system blocks are written to disk.  No constraints are placed on when a
9436  * block can be written, but unsatisfied update dependencies are made safe by
9437  * modifying (or replacing) the source memory for the duration of the disk
9438  * write.  When the disk write completes, the memory block is again brought
9439  * up-to-date.
9440  *
9441  * In-core inode structure reclamation.
9442  *
9443  * Because there are a finite number of "in-core" inode structures, they are
9444  * reused regularly.  By transferring all inode-related dependencies to the
9445  * in-memory inode block and indexing them separately (via "inodedep"s), we
9446  * can allow "in-core" inode structures to be reused at any time and avoid
9447  * any increase in contention.
9448  *
9449  * Called just before entering the device driver to initiate a new disk I/O.
9450  * The buffer must be locked, thus, no I/O completion operations can occur
9451  * while we are manipulating its associated dependencies.
9452  */
9453 static void
9454 softdep_disk_io_initiation(bp)
9455 	struct buf *bp;		/* structure describing disk write to occur */
9456 {
9457 	struct worklist *wk;
9458 	struct worklist marker;
9459 	struct inodedep *inodedep;
9460 	struct freeblks *freeblks;
9461 	struct jblkdep *jblkdep;
9462 	struct newblk *newblk;
9463 
9464 	/*
9465 	 * We only care about write operations. There should never
9466 	 * be dependencies for reads.
9467 	 */
9468 	if (bp->b_iocmd != BIO_WRITE)
9469 		panic("softdep_disk_io_initiation: not write");
9470 
9471 	if (bp->b_vflags & BV_BKGRDINPROG)
9472 		panic("softdep_disk_io_initiation: Writing buffer with "
9473 		    "background write in progress: %p", bp);
9474 
9475 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
9476 	PHOLD(curproc);			/* Don't swap out kernel stack */
9477 
9478 	ACQUIRE_LOCK(&lk);
9479 	/*
9480 	 * Do any necessary pre-I/O processing.
9481 	 */
9482 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9483 	     wk = markernext(&marker)) {
9484 		LIST_INSERT_AFTER(wk, &marker, wk_list);
9485 		switch (wk->wk_type) {
9486 
9487 		case D_PAGEDEP:
9488 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
9489 			continue;
9490 
9491 		case D_INODEDEP:
9492 			inodedep = WK_INODEDEP(wk);
9493 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
9494 				initiate_write_inodeblock_ufs1(inodedep, bp);
9495 			else
9496 				initiate_write_inodeblock_ufs2(inodedep, bp);
9497 			continue;
9498 
9499 		case D_INDIRDEP:
9500 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
9501 			continue;
9502 
9503 		case D_BMSAFEMAP:
9504 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
9505 			continue;
9506 
9507 		case D_JSEG:
9508 			WK_JSEG(wk)->js_buf = NULL;
9509 			continue;
9510 
9511 		case D_FREEBLKS:
9512 			freeblks = WK_FREEBLKS(wk);
9513 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
9514 			/*
9515 			 * We have to wait for the freeblks to be journaled
9516 			 * before we can write an inodeblock with updated
9517 			 * pointers.  Be careful to arrange the marker so
9518 			 * we revisit the freeblks if it's not removed by
9519 			 * the first jwait().
9520 			 */
9521 			if (jblkdep != NULL) {
9522 				LIST_REMOVE(&marker, wk_list);
9523 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
9524 				jwait(&jblkdep->jb_list, MNT_WAIT);
9525 			}
9526 			continue;
9527 		case D_ALLOCDIRECT:
9528 		case D_ALLOCINDIR:
9529 			/*
9530 			 * We have to wait for the jnewblk to be journaled
9531 			 * before we can write to a block if the contents
9532 			 * may be confused with an earlier file's indirect
9533 			 * at recovery time.  Handle the marker as described
9534 			 * above.
9535 			 */
9536 			newblk = WK_NEWBLK(wk);
9537 			if (newblk->nb_jnewblk != NULL &&
9538 			    indirblk_lookup(newblk->nb_list.wk_mp,
9539 			    newblk->nb_newblkno)) {
9540 				LIST_REMOVE(&marker, wk_list);
9541 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
9542 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
9543 			}
9544 			continue;
9545 
9546 		case D_SBDEP:
9547 			initiate_write_sbdep(WK_SBDEP(wk));
9548 			continue;
9549 
9550 		case D_MKDIR:
9551 		case D_FREEWORK:
9552 		case D_FREEDEP:
9553 		case D_JSEGDEP:
9554 			continue;
9555 
9556 		default:
9557 			panic("handle_disk_io_initiation: Unexpected type %s",
9558 			    TYPENAME(wk->wk_type));
9559 			/* NOTREACHED */
9560 		}
9561 	}
9562 	FREE_LOCK(&lk);
9563 	PRELE(curproc);			/* Allow swapout of kernel stack */
9564 }
9565 
9566 /*
9567  * Called from within the procedure above to deal with unsatisfied
9568  * allocation dependencies in a directory. The buffer must be locked,
9569  * thus, no I/O completion operations can occur while we are
9570  * manipulating its associated dependencies.
9571  */
9572 static void
9573 initiate_write_filepage(pagedep, bp)
9574 	struct pagedep *pagedep;
9575 	struct buf *bp;
9576 {
9577 	struct jremref *jremref;
9578 	struct jmvref *jmvref;
9579 	struct dirrem *dirrem;
9580 	struct diradd *dap;
9581 	struct direct *ep;
9582 	int i;
9583 
9584 	if (pagedep->pd_state & IOSTARTED) {
9585 		/*
9586 		 * This can only happen if there is a driver that does not
9587 		 * understand chaining. Here biodone will reissue the call
9588 		 * to strategy for the incomplete buffers.
9589 		 */
9590 		printf("initiate_write_filepage: already started\n");
9591 		return;
9592 	}
9593 	pagedep->pd_state |= IOSTARTED;
9594 	/*
9595 	 * Wait for all journal remove dependencies to hit the disk.
9596 	 * We can not allow any potentially conflicting directory adds
9597 	 * to be visible before removes and rollback is too difficult.
9598 	 * lk may be dropped and re-acquired, however we hold the buf
9599 	 * locked so the dependency can not go away.
9600 	 */
9601 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
9602 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
9603 			jwait(&jremref->jr_list, MNT_WAIT);
9604 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
9605 		jwait(&jmvref->jm_list, MNT_WAIT);
9606 	for (i = 0; i < DAHASHSZ; i++) {
9607 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
9608 			ep = (struct direct *)
9609 			    ((char *)bp->b_data + dap->da_offset);
9610 			if (ep->d_ino != dap->da_newinum)
9611 				panic("%s: dir inum %d != new %d",
9612 				    "initiate_write_filepage",
9613 				    ep->d_ino, dap->da_newinum);
9614 			if (dap->da_state & DIRCHG)
9615 				ep->d_ino = dap->da_previous->dm_oldinum;
9616 			else
9617 				ep->d_ino = 0;
9618 			dap->da_state &= ~ATTACHED;
9619 			dap->da_state |= UNDONE;
9620 		}
9621 	}
9622 }
9623 
9624 /*
9625  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
9626  * Note that any bug fixes made to this routine must be done in the
9627  * version found below.
9628  *
9629  * Called from within the procedure above to deal with unsatisfied
9630  * allocation dependencies in an inodeblock. The buffer must be
9631  * locked, thus, no I/O completion operations can occur while we
9632  * are manipulating its associated dependencies.
9633  */
9634 static void
9635 initiate_write_inodeblock_ufs1(inodedep, bp)
9636 	struct inodedep *inodedep;
9637 	struct buf *bp;			/* The inode block */
9638 {
9639 	struct allocdirect *adp, *lastadp;
9640 	struct ufs1_dinode *dp;
9641 	struct ufs1_dinode *sip;
9642 	struct inoref *inoref;
9643 	struct fs *fs;
9644 	ufs_lbn_t i;
9645 #ifdef INVARIANTS
9646 	ufs_lbn_t prevlbn = 0;
9647 #endif
9648 	int deplist;
9649 
9650 	if (inodedep->id_state & IOSTARTED)
9651 		panic("initiate_write_inodeblock_ufs1: already started");
9652 	inodedep->id_state |= IOSTARTED;
9653 	fs = inodedep->id_fs;
9654 	dp = (struct ufs1_dinode *)bp->b_data +
9655 	    ino_to_fsbo(fs, inodedep->id_ino);
9656 
9657 	/*
9658 	 * If we're on the unlinked list but have not yet written our
9659 	 * next pointer initialize it here.
9660 	 */
9661 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
9662 		struct inodedep *inon;
9663 
9664 		inon = TAILQ_NEXT(inodedep, id_unlinked);
9665 		dp->di_freelink = inon ? inon->id_ino : 0;
9666 	}
9667 	/*
9668 	 * If the bitmap is not yet written, then the allocated
9669 	 * inode cannot be written to disk.
9670 	 */
9671 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
9672 		if (inodedep->id_savedino1 != NULL)
9673 			panic("initiate_write_inodeblock_ufs1: I/O underway");
9674 		FREE_LOCK(&lk);
9675 		sip = malloc(sizeof(struct ufs1_dinode),
9676 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
9677 		ACQUIRE_LOCK(&lk);
9678 		inodedep->id_savedino1 = sip;
9679 		*inodedep->id_savedino1 = *dp;
9680 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
9681 		dp->di_gen = inodedep->id_savedino1->di_gen;
9682 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
9683 		return;
9684 	}
9685 	/*
9686 	 * If no dependencies, then there is nothing to roll back.
9687 	 */
9688 	inodedep->id_savedsize = dp->di_size;
9689 	inodedep->id_savedextsize = 0;
9690 	inodedep->id_savednlink = dp->di_nlink;
9691 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
9692 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
9693 		return;
9694 	/*
9695 	 * Revert the link count to that of the first unwritten journal entry.
9696 	 */
9697 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
9698 	if (inoref)
9699 		dp->di_nlink = inoref->if_nlink;
9700 	/*
9701 	 * Set the dependencies to busy.
9702 	 */
9703 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9704 	     adp = TAILQ_NEXT(adp, ad_next)) {
9705 #ifdef INVARIANTS
9706 		if (deplist != 0 && prevlbn >= adp->ad_offset)
9707 			panic("softdep_write_inodeblock: lbn order");
9708 		prevlbn = adp->ad_offset;
9709 		if (adp->ad_offset < NDADDR &&
9710 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
9711 			panic("%s: direct pointer #%jd mismatch %d != %jd",
9712 			    "softdep_write_inodeblock",
9713 			    (intmax_t)adp->ad_offset,
9714 			    dp->di_db[adp->ad_offset],
9715 			    (intmax_t)adp->ad_newblkno);
9716 		if (adp->ad_offset >= NDADDR &&
9717 		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
9718 			panic("%s: indirect pointer #%jd mismatch %d != %jd",
9719 			    "softdep_write_inodeblock",
9720 			    (intmax_t)adp->ad_offset - NDADDR,
9721 			    dp->di_ib[adp->ad_offset - NDADDR],
9722 			    (intmax_t)adp->ad_newblkno);
9723 		deplist |= 1 << adp->ad_offset;
9724 		if ((adp->ad_state & ATTACHED) == 0)
9725 			panic("softdep_write_inodeblock: Unknown state 0x%x",
9726 			    adp->ad_state);
9727 #endif /* INVARIANTS */
9728 		adp->ad_state &= ~ATTACHED;
9729 		adp->ad_state |= UNDONE;
9730 	}
9731 	/*
9732 	 * The on-disk inode cannot claim to be any larger than the last
9733 	 * fragment that has been written. Otherwise, the on-disk inode
9734 	 * might have fragments that were not the last block in the file
9735 	 * which would corrupt the filesystem.
9736 	 */
9737 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9738 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
9739 		if (adp->ad_offset >= NDADDR)
9740 			break;
9741 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
9742 		/* keep going until hitting a rollback to a frag */
9743 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
9744 			continue;
9745 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
9746 		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
9747 #ifdef INVARIANTS
9748 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
9749 				panic("softdep_write_inodeblock: lost dep1");
9750 #endif /* INVARIANTS */
9751 			dp->di_db[i] = 0;
9752 		}
9753 		for (i = 0; i < NIADDR; i++) {
9754 #ifdef INVARIANTS
9755 			if (dp->di_ib[i] != 0 &&
9756 			    (deplist & ((1 << NDADDR) << i)) == 0)
9757 				panic("softdep_write_inodeblock: lost dep2");
9758 #endif /* INVARIANTS */
9759 			dp->di_ib[i] = 0;
9760 		}
9761 		return;
9762 	}
9763 	/*
9764 	 * If we have zero'ed out the last allocated block of the file,
9765 	 * roll back the size to the last currently allocated block.
9766 	 * We know that this last allocated block is a full-sized as
9767 	 * we already checked for fragments in the loop above.
9768 	 */
9769 	if (lastadp != NULL &&
9770 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
9771 		for (i = lastadp->ad_offset; i >= 0; i--)
9772 			if (dp->di_db[i] != 0)
9773 				break;
9774 		dp->di_size = (i + 1) * fs->fs_bsize;
9775 	}
9776 	/*
9777 	 * The only dependencies are for indirect blocks.
9778 	 *
9779 	 * The file size for indirect block additions is not guaranteed.
9780 	 * Such a guarantee would be non-trivial to achieve. The conventional
9781 	 * synchronous write implementation also does not make this guarantee.
9782 	 * Fsck should catch and fix discrepancies. Arguably, the file size
9783 	 * can be over-estimated without destroying integrity when the file
9784 	 * moves into the indirect blocks (i.e., is large). If we want to
9785 	 * postpone fsck, we are stuck with this argument.
9786 	 */
9787 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
9788 		dp->di_ib[adp->ad_offset - NDADDR] = 0;
9789 }
9790 
9791 /*
9792  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
9793  * Note that any bug fixes made to this routine must be done in the
9794  * version found above.
9795  *
9796  * Called from within the procedure above to deal with unsatisfied
9797  * allocation dependencies in an inodeblock. The buffer must be
9798  * locked, thus, no I/O completion operations can occur while we
9799  * are manipulating its associated dependencies.
9800  */
9801 static void
9802 initiate_write_inodeblock_ufs2(inodedep, bp)
9803 	struct inodedep *inodedep;
9804 	struct buf *bp;			/* The inode block */
9805 {
9806 	struct allocdirect *adp, *lastadp;
9807 	struct ufs2_dinode *dp;
9808 	struct ufs2_dinode *sip;
9809 	struct inoref *inoref;
9810 	struct fs *fs;
9811 	ufs_lbn_t i;
9812 #ifdef INVARIANTS
9813 	ufs_lbn_t prevlbn = 0;
9814 #endif
9815 	int deplist;
9816 
9817 	if (inodedep->id_state & IOSTARTED)
9818 		panic("initiate_write_inodeblock_ufs2: already started");
9819 	inodedep->id_state |= IOSTARTED;
9820 	fs = inodedep->id_fs;
9821 	dp = (struct ufs2_dinode *)bp->b_data +
9822 	    ino_to_fsbo(fs, inodedep->id_ino);
9823 
9824 	/*
9825 	 * If we're on the unlinked list but have not yet written our
9826 	 * next pointer initialize it here.
9827 	 */
9828 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
9829 		struct inodedep *inon;
9830 
9831 		inon = TAILQ_NEXT(inodedep, id_unlinked);
9832 		dp->di_freelink = inon ? inon->id_ino : 0;
9833 	}
9834 	/*
9835 	 * If the bitmap is not yet written, then the allocated
9836 	 * inode cannot be written to disk.
9837 	 */
9838 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
9839 		if (inodedep->id_savedino2 != NULL)
9840 			panic("initiate_write_inodeblock_ufs2: I/O underway");
9841 		FREE_LOCK(&lk);
9842 		sip = malloc(sizeof(struct ufs2_dinode),
9843 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
9844 		ACQUIRE_LOCK(&lk);
9845 		inodedep->id_savedino2 = sip;
9846 		*inodedep->id_savedino2 = *dp;
9847 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
9848 		dp->di_gen = inodedep->id_savedino2->di_gen;
9849 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
9850 		return;
9851 	}
9852 	/*
9853 	 * If no dependencies, then there is nothing to roll back.
9854 	 */
9855 	inodedep->id_savedsize = dp->di_size;
9856 	inodedep->id_savedextsize = dp->di_extsize;
9857 	inodedep->id_savednlink = dp->di_nlink;
9858 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
9859 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
9860 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
9861 		return;
9862 	/*
9863 	 * Revert the link count to that of the first unwritten journal entry.
9864 	 */
9865 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
9866 	if (inoref)
9867 		dp->di_nlink = inoref->if_nlink;
9868 
9869 	/*
9870 	 * Set the ext data dependencies to busy.
9871 	 */
9872 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
9873 	     adp = TAILQ_NEXT(adp, ad_next)) {
9874 #ifdef INVARIANTS
9875 		if (deplist != 0 && prevlbn >= adp->ad_offset)
9876 			panic("softdep_write_inodeblock: lbn order");
9877 		prevlbn = adp->ad_offset;
9878 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
9879 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
9880 			    "softdep_write_inodeblock",
9881 			    (intmax_t)adp->ad_offset,
9882 			    (intmax_t)dp->di_extb[adp->ad_offset],
9883 			    (intmax_t)adp->ad_newblkno);
9884 		deplist |= 1 << adp->ad_offset;
9885 		if ((adp->ad_state & ATTACHED) == 0)
9886 			panic("softdep_write_inodeblock: Unknown state 0x%x",
9887 			    adp->ad_state);
9888 #endif /* INVARIANTS */
9889 		adp->ad_state &= ~ATTACHED;
9890 		adp->ad_state |= UNDONE;
9891 	}
9892 	/*
9893 	 * The on-disk inode cannot claim to be any larger than the last
9894 	 * fragment that has been written. Otherwise, the on-disk inode
9895 	 * might have fragments that were not the last block in the ext
9896 	 * data which would corrupt the filesystem.
9897 	 */
9898 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
9899 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
9900 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
9901 		/* keep going until hitting a rollback to a frag */
9902 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
9903 			continue;
9904 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
9905 		for (i = adp->ad_offset + 1; i < NXADDR; i++) {
9906 #ifdef INVARIANTS
9907 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
9908 				panic("softdep_write_inodeblock: lost dep1");
9909 #endif /* INVARIANTS */
9910 			dp->di_extb[i] = 0;
9911 		}
9912 		lastadp = NULL;
9913 		break;
9914 	}
9915 	/*
9916 	 * If we have zero'ed out the last allocated block of the ext
9917 	 * data, roll back the size to the last currently allocated block.
9918 	 * We know that this last allocated block is a full-sized as
9919 	 * we already checked for fragments in the loop above.
9920 	 */
9921 	if (lastadp != NULL &&
9922 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
9923 		for (i = lastadp->ad_offset; i >= 0; i--)
9924 			if (dp->di_extb[i] != 0)
9925 				break;
9926 		dp->di_extsize = (i + 1) * fs->fs_bsize;
9927 	}
9928 	/*
9929 	 * Set the file data dependencies to busy.
9930 	 */
9931 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9932 	     adp = TAILQ_NEXT(adp, ad_next)) {
9933 #ifdef INVARIANTS
9934 		if (deplist != 0 && prevlbn >= adp->ad_offset)
9935 			panic("softdep_write_inodeblock: lbn order");
9936 		if ((adp->ad_state & ATTACHED) == 0)
9937 			panic("inodedep %p and adp %p not attached", inodedep, adp);
9938 		prevlbn = adp->ad_offset;
9939 		if (adp->ad_offset < NDADDR &&
9940 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
9941 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
9942 			    "softdep_write_inodeblock",
9943 			    (intmax_t)adp->ad_offset,
9944 			    (intmax_t)dp->di_db[adp->ad_offset],
9945 			    (intmax_t)adp->ad_newblkno);
9946 		if (adp->ad_offset >= NDADDR &&
9947 		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
9948 			panic("%s indirect pointer #%jd mismatch %jd != %jd",
9949 			    "softdep_write_inodeblock:",
9950 			    (intmax_t)adp->ad_offset - NDADDR,
9951 			    (intmax_t)dp->di_ib[adp->ad_offset - NDADDR],
9952 			    (intmax_t)adp->ad_newblkno);
9953 		deplist |= 1 << adp->ad_offset;
9954 		if ((adp->ad_state & ATTACHED) == 0)
9955 			panic("softdep_write_inodeblock: Unknown state 0x%x",
9956 			    adp->ad_state);
9957 #endif /* INVARIANTS */
9958 		adp->ad_state &= ~ATTACHED;
9959 		adp->ad_state |= UNDONE;
9960 	}
9961 	/*
9962 	 * The on-disk inode cannot claim to be any larger than the last
9963 	 * fragment that has been written. Otherwise, the on-disk inode
9964 	 * might have fragments that were not the last block in the file
9965 	 * which would corrupt the filesystem.
9966 	 */
9967 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9968 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
9969 		if (adp->ad_offset >= NDADDR)
9970 			break;
9971 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
9972 		/* keep going until hitting a rollback to a frag */
9973 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
9974 			continue;
9975 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
9976 		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
9977 #ifdef INVARIANTS
9978 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
9979 				panic("softdep_write_inodeblock: lost dep2");
9980 #endif /* INVARIANTS */
9981 			dp->di_db[i] = 0;
9982 		}
9983 		for (i = 0; i < NIADDR; i++) {
9984 #ifdef INVARIANTS
9985 			if (dp->di_ib[i] != 0 &&
9986 			    (deplist & ((1 << NDADDR) << i)) == 0)
9987 				panic("softdep_write_inodeblock: lost dep3");
9988 #endif /* INVARIANTS */
9989 			dp->di_ib[i] = 0;
9990 		}
9991 		return;
9992 	}
9993 	/*
9994 	 * If we have zero'ed out the last allocated block of the file,
9995 	 * roll back the size to the last currently allocated block.
9996 	 * We know that this last allocated block is a full-sized as
9997 	 * we already checked for fragments in the loop above.
9998 	 */
9999 	if (lastadp != NULL &&
10000 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10001 		for (i = lastadp->ad_offset; i >= 0; i--)
10002 			if (dp->di_db[i] != 0)
10003 				break;
10004 		dp->di_size = (i + 1) * fs->fs_bsize;
10005 	}
10006 	/*
10007 	 * The only dependencies are for indirect blocks.
10008 	 *
10009 	 * The file size for indirect block additions is not guaranteed.
10010 	 * Such a guarantee would be non-trivial to achieve. The conventional
10011 	 * synchronous write implementation also does not make this guarantee.
10012 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10013 	 * can be over-estimated without destroying integrity when the file
10014 	 * moves into the indirect blocks (i.e., is large). If we want to
10015 	 * postpone fsck, we are stuck with this argument.
10016 	 */
10017 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10018 		dp->di_ib[adp->ad_offset - NDADDR] = 0;
10019 }
10020 
10021 /*
10022  * Cancel an indirdep as a result of truncation.  Release all of the
10023  * children allocindirs and place their journal work on the appropriate
10024  * list.
10025  */
10026 static void
10027 cancel_indirdep(indirdep, bp, freeblks)
10028 	struct indirdep *indirdep;
10029 	struct buf *bp;
10030 	struct freeblks *freeblks;
10031 {
10032 	struct allocindir *aip;
10033 
10034 	/*
10035 	 * None of the indirect pointers will ever be visible,
10036 	 * so they can simply be tossed. GOINGAWAY ensures
10037 	 * that allocated pointers will be saved in the buffer
10038 	 * cache until they are freed. Note that they will
10039 	 * only be able to be found by their physical address
10040 	 * since the inode mapping the logical address will
10041 	 * be gone. The save buffer used for the safe copy
10042 	 * was allocated in setup_allocindir_phase2 using
10043 	 * the physical address so it could be used for this
10044 	 * purpose. Hence we swap the safe copy with the real
10045 	 * copy, allowing the safe copy to be freed and holding
10046 	 * on to the real copy for later use in indir_trunc.
10047 	 */
10048 	if (indirdep->ir_state & GOINGAWAY)
10049 		panic("cancel_indirdep: already gone");
10050 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10051 		indirdep->ir_state |= DEPCOMPLETE;
10052 		LIST_REMOVE(indirdep, ir_next);
10053 	}
10054 	indirdep->ir_state |= GOINGAWAY;
10055 	VFSTOUFS(indirdep->ir_list.wk_mp)->um_numindirdeps += 1;
10056 	/*
10057 	 * Pass in bp for blocks still have journal writes
10058 	 * pending so we can cancel them on their own.
10059 	 */
10060 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
10061 		cancel_allocindir(aip, bp, freeblks, 0);
10062 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0)
10063 		cancel_allocindir(aip, NULL, freeblks, 0);
10064 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0)
10065 		cancel_allocindir(aip, NULL, freeblks, 0);
10066 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != 0)
10067 		cancel_allocindir(aip, NULL, freeblks, 0);
10068 	/*
10069 	 * If there are pending partial truncations we need to keep the
10070 	 * old block copy around until they complete.  This is because
10071 	 * the current b_data is not a perfect superset of the available
10072 	 * blocks.
10073 	 */
10074 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10075 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10076 	else
10077 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10078 	WORKLIST_REMOVE(&indirdep->ir_list);
10079 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10080 	indirdep->ir_bp = NULL;
10081 	indirdep->ir_freeblks = freeblks;
10082 }
10083 
10084 /*
10085  * Free an indirdep once it no longer has new pointers to track.
10086  */
10087 static void
10088 free_indirdep(indirdep)
10089 	struct indirdep *indirdep;
10090 {
10091 
10092 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10093 	    ("free_indirdep: Indir trunc list not empty."));
10094 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10095 	    ("free_indirdep: Complete head not empty."));
10096 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10097 	    ("free_indirdep: write head not empty."));
10098 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10099 	    ("free_indirdep: done head not empty."));
10100 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10101 	    ("free_indirdep: deplist head not empty."));
10102 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10103 	    ("free_indirdep: %p still on newblk list.", indirdep));
10104 	KASSERT(indirdep->ir_saveddata == NULL,
10105 	    ("free_indirdep: %p still has saved data.", indirdep));
10106 	if (indirdep->ir_state & ONWORKLIST)
10107 		WORKLIST_REMOVE(&indirdep->ir_list);
10108 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10109 }
10110 
10111 /*
10112  * Called before a write to an indirdep.  This routine is responsible for
10113  * rolling back pointers to a safe state which includes only those
10114  * allocindirs which have been completed.
10115  */
10116 static void
10117 initiate_write_indirdep(indirdep, bp)
10118 	struct indirdep *indirdep;
10119 	struct buf *bp;
10120 {
10121 
10122 	indirdep->ir_state |= IOSTARTED;
10123 	if (indirdep->ir_state & GOINGAWAY)
10124 		panic("disk_io_initiation: indirdep gone");
10125 	/*
10126 	 * If there are no remaining dependencies, this will be writing
10127 	 * the real pointers.
10128 	 */
10129 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10130 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10131 		return;
10132 	/*
10133 	 * Replace up-to-date version with safe version.
10134 	 */
10135 	if (indirdep->ir_saveddata == NULL) {
10136 		FREE_LOCK(&lk);
10137 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10138 		    M_SOFTDEP_FLAGS);
10139 		ACQUIRE_LOCK(&lk);
10140 	}
10141 	indirdep->ir_state &= ~ATTACHED;
10142 	indirdep->ir_state |= UNDONE;
10143 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10144 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10145 	    bp->b_bcount);
10146 }
10147 
10148 /*
10149  * Called when an inode has been cleared in a cg bitmap.  This finally
10150  * eliminates any canceled jaddrefs
10151  */
10152 void
10153 softdep_setup_inofree(mp, bp, ino, wkhd)
10154 	struct mount *mp;
10155 	struct buf *bp;
10156 	ino_t ino;
10157 	struct workhead *wkhd;
10158 {
10159 	struct worklist *wk, *wkn;
10160 	struct inodedep *inodedep;
10161 	uint8_t *inosused;
10162 	struct cg *cgp;
10163 	struct fs *fs;
10164 
10165 	ACQUIRE_LOCK(&lk);
10166 	fs = VFSTOUFS(mp)->um_fs;
10167 	cgp = (struct cg *)bp->b_data;
10168 	inosused = cg_inosused(cgp);
10169 	if (isset(inosused, ino % fs->fs_ipg))
10170 		panic("softdep_setup_inofree: inode %d not freed.", ino);
10171 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10172 		panic("softdep_setup_inofree: ino %d has existing inodedep %p",
10173 		    ino, inodedep);
10174 	if (wkhd) {
10175 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10176 			if (wk->wk_type != D_JADDREF)
10177 				continue;
10178 			WORKLIST_REMOVE(wk);
10179 			/*
10180 			 * We can free immediately even if the jaddref
10181 			 * isn't attached in a background write as now
10182 			 * the bitmaps are reconciled.
10183 		 	 */
10184 			wk->wk_state |= COMPLETE | ATTACHED;
10185 			free_jaddref(WK_JADDREF(wk));
10186 		}
10187 		jwork_move(&bp->b_dep, wkhd);
10188 	}
10189 	FREE_LOCK(&lk);
10190 }
10191 
10192 
10193 /*
10194  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10195  * map.  Any dependencies waiting for the write to clear are added to the
10196  * buf's list and any jnewblks that are being canceled are discarded
10197  * immediately.
10198  */
10199 void
10200 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10201 	struct mount *mp;
10202 	struct buf *bp;
10203 	ufs2_daddr_t blkno;
10204 	int frags;
10205 	struct workhead *wkhd;
10206 {
10207 	struct bmsafemap *bmsafemap;
10208 	struct jnewblk *jnewblk;
10209 	struct worklist *wk;
10210 	struct fs *fs;
10211 #ifdef SUJ_DEBUG
10212 	uint8_t *blksfree;
10213 	struct cg *cgp;
10214 	ufs2_daddr_t jstart;
10215 	ufs2_daddr_t jend;
10216 	ufs2_daddr_t end;
10217 	long bno;
10218 	int i;
10219 #endif
10220 
10221 	ACQUIRE_LOCK(&lk);
10222 	/* Lookup the bmsafemap so we track when it is dirty. */
10223 	fs = VFSTOUFS(mp)->um_fs;
10224 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno));
10225 	/*
10226 	 * Detach any jnewblks which have been canceled.  They must linger
10227 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10228 	 * an unjournaled allocation from hitting the disk.
10229 	 */
10230 	if (wkhd) {
10231 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10232 			WORKLIST_REMOVE(wk);
10233 			if (wk->wk_type != D_JNEWBLK) {
10234 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10235 				continue;
10236 			}
10237 			jnewblk = WK_JNEWBLK(wk);
10238 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10239 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10240 #ifdef SUJ_DEBUG
10241 			/*
10242 			 * Assert that this block is free in the bitmap
10243 			 * before we discard the jnewblk.
10244 			 */
10245 			cgp = (struct cg *)bp->b_data;
10246 			blksfree = cg_blksfree(cgp);
10247 			bno = dtogd(fs, jnewblk->jn_blkno);
10248 			for (i = jnewblk->jn_oldfrags;
10249 			    i < jnewblk->jn_frags; i++) {
10250 				if (isset(blksfree, bno + i))
10251 					continue;
10252 				panic("softdep_setup_blkfree: not free");
10253 			}
10254 #endif
10255 			/*
10256 			 * Even if it's not attached we can free immediately
10257 			 * as the new bitmap is correct.
10258 			 */
10259 			wk->wk_state |= COMPLETE | ATTACHED;
10260 			free_jnewblk(jnewblk);
10261 		}
10262 	}
10263 
10264 #ifdef SUJ_DEBUG
10265 	/*
10266 	 * Assert that we are not freeing a block which has an outstanding
10267 	 * allocation dependency.
10268 	 */
10269 	fs = VFSTOUFS(mp)->um_fs;
10270 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno));
10271 	end = blkno + frags;
10272 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10273 		/*
10274 		 * Don't match against blocks that will be freed when the
10275 		 * background write is done.
10276 		 */
10277 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10278 		    (COMPLETE | DEPCOMPLETE))
10279 			continue;
10280 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10281 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10282 		if ((blkno >= jstart && blkno < jend) ||
10283 		    (end > jstart && end <= jend)) {
10284 			printf("state 0x%X %jd - %d %d dep %p\n",
10285 			    jnewblk->jn_state, jnewblk->jn_blkno,
10286 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10287 			    jnewblk->jn_dep);
10288 			panic("softdep_setup_blkfree: "
10289 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10290 			    blkno, end, frags, jstart, jend);
10291 		}
10292 	}
10293 #endif
10294 	FREE_LOCK(&lk);
10295 }
10296 
10297 /*
10298  * Revert a block allocation when the journal record that describes it
10299  * is not yet written.
10300  */
10301 int
10302 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10303 	struct jnewblk *jnewblk;
10304 	struct fs *fs;
10305 	struct cg *cgp;
10306 	uint8_t *blksfree;
10307 {
10308 	ufs1_daddr_t fragno;
10309 	long cgbno, bbase;
10310 	int frags, blk;
10311 	int i;
10312 
10313 	frags = 0;
10314 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10315 	/*
10316 	 * We have to test which frags need to be rolled back.  We may
10317 	 * be operating on a stale copy when doing background writes.
10318 	 */
10319 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10320 		if (isclr(blksfree, cgbno + i))
10321 			frags++;
10322 	if (frags == 0)
10323 		return (0);
10324 	/*
10325 	 * This is mostly ffs_blkfree() sans some validation and
10326 	 * superblock updates.
10327 	 */
10328 	if (frags == fs->fs_frag) {
10329 		fragno = fragstoblks(fs, cgbno);
10330 		ffs_setblock(fs, blksfree, fragno);
10331 		ffs_clusteracct(fs, cgp, fragno, 1);
10332 		cgp->cg_cs.cs_nbfree++;
10333 	} else {
10334 		cgbno += jnewblk->jn_oldfrags;
10335 		bbase = cgbno - fragnum(fs, cgbno);
10336 		/* Decrement the old frags.  */
10337 		blk = blkmap(fs, blksfree, bbase);
10338 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10339 		/* Deallocate the fragment */
10340 		for (i = 0; i < frags; i++)
10341 			setbit(blksfree, cgbno + i);
10342 		cgp->cg_cs.cs_nffree += frags;
10343 		/* Add back in counts associated with the new frags */
10344 		blk = blkmap(fs, blksfree, bbase);
10345 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10346                 /* If a complete block has been reassembled, account for it. */
10347 		fragno = fragstoblks(fs, bbase);
10348 		if (ffs_isblock(fs, blksfree, fragno)) {
10349 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10350 			ffs_clusteracct(fs, cgp, fragno, 1);
10351 			cgp->cg_cs.cs_nbfree++;
10352 		}
10353 	}
10354 	stat_jnewblk++;
10355 	jnewblk->jn_state &= ~ATTACHED;
10356 	jnewblk->jn_state |= UNDONE;
10357 
10358 	return (frags);
10359 }
10360 
10361 static void
10362 initiate_write_bmsafemap(bmsafemap, bp)
10363 	struct bmsafemap *bmsafemap;
10364 	struct buf *bp;			/* The cg block. */
10365 {
10366 	struct jaddref *jaddref;
10367 	struct jnewblk *jnewblk;
10368 	uint8_t *inosused;
10369 	uint8_t *blksfree;
10370 	struct cg *cgp;
10371 	struct fs *fs;
10372 	ino_t ino;
10373 
10374 	if (bmsafemap->sm_state & IOSTARTED)
10375 		panic("initiate_write_bmsafemap: Already started\n");
10376 	bmsafemap->sm_state |= IOSTARTED;
10377 	/*
10378 	 * Clear any inode allocations which are pending journal writes.
10379 	 */
10380 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10381 		cgp = (struct cg *)bp->b_data;
10382 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10383 		inosused = cg_inosused(cgp);
10384 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10385 			ino = jaddref->ja_ino % fs->fs_ipg;
10386 			/*
10387 			 * If this is a background copy the inode may not
10388 			 * be marked used yet.
10389 			 */
10390 			if (isset(inosused, ino)) {
10391 				if ((jaddref->ja_mode & IFMT) == IFDIR)
10392 					cgp->cg_cs.cs_ndir--;
10393 				cgp->cg_cs.cs_nifree++;
10394 				clrbit(inosused, ino);
10395 				jaddref->ja_state &= ~ATTACHED;
10396 				jaddref->ja_state |= UNDONE;
10397 				stat_jaddref++;
10398 			} else if ((bp->b_xflags & BX_BKGRDMARKER) == 0)
10399 				panic("initiate_write_bmsafemap: inode %d "
10400 				    "marked free", jaddref->ja_ino);
10401 		}
10402 	}
10403 	/*
10404 	 * Clear any block allocations which are pending journal writes.
10405 	 */
10406 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10407 		cgp = (struct cg *)bp->b_data;
10408 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10409 		blksfree = cg_blksfree(cgp);
10410 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10411 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10412 				continue;
10413 			if ((bp->b_xflags & BX_BKGRDMARKER) == 0)
10414 				panic("initiate_write_bmsafemap: block %jd "
10415 				    "marked free", jnewblk->jn_blkno);
10416 		}
10417 	}
10418 	/*
10419 	 * Move allocation lists to the written lists so they can be
10420 	 * cleared once the block write is complete.
10421 	 */
10422 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10423 	    inodedep, id_deps);
10424 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10425 	    newblk, nb_deps);
10426 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10427 	    wk_list);
10428 }
10429 
10430 /*
10431  * This routine is called during the completion interrupt
10432  * service routine for a disk write (from the procedure called
10433  * by the device driver to inform the filesystem caches of
10434  * a request completion).  It should be called early in this
10435  * procedure, before the block is made available to other
10436  * processes or other routines are called.
10437  *
10438  */
10439 static void
10440 softdep_disk_write_complete(bp)
10441 	struct buf *bp;		/* describes the completed disk write */
10442 {
10443 	struct worklist *wk;
10444 	struct worklist *owk;
10445 	struct workhead reattach;
10446 	struct freeblks *freeblks;
10447 	struct buf *sbp;
10448 
10449 	/*
10450 	 * If an error occurred while doing the write, then the data
10451 	 * has not hit the disk and the dependencies cannot be unrolled.
10452 	 */
10453 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0)
10454 		return;
10455 	LIST_INIT(&reattach);
10456 	/*
10457 	 * This lock must not be released anywhere in this code segment.
10458 	 */
10459 	sbp = NULL;
10460 	owk = NULL;
10461 	ACQUIRE_LOCK(&lk);
10462 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
10463 		WORKLIST_REMOVE(wk);
10464 		dep_write[wk->wk_type]++;
10465 		if (wk == owk)
10466 			panic("duplicate worklist: %p\n", wk);
10467 		owk = wk;
10468 		switch (wk->wk_type) {
10469 
10470 		case D_PAGEDEP:
10471 			if (handle_written_filepage(WK_PAGEDEP(wk), bp))
10472 				WORKLIST_INSERT(&reattach, wk);
10473 			continue;
10474 
10475 		case D_INODEDEP:
10476 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
10477 				WORKLIST_INSERT(&reattach, wk);
10478 			continue;
10479 
10480 		case D_BMSAFEMAP:
10481 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp))
10482 				WORKLIST_INSERT(&reattach, wk);
10483 			continue;
10484 
10485 		case D_MKDIR:
10486 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
10487 			continue;
10488 
10489 		case D_ALLOCDIRECT:
10490 			wk->wk_state |= COMPLETE;
10491 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
10492 			continue;
10493 
10494 		case D_ALLOCINDIR:
10495 			wk->wk_state |= COMPLETE;
10496 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
10497 			continue;
10498 
10499 		case D_INDIRDEP:
10500 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp))
10501 				WORKLIST_INSERT(&reattach, wk);
10502 			continue;
10503 
10504 		case D_FREEBLKS:
10505 			wk->wk_state |= COMPLETE;
10506 			freeblks = WK_FREEBLKS(wk);
10507 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
10508 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
10509 				add_to_worklist(wk, WK_NODELAY);
10510 			continue;
10511 
10512 		case D_FREEWORK:
10513 			handle_written_freework(WK_FREEWORK(wk));
10514 			break;
10515 
10516 		case D_JSEGDEP:
10517 			free_jsegdep(WK_JSEGDEP(wk));
10518 			continue;
10519 
10520 		case D_JSEG:
10521 			handle_written_jseg(WK_JSEG(wk), bp);
10522 			continue;
10523 
10524 		case D_SBDEP:
10525 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
10526 				WORKLIST_INSERT(&reattach, wk);
10527 			continue;
10528 
10529 		case D_FREEDEP:
10530 			free_freedep(WK_FREEDEP(wk));
10531 			continue;
10532 
10533 		default:
10534 			panic("handle_disk_write_complete: Unknown type %s",
10535 			    TYPENAME(wk->wk_type));
10536 			/* NOTREACHED */
10537 		}
10538 	}
10539 	/*
10540 	 * Reattach any requests that must be redone.
10541 	 */
10542 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
10543 		WORKLIST_REMOVE(wk);
10544 		WORKLIST_INSERT(&bp->b_dep, wk);
10545 	}
10546 	FREE_LOCK(&lk);
10547 	if (sbp)
10548 		brelse(sbp);
10549 }
10550 
10551 /*
10552  * Called from within softdep_disk_write_complete above. Note that
10553  * this routine is always called from interrupt level with further
10554  * splbio interrupts blocked.
10555  */
10556 static void
10557 handle_allocdirect_partdone(adp, wkhd)
10558 	struct allocdirect *adp;	/* the completed allocdirect */
10559 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
10560 {
10561 	struct allocdirectlst *listhead;
10562 	struct allocdirect *listadp;
10563 	struct inodedep *inodedep;
10564 	long bsize;
10565 
10566 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
10567 		return;
10568 	/*
10569 	 * The on-disk inode cannot claim to be any larger than the last
10570 	 * fragment that has been written. Otherwise, the on-disk inode
10571 	 * might have fragments that were not the last block in the file
10572 	 * which would corrupt the filesystem. Thus, we cannot free any
10573 	 * allocdirects after one whose ad_oldblkno claims a fragment as
10574 	 * these blocks must be rolled back to zero before writing the inode.
10575 	 * We check the currently active set of allocdirects in id_inoupdt
10576 	 * or id_extupdt as appropriate.
10577 	 */
10578 	inodedep = adp->ad_inodedep;
10579 	bsize = inodedep->id_fs->fs_bsize;
10580 	if (adp->ad_state & EXTDATA)
10581 		listhead = &inodedep->id_extupdt;
10582 	else
10583 		listhead = &inodedep->id_inoupdt;
10584 	TAILQ_FOREACH(listadp, listhead, ad_next) {
10585 		/* found our block */
10586 		if (listadp == adp)
10587 			break;
10588 		/* continue if ad_oldlbn is not a fragment */
10589 		if (listadp->ad_oldsize == 0 ||
10590 		    listadp->ad_oldsize == bsize)
10591 			continue;
10592 		/* hit a fragment */
10593 		return;
10594 	}
10595 	/*
10596 	 * If we have reached the end of the current list without
10597 	 * finding the just finished dependency, then it must be
10598 	 * on the future dependency list. Future dependencies cannot
10599 	 * be freed until they are moved to the current list.
10600 	 */
10601 	if (listadp == NULL) {
10602 #ifdef DEBUG
10603 		if (adp->ad_state & EXTDATA)
10604 			listhead = &inodedep->id_newextupdt;
10605 		else
10606 			listhead = &inodedep->id_newinoupdt;
10607 		TAILQ_FOREACH(listadp, listhead, ad_next)
10608 			/* found our block */
10609 			if (listadp == adp)
10610 				break;
10611 		if (listadp == NULL)
10612 			panic("handle_allocdirect_partdone: lost dep");
10613 #endif /* DEBUG */
10614 		return;
10615 	}
10616 	/*
10617 	 * If we have found the just finished dependency, then queue
10618 	 * it along with anything that follows it that is complete.
10619 	 * Since the pointer has not yet been written in the inode
10620 	 * as the dependency prevents it, place the allocdirect on the
10621 	 * bufwait list where it will be freed once the pointer is
10622 	 * valid.
10623 	 */
10624 	if (wkhd == NULL)
10625 		wkhd = &inodedep->id_bufwait;
10626 	for (; adp; adp = listadp) {
10627 		listadp = TAILQ_NEXT(adp, ad_next);
10628 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
10629 			return;
10630 		TAILQ_REMOVE(listhead, adp, ad_next);
10631 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
10632 	}
10633 }
10634 
10635 /*
10636  * Called from within softdep_disk_write_complete above.  This routine
10637  * completes successfully written allocindirs.
10638  */
10639 static void
10640 handle_allocindir_partdone(aip)
10641 	struct allocindir *aip;		/* the completed allocindir */
10642 {
10643 	struct indirdep *indirdep;
10644 
10645 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
10646 		return;
10647 	indirdep = aip->ai_indirdep;
10648 	LIST_REMOVE(aip, ai_next);
10649 	/*
10650 	 * Don't set a pointer while the buffer is undergoing IO or while
10651 	 * we have active truncations.
10652 	 */
10653 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
10654 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
10655 		return;
10656 	}
10657 	if (indirdep->ir_state & UFS1FMT)
10658 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
10659 		    aip->ai_newblkno;
10660 	else
10661 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
10662 		    aip->ai_newblkno;
10663 	/*
10664 	 * Await the pointer write before freeing the allocindir.
10665 	 */
10666 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
10667 }
10668 
10669 /*
10670  * Release segments held on a jwork list.
10671  */
10672 static void
10673 handle_jwork(wkhd)
10674 	struct workhead *wkhd;
10675 {
10676 	struct worklist *wk;
10677 
10678 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
10679 		WORKLIST_REMOVE(wk);
10680 		switch (wk->wk_type) {
10681 		case D_JSEGDEP:
10682 			free_jsegdep(WK_JSEGDEP(wk));
10683 			continue;
10684 		case D_FREEDEP:
10685 			free_freedep(WK_FREEDEP(wk));
10686 			continue;
10687 		case D_FREEFRAG:
10688 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
10689 			WORKITEM_FREE(wk, D_FREEFRAG);
10690 		case D_FREEWORK:
10691 			handle_written_freework(WK_FREEWORK(wk));
10692 			continue;
10693 		default:
10694 			panic("handle_jwork: Unknown type %s\n",
10695 			    TYPENAME(wk->wk_type));
10696 		}
10697 	}
10698 }
10699 
10700 /*
10701  * Handle the bufwait list on an inode when it is safe to release items
10702  * held there.  This normally happens after an inode block is written but
10703  * may be delayed and handled later if there are pending journal items that
10704  * are not yet safe to be released.
10705  */
10706 static struct freefile *
10707 handle_bufwait(inodedep, refhd)
10708 	struct inodedep *inodedep;
10709 	struct workhead *refhd;
10710 {
10711 	struct jaddref *jaddref;
10712 	struct freefile *freefile;
10713 	struct worklist *wk;
10714 
10715 	freefile = NULL;
10716 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
10717 		WORKLIST_REMOVE(wk);
10718 		switch (wk->wk_type) {
10719 		case D_FREEFILE:
10720 			/*
10721 			 * We defer adding freefile to the worklist
10722 			 * until all other additions have been made to
10723 			 * ensure that it will be done after all the
10724 			 * old blocks have been freed.
10725 			 */
10726 			if (freefile != NULL)
10727 				panic("handle_bufwait: freefile");
10728 			freefile = WK_FREEFILE(wk);
10729 			continue;
10730 
10731 		case D_MKDIR:
10732 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
10733 			continue;
10734 
10735 		case D_DIRADD:
10736 			diradd_inode_written(WK_DIRADD(wk), inodedep);
10737 			continue;
10738 
10739 		case D_FREEFRAG:
10740 			wk->wk_state |= COMPLETE;
10741 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
10742 				add_to_worklist(wk, 0);
10743 			continue;
10744 
10745 		case D_DIRREM:
10746 			wk->wk_state |= COMPLETE;
10747 			add_to_worklist(wk, 0);
10748 			continue;
10749 
10750 		case D_ALLOCDIRECT:
10751 		case D_ALLOCINDIR:
10752 			free_newblk(WK_NEWBLK(wk));
10753 			continue;
10754 
10755 		case D_JNEWBLK:
10756 			wk->wk_state |= COMPLETE;
10757 			free_jnewblk(WK_JNEWBLK(wk));
10758 			continue;
10759 
10760 		/*
10761 		 * Save freed journal segments and add references on
10762 		 * the supplied list which will delay their release
10763 		 * until the cg bitmap is cleared on disk.
10764 		 */
10765 		case D_JSEGDEP:
10766 			if (refhd == NULL)
10767 				free_jsegdep(WK_JSEGDEP(wk));
10768 			else
10769 				WORKLIST_INSERT(refhd, wk);
10770 			continue;
10771 
10772 		case D_JADDREF:
10773 			jaddref = WK_JADDREF(wk);
10774 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
10775 			    if_deps);
10776 			/*
10777 			 * Transfer any jaddrefs to the list to be freed with
10778 			 * the bitmap if we're handling a removed file.
10779 			 */
10780 			if (refhd == NULL) {
10781 				wk->wk_state |= COMPLETE;
10782 				free_jaddref(jaddref);
10783 			} else
10784 				WORKLIST_INSERT(refhd, wk);
10785 			continue;
10786 
10787 		default:
10788 			panic("handle_bufwait: Unknown type %p(%s)",
10789 			    wk, TYPENAME(wk->wk_type));
10790 			/* NOTREACHED */
10791 		}
10792 	}
10793 	return (freefile);
10794 }
10795 /*
10796  * Called from within softdep_disk_write_complete above to restore
10797  * in-memory inode block contents to their most up-to-date state. Note
10798  * that this routine is always called from interrupt level with further
10799  * splbio interrupts blocked.
10800  */
10801 static int
10802 handle_written_inodeblock(inodedep, bp)
10803 	struct inodedep *inodedep;
10804 	struct buf *bp;		/* buffer containing the inode block */
10805 {
10806 	struct freefile *freefile;
10807 	struct allocdirect *adp, *nextadp;
10808 	struct ufs1_dinode *dp1 = NULL;
10809 	struct ufs2_dinode *dp2 = NULL;
10810 	struct workhead wkhd;
10811 	int hadchanges, fstype;
10812 	ino_t freelink;
10813 
10814 	LIST_INIT(&wkhd);
10815 	hadchanges = 0;
10816 	freefile = NULL;
10817 	if ((inodedep->id_state & IOSTARTED) == 0)
10818 		panic("handle_written_inodeblock: not started");
10819 	inodedep->id_state &= ~IOSTARTED;
10820 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
10821 		fstype = UFS1;
10822 		dp1 = (struct ufs1_dinode *)bp->b_data +
10823 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
10824 		freelink = dp1->di_freelink;
10825 	} else {
10826 		fstype = UFS2;
10827 		dp2 = (struct ufs2_dinode *)bp->b_data +
10828 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
10829 		freelink = dp2->di_freelink;
10830 	}
10831 	/*
10832 	 * Leave this inodeblock dirty until it's in the list.
10833 	 */
10834 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED) {
10835 		struct inodedep *inon;
10836 
10837 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10838 		if ((inon == NULL && freelink == 0) ||
10839 		    (inon && inon->id_ino == freelink)) {
10840 			if (inon)
10841 				inon->id_state |= UNLINKPREV;
10842 			inodedep->id_state |= UNLINKNEXT;
10843 		}
10844 		hadchanges = 1;
10845 	}
10846 	/*
10847 	 * If we had to rollback the inode allocation because of
10848 	 * bitmaps being incomplete, then simply restore it.
10849 	 * Keep the block dirty so that it will not be reclaimed until
10850 	 * all associated dependencies have been cleared and the
10851 	 * corresponding updates written to disk.
10852 	 */
10853 	if (inodedep->id_savedino1 != NULL) {
10854 		hadchanges = 1;
10855 		if (fstype == UFS1)
10856 			*dp1 = *inodedep->id_savedino1;
10857 		else
10858 			*dp2 = *inodedep->id_savedino2;
10859 		free(inodedep->id_savedino1, M_SAVEDINO);
10860 		inodedep->id_savedino1 = NULL;
10861 		if ((bp->b_flags & B_DELWRI) == 0)
10862 			stat_inode_bitmap++;
10863 		bdirty(bp);
10864 		/*
10865 		 * If the inode is clear here and GOINGAWAY it will never
10866 		 * be written.  Process the bufwait and clear any pending
10867 		 * work which may include the freefile.
10868 		 */
10869 		if (inodedep->id_state & GOINGAWAY)
10870 			goto bufwait;
10871 		return (1);
10872 	}
10873 	inodedep->id_state |= COMPLETE;
10874 	/*
10875 	 * Roll forward anything that had to be rolled back before
10876 	 * the inode could be updated.
10877 	 */
10878 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
10879 		nextadp = TAILQ_NEXT(adp, ad_next);
10880 		if (adp->ad_state & ATTACHED)
10881 			panic("handle_written_inodeblock: new entry");
10882 		if (fstype == UFS1) {
10883 			if (adp->ad_offset < NDADDR) {
10884 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
10885 					panic("%s %s #%jd mismatch %d != %jd",
10886 					    "handle_written_inodeblock:",
10887 					    "direct pointer",
10888 					    (intmax_t)adp->ad_offset,
10889 					    dp1->di_db[adp->ad_offset],
10890 					    (intmax_t)adp->ad_oldblkno);
10891 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
10892 			} else {
10893 				if (dp1->di_ib[adp->ad_offset - NDADDR] != 0)
10894 					panic("%s: %s #%jd allocated as %d",
10895 					    "handle_written_inodeblock",
10896 					    "indirect pointer",
10897 					    (intmax_t)adp->ad_offset - NDADDR,
10898 					    dp1->di_ib[adp->ad_offset - NDADDR]);
10899 				dp1->di_ib[adp->ad_offset - NDADDR] =
10900 				    adp->ad_newblkno;
10901 			}
10902 		} else {
10903 			if (adp->ad_offset < NDADDR) {
10904 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
10905 					panic("%s: %s #%jd %s %jd != %jd",
10906 					    "handle_written_inodeblock",
10907 					    "direct pointer",
10908 					    (intmax_t)adp->ad_offset, "mismatch",
10909 					    (intmax_t)dp2->di_db[adp->ad_offset],
10910 					    (intmax_t)adp->ad_oldblkno);
10911 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
10912 			} else {
10913 				if (dp2->di_ib[adp->ad_offset - NDADDR] != 0)
10914 					panic("%s: %s #%jd allocated as %jd",
10915 					    "handle_written_inodeblock",
10916 					    "indirect pointer",
10917 					    (intmax_t)adp->ad_offset - NDADDR,
10918 					    (intmax_t)
10919 					    dp2->di_ib[adp->ad_offset - NDADDR]);
10920 				dp2->di_ib[adp->ad_offset - NDADDR] =
10921 				    adp->ad_newblkno;
10922 			}
10923 		}
10924 		adp->ad_state &= ~UNDONE;
10925 		adp->ad_state |= ATTACHED;
10926 		hadchanges = 1;
10927 	}
10928 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
10929 		nextadp = TAILQ_NEXT(adp, ad_next);
10930 		if (adp->ad_state & ATTACHED)
10931 			panic("handle_written_inodeblock: new entry");
10932 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
10933 			panic("%s: direct pointers #%jd %s %jd != %jd",
10934 			    "handle_written_inodeblock",
10935 			    (intmax_t)adp->ad_offset, "mismatch",
10936 			    (intmax_t)dp2->di_extb[adp->ad_offset],
10937 			    (intmax_t)adp->ad_oldblkno);
10938 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
10939 		adp->ad_state &= ~UNDONE;
10940 		adp->ad_state |= ATTACHED;
10941 		hadchanges = 1;
10942 	}
10943 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
10944 		stat_direct_blk_ptrs++;
10945 	/*
10946 	 * Reset the file size to its most up-to-date value.
10947 	 */
10948 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
10949 		panic("handle_written_inodeblock: bad size");
10950 	if (inodedep->id_savednlink > LINK_MAX)
10951 		panic("handle_written_inodeblock: Invalid link count "
10952 		    "%d for inodedep %p", inodedep->id_savednlink, inodedep);
10953 	if (fstype == UFS1) {
10954 		if (dp1->di_nlink != inodedep->id_savednlink) {
10955 			dp1->di_nlink = inodedep->id_savednlink;
10956 			hadchanges = 1;
10957 		}
10958 		if (dp1->di_size != inodedep->id_savedsize) {
10959 			dp1->di_size = inodedep->id_savedsize;
10960 			hadchanges = 1;
10961 		}
10962 	} else {
10963 		if (dp2->di_nlink != inodedep->id_savednlink) {
10964 			dp2->di_nlink = inodedep->id_savednlink;
10965 			hadchanges = 1;
10966 		}
10967 		if (dp2->di_size != inodedep->id_savedsize) {
10968 			dp2->di_size = inodedep->id_savedsize;
10969 			hadchanges = 1;
10970 		}
10971 		if (dp2->di_extsize != inodedep->id_savedextsize) {
10972 			dp2->di_extsize = inodedep->id_savedextsize;
10973 			hadchanges = 1;
10974 		}
10975 	}
10976 	inodedep->id_savedsize = -1;
10977 	inodedep->id_savedextsize = -1;
10978 	inodedep->id_savednlink = -1;
10979 	/*
10980 	 * If there were any rollbacks in the inode block, then it must be
10981 	 * marked dirty so that its will eventually get written back in
10982 	 * its correct form.
10983 	 */
10984 	if (hadchanges)
10985 		bdirty(bp);
10986 bufwait:
10987 	/*
10988 	 * Process any allocdirects that completed during the update.
10989 	 */
10990 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
10991 		handle_allocdirect_partdone(adp, &wkhd);
10992 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
10993 		handle_allocdirect_partdone(adp, &wkhd);
10994 	/*
10995 	 * Process deallocations that were held pending until the
10996 	 * inode had been written to disk. Freeing of the inode
10997 	 * is delayed until after all blocks have been freed to
10998 	 * avoid creation of new <vfsid, inum, lbn> triples
10999 	 * before the old ones have been deleted.  Completely
11000 	 * unlinked inodes are not processed until the unlinked
11001 	 * inode list is written or the last reference is removed.
11002 	 */
11003 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11004 		freefile = handle_bufwait(inodedep, NULL);
11005 		if (freefile && !LIST_EMPTY(&wkhd)) {
11006 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11007 			freefile = NULL;
11008 		}
11009 	}
11010 	/*
11011 	 * Move rolled forward dependency completions to the bufwait list
11012 	 * now that those that were already written have been processed.
11013 	 */
11014 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11015 		panic("handle_written_inodeblock: bufwait but no changes");
11016 	jwork_move(&inodedep->id_bufwait, &wkhd);
11017 
11018 	if (freefile != NULL) {
11019 		/*
11020 		 * If the inode is goingaway it was never written.  Fake up
11021 		 * the state here so free_inodedep() can succeed.
11022 		 */
11023 		if (inodedep->id_state & GOINGAWAY)
11024 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11025 		if (free_inodedep(inodedep) == 0)
11026 			panic("handle_written_inodeblock: live inodedep %p",
11027 			    inodedep);
11028 		add_to_worklist(&freefile->fx_list, 0);
11029 		return (0);
11030 	}
11031 
11032 	/*
11033 	 * If no outstanding dependencies, free it.
11034 	 */
11035 	if (free_inodedep(inodedep) ||
11036 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11037 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11038 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11039 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11040 		return (0);
11041 	return (hadchanges);
11042 }
11043 
11044 static int
11045 handle_written_indirdep(indirdep, bp, bpp)
11046 	struct indirdep *indirdep;
11047 	struct buf *bp;
11048 	struct buf **bpp;
11049 {
11050 	struct allocindir *aip;
11051 	struct buf *sbp;
11052 	int chgs;
11053 
11054 	if (indirdep->ir_state & GOINGAWAY)
11055 		panic("handle_written_indirdep: indirdep gone");
11056 	if ((indirdep->ir_state & IOSTARTED) == 0)
11057 		panic("handle_written_indirdep: IO not started");
11058 	chgs = 0;
11059 	/*
11060 	 * If there were rollbacks revert them here.
11061 	 */
11062 	if (indirdep->ir_saveddata) {
11063 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11064 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11065 			free(indirdep->ir_saveddata, M_INDIRDEP);
11066 			indirdep->ir_saveddata = NULL;
11067 		}
11068 		chgs = 1;
11069 	}
11070 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11071 	indirdep->ir_state |= ATTACHED;
11072 	/*
11073 	 * Move allocindirs with written pointers to the completehd if
11074 	 * the indirdep's pointer is not yet written.  Otherwise
11075 	 * free them here.
11076 	 */
11077 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0) {
11078 		LIST_REMOVE(aip, ai_next);
11079 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11080 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11081 			    ai_next);
11082 			newblk_freefrag(&aip->ai_block);
11083 			continue;
11084 		}
11085 		free_newblk(&aip->ai_block);
11086 	}
11087 	/*
11088 	 * Move allocindirs that have finished dependency processing from
11089 	 * the done list to the write list after updating the pointers.
11090 	 */
11091 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11092 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
11093 			handle_allocindir_partdone(aip);
11094 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11095 				panic("disk_write_complete: not gone");
11096 			chgs = 1;
11097 		}
11098 	}
11099 	/*
11100 	 * Preserve the indirdep if there were any changes or if it is not
11101 	 * yet valid on disk.
11102 	 */
11103 	if (chgs) {
11104 		stat_indir_blk_ptrs++;
11105 		bdirty(bp);
11106 		return (1);
11107 	}
11108 	/*
11109 	 * If there were no changes we can discard the savedbp and detach
11110 	 * ourselves from the buf.  We are only carrying completed pointers
11111 	 * in this case.
11112 	 */
11113 	sbp = indirdep->ir_savebp;
11114 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11115 	indirdep->ir_savebp = NULL;
11116 	indirdep->ir_bp = NULL;
11117 	if (*bpp != NULL)
11118 		panic("handle_written_indirdep: bp already exists.");
11119 	*bpp = sbp;
11120 	/*
11121 	 * The indirdep may not be freed until its parent points at it.
11122 	 */
11123 	if (indirdep->ir_state & DEPCOMPLETE)
11124 		free_indirdep(indirdep);
11125 
11126 	return (0);
11127 }
11128 
11129 /*
11130  * Process a diradd entry after its dependent inode has been written.
11131  * This routine must be called with splbio interrupts blocked.
11132  */
11133 static void
11134 diradd_inode_written(dap, inodedep)
11135 	struct diradd *dap;
11136 	struct inodedep *inodedep;
11137 {
11138 
11139 	dap->da_state |= COMPLETE;
11140 	complete_diradd(dap);
11141 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11142 }
11143 
11144 /*
11145  * Returns true if the bmsafemap will have rollbacks when written.  Must
11146  * only be called with lk and the buf lock on the cg held.
11147  */
11148 static int
11149 bmsafemap_rollbacks(bmsafemap)
11150 	struct bmsafemap *bmsafemap;
11151 {
11152 
11153 	return (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11154 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd));
11155 }
11156 
11157 /*
11158  * Re-apply an allocation when a cg write is complete.
11159  */
11160 static int
11161 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11162 	struct jnewblk *jnewblk;
11163 	struct fs *fs;
11164 	struct cg *cgp;
11165 	uint8_t *blksfree;
11166 {
11167 	ufs1_daddr_t fragno;
11168 	ufs2_daddr_t blkno;
11169 	long cgbno, bbase;
11170 	int frags, blk;
11171 	int i;
11172 
11173 	frags = 0;
11174 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11175 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11176 		if (isclr(blksfree, cgbno + i))
11177 			panic("jnewblk_rollforward: re-allocated fragment");
11178 		frags++;
11179 	}
11180 	if (frags == fs->fs_frag) {
11181 		blkno = fragstoblks(fs, cgbno);
11182 		ffs_clrblock(fs, blksfree, (long)blkno);
11183 		ffs_clusteracct(fs, cgp, blkno, -1);
11184 		cgp->cg_cs.cs_nbfree--;
11185 	} else {
11186 		bbase = cgbno - fragnum(fs, cgbno);
11187 		cgbno += jnewblk->jn_oldfrags;
11188                 /* If a complete block had been reassembled, account for it. */
11189 		fragno = fragstoblks(fs, bbase);
11190 		if (ffs_isblock(fs, blksfree, fragno)) {
11191 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11192 			ffs_clusteracct(fs, cgp, fragno, -1);
11193 			cgp->cg_cs.cs_nbfree--;
11194 		}
11195 		/* Decrement the old frags.  */
11196 		blk = blkmap(fs, blksfree, bbase);
11197 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11198 		/* Allocate the fragment */
11199 		for (i = 0; i < frags; i++)
11200 			clrbit(blksfree, cgbno + i);
11201 		cgp->cg_cs.cs_nffree -= frags;
11202 		/* Add back in counts associated with the new frags */
11203 		blk = blkmap(fs, blksfree, bbase);
11204 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11205 	}
11206 	return (frags);
11207 }
11208 
11209 /*
11210  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11211  * changes if it's not a background write.  Set all written dependencies
11212  * to DEPCOMPLETE and free the structure if possible.
11213  */
11214 static int
11215 handle_written_bmsafemap(bmsafemap, bp)
11216 	struct bmsafemap *bmsafemap;
11217 	struct buf *bp;
11218 {
11219 	struct newblk *newblk;
11220 	struct inodedep *inodedep;
11221 	struct jaddref *jaddref, *jatmp;
11222 	struct jnewblk *jnewblk, *jntmp;
11223 	struct ufsmount *ump;
11224 	uint8_t *inosused;
11225 	uint8_t *blksfree;
11226 	struct cg *cgp;
11227 	struct fs *fs;
11228 	ino_t ino;
11229 	int chgs;
11230 
11231 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11232 		panic("initiate_write_bmsafemap: Not started\n");
11233 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11234 	chgs = 0;
11235 	bmsafemap->sm_state &= ~IOSTARTED;
11236 	/*
11237 	 * Release journal work that was waiting on the write.
11238 	 */
11239 	handle_jwork(&bmsafemap->sm_freewr);
11240 
11241 	/*
11242 	 * Restore unwritten inode allocation pending jaddref writes.
11243 	 */
11244 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11245 		cgp = (struct cg *)bp->b_data;
11246 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11247 		inosused = cg_inosused(cgp);
11248 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11249 		    ja_bmdeps, jatmp) {
11250 			if ((jaddref->ja_state & UNDONE) == 0)
11251 				continue;
11252 			ino = jaddref->ja_ino % fs->fs_ipg;
11253 			if (isset(inosused, ino))
11254 				panic("handle_written_bmsafemap: "
11255 				    "re-allocated inode");
11256 			if ((bp->b_xflags & BX_BKGRDMARKER) == 0) {
11257 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11258 					cgp->cg_cs.cs_ndir++;
11259 				cgp->cg_cs.cs_nifree--;
11260 				setbit(inosused, ino);
11261 				chgs = 1;
11262 			}
11263 			jaddref->ja_state &= ~UNDONE;
11264 			jaddref->ja_state |= ATTACHED;
11265 			free_jaddref(jaddref);
11266 		}
11267 	}
11268 	/*
11269 	 * Restore any block allocations which are pending journal writes.
11270 	 */
11271 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11272 		cgp = (struct cg *)bp->b_data;
11273 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11274 		blksfree = cg_blksfree(cgp);
11275 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11276 		    jntmp) {
11277 			if ((jnewblk->jn_state & UNDONE) == 0)
11278 				continue;
11279 			if ((bp->b_xflags & BX_BKGRDMARKER) == 0 &&
11280 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11281 				chgs = 1;
11282 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11283 			jnewblk->jn_state |= ATTACHED;
11284 			free_jnewblk(jnewblk);
11285 		}
11286 	}
11287 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11288 		newblk->nb_state |= DEPCOMPLETE;
11289 		newblk->nb_state &= ~ONDEPLIST;
11290 		newblk->nb_bmsafemap = NULL;
11291 		LIST_REMOVE(newblk, nb_deps);
11292 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11293 			handle_allocdirect_partdone(
11294 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11295 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11296 			handle_allocindir_partdone(
11297 			    WK_ALLOCINDIR(&newblk->nb_list));
11298 		else if (newblk->nb_list.wk_type != D_NEWBLK)
11299 			panic("handle_written_bmsafemap: Unexpected type: %s",
11300 			    TYPENAME(newblk->nb_list.wk_type));
11301 	}
11302 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11303 		inodedep->id_state |= DEPCOMPLETE;
11304 		inodedep->id_state &= ~ONDEPLIST;
11305 		LIST_REMOVE(inodedep, id_deps);
11306 		inodedep->id_bmsafemap = NULL;
11307 	}
11308 	LIST_REMOVE(bmsafemap, sm_next);
11309 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11310 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11311 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11312 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11313 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
11314 		LIST_REMOVE(bmsafemap, sm_hash);
11315 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11316 		return (0);
11317 	}
11318 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11319 	bdirty(bp);
11320 	return (1);
11321 }
11322 
11323 /*
11324  * Try to free a mkdir dependency.
11325  */
11326 static void
11327 complete_mkdir(mkdir)
11328 	struct mkdir *mkdir;
11329 {
11330 	struct diradd *dap;
11331 
11332 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11333 		return;
11334 	LIST_REMOVE(mkdir, md_mkdirs);
11335 	dap = mkdir->md_diradd;
11336 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11337 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11338 		dap->da_state |= DEPCOMPLETE;
11339 		complete_diradd(dap);
11340 	}
11341 	WORKITEM_FREE(mkdir, D_MKDIR);
11342 }
11343 
11344 /*
11345  * Handle the completion of a mkdir dependency.
11346  */
11347 static void
11348 handle_written_mkdir(mkdir, type)
11349 	struct mkdir *mkdir;
11350 	int type;
11351 {
11352 
11353 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
11354 		panic("handle_written_mkdir: bad type");
11355 	mkdir->md_state |= COMPLETE;
11356 	complete_mkdir(mkdir);
11357 }
11358 
11359 static int
11360 free_pagedep(pagedep)
11361 	struct pagedep *pagedep;
11362 {
11363 	int i;
11364 
11365 	if (pagedep->pd_state & NEWBLOCK)
11366 		return (0);
11367 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
11368 		return (0);
11369 	for (i = 0; i < DAHASHSZ; i++)
11370 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
11371 			return (0);
11372 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
11373 		return (0);
11374 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
11375 		return (0);
11376 	if (pagedep->pd_state & ONWORKLIST)
11377 		WORKLIST_REMOVE(&pagedep->pd_list);
11378 	LIST_REMOVE(pagedep, pd_hash);
11379 	WORKITEM_FREE(pagedep, D_PAGEDEP);
11380 
11381 	return (1);
11382 }
11383 
11384 /*
11385  * Called from within softdep_disk_write_complete above.
11386  * A write operation was just completed. Removed inodes can
11387  * now be freed and associated block pointers may be committed.
11388  * Note that this routine is always called from interrupt level
11389  * with further splbio interrupts blocked.
11390  */
11391 static int
11392 handle_written_filepage(pagedep, bp)
11393 	struct pagedep *pagedep;
11394 	struct buf *bp;		/* buffer containing the written page */
11395 {
11396 	struct dirrem *dirrem;
11397 	struct diradd *dap, *nextdap;
11398 	struct direct *ep;
11399 	int i, chgs;
11400 
11401 	if ((pagedep->pd_state & IOSTARTED) == 0)
11402 		panic("handle_written_filepage: not started");
11403 	pagedep->pd_state &= ~IOSTARTED;
11404 	/*
11405 	 * Process any directory removals that have been committed.
11406 	 */
11407 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
11408 		LIST_REMOVE(dirrem, dm_next);
11409 		dirrem->dm_state |= COMPLETE;
11410 		dirrem->dm_dirinum = pagedep->pd_ino;
11411 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
11412 		    ("handle_written_filepage: Journal entries not written."));
11413 		add_to_worklist(&dirrem->dm_list, 0);
11414 	}
11415 	/*
11416 	 * Free any directory additions that have been committed.
11417 	 * If it is a newly allocated block, we have to wait until
11418 	 * the on-disk directory inode claims the new block.
11419 	 */
11420 	if ((pagedep->pd_state & NEWBLOCK) == 0)
11421 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
11422 			free_diradd(dap, NULL);
11423 	/*
11424 	 * Uncommitted directory entries must be restored.
11425 	 */
11426 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
11427 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
11428 		     dap = nextdap) {
11429 			nextdap = LIST_NEXT(dap, da_pdlist);
11430 			if (dap->da_state & ATTACHED)
11431 				panic("handle_written_filepage: attached");
11432 			ep = (struct direct *)
11433 			    ((char *)bp->b_data + dap->da_offset);
11434 			ep->d_ino = dap->da_newinum;
11435 			dap->da_state &= ~UNDONE;
11436 			dap->da_state |= ATTACHED;
11437 			chgs = 1;
11438 			/*
11439 			 * If the inode referenced by the directory has
11440 			 * been written out, then the dependency can be
11441 			 * moved to the pending list.
11442 			 */
11443 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
11444 				LIST_REMOVE(dap, da_pdlist);
11445 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
11446 				    da_pdlist);
11447 			}
11448 		}
11449 	}
11450 	/*
11451 	 * If there were any rollbacks in the directory, then it must be
11452 	 * marked dirty so that its will eventually get written back in
11453 	 * its correct form.
11454 	 */
11455 	if (chgs) {
11456 		if ((bp->b_flags & B_DELWRI) == 0)
11457 			stat_dir_entry++;
11458 		bdirty(bp);
11459 		return (1);
11460 	}
11461 	/*
11462 	 * If we are not waiting for a new directory block to be
11463 	 * claimed by its inode, then the pagedep will be freed.
11464 	 * Otherwise it will remain to track any new entries on
11465 	 * the page in case they are fsync'ed.
11466 	 */
11467 	free_pagedep(pagedep);
11468 	return (0);
11469 }
11470 
11471 /*
11472  * Writing back in-core inode structures.
11473  *
11474  * The filesystem only accesses an inode's contents when it occupies an
11475  * "in-core" inode structure.  These "in-core" structures are separate from
11476  * the page frames used to cache inode blocks.  Only the latter are
11477  * transferred to/from the disk.  So, when the updated contents of the
11478  * "in-core" inode structure are copied to the corresponding in-memory inode
11479  * block, the dependencies are also transferred.  The following procedure is
11480  * called when copying a dirty "in-core" inode to a cached inode block.
11481  */
11482 
11483 /*
11484  * Called when an inode is loaded from disk. If the effective link count
11485  * differed from the actual link count when it was last flushed, then we
11486  * need to ensure that the correct effective link count is put back.
11487  */
11488 void
11489 softdep_load_inodeblock(ip)
11490 	struct inode *ip;	/* the "in_core" copy of the inode */
11491 {
11492 	struct inodedep *inodedep;
11493 
11494 	/*
11495 	 * Check for alternate nlink count.
11496 	 */
11497 	ip->i_effnlink = ip->i_nlink;
11498 	ACQUIRE_LOCK(&lk);
11499 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
11500 	    &inodedep) == 0) {
11501 		FREE_LOCK(&lk);
11502 		return;
11503 	}
11504 	ip->i_effnlink -= inodedep->id_nlinkdelta;
11505 	FREE_LOCK(&lk);
11506 }
11507 
11508 /*
11509  * This routine is called just before the "in-core" inode
11510  * information is to be copied to the in-memory inode block.
11511  * Recall that an inode block contains several inodes. If
11512  * the force flag is set, then the dependencies will be
11513  * cleared so that the update can always be made. Note that
11514  * the buffer is locked when this routine is called, so we
11515  * will never be in the middle of writing the inode block
11516  * to disk.
11517  */
11518 void
11519 softdep_update_inodeblock(ip, bp, waitfor)
11520 	struct inode *ip;	/* the "in_core" copy of the inode */
11521 	struct buf *bp;		/* the buffer containing the inode block */
11522 	int waitfor;		/* nonzero => update must be allowed */
11523 {
11524 	struct inodedep *inodedep;
11525 	struct inoref *inoref;
11526 	struct worklist *wk;
11527 	struct mount *mp;
11528 	struct buf *ibp;
11529 	struct fs *fs;
11530 	int error;
11531 
11532 	mp = UFSTOVFS(ip->i_ump);
11533 	fs = ip->i_fs;
11534 	/*
11535 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
11536 	 * does not have access to the in-core ip so must write directly into
11537 	 * the inode block buffer when setting freelink.
11538 	 */
11539 	if (fs->fs_magic == FS_UFS1_MAGIC)
11540 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
11541 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
11542 	else
11543 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
11544 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
11545 	/*
11546 	 * If the effective link count is not equal to the actual link
11547 	 * count, then we must track the difference in an inodedep while
11548 	 * the inode is (potentially) tossed out of the cache. Otherwise,
11549 	 * if there is no existing inodedep, then there are no dependencies
11550 	 * to track.
11551 	 */
11552 	ACQUIRE_LOCK(&lk);
11553 again:
11554 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
11555 		FREE_LOCK(&lk);
11556 		if (ip->i_effnlink != ip->i_nlink)
11557 			panic("softdep_update_inodeblock: bad link count");
11558 		return;
11559 	}
11560 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
11561 		panic("softdep_update_inodeblock: bad delta");
11562 	/*
11563 	 * If we're flushing all dependencies we must also move any waiting
11564 	 * for journal writes onto the bufwait list prior to I/O.
11565 	 */
11566 	if (waitfor) {
11567 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
11568 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
11569 			    == DEPCOMPLETE) {
11570 				jwait(&inoref->if_list, MNT_WAIT);
11571 				goto again;
11572 			}
11573 		}
11574 	}
11575 	/*
11576 	 * Changes have been initiated. Anything depending on these
11577 	 * changes cannot occur until this inode has been written.
11578 	 */
11579 	inodedep->id_state &= ~COMPLETE;
11580 	if ((inodedep->id_state & ONWORKLIST) == 0)
11581 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
11582 	/*
11583 	 * Any new dependencies associated with the incore inode must
11584 	 * now be moved to the list associated with the buffer holding
11585 	 * the in-memory copy of the inode. Once merged process any
11586 	 * allocdirects that are completed by the merger.
11587 	 */
11588 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
11589 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
11590 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
11591 		    NULL);
11592 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
11593 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
11594 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
11595 		    NULL);
11596 	/*
11597 	 * Now that the inode has been pushed into the buffer, the
11598 	 * operations dependent on the inode being written to disk
11599 	 * can be moved to the id_bufwait so that they will be
11600 	 * processed when the buffer I/O completes.
11601 	 */
11602 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
11603 		WORKLIST_REMOVE(wk);
11604 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
11605 	}
11606 	/*
11607 	 * Newly allocated inodes cannot be written until the bitmap
11608 	 * that allocates them have been written (indicated by
11609 	 * DEPCOMPLETE being set in id_state). If we are doing a
11610 	 * forced sync (e.g., an fsync on a file), we force the bitmap
11611 	 * to be written so that the update can be done.
11612 	 */
11613 	if (waitfor == 0) {
11614 		FREE_LOCK(&lk);
11615 		return;
11616 	}
11617 retry:
11618 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
11619 		FREE_LOCK(&lk);
11620 		return;
11621 	}
11622 	ibp = inodedep->id_bmsafemap->sm_buf;
11623 	ibp = getdirtybuf(ibp, &lk, MNT_WAIT);
11624 	if (ibp == NULL) {
11625 		/*
11626 		 * If ibp came back as NULL, the dependency could have been
11627 		 * freed while we slept.  Look it up again, and check to see
11628 		 * that it has completed.
11629 		 */
11630 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
11631 			goto retry;
11632 		FREE_LOCK(&lk);
11633 		return;
11634 	}
11635 	FREE_LOCK(&lk);
11636 	if ((error = bwrite(ibp)) != 0)
11637 		softdep_error("softdep_update_inodeblock: bwrite", error);
11638 }
11639 
11640 /*
11641  * Merge the a new inode dependency list (such as id_newinoupdt) into an
11642  * old inode dependency list (such as id_inoupdt). This routine must be
11643  * called with splbio interrupts blocked.
11644  */
11645 static void
11646 merge_inode_lists(newlisthead, oldlisthead)
11647 	struct allocdirectlst *newlisthead;
11648 	struct allocdirectlst *oldlisthead;
11649 {
11650 	struct allocdirect *listadp, *newadp;
11651 
11652 	newadp = TAILQ_FIRST(newlisthead);
11653 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
11654 		if (listadp->ad_offset < newadp->ad_offset) {
11655 			listadp = TAILQ_NEXT(listadp, ad_next);
11656 			continue;
11657 		}
11658 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
11659 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
11660 		if (listadp->ad_offset == newadp->ad_offset) {
11661 			allocdirect_merge(oldlisthead, newadp,
11662 			    listadp);
11663 			listadp = newadp;
11664 		}
11665 		newadp = TAILQ_FIRST(newlisthead);
11666 	}
11667 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
11668 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
11669 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
11670 	}
11671 }
11672 
11673 /*
11674  * If we are doing an fsync, then we must ensure that any directory
11675  * entries for the inode have been written after the inode gets to disk.
11676  */
11677 int
11678 softdep_fsync(vp)
11679 	struct vnode *vp;	/* the "in_core" copy of the inode */
11680 {
11681 	struct inodedep *inodedep;
11682 	struct pagedep *pagedep;
11683 	struct inoref *inoref;
11684 	struct worklist *wk;
11685 	struct diradd *dap;
11686 	struct mount *mp;
11687 	struct vnode *pvp;
11688 	struct inode *ip;
11689 	struct buf *bp;
11690 	struct fs *fs;
11691 	struct thread *td = curthread;
11692 	int error, flushparent, pagedep_new_block;
11693 	ino_t parentino;
11694 	ufs_lbn_t lbn;
11695 
11696 	ip = VTOI(vp);
11697 	fs = ip->i_fs;
11698 	mp = vp->v_mount;
11699 	ACQUIRE_LOCK(&lk);
11700 restart:
11701 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
11702 		FREE_LOCK(&lk);
11703 		return (0);
11704 	}
11705 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
11706 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
11707 		    == DEPCOMPLETE) {
11708 			jwait(&inoref->if_list, MNT_WAIT);
11709 			goto restart;
11710 		}
11711 	}
11712 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
11713 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
11714 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
11715 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
11716 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
11717 		panic("softdep_fsync: pending ops %p", inodedep);
11718 	for (error = 0, flushparent = 0; ; ) {
11719 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
11720 			break;
11721 		if (wk->wk_type != D_DIRADD)
11722 			panic("softdep_fsync: Unexpected type %s",
11723 			    TYPENAME(wk->wk_type));
11724 		dap = WK_DIRADD(wk);
11725 		/*
11726 		 * Flush our parent if this directory entry has a MKDIR_PARENT
11727 		 * dependency or is contained in a newly allocated block.
11728 		 */
11729 		if (dap->da_state & DIRCHG)
11730 			pagedep = dap->da_previous->dm_pagedep;
11731 		else
11732 			pagedep = dap->da_pagedep;
11733 		parentino = pagedep->pd_ino;
11734 		lbn = pagedep->pd_lbn;
11735 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
11736 			panic("softdep_fsync: dirty");
11737 		if ((dap->da_state & MKDIR_PARENT) ||
11738 		    (pagedep->pd_state & NEWBLOCK))
11739 			flushparent = 1;
11740 		else
11741 			flushparent = 0;
11742 		/*
11743 		 * If we are being fsync'ed as part of vgone'ing this vnode,
11744 		 * then we will not be able to release and recover the
11745 		 * vnode below, so we just have to give up on writing its
11746 		 * directory entry out. It will eventually be written, just
11747 		 * not now, but then the user was not asking to have it
11748 		 * written, so we are not breaking any promises.
11749 		 */
11750 		if (vp->v_iflag & VI_DOOMED)
11751 			break;
11752 		/*
11753 		 * We prevent deadlock by always fetching inodes from the
11754 		 * root, moving down the directory tree. Thus, when fetching
11755 		 * our parent directory, we first try to get the lock. If
11756 		 * that fails, we must unlock ourselves before requesting
11757 		 * the lock on our parent. See the comment in ufs_lookup
11758 		 * for details on possible races.
11759 		 */
11760 		FREE_LOCK(&lk);
11761 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
11762 		    FFSV_FORCEINSMQ)) {
11763 			error = vfs_busy(mp, MBF_NOWAIT);
11764 			if (error != 0) {
11765 				vfs_ref(mp);
11766 				VOP_UNLOCK(vp, 0);
11767 				error = vfs_busy(mp, 0);
11768 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
11769 				vfs_rel(mp);
11770 				if (error != 0)
11771 					return (ENOENT);
11772 				if (vp->v_iflag & VI_DOOMED) {
11773 					vfs_unbusy(mp);
11774 					return (ENOENT);
11775 				}
11776 			}
11777 			VOP_UNLOCK(vp, 0);
11778 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
11779 			    &pvp, FFSV_FORCEINSMQ);
11780 			vfs_unbusy(mp);
11781 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
11782 			if (vp->v_iflag & VI_DOOMED) {
11783 				if (error == 0)
11784 					vput(pvp);
11785 				error = ENOENT;
11786 			}
11787 			if (error != 0)
11788 				return (error);
11789 		}
11790 		/*
11791 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
11792 		 * that are contained in direct blocks will be resolved by
11793 		 * doing a ffs_update. Pagedeps contained in indirect blocks
11794 		 * may require a complete sync'ing of the directory. So, we
11795 		 * try the cheap and fast ffs_update first, and if that fails,
11796 		 * then we do the slower ffs_syncvnode of the directory.
11797 		 */
11798 		if (flushparent) {
11799 			int locked;
11800 
11801 			if ((error = ffs_update(pvp, 1)) != 0) {
11802 				vput(pvp);
11803 				return (error);
11804 			}
11805 			ACQUIRE_LOCK(&lk);
11806 			locked = 1;
11807 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
11808 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
11809 					if (wk->wk_type != D_DIRADD)
11810 						panic("softdep_fsync: Unexpected type %s",
11811 						      TYPENAME(wk->wk_type));
11812 					dap = WK_DIRADD(wk);
11813 					if (dap->da_state & DIRCHG)
11814 						pagedep = dap->da_previous->dm_pagedep;
11815 					else
11816 						pagedep = dap->da_pagedep;
11817 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
11818 					FREE_LOCK(&lk);
11819 					locked = 0;
11820 					if (pagedep_new_block && (error =
11821 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
11822 						vput(pvp);
11823 						return (error);
11824 					}
11825 				}
11826 			}
11827 			if (locked)
11828 				FREE_LOCK(&lk);
11829 		}
11830 		/*
11831 		 * Flush directory page containing the inode's name.
11832 		 */
11833 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
11834 		    &bp);
11835 		if (error == 0)
11836 			error = bwrite(bp);
11837 		else
11838 			brelse(bp);
11839 		vput(pvp);
11840 		if (error != 0)
11841 			return (error);
11842 		ACQUIRE_LOCK(&lk);
11843 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
11844 			break;
11845 	}
11846 	FREE_LOCK(&lk);
11847 	return (0);
11848 }
11849 
11850 /*
11851  * Flush all the dirty bitmaps associated with the block device
11852  * before flushing the rest of the dirty blocks so as to reduce
11853  * the number of dependencies that will have to be rolled back.
11854  *
11855  * XXX Unused?
11856  */
11857 void
11858 softdep_fsync_mountdev(vp)
11859 	struct vnode *vp;
11860 {
11861 	struct buf *bp, *nbp;
11862 	struct worklist *wk;
11863 	struct bufobj *bo;
11864 
11865 	if (!vn_isdisk(vp, NULL))
11866 		panic("softdep_fsync_mountdev: vnode not a disk");
11867 	bo = &vp->v_bufobj;
11868 restart:
11869 	BO_LOCK(bo);
11870 	ACQUIRE_LOCK(&lk);
11871 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
11872 		/*
11873 		 * If it is already scheduled, skip to the next buffer.
11874 		 */
11875 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
11876 			continue;
11877 
11878 		if ((bp->b_flags & B_DELWRI) == 0)
11879 			panic("softdep_fsync_mountdev: not dirty");
11880 		/*
11881 		 * We are only interested in bitmaps with outstanding
11882 		 * dependencies.
11883 		 */
11884 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
11885 		    wk->wk_type != D_BMSAFEMAP ||
11886 		    (bp->b_vflags & BV_BKGRDINPROG)) {
11887 			BUF_UNLOCK(bp);
11888 			continue;
11889 		}
11890 		FREE_LOCK(&lk);
11891 		BO_UNLOCK(bo);
11892 		bremfree(bp);
11893 		(void) bawrite(bp);
11894 		goto restart;
11895 	}
11896 	FREE_LOCK(&lk);
11897 	drain_output(vp);
11898 	BO_UNLOCK(bo);
11899 }
11900 
11901 /*
11902  * Sync all cylinder groups that were dirty at the time this function is
11903  * called.  Newly dirtied cgs will be inserted before the sintenel.  This
11904  * is used to flush freedep activity that may be holding up writes to a
11905  * indirect block.
11906  */
11907 static int
11908 sync_cgs(mp, waitfor)
11909 	struct mount *mp;
11910 	int waitfor;
11911 {
11912 	struct bmsafemap *bmsafemap;
11913 	struct bmsafemap *sintenel;
11914 	struct ufsmount *ump;
11915 	struct buf *bp;
11916 	int error;
11917 
11918 	sintenel = malloc(sizeof(*sintenel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
11919 	sintenel->sm_cg = -1;
11920 	ump = VFSTOUFS(mp);
11921 	error = 0;
11922 	ACQUIRE_LOCK(&lk);
11923 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sintenel, sm_next);
11924 	for (bmsafemap = LIST_NEXT(sintenel, sm_next); bmsafemap != NULL;
11925 	    bmsafemap = LIST_NEXT(sintenel, sm_next)) {
11926 		/* Skip sintenels and cgs with no work to release. */
11927 		if (bmsafemap->sm_cg == -1 ||
11928 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
11929 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
11930 			LIST_REMOVE(sintenel, sm_next);
11931 			LIST_INSERT_AFTER(bmsafemap, sintenel, sm_next);
11932 			continue;
11933 		}
11934 		/*
11935 		 * If we don't get the lock and we're waiting try again, if
11936 		 * not move on to the next buf and try to sync it.
11937 		 */
11938 		bp = getdirtybuf(bmsafemap->sm_buf, &lk, waitfor);
11939 		if (bp == NULL && waitfor == MNT_WAIT)
11940 			continue;
11941 		LIST_REMOVE(sintenel, sm_next);
11942 		LIST_INSERT_AFTER(bmsafemap, sintenel, sm_next);
11943 		if (bp == NULL)
11944 			continue;
11945 		FREE_LOCK(&lk);
11946 		if (waitfor == MNT_NOWAIT)
11947 			bawrite(bp);
11948 		else
11949 			error = bwrite(bp);
11950 		ACQUIRE_LOCK(&lk);
11951 		if (error)
11952 			break;
11953 	}
11954 	LIST_REMOVE(sintenel, sm_next);
11955 	FREE_LOCK(&lk);
11956 	free(sintenel, M_BMSAFEMAP);
11957 	return (error);
11958 }
11959 
11960 /*
11961  * This routine is called when we are trying to synchronously flush a
11962  * file. This routine must eliminate any filesystem metadata dependencies
11963  * so that the syncing routine can succeed.
11964  */
11965 int
11966 softdep_sync_metadata(struct vnode *vp)
11967 {
11968 	int error;
11969 
11970 	/*
11971 	 * Ensure that any direct block dependencies have been cleared,
11972 	 * truncations are started, and inode references are journaled.
11973 	 */
11974 	ACQUIRE_LOCK(&lk);
11975 	/*
11976 	 * Write all journal records to prevent rollbacks on devvp.
11977 	 */
11978 	if (vp->v_type == VCHR)
11979 		softdep_flushjournal(vp->v_mount);
11980 	error = flush_inodedep_deps(vp, vp->v_mount, VTOI(vp)->i_number);
11981 	/*
11982 	 * Ensure that all truncates are written so we won't find deps on
11983 	 * indirect blocks.
11984 	 */
11985 	process_truncates(vp);
11986 	FREE_LOCK(&lk);
11987 
11988 	return (error);
11989 }
11990 
11991 /*
11992  * This routine is called when we are attempting to sync a buf with
11993  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
11994  * other IO it can but returns EBUSY if the buffer is not yet able to
11995  * be written.  Dependencies which will not cause rollbacks will always
11996  * return 0.
11997  */
11998 int
11999 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12000 {
12001 	struct indirdep *indirdep;
12002 	struct pagedep *pagedep;
12003 	struct allocindir *aip;
12004 	struct newblk *newblk;
12005 	struct buf *nbp;
12006 	struct worklist *wk;
12007 	int i, error;
12008 
12009 	/*
12010 	 * For VCHR we just don't want to force flush any dependencies that
12011 	 * will cause rollbacks.
12012 	 */
12013 	if (vp->v_type == VCHR) {
12014 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12015 			return (EBUSY);
12016 		return (0);
12017 	}
12018 	ACQUIRE_LOCK(&lk);
12019 	/*
12020 	 * As we hold the buffer locked, none of its dependencies
12021 	 * will disappear.
12022 	 */
12023 	error = 0;
12024 top:
12025 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12026 		switch (wk->wk_type) {
12027 
12028 		case D_ALLOCDIRECT:
12029 		case D_ALLOCINDIR:
12030 			newblk = WK_NEWBLK(wk);
12031 			if (newblk->nb_jnewblk != NULL) {
12032 				if (waitfor == MNT_NOWAIT) {
12033 					error = EBUSY;
12034 					goto out_unlock;
12035 				}
12036 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12037 				goto top;
12038 			}
12039 			if (newblk->nb_state & DEPCOMPLETE ||
12040 			    waitfor == MNT_NOWAIT)
12041 				continue;
12042 			nbp = newblk->nb_bmsafemap->sm_buf;
12043 			nbp = getdirtybuf(nbp, &lk, waitfor);
12044 			if (nbp == NULL)
12045 				goto top;
12046 			FREE_LOCK(&lk);
12047 			if ((error = bwrite(nbp)) != 0)
12048 				goto out;
12049 			ACQUIRE_LOCK(&lk);
12050 			continue;
12051 
12052 		case D_INDIRDEP:
12053 			indirdep = WK_INDIRDEP(wk);
12054 			if (waitfor == MNT_NOWAIT) {
12055 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12056 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12057 					error = EBUSY;
12058 					goto out_unlock;
12059 				}
12060 			}
12061 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12062 				panic("softdep_sync_buf: truncation pending.");
12063 		restart:
12064 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12065 				newblk = (struct newblk *)aip;
12066 				if (newblk->nb_jnewblk != NULL) {
12067 					jwait(&newblk->nb_jnewblk->jn_list,
12068 					    waitfor);
12069 					goto restart;
12070 				}
12071 				if (newblk->nb_state & DEPCOMPLETE)
12072 					continue;
12073 				nbp = newblk->nb_bmsafemap->sm_buf;
12074 				nbp = getdirtybuf(nbp, &lk, waitfor);
12075 				if (nbp == NULL)
12076 					goto restart;
12077 				FREE_LOCK(&lk);
12078 				if ((error = bwrite(nbp)) != 0)
12079 					goto out;
12080 				ACQUIRE_LOCK(&lk);
12081 				goto restart;
12082 			}
12083 			continue;
12084 
12085 		case D_PAGEDEP:
12086 			/*
12087 			 * Only flush directory entries in synchronous passes.
12088 			 */
12089 			if (waitfor != MNT_WAIT) {
12090 				error = EBUSY;
12091 				goto out_unlock;
12092 			}
12093 			/*
12094 			 * While syncing snapshots, we must allow recursive
12095 			 * lookups.
12096 			 */
12097 			BUF_AREC(bp);
12098 			/*
12099 			 * We are trying to sync a directory that may
12100 			 * have dependencies on both its own metadata
12101 			 * and/or dependencies on the inodes of any
12102 			 * recently allocated files. We walk its diradd
12103 			 * lists pushing out the associated inode.
12104 			 */
12105 			pagedep = WK_PAGEDEP(wk);
12106 			for (i = 0; i < DAHASHSZ; i++) {
12107 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12108 					continue;
12109 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12110 				    &pagedep->pd_diraddhd[i]))) {
12111 					BUF_NOREC(bp);
12112 					goto out_unlock;
12113 				}
12114 			}
12115 			BUF_NOREC(bp);
12116 			continue;
12117 
12118 		case D_FREEWORK:
12119 		case D_FREEDEP:
12120 		case D_JSEGDEP:
12121 		case D_JNEWBLK:
12122 			continue;
12123 
12124 		default:
12125 			panic("softdep_sync_buf: Unknown type %s",
12126 			    TYPENAME(wk->wk_type));
12127 			/* NOTREACHED */
12128 		}
12129 	}
12130 out_unlock:
12131 	FREE_LOCK(&lk);
12132 out:
12133 	return (error);
12134 }
12135 
12136 /*
12137  * Flush the dependencies associated with an inodedep.
12138  * Called with splbio blocked.
12139  */
12140 static int
12141 flush_inodedep_deps(vp, mp, ino)
12142 	struct vnode *vp;
12143 	struct mount *mp;
12144 	ino_t ino;
12145 {
12146 	struct inodedep *inodedep;
12147 	struct inoref *inoref;
12148 	int error, waitfor;
12149 
12150 	/*
12151 	 * This work is done in two passes. The first pass grabs most
12152 	 * of the buffers and begins asynchronously writing them. The
12153 	 * only way to wait for these asynchronous writes is to sleep
12154 	 * on the filesystem vnode which may stay busy for a long time
12155 	 * if the filesystem is active. So, instead, we make a second
12156 	 * pass over the dependencies blocking on each write. In the
12157 	 * usual case we will be blocking against a write that we
12158 	 * initiated, so when it is done the dependency will have been
12159 	 * resolved. Thus the second pass is expected to end quickly.
12160 	 * We give a brief window at the top of the loop to allow
12161 	 * any pending I/O to complete.
12162 	 */
12163 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12164 		if (error)
12165 			return (error);
12166 		FREE_LOCK(&lk);
12167 		ACQUIRE_LOCK(&lk);
12168 restart:
12169 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12170 			return (0);
12171 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12172 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12173 			    == DEPCOMPLETE) {
12174 				jwait(&inoref->if_list, MNT_WAIT);
12175 				goto restart;
12176 			}
12177 		}
12178 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12179 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12180 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12181 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12182 			continue;
12183 		/*
12184 		 * If pass2, we are done, otherwise do pass 2.
12185 		 */
12186 		if (waitfor == MNT_WAIT)
12187 			break;
12188 		waitfor = MNT_WAIT;
12189 	}
12190 	/*
12191 	 * Try freeing inodedep in case all dependencies have been removed.
12192 	 */
12193 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12194 		(void) free_inodedep(inodedep);
12195 	return (0);
12196 }
12197 
12198 /*
12199  * Flush an inode dependency list.
12200  * Called with splbio blocked.
12201  */
12202 static int
12203 flush_deplist(listhead, waitfor, errorp)
12204 	struct allocdirectlst *listhead;
12205 	int waitfor;
12206 	int *errorp;
12207 {
12208 	struct allocdirect *adp;
12209 	struct newblk *newblk;
12210 	struct buf *bp;
12211 
12212 	mtx_assert(&lk, MA_OWNED);
12213 	TAILQ_FOREACH(adp, listhead, ad_next) {
12214 		newblk = (struct newblk *)adp;
12215 		if (newblk->nb_jnewblk != NULL) {
12216 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12217 			return (1);
12218 		}
12219 		if (newblk->nb_state & DEPCOMPLETE)
12220 			continue;
12221 		bp = newblk->nb_bmsafemap->sm_buf;
12222 		bp = getdirtybuf(bp, &lk, waitfor);
12223 		if (bp == NULL) {
12224 			if (waitfor == MNT_NOWAIT)
12225 				continue;
12226 			return (1);
12227 		}
12228 		FREE_LOCK(&lk);
12229 		if (waitfor == MNT_NOWAIT)
12230 			bawrite(bp);
12231 		else
12232 			*errorp = bwrite(bp);
12233 		ACQUIRE_LOCK(&lk);
12234 		return (1);
12235 	}
12236 	return (0);
12237 }
12238 
12239 /*
12240  * Flush dependencies associated with an allocdirect block.
12241  */
12242 static int
12243 flush_newblk_dep(vp, mp, lbn)
12244 	struct vnode *vp;
12245 	struct mount *mp;
12246 	ufs_lbn_t lbn;
12247 {
12248 	struct newblk *newblk;
12249 	struct bufobj *bo;
12250 	struct inode *ip;
12251 	struct buf *bp;
12252 	ufs2_daddr_t blkno;
12253 	int error;
12254 
12255 	error = 0;
12256 	bo = &vp->v_bufobj;
12257 	ip = VTOI(vp);
12258 	blkno = DIP(ip, i_db[lbn]);
12259 	if (blkno == 0)
12260 		panic("flush_newblk_dep: Missing block");
12261 	ACQUIRE_LOCK(&lk);
12262 	/*
12263 	 * Loop until all dependencies related to this block are satisfied.
12264 	 * We must be careful to restart after each sleep in case a write
12265 	 * completes some part of this process for us.
12266 	 */
12267 	for (;;) {
12268 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12269 			FREE_LOCK(&lk);
12270 			break;
12271 		}
12272 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12273 			panic("flush_newblk_deps: Bad newblk %p", newblk);
12274 		/*
12275 		 * Flush the journal.
12276 		 */
12277 		if (newblk->nb_jnewblk != NULL) {
12278 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12279 			continue;
12280 		}
12281 		/*
12282 		 * Write the bitmap dependency.
12283 		 */
12284 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12285 			bp = newblk->nb_bmsafemap->sm_buf;
12286 			bp = getdirtybuf(bp, &lk, MNT_WAIT);
12287 			if (bp == NULL)
12288 				continue;
12289 			FREE_LOCK(&lk);
12290 			error = bwrite(bp);
12291 			if (error)
12292 				break;
12293 			ACQUIRE_LOCK(&lk);
12294 			continue;
12295 		}
12296 		/*
12297 		 * Write the buffer.
12298 		 */
12299 		FREE_LOCK(&lk);
12300 		BO_LOCK(bo);
12301 		bp = gbincore(bo, lbn);
12302 		if (bp != NULL) {
12303 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12304 			    LK_INTERLOCK, BO_MTX(bo));
12305 			if (error == ENOLCK) {
12306 				ACQUIRE_LOCK(&lk);
12307 				continue; /* Slept, retry */
12308 			}
12309 			if (error != 0)
12310 				break;	/* Failed */
12311 			if (bp->b_flags & B_DELWRI) {
12312 				bremfree(bp);
12313 				error = bwrite(bp);
12314 				if (error)
12315 					break;
12316 			} else
12317 				BUF_UNLOCK(bp);
12318 		} else
12319 			BO_UNLOCK(bo);
12320 		/*
12321 		 * We have to wait for the direct pointers to
12322 		 * point at the newdirblk before the dependency
12323 		 * will go away.
12324 		 */
12325 		error = ffs_update(vp, 1);
12326 		if (error)
12327 			break;
12328 		ACQUIRE_LOCK(&lk);
12329 	}
12330 	return (error);
12331 }
12332 
12333 /*
12334  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
12335  * Called with splbio blocked.
12336  */
12337 static int
12338 flush_pagedep_deps(pvp, mp, diraddhdp)
12339 	struct vnode *pvp;
12340 	struct mount *mp;
12341 	struct diraddhd *diraddhdp;
12342 {
12343 	struct inodedep *inodedep;
12344 	struct inoref *inoref;
12345 	struct ufsmount *ump;
12346 	struct diradd *dap;
12347 	struct vnode *vp;
12348 	int error = 0;
12349 	struct buf *bp;
12350 	ino_t inum;
12351 
12352 	ump = VFSTOUFS(mp);
12353 restart:
12354 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
12355 		/*
12356 		 * Flush ourselves if this directory entry
12357 		 * has a MKDIR_PARENT dependency.
12358 		 */
12359 		if (dap->da_state & MKDIR_PARENT) {
12360 			FREE_LOCK(&lk);
12361 			if ((error = ffs_update(pvp, 1)) != 0)
12362 				break;
12363 			ACQUIRE_LOCK(&lk);
12364 			/*
12365 			 * If that cleared dependencies, go on to next.
12366 			 */
12367 			if (dap != LIST_FIRST(diraddhdp))
12368 				continue;
12369 			if (dap->da_state & MKDIR_PARENT)
12370 				panic("flush_pagedep_deps: MKDIR_PARENT");
12371 		}
12372 		/*
12373 		 * A newly allocated directory must have its "." and
12374 		 * ".." entries written out before its name can be
12375 		 * committed in its parent.
12376 		 */
12377 		inum = dap->da_newinum;
12378 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12379 			panic("flush_pagedep_deps: lost inode1");
12380 		/*
12381 		 * Wait for any pending journal adds to complete so we don't
12382 		 * cause rollbacks while syncing.
12383 		 */
12384 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12385 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12386 			    == DEPCOMPLETE) {
12387 				jwait(&inoref->if_list, MNT_WAIT);
12388 				goto restart;
12389 			}
12390 		}
12391 		if (dap->da_state & MKDIR_BODY) {
12392 			FREE_LOCK(&lk);
12393 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12394 			    FFSV_FORCEINSMQ)))
12395 				break;
12396 			error = flush_newblk_dep(vp, mp, 0);
12397 			/*
12398 			 * If we still have the dependency we might need to
12399 			 * update the vnode to sync the new link count to
12400 			 * disk.
12401 			 */
12402 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
12403 				error = ffs_update(vp, 1);
12404 			vput(vp);
12405 			if (error != 0)
12406 				break;
12407 			ACQUIRE_LOCK(&lk);
12408 			/*
12409 			 * If that cleared dependencies, go on to next.
12410 			 */
12411 			if (dap != LIST_FIRST(diraddhdp))
12412 				continue;
12413 			if (dap->da_state & MKDIR_BODY) {
12414 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
12415 				    &inodedep);
12416 				panic("flush_pagedep_deps: MKDIR_BODY "
12417 				    "inodedep %p dap %p vp %p",
12418 				    inodedep, dap, vp);
12419 			}
12420 		}
12421 		/*
12422 		 * Flush the inode on which the directory entry depends.
12423 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
12424 		 * the only remaining dependency is that the updated inode
12425 		 * count must get pushed to disk. The inode has already
12426 		 * been pushed into its inode buffer (via VOP_UPDATE) at
12427 		 * the time of the reference count change. So we need only
12428 		 * locate that buffer, ensure that there will be no rollback
12429 		 * caused by a bitmap dependency, then write the inode buffer.
12430 		 */
12431 retry:
12432 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12433 			panic("flush_pagedep_deps: lost inode");
12434 		/*
12435 		 * If the inode still has bitmap dependencies,
12436 		 * push them to disk.
12437 		 */
12438 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
12439 			bp = inodedep->id_bmsafemap->sm_buf;
12440 			bp = getdirtybuf(bp, &lk, MNT_WAIT);
12441 			if (bp == NULL)
12442 				goto retry;
12443 			FREE_LOCK(&lk);
12444 			if ((error = bwrite(bp)) != 0)
12445 				break;
12446 			ACQUIRE_LOCK(&lk);
12447 			if (dap != LIST_FIRST(diraddhdp))
12448 				continue;
12449 		}
12450 		/*
12451 		 * If the inode is still sitting in a buffer waiting
12452 		 * to be written or waiting for the link count to be
12453 		 * adjusted update it here to flush it to disk.
12454 		 */
12455 		if (dap == LIST_FIRST(diraddhdp)) {
12456 			FREE_LOCK(&lk);
12457 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12458 			    FFSV_FORCEINSMQ)))
12459 				break;
12460 			error = ffs_update(vp, 1);
12461 			vput(vp);
12462 			if (error)
12463 				break;
12464 			ACQUIRE_LOCK(&lk);
12465 		}
12466 		/*
12467 		 * If we have failed to get rid of all the dependencies
12468 		 * then something is seriously wrong.
12469 		 */
12470 		if (dap == LIST_FIRST(diraddhdp)) {
12471 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
12472 			panic("flush_pagedep_deps: failed to flush "
12473 			    "inodedep %p ino %d dap %p", inodedep, inum, dap);
12474 		}
12475 	}
12476 	if (error)
12477 		ACQUIRE_LOCK(&lk);
12478 	return (error);
12479 }
12480 
12481 /*
12482  * A large burst of file addition or deletion activity can drive the
12483  * memory load excessively high. First attempt to slow things down
12484  * using the techniques below. If that fails, this routine requests
12485  * the offending operations to fall back to running synchronously
12486  * until the memory load returns to a reasonable level.
12487  */
12488 int
12489 softdep_slowdown(vp)
12490 	struct vnode *vp;
12491 {
12492 	struct ufsmount *ump;
12493 	int jlow;
12494 	int max_softdeps_hard;
12495 
12496 	ACQUIRE_LOCK(&lk);
12497 	jlow = 0;
12498 	/*
12499 	 * Check for journal space if needed.
12500 	 */
12501 	if (DOINGSUJ(vp)) {
12502 		ump = VFSTOUFS(vp->v_mount);
12503 		if (journal_space(ump, 0) == 0)
12504 			jlow = 1;
12505 	}
12506 	max_softdeps_hard = max_softdeps * 11 / 10;
12507 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
12508 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
12509 	    VFSTOUFS(vp->v_mount)->um_numindirdeps < maxindirdeps &&
12510 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0) {
12511 		FREE_LOCK(&lk);
12512   		return (0);
12513 	}
12514 	if (VFSTOUFS(vp->v_mount)->um_numindirdeps >= maxindirdeps || jlow)
12515 		softdep_speedup();
12516 	stat_sync_limit_hit += 1;
12517 	FREE_LOCK(&lk);
12518 	if (DOINGSUJ(vp))
12519 		return (0);
12520 	return (1);
12521 }
12522 
12523 /*
12524  * Called by the allocation routines when they are about to fail
12525  * in the hope that we can free up the requested resource (inodes
12526  * or disk space).
12527  *
12528  * First check to see if the work list has anything on it. If it has,
12529  * clean up entries until we successfully free the requested resource.
12530  * Because this process holds inodes locked, we cannot handle any remove
12531  * requests that might block on a locked inode as that could lead to
12532  * deadlock. If the worklist yields none of the requested resource,
12533  * start syncing out vnodes to free up the needed space.
12534  */
12535 int
12536 softdep_request_cleanup(fs, vp, cred, resource)
12537 	struct fs *fs;
12538 	struct vnode *vp;
12539 	struct ucred *cred;
12540 	int resource;
12541 {
12542 	struct ufsmount *ump;
12543 	struct mount *mp;
12544 	struct vnode *lvp, *mvp;
12545 	long starttime;
12546 	ufs2_daddr_t needed;
12547 	int error;
12548 
12549 	/*
12550 	 * If we are being called because of a process doing a
12551 	 * copy-on-write, then it is not safe to process any
12552 	 * worklist items as we will recurse into the copyonwrite
12553 	 * routine.  This will result in an incoherent snapshot.
12554 	 * If the vnode that we hold is a snapshot, we must avoid
12555 	 * handling other resources that could cause deadlock.
12556 	 */
12557 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
12558 		return (0);
12559 
12560 	if (resource == FLUSH_BLOCKS_WAIT)
12561 		stat_cleanup_blkrequests += 1;
12562 	else
12563 		stat_cleanup_inorequests += 1;
12564 
12565 	mp = vp->v_mount;
12566 	ump = VFSTOUFS(mp);
12567 	mtx_assert(UFS_MTX(ump), MA_OWNED);
12568 	UFS_UNLOCK(ump);
12569 	error = ffs_update(vp, 1);
12570 	if (error != 0) {
12571 		UFS_LOCK(ump);
12572 		return (0);
12573 	}
12574 	/*
12575 	 * If we are in need of resources, consider pausing for
12576 	 * tickdelay to give ourselves some breathing room.
12577 	 */
12578 	ACQUIRE_LOCK(&lk);
12579 	process_removes(vp);
12580 	process_truncates(vp);
12581 	request_cleanup(UFSTOVFS(ump), resource);
12582 	FREE_LOCK(&lk);
12583 	/*
12584 	 * Now clean up at least as many resources as we will need.
12585 	 *
12586 	 * When requested to clean up inodes, the number that are needed
12587 	 * is set by the number of simultaneous writers (mnt_writeopcount)
12588 	 * plus a bit of slop (2) in case some more writers show up while
12589 	 * we are cleaning.
12590 	 *
12591 	 * When requested to free up space, the amount of space that
12592 	 * we need is enough blocks to allocate a full-sized segment
12593 	 * (fs_contigsumsize). The number of such segments that will
12594 	 * be needed is set by the number of simultaneous writers
12595 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
12596 	 * writers show up while we are cleaning.
12597 	 *
12598 	 * Additionally, if we are unpriviledged and allocating space,
12599 	 * we need to ensure that we clean up enough blocks to get the
12600 	 * needed number of blocks over the threshhold of the minimum
12601 	 * number of blocks required to be kept free by the filesystem
12602 	 * (fs_minfree).
12603 	 */
12604 	if (resource == FLUSH_INODES_WAIT) {
12605 		needed = vp->v_mount->mnt_writeopcount + 2;
12606 	} else if (resource == FLUSH_BLOCKS_WAIT) {
12607 		needed = (vp->v_mount->mnt_writeopcount + 2) *
12608 		    fs->fs_contigsumsize;
12609 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
12610 			needed += fragstoblks(fs,
12611 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
12612 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
12613 	} else {
12614 		UFS_LOCK(ump);
12615 		printf("softdep_request_cleanup: Unknown resource type %d\n",
12616 		    resource);
12617 		return (0);
12618 	}
12619 	starttime = time_second;
12620 retry:
12621 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
12622 	    fs->fs_cstotal.cs_nbfree <= needed) ||
12623 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
12624 	    fs->fs_cstotal.cs_nifree <= needed)) {
12625 		ACQUIRE_LOCK(&lk);
12626 		if (ump->softdep_on_worklist > 0 &&
12627 		    process_worklist_item(UFSTOVFS(ump),
12628 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
12629 			stat_worklist_push += 1;
12630 		FREE_LOCK(&lk);
12631 	}
12632 	/*
12633 	 * If we still need resources and there are no more worklist
12634 	 * entries to process to obtain them, we have to start flushing
12635 	 * the dirty vnodes to force the release of additional requests
12636 	 * to the worklist that we can then process to reap addition
12637 	 * resources. We walk the vnodes associated with the mount point
12638 	 * until we get the needed worklist requests that we can reap.
12639 	 */
12640 	if ((resource == FLUSH_BLOCKS_WAIT &&
12641 	     fs->fs_cstotal.cs_nbfree <= needed) ||
12642 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
12643 	     fs->fs_cstotal.cs_nifree <= needed)) {
12644 		MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
12645 			if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
12646 				VI_UNLOCK(lvp);
12647 				continue;
12648 			}
12649 			if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
12650 			    curthread))
12651 				continue;
12652 			if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
12653 				vput(lvp);
12654 				continue;
12655 			}
12656 			(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
12657 			vput(lvp);
12658 		}
12659 		lvp = ump->um_devvp;
12660 		if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
12661 			VOP_FSYNC(lvp, MNT_NOWAIT, curthread);
12662 			VOP_UNLOCK(lvp, 0);
12663 		}
12664 		if (ump->softdep_on_worklist > 0) {
12665 			stat_cleanup_retries += 1;
12666 			goto retry;
12667 		}
12668 		stat_cleanup_failures += 1;
12669 	}
12670 	if (time_second - starttime > stat_cleanup_high_delay)
12671 		stat_cleanup_high_delay = time_second - starttime;
12672 	UFS_LOCK(ump);
12673 	return (1);
12674 }
12675 
12676 /*
12677  * If memory utilization has gotten too high, deliberately slow things
12678  * down and speed up the I/O processing.
12679  */
12680 extern struct thread *syncertd;
12681 static int
12682 request_cleanup(mp, resource)
12683 	struct mount *mp;
12684 	int resource;
12685 {
12686 	struct thread *td = curthread;
12687 	struct ufsmount *ump;
12688 
12689 	mtx_assert(&lk, MA_OWNED);
12690 	/*
12691 	 * We never hold up the filesystem syncer or buf daemon.
12692 	 */
12693 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
12694 		return (0);
12695 	ump = VFSTOUFS(mp);
12696 	/*
12697 	 * First check to see if the work list has gotten backlogged.
12698 	 * If it has, co-opt this process to help clean up two entries.
12699 	 * Because this process may hold inodes locked, we cannot
12700 	 * handle any remove requests that might block on a locked
12701 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
12702 	 * to avoid recursively processing the worklist.
12703 	 */
12704 	if (ump->softdep_on_worklist > max_softdeps / 10) {
12705 		td->td_pflags |= TDP_SOFTDEP;
12706 		process_worklist_item(mp, 2, LK_NOWAIT);
12707 		td->td_pflags &= ~TDP_SOFTDEP;
12708 		stat_worklist_push += 2;
12709 		return(1);
12710 	}
12711 	/*
12712 	 * Next, we attempt to speed up the syncer process. If that
12713 	 * is successful, then we allow the process to continue.
12714 	 */
12715 	if (softdep_speedup() &&
12716 	    resource != FLUSH_BLOCKS_WAIT &&
12717 	    resource != FLUSH_INODES_WAIT)
12718 		return(0);
12719 	/*
12720 	 * If we are resource constrained on inode dependencies, try
12721 	 * flushing some dirty inodes. Otherwise, we are constrained
12722 	 * by file deletions, so try accelerating flushes of directories
12723 	 * with removal dependencies. We would like to do the cleanup
12724 	 * here, but we probably hold an inode locked at this point and
12725 	 * that might deadlock against one that we try to clean. So,
12726 	 * the best that we can do is request the syncer daemon to do
12727 	 * the cleanup for us.
12728 	 */
12729 	switch (resource) {
12730 
12731 	case FLUSH_INODES:
12732 	case FLUSH_INODES_WAIT:
12733 		stat_ino_limit_push += 1;
12734 		req_clear_inodedeps += 1;
12735 		stat_countp = &stat_ino_limit_hit;
12736 		break;
12737 
12738 	case FLUSH_BLOCKS:
12739 	case FLUSH_BLOCKS_WAIT:
12740 		stat_blk_limit_push += 1;
12741 		req_clear_remove += 1;
12742 		stat_countp = &stat_blk_limit_hit;
12743 		break;
12744 
12745 	default:
12746 		panic("request_cleanup: unknown type");
12747 	}
12748 	/*
12749 	 * Hopefully the syncer daemon will catch up and awaken us.
12750 	 * We wait at most tickdelay before proceeding in any case.
12751 	 */
12752 	proc_waiting += 1;
12753 	if (callout_pending(&softdep_callout) == FALSE)
12754 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
12755 		    pause_timer, 0);
12756 
12757 	msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
12758 	proc_waiting -= 1;
12759 	return (1);
12760 }
12761 
12762 /*
12763  * Awaken processes pausing in request_cleanup and clear proc_waiting
12764  * to indicate that there is no longer a timer running.
12765  */
12766 static void
12767 pause_timer(arg)
12768 	void *arg;
12769 {
12770 
12771 	/*
12772 	 * The callout_ API has acquired mtx and will hold it around this
12773 	 * function call.
12774 	 */
12775 	*stat_countp += 1;
12776 	wakeup_one(&proc_waiting);
12777 	if (proc_waiting > 0)
12778 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
12779 		    pause_timer, 0);
12780 }
12781 
12782 /*
12783  * Flush out a directory with at least one removal dependency in an effort to
12784  * reduce the number of dirrem, freefile, and freeblks dependency structures.
12785  */
12786 static void
12787 clear_remove(void)
12788 {
12789 	struct pagedep_hashhead *pagedephd;
12790 	struct pagedep *pagedep;
12791 	static int next = 0;
12792 	struct mount *mp;
12793 	struct vnode *vp;
12794 	struct bufobj *bo;
12795 	int error, cnt;
12796 	ino_t ino;
12797 
12798 	mtx_assert(&lk, MA_OWNED);
12799 
12800 	for (cnt = 0; cnt < pagedep_hash; cnt++) {
12801 		pagedephd = &pagedep_hashtbl[next++];
12802 		if (next >= pagedep_hash)
12803 			next = 0;
12804 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
12805 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
12806 				continue;
12807 			mp = pagedep->pd_list.wk_mp;
12808 			ino = pagedep->pd_ino;
12809 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
12810 				continue;
12811 			FREE_LOCK(&lk);
12812 
12813 			/*
12814 			 * Let unmount clear deps
12815 			 */
12816 			error = vfs_busy(mp, MBF_NOWAIT);
12817 			if (error != 0)
12818 				goto finish_write;
12819 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
12820 			     FFSV_FORCEINSMQ);
12821 			vfs_unbusy(mp);
12822 			if (error != 0) {
12823 				softdep_error("clear_remove: vget", error);
12824 				goto finish_write;
12825 			}
12826 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
12827 				softdep_error("clear_remove: fsync", error);
12828 			bo = &vp->v_bufobj;
12829 			BO_LOCK(bo);
12830 			drain_output(vp);
12831 			BO_UNLOCK(bo);
12832 			vput(vp);
12833 		finish_write:
12834 			vn_finished_write(mp);
12835 			ACQUIRE_LOCK(&lk);
12836 			return;
12837 		}
12838 	}
12839 }
12840 
12841 /*
12842  * Clear out a block of dirty inodes in an effort to reduce
12843  * the number of inodedep dependency structures.
12844  */
12845 static void
12846 clear_inodedeps(void)
12847 {
12848 	struct inodedep_hashhead *inodedephd;
12849 	struct inodedep *inodedep;
12850 	static int next = 0;
12851 	struct mount *mp;
12852 	struct vnode *vp;
12853 	struct fs *fs;
12854 	int error, cnt;
12855 	ino_t firstino, lastino, ino;
12856 
12857 	mtx_assert(&lk, MA_OWNED);
12858 	/*
12859 	 * Pick a random inode dependency to be cleared.
12860 	 * We will then gather up all the inodes in its block
12861 	 * that have dependencies and flush them out.
12862 	 */
12863 	for (cnt = 0; cnt < inodedep_hash; cnt++) {
12864 		inodedephd = &inodedep_hashtbl[next++];
12865 		if (next >= inodedep_hash)
12866 			next = 0;
12867 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
12868 			break;
12869 	}
12870 	if (inodedep == NULL)
12871 		return;
12872 	fs = inodedep->id_fs;
12873 	mp = inodedep->id_list.wk_mp;
12874 	/*
12875 	 * Find the last inode in the block with dependencies.
12876 	 */
12877 	firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
12878 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
12879 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
12880 			break;
12881 	/*
12882 	 * Asynchronously push all but the last inode with dependencies.
12883 	 * Synchronously push the last inode with dependencies to ensure
12884 	 * that the inode block gets written to free up the inodedeps.
12885 	 */
12886 	for (ino = firstino; ino <= lastino; ino++) {
12887 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12888 			continue;
12889 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
12890 			continue;
12891 		FREE_LOCK(&lk);
12892 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
12893 		if (error != 0) {
12894 			vn_finished_write(mp);
12895 			ACQUIRE_LOCK(&lk);
12896 			return;
12897 		}
12898 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
12899 		    FFSV_FORCEINSMQ)) != 0) {
12900 			softdep_error("clear_inodedeps: vget", error);
12901 			vfs_unbusy(mp);
12902 			vn_finished_write(mp);
12903 			ACQUIRE_LOCK(&lk);
12904 			return;
12905 		}
12906 		vfs_unbusy(mp);
12907 		if (ino == lastino) {
12908 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
12909 				softdep_error("clear_inodedeps: fsync1", error);
12910 		} else {
12911 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
12912 				softdep_error("clear_inodedeps: fsync2", error);
12913 			BO_LOCK(&vp->v_bufobj);
12914 			drain_output(vp);
12915 			BO_UNLOCK(&vp->v_bufobj);
12916 		}
12917 		vput(vp);
12918 		vn_finished_write(mp);
12919 		ACQUIRE_LOCK(&lk);
12920 	}
12921 }
12922 
12923 void
12924 softdep_buf_append(bp, wkhd)
12925 	struct buf *bp;
12926 	struct workhead *wkhd;
12927 {
12928 	struct worklist *wk;
12929 
12930 	ACQUIRE_LOCK(&lk);
12931 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
12932 		WORKLIST_REMOVE(wk);
12933 		WORKLIST_INSERT(&bp->b_dep, wk);
12934 	}
12935 	FREE_LOCK(&lk);
12936 
12937 }
12938 
12939 void
12940 softdep_inode_append(ip, cred, wkhd)
12941 	struct inode *ip;
12942 	struct ucred *cred;
12943 	struct workhead *wkhd;
12944 {
12945 	struct buf *bp;
12946 	struct fs *fs;
12947 	int error;
12948 
12949 	fs = ip->i_fs;
12950 	error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
12951 	    (int)fs->fs_bsize, cred, &bp);
12952 	if (error) {
12953 		softdep_freework(wkhd);
12954 		return;
12955 	}
12956 	softdep_buf_append(bp, wkhd);
12957 	bqrelse(bp);
12958 }
12959 
12960 void
12961 softdep_freework(wkhd)
12962 	struct workhead *wkhd;
12963 {
12964 
12965 	ACQUIRE_LOCK(&lk);
12966 	handle_jwork(wkhd);
12967 	FREE_LOCK(&lk);
12968 }
12969 
12970 /*
12971  * Function to determine if the buffer has outstanding dependencies
12972  * that will cause a roll-back if the buffer is written. If wantcount
12973  * is set, return number of dependencies, otherwise just yes or no.
12974  */
12975 static int
12976 softdep_count_dependencies(bp, wantcount)
12977 	struct buf *bp;
12978 	int wantcount;
12979 {
12980 	struct worklist *wk;
12981 	struct bmsafemap *bmsafemap;
12982 	struct freework *freework;
12983 	struct inodedep *inodedep;
12984 	struct indirdep *indirdep;
12985 	struct freeblks *freeblks;
12986 	struct allocindir *aip;
12987 	struct pagedep *pagedep;
12988 	struct dirrem *dirrem;
12989 	struct newblk *newblk;
12990 	struct mkdir *mkdir;
12991 	struct diradd *dap;
12992 	int i, retval;
12993 
12994 	retval = 0;
12995 	ACQUIRE_LOCK(&lk);
12996 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12997 		switch (wk->wk_type) {
12998 
12999 		case D_INODEDEP:
13000 			inodedep = WK_INODEDEP(wk);
13001 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13002 				/* bitmap allocation dependency */
13003 				retval += 1;
13004 				if (!wantcount)
13005 					goto out;
13006 			}
13007 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13008 				/* direct block pointer dependency */
13009 				retval += 1;
13010 				if (!wantcount)
13011 					goto out;
13012 			}
13013 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13014 				/* direct block pointer dependency */
13015 				retval += 1;
13016 				if (!wantcount)
13017 					goto out;
13018 			}
13019 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13020 				/* Add reference dependency. */
13021 				retval += 1;
13022 				if (!wantcount)
13023 					goto out;
13024 			}
13025 			continue;
13026 
13027 		case D_INDIRDEP:
13028 			indirdep = WK_INDIRDEP(wk);
13029 
13030 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
13031 				/* indirect truncation dependency */
13032 				retval += 1;
13033 				if (!wantcount)
13034 					goto out;
13035 			}
13036 
13037 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13038 				/* indirect block pointer dependency */
13039 				retval += 1;
13040 				if (!wantcount)
13041 					goto out;
13042 			}
13043 			continue;
13044 
13045 		case D_PAGEDEP:
13046 			pagedep = WK_PAGEDEP(wk);
13047 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
13048 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
13049 					/* Journal remove ref dependency. */
13050 					retval += 1;
13051 					if (!wantcount)
13052 						goto out;
13053 				}
13054 			}
13055 			for (i = 0; i < DAHASHSZ; i++) {
13056 
13057 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
13058 					/* directory entry dependency */
13059 					retval += 1;
13060 					if (!wantcount)
13061 						goto out;
13062 				}
13063 			}
13064 			continue;
13065 
13066 		case D_BMSAFEMAP:
13067 			bmsafemap = WK_BMSAFEMAP(wk);
13068 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
13069 				/* Add reference dependency. */
13070 				retval += 1;
13071 				if (!wantcount)
13072 					goto out;
13073 			}
13074 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
13075 				/* Allocate block dependency. */
13076 				retval += 1;
13077 				if (!wantcount)
13078 					goto out;
13079 			}
13080 			continue;
13081 
13082 		case D_FREEBLKS:
13083 			freeblks = WK_FREEBLKS(wk);
13084 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
13085 				/* Freeblk journal dependency. */
13086 				retval += 1;
13087 				if (!wantcount)
13088 					goto out;
13089 			}
13090 			continue;
13091 
13092 		case D_ALLOCDIRECT:
13093 		case D_ALLOCINDIR:
13094 			newblk = WK_NEWBLK(wk);
13095 			if (newblk->nb_jnewblk) {
13096 				/* Journal allocate dependency. */
13097 				retval += 1;
13098 				if (!wantcount)
13099 					goto out;
13100 			}
13101 			continue;
13102 
13103 		case D_MKDIR:
13104 			mkdir = WK_MKDIR(wk);
13105 			if (mkdir->md_jaddref) {
13106 				/* Journal reference dependency. */
13107 				retval += 1;
13108 				if (!wantcount)
13109 					goto out;
13110 			}
13111 			continue;
13112 
13113 		case D_FREEWORK:
13114 		case D_FREEDEP:
13115 		case D_JSEGDEP:
13116 		case D_JSEG:
13117 		case D_SBDEP:
13118 			/* never a dependency on these blocks */
13119 			continue;
13120 
13121 		default:
13122 			panic("softdep_count_dependencies: Unexpected type %s",
13123 			    TYPENAME(wk->wk_type));
13124 			/* NOTREACHED */
13125 		}
13126 	}
13127 out:
13128 	FREE_LOCK(&lk);
13129 	return retval;
13130 }
13131 
13132 /*
13133  * Acquire exclusive access to a buffer.
13134  * Must be called with a locked mtx parameter.
13135  * Return acquired buffer or NULL on failure.
13136  */
13137 static struct buf *
13138 getdirtybuf(bp, mtx, waitfor)
13139 	struct buf *bp;
13140 	struct mtx *mtx;
13141 	int waitfor;
13142 {
13143 	int error;
13144 
13145 	mtx_assert(mtx, MA_OWNED);
13146 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
13147 		if (waitfor != MNT_WAIT)
13148 			return (NULL);
13149 		error = BUF_LOCK(bp,
13150 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, mtx);
13151 		/*
13152 		 * Even if we sucessfully acquire bp here, we have dropped
13153 		 * mtx, which may violates our guarantee.
13154 		 */
13155 		if (error == 0)
13156 			BUF_UNLOCK(bp);
13157 		else if (error != ENOLCK)
13158 			panic("getdirtybuf: inconsistent lock: %d", error);
13159 		mtx_lock(mtx);
13160 		return (NULL);
13161 	}
13162 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13163 		if (mtx == &lk && waitfor == MNT_WAIT) {
13164 			mtx_unlock(mtx);
13165 			BO_LOCK(bp->b_bufobj);
13166 			BUF_UNLOCK(bp);
13167 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13168 				bp->b_vflags |= BV_BKGRDWAIT;
13169 				msleep(&bp->b_xflags, BO_MTX(bp->b_bufobj),
13170 				       PRIBIO | PDROP, "getbuf", 0);
13171 			} else
13172 				BO_UNLOCK(bp->b_bufobj);
13173 			mtx_lock(mtx);
13174 			return (NULL);
13175 		}
13176 		BUF_UNLOCK(bp);
13177 		if (waitfor != MNT_WAIT)
13178 			return (NULL);
13179 		/*
13180 		 * The mtx argument must be bp->b_vp's mutex in
13181 		 * this case.
13182 		 */
13183 #ifdef	DEBUG_VFS_LOCKS
13184 		if (bp->b_vp->v_type != VCHR)
13185 			ASSERT_BO_LOCKED(bp->b_bufobj);
13186 #endif
13187 		bp->b_vflags |= BV_BKGRDWAIT;
13188 		msleep(&bp->b_xflags, mtx, PRIBIO, "getbuf", 0);
13189 		return (NULL);
13190 	}
13191 	if ((bp->b_flags & B_DELWRI) == 0) {
13192 		BUF_UNLOCK(bp);
13193 		return (NULL);
13194 	}
13195 	bremfree(bp);
13196 	return (bp);
13197 }
13198 
13199 
13200 /*
13201  * Check if it is safe to suspend the file system now.  On entry,
13202  * the vnode interlock for devvp should be held.  Return 0 with
13203  * the mount interlock held if the file system can be suspended now,
13204  * otherwise return EAGAIN with the mount interlock held.
13205  */
13206 int
13207 softdep_check_suspend(struct mount *mp,
13208 		      struct vnode *devvp,
13209 		      int softdep_deps,
13210 		      int softdep_accdeps,
13211 		      int secondary_writes,
13212 		      int secondary_accwrites)
13213 {
13214 	struct bufobj *bo;
13215 	struct ufsmount *ump;
13216 	int error;
13217 
13218 	ump = VFSTOUFS(mp);
13219 	bo = &devvp->v_bufobj;
13220 	ASSERT_BO_LOCKED(bo);
13221 
13222 	for (;;) {
13223 		if (!TRY_ACQUIRE_LOCK(&lk)) {
13224 			BO_UNLOCK(bo);
13225 			ACQUIRE_LOCK(&lk);
13226 			FREE_LOCK(&lk);
13227 			BO_LOCK(bo);
13228 			continue;
13229 		}
13230 		MNT_ILOCK(mp);
13231 		if (mp->mnt_secondary_writes != 0) {
13232 			FREE_LOCK(&lk);
13233 			BO_UNLOCK(bo);
13234 			msleep(&mp->mnt_secondary_writes,
13235 			       MNT_MTX(mp),
13236 			       (PUSER - 1) | PDROP, "secwr", 0);
13237 			BO_LOCK(bo);
13238 			continue;
13239 		}
13240 		break;
13241 	}
13242 
13243 	/*
13244 	 * Reasons for needing more work before suspend:
13245 	 * - Dirty buffers on devvp.
13246 	 * - Softdep activity occurred after start of vnode sync loop
13247 	 * - Secondary writes occurred after start of vnode sync loop
13248 	 */
13249 	error = 0;
13250 	if (bo->bo_numoutput > 0 ||
13251 	    bo->bo_dirty.bv_cnt > 0 ||
13252 	    softdep_deps != 0 ||
13253 	    ump->softdep_deps != 0 ||
13254 	    softdep_accdeps != ump->softdep_accdeps ||
13255 	    secondary_writes != 0 ||
13256 	    mp->mnt_secondary_writes != 0 ||
13257 	    secondary_accwrites != mp->mnt_secondary_accwrites)
13258 		error = EAGAIN;
13259 	FREE_LOCK(&lk);
13260 	BO_UNLOCK(bo);
13261 	return (error);
13262 }
13263 
13264 
13265 /*
13266  * Get the number of dependency structures for the file system, both
13267  * the current number and the total number allocated.  These will
13268  * later be used to detect that softdep processing has occurred.
13269  */
13270 void
13271 softdep_get_depcounts(struct mount *mp,
13272 		      int *softdep_depsp,
13273 		      int *softdep_accdepsp)
13274 {
13275 	struct ufsmount *ump;
13276 
13277 	ump = VFSTOUFS(mp);
13278 	ACQUIRE_LOCK(&lk);
13279 	*softdep_depsp = ump->softdep_deps;
13280 	*softdep_accdepsp = ump->softdep_accdeps;
13281 	FREE_LOCK(&lk);
13282 }
13283 
13284 /*
13285  * Wait for pending output on a vnode to complete.
13286  * Must be called with vnode lock and interlock locked.
13287  *
13288  * XXX: Should just be a call to bufobj_wwait().
13289  */
13290 static void
13291 drain_output(vp)
13292 	struct vnode *vp;
13293 {
13294 	struct bufobj *bo;
13295 
13296 	bo = &vp->v_bufobj;
13297 	ASSERT_VOP_LOCKED(vp, "drain_output");
13298 	ASSERT_BO_LOCKED(bo);
13299 
13300 	while (bo->bo_numoutput) {
13301 		bo->bo_flag |= BO_WWAIT;
13302 		msleep((caddr_t)&bo->bo_numoutput,
13303 		    BO_MTX(bo), PRIBIO + 1, "drainvp", 0);
13304 	}
13305 }
13306 
13307 /*
13308  * Called whenever a buffer that is being invalidated or reallocated
13309  * contains dependencies. This should only happen if an I/O error has
13310  * occurred. The routine is called with the buffer locked.
13311  */
13312 static void
13313 softdep_deallocate_dependencies(bp)
13314 	struct buf *bp;
13315 {
13316 
13317 	if ((bp->b_ioflags & BIO_ERROR) == 0)
13318 		panic("softdep_deallocate_dependencies: dangling deps");
13319 	softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
13320 	panic("softdep_deallocate_dependencies: unrecovered I/O error");
13321 }
13322 
13323 /*
13324  * Function to handle asynchronous write errors in the filesystem.
13325  */
13326 static void
13327 softdep_error(func, error)
13328 	char *func;
13329 	int error;
13330 {
13331 
13332 	/* XXX should do something better! */
13333 	printf("%s: got error %d while accessing filesystem\n", func, error);
13334 }
13335 
13336 #ifdef DDB
13337 
13338 static void
13339 inodedep_print(struct inodedep *inodedep, int verbose)
13340 {
13341 	db_printf("%p fs %p st %x ino %jd inoblk %jd delta %d nlink %d"
13342 	    " saveino %p\n",
13343 	    inodedep, inodedep->id_fs, inodedep->id_state,
13344 	    (intmax_t)inodedep->id_ino,
13345 	    (intmax_t)fsbtodb(inodedep->id_fs,
13346 	    ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
13347 	    inodedep->id_nlinkdelta, inodedep->id_savednlink,
13348 	    inodedep->id_savedino1);
13349 
13350 	if (verbose == 0)
13351 		return;
13352 
13353 	db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
13354 	    "mkdiradd %p\n",
13355 	    LIST_FIRST(&inodedep->id_pendinghd),
13356 	    LIST_FIRST(&inodedep->id_bufwait),
13357 	    LIST_FIRST(&inodedep->id_inowait),
13358 	    TAILQ_FIRST(&inodedep->id_inoreflst),
13359 	    inodedep->id_mkdiradd);
13360 	db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
13361 	    TAILQ_FIRST(&inodedep->id_inoupdt),
13362 	    TAILQ_FIRST(&inodedep->id_newinoupdt),
13363 	    TAILQ_FIRST(&inodedep->id_extupdt),
13364 	    TAILQ_FIRST(&inodedep->id_newextupdt));
13365 }
13366 
13367 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
13368 {
13369 
13370 	if (have_addr == 0) {
13371 		db_printf("Address required\n");
13372 		return;
13373 	}
13374 	inodedep_print((struct inodedep*)addr, 1);
13375 }
13376 
13377 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
13378 {
13379 	struct inodedep_hashhead *inodedephd;
13380 	struct inodedep *inodedep;
13381 	struct fs *fs;
13382 	int cnt;
13383 
13384 	fs = have_addr ? (struct fs *)addr : NULL;
13385 	for (cnt = 0; cnt < inodedep_hash; cnt++) {
13386 		inodedephd = &inodedep_hashtbl[cnt];
13387 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
13388 			if (fs != NULL && fs != inodedep->id_fs)
13389 				continue;
13390 			inodedep_print(inodedep, 0);
13391 		}
13392 	}
13393 }
13394 
13395 DB_SHOW_COMMAND(worklist, db_show_worklist)
13396 {
13397 	struct worklist *wk;
13398 
13399 	if (have_addr == 0) {
13400 		db_printf("Address required\n");
13401 		return;
13402 	}
13403 	wk = (struct worklist *)addr;
13404 	printf("worklist: %p type %s state 0x%X\n",
13405 	    wk, TYPENAME(wk->wk_type), wk->wk_state);
13406 }
13407 
13408 DB_SHOW_COMMAND(workhead, db_show_workhead)
13409 {
13410 	struct workhead *wkhd;
13411 	struct worklist *wk;
13412 	int i;
13413 
13414 	if (have_addr == 0) {
13415 		db_printf("Address required\n");
13416 		return;
13417 	}
13418 	wkhd = (struct workhead *)addr;
13419 	wk = LIST_FIRST(wkhd);
13420 	for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
13421 		db_printf("worklist: %p type %s state 0x%X",
13422 		    wk, TYPENAME(wk->wk_type), wk->wk_state);
13423 	if (i == 100)
13424 		db_printf("workhead overflow");
13425 	printf("\n");
13426 }
13427 
13428 
13429 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
13430 {
13431 	struct jaddref *jaddref;
13432 	struct diradd *diradd;
13433 	struct mkdir *mkdir;
13434 
13435 	LIST_FOREACH(mkdir, &mkdirlisthd, md_mkdirs) {
13436 		diradd = mkdir->md_diradd;
13437 		db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
13438 		    mkdir, mkdir->md_state, diradd, diradd->da_state);
13439 		if ((jaddref = mkdir->md_jaddref) != NULL)
13440 			db_printf(" jaddref %p jaddref state 0x%X",
13441 			    jaddref, jaddref->ja_state);
13442 		db_printf("\n");
13443 	}
13444 }
13445 
13446 #endif /* DDB */
13447 
13448 #endif /* SOFTUPDATES */
13449