xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision ca987d4641cdcd7f27e153db17c5bf064934faf5)
1 /*-
2  * Copyright 1998, 2000 Marshall Kirk McKusick.
3  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
4  * All rights reserved.
5  *
6  * The soft updates code is derived from the appendix of a University
7  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
8  * "Soft Updates: A Solution to the Metadata Update Problem in File
9  * Systems", CSE-TR-254-95, August 1995).
10  *
11  * Further information about soft updates can be obtained from:
12  *
13  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
14  *	1614 Oxford Street		mckusick@mckusick.com
15  *	Berkeley, CA 94709-1608		+1-510-843-9542
16  *	USA
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  *
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  *
39  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
40  */
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include "opt_ffs.h"
46 #include "opt_quota.h"
47 #include "opt_ddb.h"
48 
49 /*
50  * For now we want the safety net that the DEBUG flag provides.
51  */
52 #ifndef DEBUG
53 #define DEBUG
54 #endif
55 
56 #include <sys/param.h>
57 #include <sys/kernel.h>
58 #include <sys/systm.h>
59 #include <sys/bio.h>
60 #include <sys/buf.h>
61 #include <sys/kdb.h>
62 #include <sys/kthread.h>
63 #include <sys/ktr.h>
64 #include <sys/limits.h>
65 #include <sys/lock.h>
66 #include <sys/malloc.h>
67 #include <sys/mount.h>
68 #include <sys/mutex.h>
69 #include <sys/namei.h>
70 #include <sys/priv.h>
71 #include <sys/proc.h>
72 #include <sys/racct.h>
73 #include <sys/rwlock.h>
74 #include <sys/stat.h>
75 #include <sys/sysctl.h>
76 #include <sys/syslog.h>
77 #include <sys/vnode.h>
78 #include <sys/conf.h>
79 
80 #include <ufs/ufs/dir.h>
81 #include <ufs/ufs/extattr.h>
82 #include <ufs/ufs/quota.h>
83 #include <ufs/ufs/inode.h>
84 #include <ufs/ufs/ufsmount.h>
85 #include <ufs/ffs/fs.h>
86 #include <ufs/ffs/softdep.h>
87 #include <ufs/ffs/ffs_extern.h>
88 #include <ufs/ufs/ufs_extern.h>
89 
90 #include <vm/vm.h>
91 #include <vm/vm_extern.h>
92 #include <vm/vm_object.h>
93 
94 #include <geom/geom.h>
95 
96 #include <ddb/ddb.h>
97 
98 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
99 
100 #ifndef SOFTUPDATES
101 
102 int
103 softdep_flushfiles(oldmnt, flags, td)
104 	struct mount *oldmnt;
105 	int flags;
106 	struct thread *td;
107 {
108 
109 	panic("softdep_flushfiles called");
110 }
111 
112 int
113 softdep_mount(devvp, mp, fs, cred)
114 	struct vnode *devvp;
115 	struct mount *mp;
116 	struct fs *fs;
117 	struct ucred *cred;
118 {
119 
120 	return (0);
121 }
122 
123 void
124 softdep_initialize()
125 {
126 
127 	return;
128 }
129 
130 void
131 softdep_uninitialize()
132 {
133 
134 	return;
135 }
136 
137 void
138 softdep_unmount(mp)
139 	struct mount *mp;
140 {
141 
142 	panic("softdep_unmount called");
143 }
144 
145 void
146 softdep_setup_sbupdate(ump, fs, bp)
147 	struct ufsmount *ump;
148 	struct fs *fs;
149 	struct buf *bp;
150 {
151 
152 	panic("softdep_setup_sbupdate called");
153 }
154 
155 void
156 softdep_setup_inomapdep(bp, ip, newinum, mode)
157 	struct buf *bp;
158 	struct inode *ip;
159 	ino_t newinum;
160 	int mode;
161 {
162 
163 	panic("softdep_setup_inomapdep called");
164 }
165 
166 void
167 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
168 	struct buf *bp;
169 	struct mount *mp;
170 	ufs2_daddr_t newblkno;
171 	int frags;
172 	int oldfrags;
173 {
174 
175 	panic("softdep_setup_blkmapdep called");
176 }
177 
178 void
179 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
180 	struct inode *ip;
181 	ufs_lbn_t lbn;
182 	ufs2_daddr_t newblkno;
183 	ufs2_daddr_t oldblkno;
184 	long newsize;
185 	long oldsize;
186 	struct buf *bp;
187 {
188 
189 	panic("softdep_setup_allocdirect called");
190 }
191 
192 void
193 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
194 	struct inode *ip;
195 	ufs_lbn_t lbn;
196 	ufs2_daddr_t newblkno;
197 	ufs2_daddr_t oldblkno;
198 	long newsize;
199 	long oldsize;
200 	struct buf *bp;
201 {
202 
203 	panic("softdep_setup_allocext called");
204 }
205 
206 void
207 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
208 	struct inode *ip;
209 	ufs_lbn_t lbn;
210 	struct buf *bp;
211 	int ptrno;
212 	ufs2_daddr_t newblkno;
213 	ufs2_daddr_t oldblkno;
214 	struct buf *nbp;
215 {
216 
217 	panic("softdep_setup_allocindir_page called");
218 }
219 
220 void
221 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
222 	struct buf *nbp;
223 	struct inode *ip;
224 	struct buf *bp;
225 	int ptrno;
226 	ufs2_daddr_t newblkno;
227 {
228 
229 	panic("softdep_setup_allocindir_meta called");
230 }
231 
232 void
233 softdep_journal_freeblocks(ip, cred, length, flags)
234 	struct inode *ip;
235 	struct ucred *cred;
236 	off_t length;
237 	int flags;
238 {
239 
240 	panic("softdep_journal_freeblocks called");
241 }
242 
243 void
244 softdep_journal_fsync(ip)
245 	struct inode *ip;
246 {
247 
248 	panic("softdep_journal_fsync called");
249 }
250 
251 void
252 softdep_setup_freeblocks(ip, length, flags)
253 	struct inode *ip;
254 	off_t length;
255 	int flags;
256 {
257 
258 	panic("softdep_setup_freeblocks called");
259 }
260 
261 void
262 softdep_freefile(pvp, ino, mode)
263 		struct vnode *pvp;
264 		ino_t ino;
265 		int mode;
266 {
267 
268 	panic("softdep_freefile called");
269 }
270 
271 int
272 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
273 	struct buf *bp;
274 	struct inode *dp;
275 	off_t diroffset;
276 	ino_t newinum;
277 	struct buf *newdirbp;
278 	int isnewblk;
279 {
280 
281 	panic("softdep_setup_directory_add called");
282 }
283 
284 void
285 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
286 	struct buf *bp;
287 	struct inode *dp;
288 	caddr_t base;
289 	caddr_t oldloc;
290 	caddr_t newloc;
291 	int entrysize;
292 {
293 
294 	panic("softdep_change_directoryentry_offset called");
295 }
296 
297 void
298 softdep_setup_remove(bp, dp, ip, isrmdir)
299 	struct buf *bp;
300 	struct inode *dp;
301 	struct inode *ip;
302 	int isrmdir;
303 {
304 
305 	panic("softdep_setup_remove called");
306 }
307 
308 void
309 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
310 	struct buf *bp;
311 	struct inode *dp;
312 	struct inode *ip;
313 	ino_t newinum;
314 	int isrmdir;
315 {
316 
317 	panic("softdep_setup_directory_change called");
318 }
319 
320 void
321 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
322 	struct mount *mp;
323 	struct buf *bp;
324 	ufs2_daddr_t blkno;
325 	int frags;
326 	struct workhead *wkhd;
327 {
328 
329 	panic("%s called", __FUNCTION__);
330 }
331 
332 void
333 softdep_setup_inofree(mp, bp, ino, wkhd)
334 	struct mount *mp;
335 	struct buf *bp;
336 	ino_t ino;
337 	struct workhead *wkhd;
338 {
339 
340 	panic("%s called", __FUNCTION__);
341 }
342 
343 void
344 softdep_setup_unlink(dp, ip)
345 	struct inode *dp;
346 	struct inode *ip;
347 {
348 
349 	panic("%s called", __FUNCTION__);
350 }
351 
352 void
353 softdep_setup_link(dp, ip)
354 	struct inode *dp;
355 	struct inode *ip;
356 {
357 
358 	panic("%s called", __FUNCTION__);
359 }
360 
361 void
362 softdep_revert_link(dp, ip)
363 	struct inode *dp;
364 	struct inode *ip;
365 {
366 
367 	panic("%s called", __FUNCTION__);
368 }
369 
370 void
371 softdep_setup_rmdir(dp, ip)
372 	struct inode *dp;
373 	struct inode *ip;
374 {
375 
376 	panic("%s called", __FUNCTION__);
377 }
378 
379 void
380 softdep_revert_rmdir(dp, ip)
381 	struct inode *dp;
382 	struct inode *ip;
383 {
384 
385 	panic("%s called", __FUNCTION__);
386 }
387 
388 void
389 softdep_setup_create(dp, ip)
390 	struct inode *dp;
391 	struct inode *ip;
392 {
393 
394 	panic("%s called", __FUNCTION__);
395 }
396 
397 void
398 softdep_revert_create(dp, ip)
399 	struct inode *dp;
400 	struct inode *ip;
401 {
402 
403 	panic("%s called", __FUNCTION__);
404 }
405 
406 void
407 softdep_setup_mkdir(dp, ip)
408 	struct inode *dp;
409 	struct inode *ip;
410 {
411 
412 	panic("%s called", __FUNCTION__);
413 }
414 
415 void
416 softdep_revert_mkdir(dp, ip)
417 	struct inode *dp;
418 	struct inode *ip;
419 {
420 
421 	panic("%s called", __FUNCTION__);
422 }
423 
424 void
425 softdep_setup_dotdot_link(dp, ip)
426 	struct inode *dp;
427 	struct inode *ip;
428 {
429 
430 	panic("%s called", __FUNCTION__);
431 }
432 
433 int
434 softdep_prealloc(vp, waitok)
435 	struct vnode *vp;
436 	int waitok;
437 {
438 
439 	panic("%s called", __FUNCTION__);
440 }
441 
442 int
443 softdep_journal_lookup(mp, vpp)
444 	struct mount *mp;
445 	struct vnode **vpp;
446 {
447 
448 	return (ENOENT);
449 }
450 
451 void
452 softdep_change_linkcnt(ip)
453 	struct inode *ip;
454 {
455 
456 	panic("softdep_change_linkcnt called");
457 }
458 
459 void
460 softdep_load_inodeblock(ip)
461 	struct inode *ip;
462 {
463 
464 	panic("softdep_load_inodeblock called");
465 }
466 
467 void
468 softdep_update_inodeblock(ip, bp, waitfor)
469 	struct inode *ip;
470 	struct buf *bp;
471 	int waitfor;
472 {
473 
474 	panic("softdep_update_inodeblock called");
475 }
476 
477 int
478 softdep_fsync(vp)
479 	struct vnode *vp;	/* the "in_core" copy of the inode */
480 {
481 
482 	return (0);
483 }
484 
485 void
486 softdep_fsync_mountdev(vp)
487 	struct vnode *vp;
488 {
489 
490 	return;
491 }
492 
493 int
494 softdep_flushworklist(oldmnt, countp, td)
495 	struct mount *oldmnt;
496 	int *countp;
497 	struct thread *td;
498 {
499 
500 	*countp = 0;
501 	return (0);
502 }
503 
504 int
505 softdep_sync_metadata(struct vnode *vp)
506 {
507 
508 	panic("softdep_sync_metadata called");
509 }
510 
511 int
512 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
513 {
514 
515 	panic("softdep_sync_buf called");
516 }
517 
518 int
519 softdep_slowdown(vp)
520 	struct vnode *vp;
521 {
522 
523 	panic("softdep_slowdown called");
524 }
525 
526 int
527 softdep_request_cleanup(fs, vp, cred, resource)
528 	struct fs *fs;
529 	struct vnode *vp;
530 	struct ucred *cred;
531 	int resource;
532 {
533 
534 	return (0);
535 }
536 
537 int
538 softdep_check_suspend(struct mount *mp,
539 		      struct vnode *devvp,
540 		      int softdep_depcnt,
541 		      int softdep_accdepcnt,
542 		      int secondary_writes,
543 		      int secondary_accwrites)
544 {
545 	struct bufobj *bo;
546 	int error;
547 
548 	(void) softdep_depcnt,
549 	(void) softdep_accdepcnt;
550 
551 	bo = &devvp->v_bufobj;
552 	ASSERT_BO_WLOCKED(bo);
553 
554 	MNT_ILOCK(mp);
555 	while (mp->mnt_secondary_writes != 0) {
556 		BO_UNLOCK(bo);
557 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
558 		    (PUSER - 1) | PDROP, "secwr", 0);
559 		BO_LOCK(bo);
560 		MNT_ILOCK(mp);
561 	}
562 
563 	/*
564 	 * Reasons for needing more work before suspend:
565 	 * - Dirty buffers on devvp.
566 	 * - Secondary writes occurred after start of vnode sync loop
567 	 */
568 	error = 0;
569 	if (bo->bo_numoutput > 0 ||
570 	    bo->bo_dirty.bv_cnt > 0 ||
571 	    secondary_writes != 0 ||
572 	    mp->mnt_secondary_writes != 0 ||
573 	    secondary_accwrites != mp->mnt_secondary_accwrites)
574 		error = EAGAIN;
575 	BO_UNLOCK(bo);
576 	return (error);
577 }
578 
579 void
580 softdep_get_depcounts(struct mount *mp,
581 		      int *softdepactivep,
582 		      int *softdepactiveaccp)
583 {
584 	(void) mp;
585 	*softdepactivep = 0;
586 	*softdepactiveaccp = 0;
587 }
588 
589 void
590 softdep_buf_append(bp, wkhd)
591 	struct buf *bp;
592 	struct workhead *wkhd;
593 {
594 
595 	panic("softdep_buf_appendwork called");
596 }
597 
598 void
599 softdep_inode_append(ip, cred, wkhd)
600 	struct inode *ip;
601 	struct ucred *cred;
602 	struct workhead *wkhd;
603 {
604 
605 	panic("softdep_inode_appendwork called");
606 }
607 
608 void
609 softdep_freework(wkhd)
610 	struct workhead *wkhd;
611 {
612 
613 	panic("softdep_freework called");
614 }
615 
616 #else
617 
618 FEATURE(softupdates, "FFS soft-updates support");
619 
620 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
621     "soft updates stats");
622 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
623     "total dependencies allocated");
624 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
625     "high use dependencies allocated");
626 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
627     "current dependencies allocated");
628 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
629     "current dependencies written");
630 
631 unsigned long dep_current[D_LAST + 1];
632 unsigned long dep_highuse[D_LAST + 1];
633 unsigned long dep_total[D_LAST + 1];
634 unsigned long dep_write[D_LAST + 1];
635 
636 #define	SOFTDEP_TYPE(type, str, long)					\
637     static MALLOC_DEFINE(M_ ## type, #str, long);			\
638     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
639 	&dep_total[D_ ## type], 0, "");					\
640     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
641 	&dep_current[D_ ## type], 0, "");				\
642     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
643 	&dep_highuse[D_ ## type], 0, "");				\
644     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
645 	&dep_write[D_ ## type], 0, "");
646 
647 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
648 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
649 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
650     "Block or frag allocated from cyl group map");
651 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
652 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
653 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
654 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
655 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
656 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
657 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
658 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
659 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
660 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
661 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
662 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
663 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
664 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
665 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
666 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
667 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
668 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
669 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
670 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
671 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
672 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
673 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
674 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
675 
676 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
677 
678 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
679 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
680 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
681 
682 #define M_SOFTDEP_FLAGS	(M_WAITOK)
683 
684 /*
685  * translate from workitem type to memory type
686  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
687  */
688 static struct malloc_type *memtype[] = {
689 	M_PAGEDEP,
690 	M_INODEDEP,
691 	M_BMSAFEMAP,
692 	M_NEWBLK,
693 	M_ALLOCDIRECT,
694 	M_INDIRDEP,
695 	M_ALLOCINDIR,
696 	M_FREEFRAG,
697 	M_FREEBLKS,
698 	M_FREEFILE,
699 	M_DIRADD,
700 	M_MKDIR,
701 	M_DIRREM,
702 	M_NEWDIRBLK,
703 	M_FREEWORK,
704 	M_FREEDEP,
705 	M_JADDREF,
706 	M_JREMREF,
707 	M_JMVREF,
708 	M_JNEWBLK,
709 	M_JFREEBLK,
710 	M_JFREEFRAG,
711 	M_JSEG,
712 	M_JSEGDEP,
713 	M_SBDEP,
714 	M_JTRUNC,
715 	M_JFSYNC,
716 	M_SENTINEL
717 };
718 
719 #define DtoM(type) (memtype[type])
720 
721 /*
722  * Names of malloc types.
723  */
724 #define TYPENAME(type)  \
725 	((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
726 /*
727  * End system adaptation definitions.
728  */
729 
730 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
731 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
732 
733 /*
734  * Internal function prototypes.
735  */
736 static	void check_clear_deps(struct mount *);
737 static	void softdep_error(char *, int);
738 static	int softdep_process_worklist(struct mount *, int);
739 static	int softdep_waitidle(struct mount *, int);
740 static	void drain_output(struct vnode *);
741 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
742 static	int check_inodedep_free(struct inodedep *);
743 static	void clear_remove(struct mount *);
744 static	void clear_inodedeps(struct mount *);
745 static	void unlinked_inodedep(struct mount *, struct inodedep *);
746 static	void clear_unlinked_inodedep(struct inodedep *);
747 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
748 static	int flush_pagedep_deps(struct vnode *, struct mount *,
749 	    struct diraddhd *);
750 static	int free_pagedep(struct pagedep *);
751 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
752 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
753 static	int flush_deplist(struct allocdirectlst *, int, int *);
754 static	int sync_cgs(struct mount *, int);
755 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
756 static	int handle_written_sbdep(struct sbdep *, struct buf *);
757 static	void initiate_write_sbdep(struct sbdep *);
758 static	void diradd_inode_written(struct diradd *, struct inodedep *);
759 static	int handle_written_indirdep(struct indirdep *, struct buf *,
760 	    struct buf**, int);
761 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
762 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
763 	    uint8_t *);
764 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
765 static	void handle_written_jaddref(struct jaddref *);
766 static	void handle_written_jremref(struct jremref *);
767 static	void handle_written_jseg(struct jseg *, struct buf *);
768 static	void handle_written_jnewblk(struct jnewblk *);
769 static	void handle_written_jblkdep(struct jblkdep *);
770 static	void handle_written_jfreefrag(struct jfreefrag *);
771 static	void complete_jseg(struct jseg *);
772 static	void complete_jsegs(struct jseg *);
773 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
774 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
775 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
776 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
777 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
778 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
779 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
780 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
781 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
782 static	inline void inoref_write(struct inoref *, struct jseg *,
783 	    struct jrefrec *);
784 static	void handle_allocdirect_partdone(struct allocdirect *,
785 	    struct workhead *);
786 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
787 	    struct workhead *);
788 static	void indirdep_complete(struct indirdep *);
789 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
790 static	void indirblk_insert(struct freework *);
791 static	void indirblk_remove(struct freework *);
792 static	void handle_allocindir_partdone(struct allocindir *);
793 static	void initiate_write_filepage(struct pagedep *, struct buf *);
794 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
795 static	void handle_written_mkdir(struct mkdir *, int);
796 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
797 	    uint8_t *);
798 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
799 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
800 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
801 static	void handle_workitem_freefile(struct freefile *);
802 static	int handle_workitem_remove(struct dirrem *, int);
803 static	struct dirrem *newdirrem(struct buf *, struct inode *,
804 	    struct inode *, int, struct dirrem **);
805 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
806 	    struct buf *);
807 static	void cancel_indirdep(struct indirdep *, struct buf *,
808 	    struct freeblks *);
809 static	void free_indirdep(struct indirdep *);
810 static	void free_diradd(struct diradd *, struct workhead *);
811 static	void merge_diradd(struct inodedep *, struct diradd *);
812 static	void complete_diradd(struct diradd *);
813 static	struct diradd *diradd_lookup(struct pagedep *, int);
814 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
815 	    struct jremref *);
816 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
817 	    struct jremref *);
818 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
819 	    struct jremref *, struct jremref *);
820 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
821 	    struct jremref *);
822 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
823 	    struct freeblks *, int);
824 static	int setup_trunc_indir(struct freeblks *, struct inode *,
825 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
826 static	void complete_trunc_indir(struct freework *);
827 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
828 	    int);
829 static	void complete_mkdir(struct mkdir *);
830 static	void free_newdirblk(struct newdirblk *);
831 static	void free_jremref(struct jremref *);
832 static	void free_jaddref(struct jaddref *);
833 static	void free_jsegdep(struct jsegdep *);
834 static	void free_jsegs(struct jblocks *);
835 static	void rele_jseg(struct jseg *);
836 static	void free_jseg(struct jseg *, struct jblocks *);
837 static	void free_jnewblk(struct jnewblk *);
838 static	void free_jblkdep(struct jblkdep *);
839 static	void free_jfreefrag(struct jfreefrag *);
840 static	void free_freedep(struct freedep *);
841 static	void journal_jremref(struct dirrem *, struct jremref *,
842 	    struct inodedep *);
843 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
844 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
845 	    struct workhead *);
846 static	void cancel_jfreefrag(struct jfreefrag *);
847 static	inline void setup_freedirect(struct freeblks *, struct inode *,
848 	    int, int);
849 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
850 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
851 	    ufs_lbn_t, int);
852 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
853 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
854 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
855 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
856 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
857 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
858 	    int, int);
859 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
860 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
861 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
862 static	void newblk_freefrag(struct newblk*);
863 static	void free_newblk(struct newblk *);
864 static	void cancel_allocdirect(struct allocdirectlst *,
865 	    struct allocdirect *, struct freeblks *);
866 static	int check_inode_unwritten(struct inodedep *);
867 static	int free_inodedep(struct inodedep *);
868 static	void freework_freeblock(struct freework *);
869 static	void freework_enqueue(struct freework *);
870 static	int handle_workitem_freeblocks(struct freeblks *, int);
871 static	int handle_complete_freeblocks(struct freeblks *, int);
872 static	void handle_workitem_indirblk(struct freework *);
873 static	void handle_written_freework(struct freework *);
874 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
875 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
876 	    struct workhead *);
877 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
878 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
879 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
880 	    ufs2_daddr_t, ufs_lbn_t);
881 static	void handle_workitem_freefrag(struct freefrag *);
882 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
883 	    ufs_lbn_t);
884 static	void allocdirect_merge(struct allocdirectlst *,
885 	    struct allocdirect *, struct allocdirect *);
886 static	struct freefrag *allocindir_merge(struct allocindir *,
887 	    struct allocindir *);
888 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
889 	    struct bmsafemap **);
890 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
891 	    int cg, struct bmsafemap *);
892 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
893 	    struct newblk **);
894 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
895 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
896 	    struct inodedep **);
897 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
898 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
899 	    int, struct pagedep **);
900 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
901 	    struct pagedep **);
902 static	void pause_timer(void *);
903 static	int request_cleanup(struct mount *, int);
904 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
905 static	void schedule_cleanup(struct mount *);
906 static void softdep_ast_cleanup_proc(struct thread *);
907 static	int process_worklist_item(struct mount *, int, int);
908 static	void process_removes(struct vnode *);
909 static	void process_truncates(struct vnode *);
910 static	void jwork_move(struct workhead *, struct workhead *);
911 static	void jwork_insert(struct workhead *, struct jsegdep *);
912 static	void add_to_worklist(struct worklist *, int);
913 static	void wake_worklist(struct worklist *);
914 static	void wait_worklist(struct worklist *, char *);
915 static	void remove_from_worklist(struct worklist *);
916 static	void softdep_flush(void *);
917 static	void softdep_flushjournal(struct mount *);
918 static	int softdep_speedup(struct ufsmount *);
919 static	void worklist_speedup(struct mount *);
920 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
921 static	void journal_unmount(struct ufsmount *);
922 static	int journal_space(struct ufsmount *, int);
923 static	void journal_suspend(struct ufsmount *);
924 static	int journal_unsuspend(struct ufsmount *ump);
925 static	void softdep_prelink(struct vnode *, struct vnode *);
926 static	void add_to_journal(struct worklist *);
927 static	void remove_from_journal(struct worklist *);
928 static	bool softdep_excess_items(struct ufsmount *, int);
929 static	void softdep_process_journal(struct mount *, struct worklist *, int);
930 static	struct jremref *newjremref(struct dirrem *, struct inode *,
931 	    struct inode *ip, off_t, nlink_t);
932 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
933 	    uint16_t);
934 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
935 	    uint16_t);
936 static	inline struct jsegdep *inoref_jseg(struct inoref *);
937 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
938 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
939 	    ufs2_daddr_t, int);
940 static	void adjust_newfreework(struct freeblks *, int);
941 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
942 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
943 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
944 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
945 	    ufs2_daddr_t, long, ufs_lbn_t);
946 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
947 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
948 static	int jwait(struct worklist *, int);
949 static	struct inodedep *inodedep_lookup_ip(struct inode *);
950 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
951 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
952 static	void handle_jwork(struct workhead *);
953 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
954 	    struct mkdir **);
955 static	struct jblocks *jblocks_create(void);
956 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
957 static	void jblocks_free(struct jblocks *, struct mount *, int);
958 static	void jblocks_destroy(struct jblocks *);
959 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
960 
961 /*
962  * Exported softdep operations.
963  */
964 static	void softdep_disk_io_initiation(struct buf *);
965 static	void softdep_disk_write_complete(struct buf *);
966 static	void softdep_deallocate_dependencies(struct buf *);
967 static	int softdep_count_dependencies(struct buf *bp, int);
968 
969 /*
970  * Global lock over all of soft updates.
971  */
972 static struct mtx lk;
973 MTX_SYSINIT(softdep_lock, &lk, "Global Softdep Lock", MTX_DEF);
974 
975 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
976 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
977 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
978 
979 /*
980  * Per-filesystem soft-updates locking.
981  */
982 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
983 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
984 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
985 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
986 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
987 				    RA_WLOCKED)
988 
989 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
990 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
991 
992 /*
993  * Worklist queue management.
994  * These routines require that the lock be held.
995  */
996 #ifndef /* NOT */ DEBUG
997 #define WORKLIST_INSERT(head, item) do {	\
998 	(item)->wk_state |= ONWORKLIST;		\
999 	LIST_INSERT_HEAD(head, item, wk_list);	\
1000 } while (0)
1001 #define WORKLIST_REMOVE(item) do {		\
1002 	(item)->wk_state &= ~ONWORKLIST;	\
1003 	LIST_REMOVE(item, wk_list);		\
1004 } while (0)
1005 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1006 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1007 
1008 #else /* DEBUG */
1009 static	void worklist_insert(struct workhead *, struct worklist *, int);
1010 static	void worklist_remove(struct worklist *, int);
1011 
1012 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1013 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1014 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1015 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1016 
1017 static void
1018 worklist_insert(head, item, locked)
1019 	struct workhead *head;
1020 	struct worklist *item;
1021 	int locked;
1022 {
1023 
1024 	if (locked)
1025 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1026 	if (item->wk_state & ONWORKLIST)
1027 		panic("worklist_insert: %p %s(0x%X) already on list",
1028 		    item, TYPENAME(item->wk_type), item->wk_state);
1029 	item->wk_state |= ONWORKLIST;
1030 	LIST_INSERT_HEAD(head, item, wk_list);
1031 }
1032 
1033 static void
1034 worklist_remove(item, locked)
1035 	struct worklist *item;
1036 	int locked;
1037 {
1038 
1039 	if (locked)
1040 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1041 	if ((item->wk_state & ONWORKLIST) == 0)
1042 		panic("worklist_remove: %p %s(0x%X) not on list",
1043 		    item, TYPENAME(item->wk_type), item->wk_state);
1044 	item->wk_state &= ~ONWORKLIST;
1045 	LIST_REMOVE(item, wk_list);
1046 }
1047 #endif /* DEBUG */
1048 
1049 /*
1050  * Merge two jsegdeps keeping only the oldest one as newer references
1051  * can't be discarded until after older references.
1052  */
1053 static inline struct jsegdep *
1054 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1055 {
1056 	struct jsegdep *swp;
1057 
1058 	if (two == NULL)
1059 		return (one);
1060 
1061 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1062 		swp = one;
1063 		one = two;
1064 		two = swp;
1065 	}
1066 	WORKLIST_REMOVE(&two->jd_list);
1067 	free_jsegdep(two);
1068 
1069 	return (one);
1070 }
1071 
1072 /*
1073  * If two freedeps are compatible free one to reduce list size.
1074  */
1075 static inline struct freedep *
1076 freedep_merge(struct freedep *one, struct freedep *two)
1077 {
1078 	if (two == NULL)
1079 		return (one);
1080 
1081 	if (one->fd_freework == two->fd_freework) {
1082 		WORKLIST_REMOVE(&two->fd_list);
1083 		free_freedep(two);
1084 	}
1085 	return (one);
1086 }
1087 
1088 /*
1089  * Move journal work from one list to another.  Duplicate freedeps and
1090  * jsegdeps are coalesced to keep the lists as small as possible.
1091  */
1092 static void
1093 jwork_move(dst, src)
1094 	struct workhead *dst;
1095 	struct workhead *src;
1096 {
1097 	struct freedep *freedep;
1098 	struct jsegdep *jsegdep;
1099 	struct worklist *wkn;
1100 	struct worklist *wk;
1101 
1102 	KASSERT(dst != src,
1103 	    ("jwork_move: dst == src"));
1104 	freedep = NULL;
1105 	jsegdep = NULL;
1106 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1107 		if (wk->wk_type == D_JSEGDEP)
1108 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1109 		else if (wk->wk_type == D_FREEDEP)
1110 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1111 	}
1112 
1113 	while ((wk = LIST_FIRST(src)) != NULL) {
1114 		WORKLIST_REMOVE(wk);
1115 		WORKLIST_INSERT(dst, wk);
1116 		if (wk->wk_type == D_JSEGDEP) {
1117 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1118 			continue;
1119 		}
1120 		if (wk->wk_type == D_FREEDEP)
1121 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1122 	}
1123 }
1124 
1125 static void
1126 jwork_insert(dst, jsegdep)
1127 	struct workhead *dst;
1128 	struct jsegdep *jsegdep;
1129 {
1130 	struct jsegdep *jsegdepn;
1131 	struct worklist *wk;
1132 
1133 	LIST_FOREACH(wk, dst, wk_list)
1134 		if (wk->wk_type == D_JSEGDEP)
1135 			break;
1136 	if (wk == NULL) {
1137 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1138 		return;
1139 	}
1140 	jsegdepn = WK_JSEGDEP(wk);
1141 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1142 		WORKLIST_REMOVE(wk);
1143 		free_jsegdep(jsegdepn);
1144 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1145 	} else
1146 		free_jsegdep(jsegdep);
1147 }
1148 
1149 /*
1150  * Routines for tracking and managing workitems.
1151  */
1152 static	void workitem_free(struct worklist *, int);
1153 static	void workitem_alloc(struct worklist *, int, struct mount *);
1154 static	void workitem_reassign(struct worklist *, int);
1155 
1156 #define	WORKITEM_FREE(item, type) \
1157 	workitem_free((struct worklist *)(item), (type))
1158 #define	WORKITEM_REASSIGN(item, type) \
1159 	workitem_reassign((struct worklist *)(item), (type))
1160 
1161 static void
1162 workitem_free(item, type)
1163 	struct worklist *item;
1164 	int type;
1165 {
1166 	struct ufsmount *ump;
1167 
1168 #ifdef DEBUG
1169 	if (item->wk_state & ONWORKLIST)
1170 		panic("workitem_free: %s(0x%X) still on list",
1171 		    TYPENAME(item->wk_type), item->wk_state);
1172 	if (item->wk_type != type && type != D_NEWBLK)
1173 		panic("workitem_free: type mismatch %s != %s",
1174 		    TYPENAME(item->wk_type), TYPENAME(type));
1175 #endif
1176 	if (item->wk_state & IOWAITING)
1177 		wakeup(item);
1178 	ump = VFSTOUFS(item->wk_mp);
1179 	LOCK_OWNED(ump);
1180 	KASSERT(ump->softdep_deps > 0,
1181 	    ("workitem_free: %s: softdep_deps going negative",
1182 	    ump->um_fs->fs_fsmnt));
1183 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1184 		wakeup(&ump->softdep_deps);
1185 	KASSERT(dep_current[item->wk_type] > 0,
1186 	    ("workitem_free: %s: dep_current[%s] going negative",
1187 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1188 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1189 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1190 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1191 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1192 	ump->softdep_curdeps[item->wk_type] -= 1;
1193 	free(item, DtoM(type));
1194 }
1195 
1196 static void
1197 workitem_alloc(item, type, mp)
1198 	struct worklist *item;
1199 	int type;
1200 	struct mount *mp;
1201 {
1202 	struct ufsmount *ump;
1203 
1204 	item->wk_type = type;
1205 	item->wk_mp = mp;
1206 	item->wk_state = 0;
1207 
1208 	ump = VFSTOUFS(mp);
1209 	ACQUIRE_GBLLOCK(&lk);
1210 	dep_current[type]++;
1211 	if (dep_current[type] > dep_highuse[type])
1212 		dep_highuse[type] = dep_current[type];
1213 	dep_total[type]++;
1214 	FREE_GBLLOCK(&lk);
1215 	ACQUIRE_LOCK(ump);
1216 	ump->softdep_curdeps[type] += 1;
1217 	ump->softdep_deps++;
1218 	ump->softdep_accdeps++;
1219 	FREE_LOCK(ump);
1220 }
1221 
1222 static void
1223 workitem_reassign(item, newtype)
1224 	struct worklist *item;
1225 	int newtype;
1226 {
1227 	struct ufsmount *ump;
1228 
1229 	ump = VFSTOUFS(item->wk_mp);
1230 	LOCK_OWNED(ump);
1231 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1232 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1233 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1234 	ump->softdep_curdeps[item->wk_type] -= 1;
1235 	ump->softdep_curdeps[newtype] += 1;
1236 	KASSERT(dep_current[item->wk_type] > 0,
1237 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1238 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1239 	ACQUIRE_GBLLOCK(&lk);
1240 	dep_current[newtype]++;
1241 	dep_current[item->wk_type]--;
1242 	if (dep_current[newtype] > dep_highuse[newtype])
1243 		dep_highuse[newtype] = dep_current[newtype];
1244 	dep_total[newtype]++;
1245 	FREE_GBLLOCK(&lk);
1246 	item->wk_type = newtype;
1247 }
1248 
1249 /*
1250  * Workitem queue management
1251  */
1252 static int max_softdeps;	/* maximum number of structs before slowdown */
1253 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1254 static int proc_waiting;	/* tracks whether we have a timeout posted */
1255 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1256 static struct callout softdep_callout;
1257 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1258 static int req_clear_remove;	/* syncer process flush some freeblks */
1259 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1260 
1261 /*
1262  * runtime statistics
1263  */
1264 static int stat_flush_threads;	/* number of softdep flushing threads */
1265 static int stat_worklist_push;	/* number of worklist cleanups */
1266 static int stat_blk_limit_push;	/* number of times block limit neared */
1267 static int stat_ino_limit_push;	/* number of times inode limit neared */
1268 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1269 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1270 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1271 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1272 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1273 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1274 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1275 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1276 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1277 static int stat_journal_min;	/* Times hit journal min threshold */
1278 static int stat_journal_low;	/* Times hit journal low threshold */
1279 static int stat_journal_wait;	/* Times blocked in jwait(). */
1280 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1281 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1282 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1283 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1284 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1285 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1286 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1287 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1288 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1289 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1290 
1291 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1292     &max_softdeps, 0, "");
1293 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1294     &tickdelay, 0, "");
1295 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1296     &stat_flush_threads, 0, "");
1297 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1298     &stat_worklist_push, 0,"");
1299 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1300     &stat_blk_limit_push, 0,"");
1301 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1302     &stat_ino_limit_push, 0,"");
1303 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1304     &stat_blk_limit_hit, 0, "");
1305 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1306     &stat_ino_limit_hit, 0, "");
1307 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1308     &stat_sync_limit_hit, 0, "");
1309 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1310     &stat_indir_blk_ptrs, 0, "");
1311 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1312     &stat_inode_bitmap, 0, "");
1313 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1314     &stat_direct_blk_ptrs, 0, "");
1315 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1316     &stat_dir_entry, 0, "");
1317 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1318     &stat_jaddref, 0, "");
1319 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1320     &stat_jnewblk, 0, "");
1321 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1322     &stat_journal_low, 0, "");
1323 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1324     &stat_journal_min, 0, "");
1325 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1326     &stat_journal_wait, 0, "");
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1328     &stat_jwait_filepage, 0, "");
1329 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1330     &stat_jwait_freeblks, 0, "");
1331 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1332     &stat_jwait_inode, 0, "");
1333 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1334     &stat_jwait_newblk, 0, "");
1335 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1336     &stat_cleanup_blkrequests, 0, "");
1337 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1338     &stat_cleanup_inorequests, 0, "");
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1340     &stat_cleanup_high_delay, 0, "");
1341 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1342     &stat_cleanup_retries, 0, "");
1343 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1344     &stat_cleanup_failures, 0, "");
1345 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1346     &softdep_flushcache, 0, "");
1347 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1348     &stat_emptyjblocks, 0, "");
1349 
1350 SYSCTL_DECL(_vfs_ffs);
1351 
1352 /* Whether to recompute the summary at mount time */
1353 static int compute_summary_at_mount = 0;
1354 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1355 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1356 static int print_threads = 0;
1357 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1358     &print_threads, 0, "Notify flusher thread start/stop");
1359 
1360 /* List of all filesystems mounted with soft updates */
1361 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1362 
1363 /*
1364  * This function cleans the worklist for a filesystem.
1365  * Each filesystem running with soft dependencies gets its own
1366  * thread to run in this function. The thread is started up in
1367  * softdep_mount and shutdown in softdep_unmount. They show up
1368  * as part of the kernel "bufdaemon" process whose process
1369  * entry is available in bufdaemonproc.
1370  */
1371 static int searchfailed;
1372 extern struct proc *bufdaemonproc;
1373 static void
1374 softdep_flush(addr)
1375 	void *addr;
1376 {
1377 	struct mount *mp;
1378 	struct thread *td;
1379 	struct ufsmount *ump;
1380 
1381 	td = curthread;
1382 	td->td_pflags |= TDP_NORUNNINGBUF;
1383 	mp = (struct mount *)addr;
1384 	ump = VFSTOUFS(mp);
1385 	atomic_add_int(&stat_flush_threads, 1);
1386 	ACQUIRE_LOCK(ump);
1387 	ump->softdep_flags &= ~FLUSH_STARTING;
1388 	wakeup(&ump->softdep_flushtd);
1389 	FREE_LOCK(ump);
1390 	if (print_threads) {
1391 		if (stat_flush_threads == 1)
1392 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1393 			    bufdaemonproc->p_pid);
1394 		printf("Start thread %s\n", td->td_name);
1395 	}
1396 	for (;;) {
1397 		while (softdep_process_worklist(mp, 0) > 0 ||
1398 		    (MOUNTEDSUJ(mp) &&
1399 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1400 			kthread_suspend_check();
1401 		ACQUIRE_LOCK(ump);
1402 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1403 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1404 			    "sdflush", hz / 2);
1405 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1406 		/*
1407 		 * Check to see if we are done and need to exit.
1408 		 */
1409 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1410 			FREE_LOCK(ump);
1411 			continue;
1412 		}
1413 		ump->softdep_flags &= ~FLUSH_EXIT;
1414 		FREE_LOCK(ump);
1415 		wakeup(&ump->softdep_flags);
1416 		if (print_threads)
1417 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1418 		atomic_subtract_int(&stat_flush_threads, 1);
1419 		kthread_exit();
1420 		panic("kthread_exit failed\n");
1421 	}
1422 }
1423 
1424 static void
1425 worklist_speedup(mp)
1426 	struct mount *mp;
1427 {
1428 	struct ufsmount *ump;
1429 
1430 	ump = VFSTOUFS(mp);
1431 	LOCK_OWNED(ump);
1432 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1433 		ump->softdep_flags |= FLUSH_CLEANUP;
1434 	wakeup(&ump->softdep_flushtd);
1435 }
1436 
1437 static int
1438 softdep_speedup(ump)
1439 	struct ufsmount *ump;
1440 {
1441 	struct ufsmount *altump;
1442 	struct mount_softdeps *sdp;
1443 
1444 	LOCK_OWNED(ump);
1445 	worklist_speedup(ump->um_mountp);
1446 	bd_speedup();
1447 	/*
1448 	 * If we have global shortages, then we need other
1449 	 * filesystems to help with the cleanup. Here we wakeup a
1450 	 * flusher thread for a filesystem that is over its fair
1451 	 * share of resources.
1452 	 */
1453 	if (req_clear_inodedeps || req_clear_remove) {
1454 		ACQUIRE_GBLLOCK(&lk);
1455 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1456 			if ((altump = sdp->sd_ump) == ump)
1457 				continue;
1458 			if (((req_clear_inodedeps &&
1459 			    altump->softdep_curdeps[D_INODEDEP] >
1460 			    max_softdeps / stat_flush_threads) ||
1461 			    (req_clear_remove &&
1462 			    altump->softdep_curdeps[D_DIRREM] >
1463 			    (max_softdeps / 2) / stat_flush_threads)) &&
1464 			    TRY_ACQUIRE_LOCK(altump))
1465 				break;
1466 		}
1467 		if (sdp == NULL) {
1468 			searchfailed++;
1469 			FREE_GBLLOCK(&lk);
1470 		} else {
1471 			/*
1472 			 * Move to the end of the list so we pick a
1473 			 * different one on out next try.
1474 			 */
1475 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1476 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1477 			FREE_GBLLOCK(&lk);
1478 			if ((altump->softdep_flags &
1479 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1480 				altump->softdep_flags |= FLUSH_CLEANUP;
1481 			altump->um_softdep->sd_cleanups++;
1482 			wakeup(&altump->softdep_flushtd);
1483 			FREE_LOCK(altump);
1484 		}
1485 	}
1486 	return (speedup_syncer());
1487 }
1488 
1489 /*
1490  * Add an item to the end of the work queue.
1491  * This routine requires that the lock be held.
1492  * This is the only routine that adds items to the list.
1493  * The following routine is the only one that removes items
1494  * and does so in order from first to last.
1495  */
1496 
1497 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1498 #define	WK_NODELAY	0x0002	/* Process immediately. */
1499 
1500 static void
1501 add_to_worklist(wk, flags)
1502 	struct worklist *wk;
1503 	int flags;
1504 {
1505 	struct ufsmount *ump;
1506 
1507 	ump = VFSTOUFS(wk->wk_mp);
1508 	LOCK_OWNED(ump);
1509 	if (wk->wk_state & ONWORKLIST)
1510 		panic("add_to_worklist: %s(0x%X) already on list",
1511 		    TYPENAME(wk->wk_type), wk->wk_state);
1512 	wk->wk_state |= ONWORKLIST;
1513 	if (ump->softdep_on_worklist == 0) {
1514 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1515 		ump->softdep_worklist_tail = wk;
1516 	} else if (flags & WK_HEAD) {
1517 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1518 	} else {
1519 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1520 		ump->softdep_worklist_tail = wk;
1521 	}
1522 	ump->softdep_on_worklist += 1;
1523 	if (flags & WK_NODELAY)
1524 		worklist_speedup(wk->wk_mp);
1525 }
1526 
1527 /*
1528  * Remove the item to be processed. If we are removing the last
1529  * item on the list, we need to recalculate the tail pointer.
1530  */
1531 static void
1532 remove_from_worklist(wk)
1533 	struct worklist *wk;
1534 {
1535 	struct ufsmount *ump;
1536 
1537 	ump = VFSTOUFS(wk->wk_mp);
1538 	if (ump->softdep_worklist_tail == wk)
1539 		ump->softdep_worklist_tail =
1540 		    (struct worklist *)wk->wk_list.le_prev;
1541 	WORKLIST_REMOVE(wk);
1542 	ump->softdep_on_worklist -= 1;
1543 }
1544 
1545 static void
1546 wake_worklist(wk)
1547 	struct worklist *wk;
1548 {
1549 	if (wk->wk_state & IOWAITING) {
1550 		wk->wk_state &= ~IOWAITING;
1551 		wakeup(wk);
1552 	}
1553 }
1554 
1555 static void
1556 wait_worklist(wk, wmesg)
1557 	struct worklist *wk;
1558 	char *wmesg;
1559 {
1560 	struct ufsmount *ump;
1561 
1562 	ump = VFSTOUFS(wk->wk_mp);
1563 	wk->wk_state |= IOWAITING;
1564 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1565 }
1566 
1567 /*
1568  * Process that runs once per second to handle items in the background queue.
1569  *
1570  * Note that we ensure that everything is done in the order in which they
1571  * appear in the queue. The code below depends on this property to ensure
1572  * that blocks of a file are freed before the inode itself is freed. This
1573  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1574  * until all the old ones have been purged from the dependency lists.
1575  */
1576 static int
1577 softdep_process_worklist(mp, full)
1578 	struct mount *mp;
1579 	int full;
1580 {
1581 	int cnt, matchcnt;
1582 	struct ufsmount *ump;
1583 	long starttime;
1584 
1585 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1586 	if (MOUNTEDSOFTDEP(mp) == 0)
1587 		return (0);
1588 	matchcnt = 0;
1589 	ump = VFSTOUFS(mp);
1590 	ACQUIRE_LOCK(ump);
1591 	starttime = time_second;
1592 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1593 	check_clear_deps(mp);
1594 	while (ump->softdep_on_worklist > 0) {
1595 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1596 			break;
1597 		else
1598 			matchcnt += cnt;
1599 		check_clear_deps(mp);
1600 		/*
1601 		 * We do not generally want to stop for buffer space, but if
1602 		 * we are really being a buffer hog, we will stop and wait.
1603 		 */
1604 		if (should_yield()) {
1605 			FREE_LOCK(ump);
1606 			kern_yield(PRI_USER);
1607 			bwillwrite();
1608 			ACQUIRE_LOCK(ump);
1609 		}
1610 		/*
1611 		 * Never allow processing to run for more than one
1612 		 * second. This gives the syncer thread the opportunity
1613 		 * to pause if appropriate.
1614 		 */
1615 		if (!full && starttime != time_second)
1616 			break;
1617 	}
1618 	if (full == 0)
1619 		journal_unsuspend(ump);
1620 	FREE_LOCK(ump);
1621 	return (matchcnt);
1622 }
1623 
1624 /*
1625  * Process all removes associated with a vnode if we are running out of
1626  * journal space.  Any other process which attempts to flush these will
1627  * be unable as we have the vnodes locked.
1628  */
1629 static void
1630 process_removes(vp)
1631 	struct vnode *vp;
1632 {
1633 	struct inodedep *inodedep;
1634 	struct dirrem *dirrem;
1635 	struct ufsmount *ump;
1636 	struct mount *mp;
1637 	ino_t inum;
1638 
1639 	mp = vp->v_mount;
1640 	ump = VFSTOUFS(mp);
1641 	LOCK_OWNED(ump);
1642 	inum = VTOI(vp)->i_number;
1643 	for (;;) {
1644 top:
1645 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1646 			return;
1647 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1648 			/*
1649 			 * If another thread is trying to lock this vnode
1650 			 * it will fail but we must wait for it to do so
1651 			 * before we can proceed.
1652 			 */
1653 			if (dirrem->dm_state & INPROGRESS) {
1654 				wait_worklist(&dirrem->dm_list, "pwrwait");
1655 				goto top;
1656 			}
1657 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1658 			    (COMPLETE | ONWORKLIST))
1659 				break;
1660 		}
1661 		if (dirrem == NULL)
1662 			return;
1663 		remove_from_worklist(&dirrem->dm_list);
1664 		FREE_LOCK(ump);
1665 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1666 			panic("process_removes: suspended filesystem");
1667 		handle_workitem_remove(dirrem, 0);
1668 		vn_finished_secondary_write(mp);
1669 		ACQUIRE_LOCK(ump);
1670 	}
1671 }
1672 
1673 /*
1674  * Process all truncations associated with a vnode if we are running out
1675  * of journal space.  This is called when the vnode lock is already held
1676  * and no other process can clear the truncation.  This function returns
1677  * a value greater than zero if it did any work.
1678  */
1679 static void
1680 process_truncates(vp)
1681 	struct vnode *vp;
1682 {
1683 	struct inodedep *inodedep;
1684 	struct freeblks *freeblks;
1685 	struct ufsmount *ump;
1686 	struct mount *mp;
1687 	ino_t inum;
1688 	int cgwait;
1689 
1690 	mp = vp->v_mount;
1691 	ump = VFSTOUFS(mp);
1692 	LOCK_OWNED(ump);
1693 	inum = VTOI(vp)->i_number;
1694 	for (;;) {
1695 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1696 			return;
1697 		cgwait = 0;
1698 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1699 			/* Journal entries not yet written.  */
1700 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1701 				jwait(&LIST_FIRST(
1702 				    &freeblks->fb_jblkdephd)->jb_list,
1703 				    MNT_WAIT);
1704 				break;
1705 			}
1706 			/* Another thread is executing this item. */
1707 			if (freeblks->fb_state & INPROGRESS) {
1708 				wait_worklist(&freeblks->fb_list, "ptrwait");
1709 				break;
1710 			}
1711 			/* Freeblks is waiting on a inode write. */
1712 			if ((freeblks->fb_state & COMPLETE) == 0) {
1713 				FREE_LOCK(ump);
1714 				ffs_update(vp, 1);
1715 				ACQUIRE_LOCK(ump);
1716 				break;
1717 			}
1718 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1719 			    (ALLCOMPLETE | ONWORKLIST)) {
1720 				remove_from_worklist(&freeblks->fb_list);
1721 				freeblks->fb_state |= INPROGRESS;
1722 				FREE_LOCK(ump);
1723 				if (vn_start_secondary_write(NULL, &mp,
1724 				    V_NOWAIT))
1725 					panic("process_truncates: "
1726 					    "suspended filesystem");
1727 				handle_workitem_freeblocks(freeblks, 0);
1728 				vn_finished_secondary_write(mp);
1729 				ACQUIRE_LOCK(ump);
1730 				break;
1731 			}
1732 			if (freeblks->fb_cgwait)
1733 				cgwait++;
1734 		}
1735 		if (cgwait) {
1736 			FREE_LOCK(ump);
1737 			sync_cgs(mp, MNT_WAIT);
1738 			ffs_sync_snap(mp, MNT_WAIT);
1739 			ACQUIRE_LOCK(ump);
1740 			continue;
1741 		}
1742 		if (freeblks == NULL)
1743 			break;
1744 	}
1745 	return;
1746 }
1747 
1748 /*
1749  * Process one item on the worklist.
1750  */
1751 static int
1752 process_worklist_item(mp, target, flags)
1753 	struct mount *mp;
1754 	int target;
1755 	int flags;
1756 {
1757 	struct worklist sentinel;
1758 	struct worklist *wk;
1759 	struct ufsmount *ump;
1760 	int matchcnt;
1761 	int error;
1762 
1763 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1764 	/*
1765 	 * If we are being called because of a process doing a
1766 	 * copy-on-write, then it is not safe to write as we may
1767 	 * recurse into the copy-on-write routine.
1768 	 */
1769 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1770 		return (-1);
1771 	PHOLD(curproc);	/* Don't let the stack go away. */
1772 	ump = VFSTOUFS(mp);
1773 	LOCK_OWNED(ump);
1774 	matchcnt = 0;
1775 	sentinel.wk_mp = NULL;
1776 	sentinel.wk_type = D_SENTINEL;
1777 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1778 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1779 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1780 		if (wk->wk_type == D_SENTINEL) {
1781 			LIST_REMOVE(&sentinel, wk_list);
1782 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1783 			continue;
1784 		}
1785 		if (wk->wk_state & INPROGRESS)
1786 			panic("process_worklist_item: %p already in progress.",
1787 			    wk);
1788 		wk->wk_state |= INPROGRESS;
1789 		remove_from_worklist(wk);
1790 		FREE_LOCK(ump);
1791 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1792 			panic("process_worklist_item: suspended filesystem");
1793 		switch (wk->wk_type) {
1794 		case D_DIRREM:
1795 			/* removal of a directory entry */
1796 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1797 			break;
1798 
1799 		case D_FREEBLKS:
1800 			/* releasing blocks and/or fragments from a file */
1801 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1802 			    flags);
1803 			break;
1804 
1805 		case D_FREEFRAG:
1806 			/* releasing a fragment when replaced as a file grows */
1807 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1808 			error = 0;
1809 			break;
1810 
1811 		case D_FREEFILE:
1812 			/* releasing an inode when its link count drops to 0 */
1813 			handle_workitem_freefile(WK_FREEFILE(wk));
1814 			error = 0;
1815 			break;
1816 
1817 		default:
1818 			panic("%s_process_worklist: Unknown type %s",
1819 			    "softdep", TYPENAME(wk->wk_type));
1820 			/* NOTREACHED */
1821 		}
1822 		vn_finished_secondary_write(mp);
1823 		ACQUIRE_LOCK(ump);
1824 		if (error == 0) {
1825 			if (++matchcnt == target)
1826 				break;
1827 			continue;
1828 		}
1829 		/*
1830 		 * We have to retry the worklist item later.  Wake up any
1831 		 * waiters who may be able to complete it immediately and
1832 		 * add the item back to the head so we don't try to execute
1833 		 * it again.
1834 		 */
1835 		wk->wk_state &= ~INPROGRESS;
1836 		wake_worklist(wk);
1837 		add_to_worklist(wk, WK_HEAD);
1838 	}
1839 	/* Sentinal could've become the tail from remove_from_worklist. */
1840 	if (ump->softdep_worklist_tail == &sentinel)
1841 		ump->softdep_worklist_tail =
1842 		    (struct worklist *)sentinel.wk_list.le_prev;
1843 	LIST_REMOVE(&sentinel, wk_list);
1844 	PRELE(curproc);
1845 	return (matchcnt);
1846 }
1847 
1848 /*
1849  * Move dependencies from one buffer to another.
1850  */
1851 int
1852 softdep_move_dependencies(oldbp, newbp)
1853 	struct buf *oldbp;
1854 	struct buf *newbp;
1855 {
1856 	struct worklist *wk, *wktail;
1857 	struct ufsmount *ump;
1858 	int dirty;
1859 
1860 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1861 		return (0);
1862 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1863 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1864 	dirty = 0;
1865 	wktail = NULL;
1866 	ump = VFSTOUFS(wk->wk_mp);
1867 	ACQUIRE_LOCK(ump);
1868 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1869 		LIST_REMOVE(wk, wk_list);
1870 		if (wk->wk_type == D_BMSAFEMAP &&
1871 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1872 			dirty = 1;
1873 		if (wktail == NULL)
1874 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1875 		else
1876 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1877 		wktail = wk;
1878 	}
1879 	FREE_LOCK(ump);
1880 
1881 	return (dirty);
1882 }
1883 
1884 /*
1885  * Purge the work list of all items associated with a particular mount point.
1886  */
1887 int
1888 softdep_flushworklist(oldmnt, countp, td)
1889 	struct mount *oldmnt;
1890 	int *countp;
1891 	struct thread *td;
1892 {
1893 	struct vnode *devvp;
1894 	struct ufsmount *ump;
1895 	int count, error;
1896 
1897 	/*
1898 	 * Alternately flush the block device associated with the mount
1899 	 * point and process any dependencies that the flushing
1900 	 * creates. We continue until no more worklist dependencies
1901 	 * are found.
1902 	 */
1903 	*countp = 0;
1904 	error = 0;
1905 	ump = VFSTOUFS(oldmnt);
1906 	devvp = ump->um_devvp;
1907 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1908 		*countp += count;
1909 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1910 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1911 		VOP_UNLOCK(devvp, 0);
1912 		if (error != 0)
1913 			break;
1914 	}
1915 	return (error);
1916 }
1917 
1918 #define	SU_WAITIDLE_RETRIES	20
1919 static int
1920 softdep_waitidle(struct mount *mp, int flags __unused)
1921 {
1922 	struct ufsmount *ump;
1923 	struct vnode *devvp;
1924 	struct thread *td;
1925 	int error, i;
1926 
1927 	ump = VFSTOUFS(mp);
1928 	devvp = ump->um_devvp;
1929 	td = curthread;
1930 	error = 0;
1931 	ACQUIRE_LOCK(ump);
1932 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1933 		ump->softdep_req = 1;
1934 		KASSERT((flags & FORCECLOSE) == 0 ||
1935 		    ump->softdep_on_worklist == 0,
1936 		    ("softdep_waitidle: work added after flush"));
1937 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1938 		    "softdeps", 10 * hz);
1939 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1940 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1941 		VOP_UNLOCK(devvp, 0);
1942 		ACQUIRE_LOCK(ump);
1943 		if (error != 0)
1944 			break;
1945 	}
1946 	ump->softdep_req = 0;
1947 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1948 		error = EBUSY;
1949 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1950 		    mp);
1951 	}
1952 	FREE_LOCK(ump);
1953 	return (error);
1954 }
1955 
1956 /*
1957  * Flush all vnodes and worklist items associated with a specified mount point.
1958  */
1959 int
1960 softdep_flushfiles(oldmnt, flags, td)
1961 	struct mount *oldmnt;
1962 	int flags;
1963 	struct thread *td;
1964 {
1965 #ifdef QUOTA
1966 	struct ufsmount *ump;
1967 	int i;
1968 #endif
1969 	int error, early, depcount, loopcnt, retry_flush_count, retry;
1970 	int morework;
1971 
1972 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1973 	    ("softdep_flushfiles called on non-softdep filesystem"));
1974 	loopcnt = 10;
1975 	retry_flush_count = 3;
1976 retry_flush:
1977 	error = 0;
1978 
1979 	/*
1980 	 * Alternately flush the vnodes associated with the mount
1981 	 * point and process any dependencies that the flushing
1982 	 * creates. In theory, this loop can happen at most twice,
1983 	 * but we give it a few extra just to be sure.
1984 	 */
1985 	for (; loopcnt > 0; loopcnt--) {
1986 		/*
1987 		 * Do another flush in case any vnodes were brought in
1988 		 * as part of the cleanup operations.
1989 		 */
1990 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
1991 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
1992 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
1993 			break;
1994 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1995 		    depcount == 0)
1996 			break;
1997 	}
1998 	/*
1999 	 * If we are unmounting then it is an error to fail. If we
2000 	 * are simply trying to downgrade to read-only, then filesystem
2001 	 * activity can keep us busy forever, so we just fail with EBUSY.
2002 	 */
2003 	if (loopcnt == 0) {
2004 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2005 			panic("softdep_flushfiles: looping");
2006 		error = EBUSY;
2007 	}
2008 	if (!error)
2009 		error = softdep_waitidle(oldmnt, flags);
2010 	if (!error) {
2011 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2012 			retry = 0;
2013 			MNT_ILOCK(oldmnt);
2014 			KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
2015 			    ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
2016 			morework = oldmnt->mnt_nvnodelistsize > 0;
2017 #ifdef QUOTA
2018 			ump = VFSTOUFS(oldmnt);
2019 			UFS_LOCK(ump);
2020 			for (i = 0; i < MAXQUOTAS; i++) {
2021 				if (ump->um_quotas[i] != NULLVP)
2022 					morework = 1;
2023 			}
2024 			UFS_UNLOCK(ump);
2025 #endif
2026 			if (morework) {
2027 				if (--retry_flush_count > 0) {
2028 					retry = 1;
2029 					loopcnt = 3;
2030 				} else
2031 					error = EBUSY;
2032 			}
2033 			MNT_IUNLOCK(oldmnt);
2034 			if (retry)
2035 				goto retry_flush;
2036 		}
2037 	}
2038 	return (error);
2039 }
2040 
2041 /*
2042  * Structure hashing.
2043  *
2044  * There are four types of structures that can be looked up:
2045  *	1) pagedep structures identified by mount point, inode number,
2046  *	   and logical block.
2047  *	2) inodedep structures identified by mount point and inode number.
2048  *	3) newblk structures identified by mount point and
2049  *	   physical block number.
2050  *	4) bmsafemap structures identified by mount point and
2051  *	   cylinder group number.
2052  *
2053  * The "pagedep" and "inodedep" dependency structures are hashed
2054  * separately from the file blocks and inodes to which they correspond.
2055  * This separation helps when the in-memory copy of an inode or
2056  * file block must be replaced. It also obviates the need to access
2057  * an inode or file page when simply updating (or de-allocating)
2058  * dependency structures. Lookup of newblk structures is needed to
2059  * find newly allocated blocks when trying to associate them with
2060  * their allocdirect or allocindir structure.
2061  *
2062  * The lookup routines optionally create and hash a new instance when
2063  * an existing entry is not found. The bmsafemap lookup routine always
2064  * allocates a new structure if an existing one is not found.
2065  */
2066 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2067 
2068 /*
2069  * Structures and routines associated with pagedep caching.
2070  */
2071 #define	PAGEDEP_HASH(ump, inum, lbn) \
2072 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2073 
2074 static int
2075 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2076 	struct pagedep_hashhead *pagedephd;
2077 	ino_t ino;
2078 	ufs_lbn_t lbn;
2079 	struct pagedep **pagedeppp;
2080 {
2081 	struct pagedep *pagedep;
2082 
2083 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2084 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2085 			*pagedeppp = pagedep;
2086 			return (1);
2087 		}
2088 	}
2089 	*pagedeppp = NULL;
2090 	return (0);
2091 }
2092 /*
2093  * Look up a pagedep. Return 1 if found, 0 otherwise.
2094  * If not found, allocate if DEPALLOC flag is passed.
2095  * Found or allocated entry is returned in pagedeppp.
2096  * This routine must be called with splbio interrupts blocked.
2097  */
2098 static int
2099 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2100 	struct mount *mp;
2101 	struct buf *bp;
2102 	ino_t ino;
2103 	ufs_lbn_t lbn;
2104 	int flags;
2105 	struct pagedep **pagedeppp;
2106 {
2107 	struct pagedep *pagedep;
2108 	struct pagedep_hashhead *pagedephd;
2109 	struct worklist *wk;
2110 	struct ufsmount *ump;
2111 	int ret;
2112 	int i;
2113 
2114 	ump = VFSTOUFS(mp);
2115 	LOCK_OWNED(ump);
2116 	if (bp) {
2117 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2118 			if (wk->wk_type == D_PAGEDEP) {
2119 				*pagedeppp = WK_PAGEDEP(wk);
2120 				return (1);
2121 			}
2122 		}
2123 	}
2124 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2125 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2126 	if (ret) {
2127 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2128 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2129 		return (1);
2130 	}
2131 	if ((flags & DEPALLOC) == 0)
2132 		return (0);
2133 	FREE_LOCK(ump);
2134 	pagedep = malloc(sizeof(struct pagedep),
2135 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2136 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2137 	ACQUIRE_LOCK(ump);
2138 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2139 	if (*pagedeppp) {
2140 		/*
2141 		 * This should never happen since we only create pagedeps
2142 		 * with the vnode lock held.  Could be an assert.
2143 		 */
2144 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2145 		return (ret);
2146 	}
2147 	pagedep->pd_ino = ino;
2148 	pagedep->pd_lbn = lbn;
2149 	LIST_INIT(&pagedep->pd_dirremhd);
2150 	LIST_INIT(&pagedep->pd_pendinghd);
2151 	for (i = 0; i < DAHASHSZ; i++)
2152 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2153 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2154 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2155 	*pagedeppp = pagedep;
2156 	return (0);
2157 }
2158 
2159 /*
2160  * Structures and routines associated with inodedep caching.
2161  */
2162 #define	INODEDEP_HASH(ump, inum) \
2163       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2164 
2165 static int
2166 inodedep_find(inodedephd, inum, inodedeppp)
2167 	struct inodedep_hashhead *inodedephd;
2168 	ino_t inum;
2169 	struct inodedep **inodedeppp;
2170 {
2171 	struct inodedep *inodedep;
2172 
2173 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2174 		if (inum == inodedep->id_ino)
2175 			break;
2176 	if (inodedep) {
2177 		*inodedeppp = inodedep;
2178 		return (1);
2179 	}
2180 	*inodedeppp = NULL;
2181 
2182 	return (0);
2183 }
2184 /*
2185  * Look up an inodedep. Return 1 if found, 0 if not found.
2186  * If not found, allocate if DEPALLOC flag is passed.
2187  * Found or allocated entry is returned in inodedeppp.
2188  * This routine must be called with splbio interrupts blocked.
2189  */
2190 static int
2191 inodedep_lookup(mp, inum, flags, inodedeppp)
2192 	struct mount *mp;
2193 	ino_t inum;
2194 	int flags;
2195 	struct inodedep **inodedeppp;
2196 {
2197 	struct inodedep *inodedep;
2198 	struct inodedep_hashhead *inodedephd;
2199 	struct ufsmount *ump;
2200 	struct fs *fs;
2201 
2202 	ump = VFSTOUFS(mp);
2203 	LOCK_OWNED(ump);
2204 	fs = ump->um_fs;
2205 	inodedephd = INODEDEP_HASH(ump, inum);
2206 
2207 	if (inodedep_find(inodedephd, inum, inodedeppp))
2208 		return (1);
2209 	if ((flags & DEPALLOC) == 0)
2210 		return (0);
2211 	/*
2212 	 * If the system is over its limit and our filesystem is
2213 	 * responsible for more than our share of that usage and
2214 	 * we are not in a rush, request some inodedep cleanup.
2215 	 */
2216 	if (softdep_excess_items(ump, D_INODEDEP))
2217 		schedule_cleanup(mp);
2218 	else
2219 		FREE_LOCK(ump);
2220 	inodedep = malloc(sizeof(struct inodedep),
2221 		M_INODEDEP, M_SOFTDEP_FLAGS);
2222 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2223 	ACQUIRE_LOCK(ump);
2224 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2225 		WORKITEM_FREE(inodedep, D_INODEDEP);
2226 		return (1);
2227 	}
2228 	inodedep->id_fs = fs;
2229 	inodedep->id_ino = inum;
2230 	inodedep->id_state = ALLCOMPLETE;
2231 	inodedep->id_nlinkdelta = 0;
2232 	inodedep->id_savedino1 = NULL;
2233 	inodedep->id_savedsize = -1;
2234 	inodedep->id_savedextsize = -1;
2235 	inodedep->id_savednlink = -1;
2236 	inodedep->id_bmsafemap = NULL;
2237 	inodedep->id_mkdiradd = NULL;
2238 	LIST_INIT(&inodedep->id_dirremhd);
2239 	LIST_INIT(&inodedep->id_pendinghd);
2240 	LIST_INIT(&inodedep->id_inowait);
2241 	LIST_INIT(&inodedep->id_bufwait);
2242 	TAILQ_INIT(&inodedep->id_inoreflst);
2243 	TAILQ_INIT(&inodedep->id_inoupdt);
2244 	TAILQ_INIT(&inodedep->id_newinoupdt);
2245 	TAILQ_INIT(&inodedep->id_extupdt);
2246 	TAILQ_INIT(&inodedep->id_newextupdt);
2247 	TAILQ_INIT(&inodedep->id_freeblklst);
2248 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2249 	*inodedeppp = inodedep;
2250 	return (0);
2251 }
2252 
2253 /*
2254  * Structures and routines associated with newblk caching.
2255  */
2256 #define	NEWBLK_HASH(ump, inum) \
2257 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2258 
2259 static int
2260 newblk_find(newblkhd, newblkno, flags, newblkpp)
2261 	struct newblk_hashhead *newblkhd;
2262 	ufs2_daddr_t newblkno;
2263 	int flags;
2264 	struct newblk **newblkpp;
2265 {
2266 	struct newblk *newblk;
2267 
2268 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2269 		if (newblkno != newblk->nb_newblkno)
2270 			continue;
2271 		/*
2272 		 * If we're creating a new dependency don't match those that
2273 		 * have already been converted to allocdirects.  This is for
2274 		 * a frag extend.
2275 		 */
2276 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2277 			continue;
2278 		break;
2279 	}
2280 	if (newblk) {
2281 		*newblkpp = newblk;
2282 		return (1);
2283 	}
2284 	*newblkpp = NULL;
2285 	return (0);
2286 }
2287 
2288 /*
2289  * Look up a newblk. Return 1 if found, 0 if not found.
2290  * If not found, allocate if DEPALLOC flag is passed.
2291  * Found or allocated entry is returned in newblkpp.
2292  */
2293 static int
2294 newblk_lookup(mp, newblkno, flags, newblkpp)
2295 	struct mount *mp;
2296 	ufs2_daddr_t newblkno;
2297 	int flags;
2298 	struct newblk **newblkpp;
2299 {
2300 	struct newblk *newblk;
2301 	struct newblk_hashhead *newblkhd;
2302 	struct ufsmount *ump;
2303 
2304 	ump = VFSTOUFS(mp);
2305 	LOCK_OWNED(ump);
2306 	newblkhd = NEWBLK_HASH(ump, newblkno);
2307 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2308 		return (1);
2309 	if ((flags & DEPALLOC) == 0)
2310 		return (0);
2311 	if (softdep_excess_items(ump, D_NEWBLK) ||
2312 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2313 	    softdep_excess_items(ump, D_ALLOCINDIR))
2314 		schedule_cleanup(mp);
2315 	else
2316 		FREE_LOCK(ump);
2317 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2318 	    M_SOFTDEP_FLAGS | M_ZERO);
2319 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2320 	ACQUIRE_LOCK(ump);
2321 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2322 		WORKITEM_FREE(newblk, D_NEWBLK);
2323 		return (1);
2324 	}
2325 	newblk->nb_freefrag = NULL;
2326 	LIST_INIT(&newblk->nb_indirdeps);
2327 	LIST_INIT(&newblk->nb_newdirblk);
2328 	LIST_INIT(&newblk->nb_jwork);
2329 	newblk->nb_state = ATTACHED;
2330 	newblk->nb_newblkno = newblkno;
2331 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2332 	*newblkpp = newblk;
2333 	return (0);
2334 }
2335 
2336 /*
2337  * Structures and routines associated with freed indirect block caching.
2338  */
2339 #define	INDIR_HASH(ump, blkno) \
2340 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2341 
2342 /*
2343  * Lookup an indirect block in the indir hash table.  The freework is
2344  * removed and potentially freed.  The caller must do a blocking journal
2345  * write before writing to the blkno.
2346  */
2347 static int
2348 indirblk_lookup(mp, blkno)
2349 	struct mount *mp;
2350 	ufs2_daddr_t blkno;
2351 {
2352 	struct freework *freework;
2353 	struct indir_hashhead *wkhd;
2354 	struct ufsmount *ump;
2355 
2356 	ump = VFSTOUFS(mp);
2357 	wkhd = INDIR_HASH(ump, blkno);
2358 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2359 		if (freework->fw_blkno != blkno)
2360 			continue;
2361 		indirblk_remove(freework);
2362 		return (1);
2363 	}
2364 	return (0);
2365 }
2366 
2367 /*
2368  * Insert an indirect block represented by freework into the indirblk
2369  * hash table so that it may prevent the block from being re-used prior
2370  * to the journal being written.
2371  */
2372 static void
2373 indirblk_insert(freework)
2374 	struct freework *freework;
2375 {
2376 	struct jblocks *jblocks;
2377 	struct jseg *jseg;
2378 	struct ufsmount *ump;
2379 
2380 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2381 	jblocks = ump->softdep_jblocks;
2382 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2383 	if (jseg == NULL)
2384 		return;
2385 
2386 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2387 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2388 	    fw_next);
2389 	freework->fw_state &= ~DEPCOMPLETE;
2390 }
2391 
2392 static void
2393 indirblk_remove(freework)
2394 	struct freework *freework;
2395 {
2396 	struct ufsmount *ump;
2397 
2398 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2399 	LIST_REMOVE(freework, fw_segs);
2400 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2401 	freework->fw_state |= DEPCOMPLETE;
2402 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2403 		WORKITEM_FREE(freework, D_FREEWORK);
2404 }
2405 
2406 /*
2407  * Executed during filesystem system initialization before
2408  * mounting any filesystems.
2409  */
2410 void
2411 softdep_initialize()
2412 {
2413 
2414 	TAILQ_INIT(&softdepmounts);
2415 #ifdef __LP64__
2416 	max_softdeps = desiredvnodes * 4;
2417 #else
2418 	max_softdeps = desiredvnodes * 2;
2419 #endif
2420 
2421 	/* initialise bioops hack */
2422 	bioops.io_start = softdep_disk_io_initiation;
2423 	bioops.io_complete = softdep_disk_write_complete;
2424 	bioops.io_deallocate = softdep_deallocate_dependencies;
2425 	bioops.io_countdeps = softdep_count_dependencies;
2426 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2427 
2428 	/* Initialize the callout with an mtx. */
2429 	callout_init_mtx(&softdep_callout, &lk, 0);
2430 }
2431 
2432 /*
2433  * Executed after all filesystems have been unmounted during
2434  * filesystem module unload.
2435  */
2436 void
2437 softdep_uninitialize()
2438 {
2439 
2440 	/* clear bioops hack */
2441 	bioops.io_start = NULL;
2442 	bioops.io_complete = NULL;
2443 	bioops.io_deallocate = NULL;
2444 	bioops.io_countdeps = NULL;
2445 	softdep_ast_cleanup = NULL;
2446 
2447 	callout_drain(&softdep_callout);
2448 }
2449 
2450 /*
2451  * Called at mount time to notify the dependency code that a
2452  * filesystem wishes to use it.
2453  */
2454 int
2455 softdep_mount(devvp, mp, fs, cred)
2456 	struct vnode *devvp;
2457 	struct mount *mp;
2458 	struct fs *fs;
2459 	struct ucred *cred;
2460 {
2461 	struct csum_total cstotal;
2462 	struct mount_softdeps *sdp;
2463 	struct ufsmount *ump;
2464 	struct cg *cgp;
2465 	struct buf *bp;
2466 	int i, error, cyl;
2467 
2468 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2469 	    M_WAITOK | M_ZERO);
2470 	MNT_ILOCK(mp);
2471 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2472 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2473 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2474 			MNTK_SOFTDEP | MNTK_NOASYNC;
2475 	}
2476 	ump = VFSTOUFS(mp);
2477 	ump->um_softdep = sdp;
2478 	MNT_IUNLOCK(mp);
2479 	rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2480 	sdp->sd_ump = ump;
2481 	LIST_INIT(&ump->softdep_workitem_pending);
2482 	LIST_INIT(&ump->softdep_journal_pending);
2483 	TAILQ_INIT(&ump->softdep_unlinked);
2484 	LIST_INIT(&ump->softdep_dirtycg);
2485 	ump->softdep_worklist_tail = NULL;
2486 	ump->softdep_on_worklist = 0;
2487 	ump->softdep_deps = 0;
2488 	LIST_INIT(&ump->softdep_mkdirlisthd);
2489 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2490 	    &ump->pagedep_hash_size);
2491 	ump->pagedep_nextclean = 0;
2492 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2493 	    &ump->inodedep_hash_size);
2494 	ump->inodedep_nextclean = 0;
2495 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2496 	    &ump->newblk_hash_size);
2497 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2498 	    &ump->bmsafemap_hash_size);
2499 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2500 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2501 	    M_FREEWORK, M_WAITOK);
2502 	ump->indir_hash_size = i - 1;
2503 	for (i = 0; i <= ump->indir_hash_size; i++)
2504 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2505 	ACQUIRE_GBLLOCK(&lk);
2506 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2507 	FREE_GBLLOCK(&lk);
2508 	if ((fs->fs_flags & FS_SUJ) &&
2509 	    (error = journal_mount(mp, fs, cred)) != 0) {
2510 		printf("Failed to start journal: %d\n", error);
2511 		softdep_unmount(mp);
2512 		return (error);
2513 	}
2514 	/*
2515 	 * Start our flushing thread in the bufdaemon process.
2516 	 */
2517 	ACQUIRE_LOCK(ump);
2518 	ump->softdep_flags |= FLUSH_STARTING;
2519 	FREE_LOCK(ump);
2520 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2521 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2522 	    mp->mnt_stat.f_mntonname);
2523 	ACQUIRE_LOCK(ump);
2524 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2525 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2526 		    hz / 2);
2527 	}
2528 	FREE_LOCK(ump);
2529 	/*
2530 	 * When doing soft updates, the counters in the
2531 	 * superblock may have gotten out of sync. Recomputation
2532 	 * can take a long time and can be deferred for background
2533 	 * fsck.  However, the old behavior of scanning the cylinder
2534 	 * groups and recalculating them at mount time is available
2535 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2536 	 */
2537 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2538 		return (0);
2539 	bzero(&cstotal, sizeof cstotal);
2540 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2541 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2542 		    fs->fs_cgsize, cred, &bp)) != 0) {
2543 			brelse(bp);
2544 			softdep_unmount(mp);
2545 			return (error);
2546 		}
2547 		cgp = (struct cg *)bp->b_data;
2548 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2549 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2550 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2551 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2552 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2553 		brelse(bp);
2554 	}
2555 #ifdef DEBUG
2556 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2557 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2558 #endif
2559 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2560 	return (0);
2561 }
2562 
2563 void
2564 softdep_unmount(mp)
2565 	struct mount *mp;
2566 {
2567 	struct ufsmount *ump;
2568 #ifdef INVARIANTS
2569 	int i;
2570 #endif
2571 
2572 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2573 	    ("softdep_unmount called on non-softdep filesystem"));
2574 	ump = VFSTOUFS(mp);
2575 	MNT_ILOCK(mp);
2576 	mp->mnt_flag &= ~MNT_SOFTDEP;
2577 	if (MOUNTEDSUJ(mp) == 0) {
2578 		MNT_IUNLOCK(mp);
2579 	} else {
2580 		mp->mnt_flag &= ~MNT_SUJ;
2581 		MNT_IUNLOCK(mp);
2582 		journal_unmount(ump);
2583 	}
2584 	/*
2585 	 * Shut down our flushing thread. Check for NULL is if
2586 	 * softdep_mount errors out before the thread has been created.
2587 	 */
2588 	if (ump->softdep_flushtd != NULL) {
2589 		ACQUIRE_LOCK(ump);
2590 		ump->softdep_flags |= FLUSH_EXIT;
2591 		wakeup(&ump->softdep_flushtd);
2592 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2593 		    "sdwait", 0);
2594 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2595 		    ("Thread shutdown failed"));
2596 	}
2597 	/*
2598 	 * Free up our resources.
2599 	 */
2600 	ACQUIRE_GBLLOCK(&lk);
2601 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2602 	FREE_GBLLOCK(&lk);
2603 	rw_destroy(LOCK_PTR(ump));
2604 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2605 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2606 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2607 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2608 	    ump->bmsafemap_hash_size);
2609 	free(ump->indir_hashtbl, M_FREEWORK);
2610 #ifdef INVARIANTS
2611 	for (i = 0; i <= D_LAST; i++)
2612 		KASSERT(ump->softdep_curdeps[i] == 0,
2613 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2614 		    TYPENAME(i), ump->softdep_curdeps[i]));
2615 #endif
2616 	free(ump->um_softdep, M_MOUNTDATA);
2617 }
2618 
2619 static struct jblocks *
2620 jblocks_create(void)
2621 {
2622 	struct jblocks *jblocks;
2623 
2624 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2625 	TAILQ_INIT(&jblocks->jb_segs);
2626 	jblocks->jb_avail = 10;
2627 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2628 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2629 
2630 	return (jblocks);
2631 }
2632 
2633 static ufs2_daddr_t
2634 jblocks_alloc(jblocks, bytes, actual)
2635 	struct jblocks *jblocks;
2636 	int bytes;
2637 	int *actual;
2638 {
2639 	ufs2_daddr_t daddr;
2640 	struct jextent *jext;
2641 	int freecnt;
2642 	int blocks;
2643 
2644 	blocks = bytes / DEV_BSIZE;
2645 	jext = &jblocks->jb_extent[jblocks->jb_head];
2646 	freecnt = jext->je_blocks - jblocks->jb_off;
2647 	if (freecnt == 0) {
2648 		jblocks->jb_off = 0;
2649 		if (++jblocks->jb_head > jblocks->jb_used)
2650 			jblocks->jb_head = 0;
2651 		jext = &jblocks->jb_extent[jblocks->jb_head];
2652 		freecnt = jext->je_blocks;
2653 	}
2654 	if (freecnt > blocks)
2655 		freecnt = blocks;
2656 	*actual = freecnt * DEV_BSIZE;
2657 	daddr = jext->je_daddr + jblocks->jb_off;
2658 	jblocks->jb_off += freecnt;
2659 	jblocks->jb_free -= freecnt;
2660 
2661 	return (daddr);
2662 }
2663 
2664 static void
2665 jblocks_free(jblocks, mp, bytes)
2666 	struct jblocks *jblocks;
2667 	struct mount *mp;
2668 	int bytes;
2669 {
2670 
2671 	LOCK_OWNED(VFSTOUFS(mp));
2672 	jblocks->jb_free += bytes / DEV_BSIZE;
2673 	if (jblocks->jb_suspended)
2674 		worklist_speedup(mp);
2675 	wakeup(jblocks);
2676 }
2677 
2678 static void
2679 jblocks_destroy(jblocks)
2680 	struct jblocks *jblocks;
2681 {
2682 
2683 	if (jblocks->jb_extent)
2684 		free(jblocks->jb_extent, M_JBLOCKS);
2685 	free(jblocks, M_JBLOCKS);
2686 }
2687 
2688 static void
2689 jblocks_add(jblocks, daddr, blocks)
2690 	struct jblocks *jblocks;
2691 	ufs2_daddr_t daddr;
2692 	int blocks;
2693 {
2694 	struct jextent *jext;
2695 
2696 	jblocks->jb_blocks += blocks;
2697 	jblocks->jb_free += blocks;
2698 	jext = &jblocks->jb_extent[jblocks->jb_used];
2699 	/* Adding the first block. */
2700 	if (jext->je_daddr == 0) {
2701 		jext->je_daddr = daddr;
2702 		jext->je_blocks = blocks;
2703 		return;
2704 	}
2705 	/* Extending the last extent. */
2706 	if (jext->je_daddr + jext->je_blocks == daddr) {
2707 		jext->je_blocks += blocks;
2708 		return;
2709 	}
2710 	/* Adding a new extent. */
2711 	if (++jblocks->jb_used == jblocks->jb_avail) {
2712 		jblocks->jb_avail *= 2;
2713 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2714 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2715 		memcpy(jext, jblocks->jb_extent,
2716 		    sizeof(struct jextent) * jblocks->jb_used);
2717 		free(jblocks->jb_extent, M_JBLOCKS);
2718 		jblocks->jb_extent = jext;
2719 	}
2720 	jext = &jblocks->jb_extent[jblocks->jb_used];
2721 	jext->je_daddr = daddr;
2722 	jext->je_blocks = blocks;
2723 	return;
2724 }
2725 
2726 int
2727 softdep_journal_lookup(mp, vpp)
2728 	struct mount *mp;
2729 	struct vnode **vpp;
2730 {
2731 	struct componentname cnp;
2732 	struct vnode *dvp;
2733 	ino_t sujournal;
2734 	int error;
2735 
2736 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2737 	if (error)
2738 		return (error);
2739 	bzero(&cnp, sizeof(cnp));
2740 	cnp.cn_nameiop = LOOKUP;
2741 	cnp.cn_flags = ISLASTCN;
2742 	cnp.cn_thread = curthread;
2743 	cnp.cn_cred = curthread->td_ucred;
2744 	cnp.cn_pnbuf = SUJ_FILE;
2745 	cnp.cn_nameptr = SUJ_FILE;
2746 	cnp.cn_namelen = strlen(SUJ_FILE);
2747 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2748 	vput(dvp);
2749 	if (error != 0)
2750 		return (error);
2751 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2752 	return (error);
2753 }
2754 
2755 /*
2756  * Open and verify the journal file.
2757  */
2758 static int
2759 journal_mount(mp, fs, cred)
2760 	struct mount *mp;
2761 	struct fs *fs;
2762 	struct ucred *cred;
2763 {
2764 	struct jblocks *jblocks;
2765 	struct ufsmount *ump;
2766 	struct vnode *vp;
2767 	struct inode *ip;
2768 	ufs2_daddr_t blkno;
2769 	int bcount;
2770 	int error;
2771 	int i;
2772 
2773 	ump = VFSTOUFS(mp);
2774 	ump->softdep_journal_tail = NULL;
2775 	ump->softdep_on_journal = 0;
2776 	ump->softdep_accdeps = 0;
2777 	ump->softdep_req = 0;
2778 	ump->softdep_jblocks = NULL;
2779 	error = softdep_journal_lookup(mp, &vp);
2780 	if (error != 0) {
2781 		printf("Failed to find journal.  Use tunefs to create one\n");
2782 		return (error);
2783 	}
2784 	ip = VTOI(vp);
2785 	if (ip->i_size < SUJ_MIN) {
2786 		error = ENOSPC;
2787 		goto out;
2788 	}
2789 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2790 	jblocks = jblocks_create();
2791 	for (i = 0; i < bcount; i++) {
2792 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2793 		if (error)
2794 			break;
2795 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2796 	}
2797 	if (error) {
2798 		jblocks_destroy(jblocks);
2799 		goto out;
2800 	}
2801 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2802 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2803 	ump->softdep_jblocks = jblocks;
2804 out:
2805 	if (error == 0) {
2806 		MNT_ILOCK(mp);
2807 		mp->mnt_flag |= MNT_SUJ;
2808 		mp->mnt_flag &= ~MNT_SOFTDEP;
2809 		MNT_IUNLOCK(mp);
2810 		/*
2811 		 * Only validate the journal contents if the
2812 		 * filesystem is clean, otherwise we write the logs
2813 		 * but they'll never be used.  If the filesystem was
2814 		 * still dirty when we mounted it the journal is
2815 		 * invalid and a new journal can only be valid if it
2816 		 * starts from a clean mount.
2817 		 */
2818 		if (fs->fs_clean) {
2819 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2820 			ip->i_flags |= IN_MODIFIED;
2821 			ffs_update(vp, 1);
2822 		}
2823 	}
2824 	vput(vp);
2825 	return (error);
2826 }
2827 
2828 static void
2829 journal_unmount(ump)
2830 	struct ufsmount *ump;
2831 {
2832 
2833 	if (ump->softdep_jblocks)
2834 		jblocks_destroy(ump->softdep_jblocks);
2835 	ump->softdep_jblocks = NULL;
2836 }
2837 
2838 /*
2839  * Called when a journal record is ready to be written.  Space is allocated
2840  * and the journal entry is created when the journal is flushed to stable
2841  * store.
2842  */
2843 static void
2844 add_to_journal(wk)
2845 	struct worklist *wk;
2846 {
2847 	struct ufsmount *ump;
2848 
2849 	ump = VFSTOUFS(wk->wk_mp);
2850 	LOCK_OWNED(ump);
2851 	if (wk->wk_state & ONWORKLIST)
2852 		panic("add_to_journal: %s(0x%X) already on list",
2853 		    TYPENAME(wk->wk_type), wk->wk_state);
2854 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2855 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2856 		ump->softdep_jblocks->jb_age = ticks;
2857 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2858 	} else
2859 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2860 	ump->softdep_journal_tail = wk;
2861 	ump->softdep_on_journal += 1;
2862 }
2863 
2864 /*
2865  * Remove an arbitrary item for the journal worklist maintain the tail
2866  * pointer.  This happens when a new operation obviates the need to
2867  * journal an old operation.
2868  */
2869 static void
2870 remove_from_journal(wk)
2871 	struct worklist *wk;
2872 {
2873 	struct ufsmount *ump;
2874 
2875 	ump = VFSTOUFS(wk->wk_mp);
2876 	LOCK_OWNED(ump);
2877 #ifdef SUJ_DEBUG
2878 	{
2879 		struct worklist *wkn;
2880 
2881 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2882 			if (wkn == wk)
2883 				break;
2884 		if (wkn == NULL)
2885 			panic("remove_from_journal: %p is not in journal", wk);
2886 	}
2887 #endif
2888 	/*
2889 	 * We emulate a TAILQ to save space in most structures which do not
2890 	 * require TAILQ semantics.  Here we must update the tail position
2891 	 * when removing the tail which is not the final entry. This works
2892 	 * only if the worklist linkage are at the beginning of the structure.
2893 	 */
2894 	if (ump->softdep_journal_tail == wk)
2895 		ump->softdep_journal_tail =
2896 		    (struct worklist *)wk->wk_list.le_prev;
2897 	WORKLIST_REMOVE(wk);
2898 	ump->softdep_on_journal -= 1;
2899 }
2900 
2901 /*
2902  * Check for journal space as well as dependency limits so the prelink
2903  * code can throttle both journaled and non-journaled filesystems.
2904  * Threshold is 0 for low and 1 for min.
2905  */
2906 static int
2907 journal_space(ump, thresh)
2908 	struct ufsmount *ump;
2909 	int thresh;
2910 {
2911 	struct jblocks *jblocks;
2912 	int limit, avail;
2913 
2914 	jblocks = ump->softdep_jblocks;
2915 	if (jblocks == NULL)
2916 		return (1);
2917 	/*
2918 	 * We use a tighter restriction here to prevent request_cleanup()
2919 	 * running in threads from running into locks we currently hold.
2920 	 * We have to be over the limit and our filesystem has to be
2921 	 * responsible for more than our share of that usage.
2922 	 */
2923 	limit = (max_softdeps / 10) * 9;
2924 	if (dep_current[D_INODEDEP] > limit &&
2925 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2926 		return (0);
2927 	if (thresh)
2928 		thresh = jblocks->jb_min;
2929 	else
2930 		thresh = jblocks->jb_low;
2931 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2932 	avail = jblocks->jb_free - avail;
2933 
2934 	return (avail > thresh);
2935 }
2936 
2937 static void
2938 journal_suspend(ump)
2939 	struct ufsmount *ump;
2940 {
2941 	struct jblocks *jblocks;
2942 	struct mount *mp;
2943 
2944 	mp = UFSTOVFS(ump);
2945 	jblocks = ump->softdep_jblocks;
2946 	MNT_ILOCK(mp);
2947 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2948 		stat_journal_min++;
2949 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2950 		mp->mnt_susp_owner = ump->softdep_flushtd;
2951 	}
2952 	jblocks->jb_suspended = 1;
2953 	MNT_IUNLOCK(mp);
2954 }
2955 
2956 static int
2957 journal_unsuspend(struct ufsmount *ump)
2958 {
2959 	struct jblocks *jblocks;
2960 	struct mount *mp;
2961 
2962 	mp = UFSTOVFS(ump);
2963 	jblocks = ump->softdep_jblocks;
2964 
2965 	if (jblocks != NULL && jblocks->jb_suspended &&
2966 	    journal_space(ump, jblocks->jb_min)) {
2967 		jblocks->jb_suspended = 0;
2968 		FREE_LOCK(ump);
2969 		mp->mnt_susp_owner = curthread;
2970 		vfs_write_resume(mp, 0);
2971 		ACQUIRE_LOCK(ump);
2972 		return (1);
2973 	}
2974 	return (0);
2975 }
2976 
2977 /*
2978  * Called before any allocation function to be certain that there is
2979  * sufficient space in the journal prior to creating any new records.
2980  * Since in the case of block allocation we may have multiple locked
2981  * buffers at the time of the actual allocation we can not block
2982  * when the journal records are created.  Doing so would create a deadlock
2983  * if any of these buffers needed to be flushed to reclaim space.  Instead
2984  * we require a sufficiently large amount of available space such that
2985  * each thread in the system could have passed this allocation check and
2986  * still have sufficient free space.  With 20% of a minimum journal size
2987  * of 1MB we have 6553 records available.
2988  */
2989 int
2990 softdep_prealloc(vp, waitok)
2991 	struct vnode *vp;
2992 	int waitok;
2993 {
2994 	struct ufsmount *ump;
2995 
2996 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
2997 	    ("softdep_prealloc called on non-softdep filesystem"));
2998 	/*
2999 	 * Nothing to do if we are not running journaled soft updates.
3000 	 * If we currently hold the snapshot lock, we must avoid
3001 	 * handling other resources that could cause deadlock.  Do not
3002 	 * touch quotas vnode since it is typically recursed with
3003 	 * other vnode locks held.
3004 	 */
3005 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3006 	    (vp->v_vflag & VV_SYSTEM) != 0)
3007 		return (0);
3008 	ump = VFSTOUFS(vp->v_mount);
3009 	ACQUIRE_LOCK(ump);
3010 	if (journal_space(ump, 0)) {
3011 		FREE_LOCK(ump);
3012 		return (0);
3013 	}
3014 	stat_journal_low++;
3015 	FREE_LOCK(ump);
3016 	if (waitok == MNT_NOWAIT)
3017 		return (ENOSPC);
3018 	/*
3019 	 * Attempt to sync this vnode once to flush any journal
3020 	 * work attached to it.
3021 	 */
3022 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3023 		ffs_syncvnode(vp, waitok, 0);
3024 	ACQUIRE_LOCK(ump);
3025 	process_removes(vp);
3026 	process_truncates(vp);
3027 	if (journal_space(ump, 0) == 0) {
3028 		softdep_speedup(ump);
3029 		if (journal_space(ump, 1) == 0)
3030 			journal_suspend(ump);
3031 	}
3032 	FREE_LOCK(ump);
3033 
3034 	return (0);
3035 }
3036 
3037 /*
3038  * Before adjusting a link count on a vnode verify that we have sufficient
3039  * journal space.  If not, process operations that depend on the currently
3040  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3041  * and softdep flush threads can not acquire these locks to reclaim space.
3042  */
3043 static void
3044 softdep_prelink(dvp, vp)
3045 	struct vnode *dvp;
3046 	struct vnode *vp;
3047 {
3048 	struct ufsmount *ump;
3049 
3050 	ump = VFSTOUFS(dvp->v_mount);
3051 	LOCK_OWNED(ump);
3052 	/*
3053 	 * Nothing to do if we have sufficient journal space.
3054 	 * If we currently hold the snapshot lock, we must avoid
3055 	 * handling other resources that could cause deadlock.
3056 	 */
3057 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3058 		return;
3059 	stat_journal_low++;
3060 	FREE_LOCK(ump);
3061 	if (vp)
3062 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3063 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3064 	ACQUIRE_LOCK(ump);
3065 	/* Process vp before dvp as it may create .. removes. */
3066 	if (vp) {
3067 		process_removes(vp);
3068 		process_truncates(vp);
3069 	}
3070 	process_removes(dvp);
3071 	process_truncates(dvp);
3072 	softdep_speedup(ump);
3073 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3074 	if (journal_space(ump, 0) == 0) {
3075 		softdep_speedup(ump);
3076 		if (journal_space(ump, 1) == 0)
3077 			journal_suspend(ump);
3078 	}
3079 }
3080 
3081 static void
3082 jseg_write(ump, jseg, data)
3083 	struct ufsmount *ump;
3084 	struct jseg *jseg;
3085 	uint8_t *data;
3086 {
3087 	struct jsegrec *rec;
3088 
3089 	rec = (struct jsegrec *)data;
3090 	rec->jsr_seq = jseg->js_seq;
3091 	rec->jsr_oldest = jseg->js_oldseq;
3092 	rec->jsr_cnt = jseg->js_cnt;
3093 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3094 	rec->jsr_crc = 0;
3095 	rec->jsr_time = ump->um_fs->fs_mtime;
3096 }
3097 
3098 static inline void
3099 inoref_write(inoref, jseg, rec)
3100 	struct inoref *inoref;
3101 	struct jseg *jseg;
3102 	struct jrefrec *rec;
3103 {
3104 
3105 	inoref->if_jsegdep->jd_seg = jseg;
3106 	rec->jr_ino = inoref->if_ino;
3107 	rec->jr_parent = inoref->if_parent;
3108 	rec->jr_nlink = inoref->if_nlink;
3109 	rec->jr_mode = inoref->if_mode;
3110 	rec->jr_diroff = inoref->if_diroff;
3111 }
3112 
3113 static void
3114 jaddref_write(jaddref, jseg, data)
3115 	struct jaddref *jaddref;
3116 	struct jseg *jseg;
3117 	uint8_t *data;
3118 {
3119 	struct jrefrec *rec;
3120 
3121 	rec = (struct jrefrec *)data;
3122 	rec->jr_op = JOP_ADDREF;
3123 	inoref_write(&jaddref->ja_ref, jseg, rec);
3124 }
3125 
3126 static void
3127 jremref_write(jremref, jseg, data)
3128 	struct jremref *jremref;
3129 	struct jseg *jseg;
3130 	uint8_t *data;
3131 {
3132 	struct jrefrec *rec;
3133 
3134 	rec = (struct jrefrec *)data;
3135 	rec->jr_op = JOP_REMREF;
3136 	inoref_write(&jremref->jr_ref, jseg, rec);
3137 }
3138 
3139 static void
3140 jmvref_write(jmvref, jseg, data)
3141 	struct jmvref *jmvref;
3142 	struct jseg *jseg;
3143 	uint8_t *data;
3144 {
3145 	struct jmvrec *rec;
3146 
3147 	rec = (struct jmvrec *)data;
3148 	rec->jm_op = JOP_MVREF;
3149 	rec->jm_ino = jmvref->jm_ino;
3150 	rec->jm_parent = jmvref->jm_parent;
3151 	rec->jm_oldoff = jmvref->jm_oldoff;
3152 	rec->jm_newoff = jmvref->jm_newoff;
3153 }
3154 
3155 static void
3156 jnewblk_write(jnewblk, jseg, data)
3157 	struct jnewblk *jnewblk;
3158 	struct jseg *jseg;
3159 	uint8_t *data;
3160 {
3161 	struct jblkrec *rec;
3162 
3163 	jnewblk->jn_jsegdep->jd_seg = jseg;
3164 	rec = (struct jblkrec *)data;
3165 	rec->jb_op = JOP_NEWBLK;
3166 	rec->jb_ino = jnewblk->jn_ino;
3167 	rec->jb_blkno = jnewblk->jn_blkno;
3168 	rec->jb_lbn = jnewblk->jn_lbn;
3169 	rec->jb_frags = jnewblk->jn_frags;
3170 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3171 }
3172 
3173 static void
3174 jfreeblk_write(jfreeblk, jseg, data)
3175 	struct jfreeblk *jfreeblk;
3176 	struct jseg *jseg;
3177 	uint8_t *data;
3178 {
3179 	struct jblkrec *rec;
3180 
3181 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3182 	rec = (struct jblkrec *)data;
3183 	rec->jb_op = JOP_FREEBLK;
3184 	rec->jb_ino = jfreeblk->jf_ino;
3185 	rec->jb_blkno = jfreeblk->jf_blkno;
3186 	rec->jb_lbn = jfreeblk->jf_lbn;
3187 	rec->jb_frags = jfreeblk->jf_frags;
3188 	rec->jb_oldfrags = 0;
3189 }
3190 
3191 static void
3192 jfreefrag_write(jfreefrag, jseg, data)
3193 	struct jfreefrag *jfreefrag;
3194 	struct jseg *jseg;
3195 	uint8_t *data;
3196 {
3197 	struct jblkrec *rec;
3198 
3199 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3200 	rec = (struct jblkrec *)data;
3201 	rec->jb_op = JOP_FREEBLK;
3202 	rec->jb_ino = jfreefrag->fr_ino;
3203 	rec->jb_blkno = jfreefrag->fr_blkno;
3204 	rec->jb_lbn = jfreefrag->fr_lbn;
3205 	rec->jb_frags = jfreefrag->fr_frags;
3206 	rec->jb_oldfrags = 0;
3207 }
3208 
3209 static void
3210 jtrunc_write(jtrunc, jseg, data)
3211 	struct jtrunc *jtrunc;
3212 	struct jseg *jseg;
3213 	uint8_t *data;
3214 {
3215 	struct jtrncrec *rec;
3216 
3217 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3218 	rec = (struct jtrncrec *)data;
3219 	rec->jt_op = JOP_TRUNC;
3220 	rec->jt_ino = jtrunc->jt_ino;
3221 	rec->jt_size = jtrunc->jt_size;
3222 	rec->jt_extsize = jtrunc->jt_extsize;
3223 }
3224 
3225 static void
3226 jfsync_write(jfsync, jseg, data)
3227 	struct jfsync *jfsync;
3228 	struct jseg *jseg;
3229 	uint8_t *data;
3230 {
3231 	struct jtrncrec *rec;
3232 
3233 	rec = (struct jtrncrec *)data;
3234 	rec->jt_op = JOP_SYNC;
3235 	rec->jt_ino = jfsync->jfs_ino;
3236 	rec->jt_size = jfsync->jfs_size;
3237 	rec->jt_extsize = jfsync->jfs_extsize;
3238 }
3239 
3240 static void
3241 softdep_flushjournal(mp)
3242 	struct mount *mp;
3243 {
3244 	struct jblocks *jblocks;
3245 	struct ufsmount *ump;
3246 
3247 	if (MOUNTEDSUJ(mp) == 0)
3248 		return;
3249 	ump = VFSTOUFS(mp);
3250 	jblocks = ump->softdep_jblocks;
3251 	ACQUIRE_LOCK(ump);
3252 	while (ump->softdep_on_journal) {
3253 		jblocks->jb_needseg = 1;
3254 		softdep_process_journal(mp, NULL, MNT_WAIT);
3255 	}
3256 	FREE_LOCK(ump);
3257 }
3258 
3259 static void softdep_synchronize_completed(struct bio *);
3260 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3261 
3262 static void
3263 softdep_synchronize_completed(bp)
3264         struct bio *bp;
3265 {
3266 	struct jseg *oldest;
3267 	struct jseg *jseg;
3268 	struct ufsmount *ump;
3269 
3270 	/*
3271 	 * caller1 marks the last segment written before we issued the
3272 	 * synchronize cache.
3273 	 */
3274 	jseg = bp->bio_caller1;
3275 	if (jseg == NULL) {
3276 		g_destroy_bio(bp);
3277 		return;
3278 	}
3279 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3280 	ACQUIRE_LOCK(ump);
3281 	oldest = NULL;
3282 	/*
3283 	 * Mark all the journal entries waiting on the synchronize cache
3284 	 * as completed so they may continue on.
3285 	 */
3286 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3287 		jseg->js_state |= COMPLETE;
3288 		oldest = jseg;
3289 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3290 	}
3291 	/*
3292 	 * Restart deferred journal entry processing from the oldest
3293 	 * completed jseg.
3294 	 */
3295 	if (oldest)
3296 		complete_jsegs(oldest);
3297 
3298 	FREE_LOCK(ump);
3299 	g_destroy_bio(bp);
3300 }
3301 
3302 /*
3303  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3304  * barriers.  The journal must be written prior to any blocks that depend
3305  * on it and the journal can not be released until the blocks have be
3306  * written.  This code handles both barriers simultaneously.
3307  */
3308 static void
3309 softdep_synchronize(bp, ump, caller1)
3310 	struct bio *bp;
3311 	struct ufsmount *ump;
3312 	void *caller1;
3313 {
3314 
3315 	bp->bio_cmd = BIO_FLUSH;
3316 	bp->bio_flags |= BIO_ORDERED;
3317 	bp->bio_data = NULL;
3318 	bp->bio_offset = ump->um_cp->provider->mediasize;
3319 	bp->bio_length = 0;
3320 	bp->bio_done = softdep_synchronize_completed;
3321 	bp->bio_caller1 = caller1;
3322 	g_io_request(bp,
3323 	    (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3324 }
3325 
3326 /*
3327  * Flush some journal records to disk.
3328  */
3329 static void
3330 softdep_process_journal(mp, needwk, flags)
3331 	struct mount *mp;
3332 	struct worklist *needwk;
3333 	int flags;
3334 {
3335 	struct jblocks *jblocks;
3336 	struct ufsmount *ump;
3337 	struct worklist *wk;
3338 	struct jseg *jseg;
3339 	struct buf *bp;
3340 	struct bio *bio;
3341 	uint8_t *data;
3342 	struct fs *fs;
3343 	int shouldflush;
3344 	int segwritten;
3345 	int jrecmin;	/* Minimum records per block. */
3346 	int jrecmax;	/* Maximum records per block. */
3347 	int size;
3348 	int cnt;
3349 	int off;
3350 	int devbsize;
3351 
3352 	if (MOUNTEDSUJ(mp) == 0)
3353 		return;
3354 	shouldflush = softdep_flushcache;
3355 	bio = NULL;
3356 	jseg = NULL;
3357 	ump = VFSTOUFS(mp);
3358 	LOCK_OWNED(ump);
3359 	fs = ump->um_fs;
3360 	jblocks = ump->softdep_jblocks;
3361 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3362 	/*
3363 	 * We write anywhere between a disk block and fs block.  The upper
3364 	 * bound is picked to prevent buffer cache fragmentation and limit
3365 	 * processing time per I/O.
3366 	 */
3367 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3368 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3369 	segwritten = 0;
3370 	for (;;) {
3371 		cnt = ump->softdep_on_journal;
3372 		/*
3373 		 * Criteria for writing a segment:
3374 		 * 1) We have a full block.
3375 		 * 2) We're called from jwait() and haven't found the
3376 		 *    journal item yet.
3377 		 * 3) Always write if needseg is set.
3378 		 * 4) If we are called from process_worklist and have
3379 		 *    not yet written anything we write a partial block
3380 		 *    to enforce a 1 second maximum latency on journal
3381 		 *    entries.
3382 		 */
3383 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3384 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3385 			break;
3386 		cnt++;
3387 		/*
3388 		 * Verify some free journal space.  softdep_prealloc() should
3389 		 * guarantee that we don't run out so this is indicative of
3390 		 * a problem with the flow control.  Try to recover
3391 		 * gracefully in any event.
3392 		 */
3393 		while (jblocks->jb_free == 0) {
3394 			if (flags != MNT_WAIT)
3395 				break;
3396 			printf("softdep: Out of journal space!\n");
3397 			softdep_speedup(ump);
3398 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3399 		}
3400 		FREE_LOCK(ump);
3401 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3402 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3403 		LIST_INIT(&jseg->js_entries);
3404 		LIST_INIT(&jseg->js_indirs);
3405 		jseg->js_state = ATTACHED;
3406 		if (shouldflush == 0)
3407 			jseg->js_state |= COMPLETE;
3408 		else if (bio == NULL)
3409 			bio = g_alloc_bio();
3410 		jseg->js_jblocks = jblocks;
3411 		bp = geteblk(fs->fs_bsize, 0);
3412 		ACQUIRE_LOCK(ump);
3413 		/*
3414 		 * If there was a race while we were allocating the block
3415 		 * and jseg the entry we care about was likely written.
3416 		 * We bail out in both the WAIT and NOWAIT case and assume
3417 		 * the caller will loop if the entry it cares about is
3418 		 * not written.
3419 		 */
3420 		cnt = ump->softdep_on_journal;
3421 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3422 			bp->b_flags |= B_INVAL | B_NOCACHE;
3423 			WORKITEM_FREE(jseg, D_JSEG);
3424 			FREE_LOCK(ump);
3425 			brelse(bp);
3426 			ACQUIRE_LOCK(ump);
3427 			break;
3428 		}
3429 		/*
3430 		 * Calculate the disk block size required for the available
3431 		 * records rounded to the min size.
3432 		 */
3433 		if (cnt == 0)
3434 			size = devbsize;
3435 		else if (cnt < jrecmax)
3436 			size = howmany(cnt, jrecmin) * devbsize;
3437 		else
3438 			size = fs->fs_bsize;
3439 		/*
3440 		 * Allocate a disk block for this journal data and account
3441 		 * for truncation of the requested size if enough contiguous
3442 		 * space was not available.
3443 		 */
3444 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3445 		bp->b_lblkno = bp->b_blkno;
3446 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3447 		bp->b_bcount = size;
3448 		bp->b_flags &= ~B_INVAL;
3449 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3450 		/*
3451 		 * Initialize our jseg with cnt records.  Assign the next
3452 		 * sequence number to it and link it in-order.
3453 		 */
3454 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3455 		jseg->js_buf = bp;
3456 		jseg->js_cnt = cnt;
3457 		jseg->js_refs = cnt + 1;	/* Self ref. */
3458 		jseg->js_size = size;
3459 		jseg->js_seq = jblocks->jb_nextseq++;
3460 		if (jblocks->jb_oldestseg == NULL)
3461 			jblocks->jb_oldestseg = jseg;
3462 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3463 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3464 		if (jblocks->jb_writeseg == NULL)
3465 			jblocks->jb_writeseg = jseg;
3466 		/*
3467 		 * Start filling in records from the pending list.
3468 		 */
3469 		data = bp->b_data;
3470 		off = 0;
3471 
3472 		/*
3473 		 * Always put a header on the first block.
3474 		 * XXX As with below, there might not be a chance to get
3475 		 * into the loop.  Ensure that something valid is written.
3476 		 */
3477 		jseg_write(ump, jseg, data);
3478 		off += JREC_SIZE;
3479 		data = bp->b_data + off;
3480 
3481 		/*
3482 		 * XXX Something is wrong here.  There's no work to do,
3483 		 * but we need to perform and I/O and allow it to complete
3484 		 * anyways.
3485 		 */
3486 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3487 			stat_emptyjblocks++;
3488 
3489 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3490 		    != NULL) {
3491 			if (cnt == 0)
3492 				break;
3493 			/* Place a segment header on every device block. */
3494 			if ((off % devbsize) == 0) {
3495 				jseg_write(ump, jseg, data);
3496 				off += JREC_SIZE;
3497 				data = bp->b_data + off;
3498 			}
3499 			if (wk == needwk)
3500 				needwk = NULL;
3501 			remove_from_journal(wk);
3502 			wk->wk_state |= INPROGRESS;
3503 			WORKLIST_INSERT(&jseg->js_entries, wk);
3504 			switch (wk->wk_type) {
3505 			case D_JADDREF:
3506 				jaddref_write(WK_JADDREF(wk), jseg, data);
3507 				break;
3508 			case D_JREMREF:
3509 				jremref_write(WK_JREMREF(wk), jseg, data);
3510 				break;
3511 			case D_JMVREF:
3512 				jmvref_write(WK_JMVREF(wk), jseg, data);
3513 				break;
3514 			case D_JNEWBLK:
3515 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3516 				break;
3517 			case D_JFREEBLK:
3518 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3519 				break;
3520 			case D_JFREEFRAG:
3521 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3522 				break;
3523 			case D_JTRUNC:
3524 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3525 				break;
3526 			case D_JFSYNC:
3527 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3528 				break;
3529 			default:
3530 				panic("process_journal: Unknown type %s",
3531 				    TYPENAME(wk->wk_type));
3532 				/* NOTREACHED */
3533 			}
3534 			off += JREC_SIZE;
3535 			data = bp->b_data + off;
3536 			cnt--;
3537 		}
3538 
3539 		/* Clear any remaining space so we don't leak kernel data */
3540 		if (size > off)
3541 			bzero(data, size - off);
3542 
3543 		/*
3544 		 * Write this one buffer and continue.
3545 		 */
3546 		segwritten = 1;
3547 		jblocks->jb_needseg = 0;
3548 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3549 		FREE_LOCK(ump);
3550 		pbgetvp(ump->um_devvp, bp);
3551 		/*
3552 		 * We only do the blocking wait once we find the journal
3553 		 * entry we're looking for.
3554 		 */
3555 		if (needwk == NULL && flags == MNT_WAIT)
3556 			bwrite(bp);
3557 		else
3558 			bawrite(bp);
3559 		ACQUIRE_LOCK(ump);
3560 	}
3561 	/*
3562 	 * If we wrote a segment issue a synchronize cache so the journal
3563 	 * is reflected on disk before the data is written.  Since reclaiming
3564 	 * journal space also requires writing a journal record this
3565 	 * process also enforces a barrier before reclamation.
3566 	 */
3567 	if (segwritten && shouldflush) {
3568 		softdep_synchronize(bio, ump,
3569 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3570 	} else if (bio)
3571 		g_destroy_bio(bio);
3572 	/*
3573 	 * If we've suspended the filesystem because we ran out of journal
3574 	 * space either try to sync it here to make some progress or
3575 	 * unsuspend it if we already have.
3576 	 */
3577 	if (flags == 0 && jblocks->jb_suspended) {
3578 		if (journal_unsuspend(ump))
3579 			return;
3580 		FREE_LOCK(ump);
3581 		VFS_SYNC(mp, MNT_NOWAIT);
3582 		ffs_sbupdate(ump, MNT_WAIT, 0);
3583 		ACQUIRE_LOCK(ump);
3584 	}
3585 }
3586 
3587 /*
3588  * Complete a jseg, allowing all dependencies awaiting journal writes
3589  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3590  * structures so that the journal segment can be freed to reclaim space.
3591  */
3592 static void
3593 complete_jseg(jseg)
3594 	struct jseg *jseg;
3595 {
3596 	struct worklist *wk;
3597 	struct jmvref *jmvref;
3598 #ifdef INVARIANTS
3599 	int i = 0;
3600 #endif
3601 
3602 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3603 		WORKLIST_REMOVE(wk);
3604 		wk->wk_state &= ~INPROGRESS;
3605 		wk->wk_state |= COMPLETE;
3606 		KASSERT(i++ < jseg->js_cnt,
3607 		    ("handle_written_jseg: overflow %d >= %d",
3608 		    i - 1, jseg->js_cnt));
3609 		switch (wk->wk_type) {
3610 		case D_JADDREF:
3611 			handle_written_jaddref(WK_JADDREF(wk));
3612 			break;
3613 		case D_JREMREF:
3614 			handle_written_jremref(WK_JREMREF(wk));
3615 			break;
3616 		case D_JMVREF:
3617 			rele_jseg(jseg);	/* No jsegdep. */
3618 			jmvref = WK_JMVREF(wk);
3619 			LIST_REMOVE(jmvref, jm_deps);
3620 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3621 				free_pagedep(jmvref->jm_pagedep);
3622 			WORKITEM_FREE(jmvref, D_JMVREF);
3623 			break;
3624 		case D_JNEWBLK:
3625 			handle_written_jnewblk(WK_JNEWBLK(wk));
3626 			break;
3627 		case D_JFREEBLK:
3628 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3629 			break;
3630 		case D_JTRUNC:
3631 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3632 			break;
3633 		case D_JFSYNC:
3634 			rele_jseg(jseg);	/* No jsegdep. */
3635 			WORKITEM_FREE(wk, D_JFSYNC);
3636 			break;
3637 		case D_JFREEFRAG:
3638 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3639 			break;
3640 		default:
3641 			panic("handle_written_jseg: Unknown type %s",
3642 			    TYPENAME(wk->wk_type));
3643 			/* NOTREACHED */
3644 		}
3645 	}
3646 	/* Release the self reference so the structure may be freed. */
3647 	rele_jseg(jseg);
3648 }
3649 
3650 /*
3651  * Determine which jsegs are ready for completion processing.  Waits for
3652  * synchronize cache to complete as well as forcing in-order completion
3653  * of journal entries.
3654  */
3655 static void
3656 complete_jsegs(jseg)
3657 	struct jseg *jseg;
3658 {
3659 	struct jblocks *jblocks;
3660 	struct jseg *jsegn;
3661 
3662 	jblocks = jseg->js_jblocks;
3663 	/*
3664 	 * Don't allow out of order completions.  If this isn't the first
3665 	 * block wait for it to write before we're done.
3666 	 */
3667 	if (jseg != jblocks->jb_writeseg)
3668 		return;
3669 	/* Iterate through available jsegs processing their entries. */
3670 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3671 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3672 		jsegn = TAILQ_NEXT(jseg, js_next);
3673 		complete_jseg(jseg);
3674 		jseg = jsegn;
3675 	}
3676 	jblocks->jb_writeseg = jseg;
3677 	/*
3678 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3679 	 */
3680 	free_jsegs(jblocks);
3681 }
3682 
3683 /*
3684  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3685  * the final completions.
3686  */
3687 static void
3688 handle_written_jseg(jseg, bp)
3689 	struct jseg *jseg;
3690 	struct buf *bp;
3691 {
3692 
3693 	if (jseg->js_refs == 0)
3694 		panic("handle_written_jseg: No self-reference on %p", jseg);
3695 	jseg->js_state |= DEPCOMPLETE;
3696 	/*
3697 	 * We'll never need this buffer again, set flags so it will be
3698 	 * discarded.
3699 	 */
3700 	bp->b_flags |= B_INVAL | B_NOCACHE;
3701 	pbrelvp(bp);
3702 	complete_jsegs(jseg);
3703 }
3704 
3705 static inline struct jsegdep *
3706 inoref_jseg(inoref)
3707 	struct inoref *inoref;
3708 {
3709 	struct jsegdep *jsegdep;
3710 
3711 	jsegdep = inoref->if_jsegdep;
3712 	inoref->if_jsegdep = NULL;
3713 
3714 	return (jsegdep);
3715 }
3716 
3717 /*
3718  * Called once a jremref has made it to stable store.  The jremref is marked
3719  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3720  * for the jremref to complete will be awoken by free_jremref.
3721  */
3722 static void
3723 handle_written_jremref(jremref)
3724 	struct jremref *jremref;
3725 {
3726 	struct inodedep *inodedep;
3727 	struct jsegdep *jsegdep;
3728 	struct dirrem *dirrem;
3729 
3730 	/* Grab the jsegdep. */
3731 	jsegdep = inoref_jseg(&jremref->jr_ref);
3732 	/*
3733 	 * Remove us from the inoref list.
3734 	 */
3735 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3736 	    0, &inodedep) == 0)
3737 		panic("handle_written_jremref: Lost inodedep");
3738 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3739 	/*
3740 	 * Complete the dirrem.
3741 	 */
3742 	dirrem = jremref->jr_dirrem;
3743 	jremref->jr_dirrem = NULL;
3744 	LIST_REMOVE(jremref, jr_deps);
3745 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3746 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3747 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3748 	    (dirrem->dm_state & COMPLETE) != 0)
3749 		add_to_worklist(&dirrem->dm_list, 0);
3750 	free_jremref(jremref);
3751 }
3752 
3753 /*
3754  * Called once a jaddref has made it to stable store.  The dependency is
3755  * marked complete and any dependent structures are added to the inode
3756  * bufwait list to be completed as soon as it is written.  If a bitmap write
3757  * depends on this entry we move the inode into the inodedephd of the
3758  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3759  */
3760 static void
3761 handle_written_jaddref(jaddref)
3762 	struct jaddref *jaddref;
3763 {
3764 	struct jsegdep *jsegdep;
3765 	struct inodedep *inodedep;
3766 	struct diradd *diradd;
3767 	struct mkdir *mkdir;
3768 
3769 	/* Grab the jsegdep. */
3770 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3771 	mkdir = NULL;
3772 	diradd = NULL;
3773 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3774 	    0, &inodedep) == 0)
3775 		panic("handle_written_jaddref: Lost inodedep.");
3776 	if (jaddref->ja_diradd == NULL)
3777 		panic("handle_written_jaddref: No dependency");
3778 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3779 		diradd = jaddref->ja_diradd;
3780 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3781 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3782 		mkdir = jaddref->ja_mkdir;
3783 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3784 	} else if (jaddref->ja_state & MKDIR_BODY)
3785 		mkdir = jaddref->ja_mkdir;
3786 	else
3787 		panic("handle_written_jaddref: Unknown dependency %p",
3788 		    jaddref->ja_diradd);
3789 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3790 	/*
3791 	 * Remove us from the inode list.
3792 	 */
3793 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3794 	/*
3795 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3796 	 */
3797 	if (mkdir) {
3798 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3799 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3800 		    TYPENAME(mkdir->md_list.wk_type)));
3801 		mkdir->md_jaddref = NULL;
3802 		diradd = mkdir->md_diradd;
3803 		mkdir->md_state |= DEPCOMPLETE;
3804 		complete_mkdir(mkdir);
3805 	}
3806 	jwork_insert(&diradd->da_jwork, jsegdep);
3807 	if (jaddref->ja_state & NEWBLOCK) {
3808 		inodedep->id_state |= ONDEPLIST;
3809 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3810 		    inodedep, id_deps);
3811 	}
3812 	free_jaddref(jaddref);
3813 }
3814 
3815 /*
3816  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3817  * is placed in the bmsafemap to await notification of a written bitmap.  If
3818  * the operation was canceled we add the segdep to the appropriate
3819  * dependency to free the journal space once the canceling operation
3820  * completes.
3821  */
3822 static void
3823 handle_written_jnewblk(jnewblk)
3824 	struct jnewblk *jnewblk;
3825 {
3826 	struct bmsafemap *bmsafemap;
3827 	struct freefrag *freefrag;
3828 	struct freework *freework;
3829 	struct jsegdep *jsegdep;
3830 	struct newblk *newblk;
3831 
3832 	/* Grab the jsegdep. */
3833 	jsegdep = jnewblk->jn_jsegdep;
3834 	jnewblk->jn_jsegdep = NULL;
3835 	if (jnewblk->jn_dep == NULL)
3836 		panic("handle_written_jnewblk: No dependency for the segdep.");
3837 	switch (jnewblk->jn_dep->wk_type) {
3838 	case D_NEWBLK:
3839 	case D_ALLOCDIRECT:
3840 	case D_ALLOCINDIR:
3841 		/*
3842 		 * Add the written block to the bmsafemap so it can
3843 		 * be notified when the bitmap is on disk.
3844 		 */
3845 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3846 		newblk->nb_jnewblk = NULL;
3847 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3848 			bmsafemap = newblk->nb_bmsafemap;
3849 			newblk->nb_state |= ONDEPLIST;
3850 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3851 			    nb_deps);
3852 		}
3853 		jwork_insert(&newblk->nb_jwork, jsegdep);
3854 		break;
3855 	case D_FREEFRAG:
3856 		/*
3857 		 * A newblock being removed by a freefrag when replaced by
3858 		 * frag extension.
3859 		 */
3860 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3861 		freefrag->ff_jdep = NULL;
3862 		jwork_insert(&freefrag->ff_jwork, jsegdep);
3863 		break;
3864 	case D_FREEWORK:
3865 		/*
3866 		 * A direct block was removed by truncate.
3867 		 */
3868 		freework = WK_FREEWORK(jnewblk->jn_dep);
3869 		freework->fw_jnewblk = NULL;
3870 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3871 		break;
3872 	default:
3873 		panic("handle_written_jnewblk: Unknown type %d.",
3874 		    jnewblk->jn_dep->wk_type);
3875 	}
3876 	jnewblk->jn_dep = NULL;
3877 	free_jnewblk(jnewblk);
3878 }
3879 
3880 /*
3881  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3882  * an in-flight allocation that has not yet been committed.  Divorce us
3883  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3884  * to the worklist.
3885  */
3886 static void
3887 cancel_jfreefrag(jfreefrag)
3888 	struct jfreefrag *jfreefrag;
3889 {
3890 	struct freefrag *freefrag;
3891 
3892 	if (jfreefrag->fr_jsegdep) {
3893 		free_jsegdep(jfreefrag->fr_jsegdep);
3894 		jfreefrag->fr_jsegdep = NULL;
3895 	}
3896 	freefrag = jfreefrag->fr_freefrag;
3897 	jfreefrag->fr_freefrag = NULL;
3898 	free_jfreefrag(jfreefrag);
3899 	freefrag->ff_state |= DEPCOMPLETE;
3900 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3901 }
3902 
3903 /*
3904  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3905  */
3906 static void
3907 free_jfreefrag(jfreefrag)
3908 	struct jfreefrag *jfreefrag;
3909 {
3910 
3911 	if (jfreefrag->fr_state & INPROGRESS)
3912 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3913 	else if (jfreefrag->fr_state & ONWORKLIST)
3914 		remove_from_journal(&jfreefrag->fr_list);
3915 	if (jfreefrag->fr_freefrag != NULL)
3916 		panic("free_jfreefrag:  Still attached to a freefrag.");
3917 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3918 }
3919 
3920 /*
3921  * Called when the journal write for a jfreefrag completes.  The parent
3922  * freefrag is added to the worklist if this completes its dependencies.
3923  */
3924 static void
3925 handle_written_jfreefrag(jfreefrag)
3926 	struct jfreefrag *jfreefrag;
3927 {
3928 	struct jsegdep *jsegdep;
3929 	struct freefrag *freefrag;
3930 
3931 	/* Grab the jsegdep. */
3932 	jsegdep = jfreefrag->fr_jsegdep;
3933 	jfreefrag->fr_jsegdep = NULL;
3934 	freefrag = jfreefrag->fr_freefrag;
3935 	if (freefrag == NULL)
3936 		panic("handle_written_jfreefrag: No freefrag.");
3937 	freefrag->ff_state |= DEPCOMPLETE;
3938 	freefrag->ff_jdep = NULL;
3939 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3940 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3941 		add_to_worklist(&freefrag->ff_list, 0);
3942 	jfreefrag->fr_freefrag = NULL;
3943 	free_jfreefrag(jfreefrag);
3944 }
3945 
3946 /*
3947  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3948  * is removed from the freeblks list of pending journal writes and the
3949  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3950  * have been reclaimed.
3951  */
3952 static void
3953 handle_written_jblkdep(jblkdep)
3954 	struct jblkdep *jblkdep;
3955 {
3956 	struct freeblks *freeblks;
3957 	struct jsegdep *jsegdep;
3958 
3959 	/* Grab the jsegdep. */
3960 	jsegdep = jblkdep->jb_jsegdep;
3961 	jblkdep->jb_jsegdep = NULL;
3962 	freeblks = jblkdep->jb_freeblks;
3963 	LIST_REMOVE(jblkdep, jb_deps);
3964 	jwork_insert(&freeblks->fb_jwork, jsegdep);
3965 	/*
3966 	 * If the freeblks is all journaled, we can add it to the worklist.
3967 	 */
3968 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3969 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3970 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3971 
3972 	free_jblkdep(jblkdep);
3973 }
3974 
3975 static struct jsegdep *
3976 newjsegdep(struct worklist *wk)
3977 {
3978 	struct jsegdep *jsegdep;
3979 
3980 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3981 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3982 	jsegdep->jd_seg = NULL;
3983 
3984 	return (jsegdep);
3985 }
3986 
3987 static struct jmvref *
3988 newjmvref(dp, ino, oldoff, newoff)
3989 	struct inode *dp;
3990 	ino_t ino;
3991 	off_t oldoff;
3992 	off_t newoff;
3993 {
3994 	struct jmvref *jmvref;
3995 
3996 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
3997 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
3998 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
3999 	jmvref->jm_parent = dp->i_number;
4000 	jmvref->jm_ino = ino;
4001 	jmvref->jm_oldoff = oldoff;
4002 	jmvref->jm_newoff = newoff;
4003 
4004 	return (jmvref);
4005 }
4006 
4007 /*
4008  * Allocate a new jremref that tracks the removal of ip from dp with the
4009  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4010  * DEPCOMPLETE as we have all the information required for the journal write
4011  * and the directory has already been removed from the buffer.  The caller
4012  * is responsible for linking the jremref into the pagedep and adding it
4013  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4014  * a DOTDOT addition so handle_workitem_remove() can properly assign
4015  * the jsegdep when we're done.
4016  */
4017 static struct jremref *
4018 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4019     off_t diroff, nlink_t nlink)
4020 {
4021 	struct jremref *jremref;
4022 
4023 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4024 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4025 	jremref->jr_state = ATTACHED;
4026 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4027 	   nlink, ip->i_mode);
4028 	jremref->jr_dirrem = dirrem;
4029 
4030 	return (jremref);
4031 }
4032 
4033 static inline void
4034 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4035     nlink_t nlink, uint16_t mode)
4036 {
4037 
4038 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4039 	inoref->if_diroff = diroff;
4040 	inoref->if_ino = ino;
4041 	inoref->if_parent = parent;
4042 	inoref->if_nlink = nlink;
4043 	inoref->if_mode = mode;
4044 }
4045 
4046 /*
4047  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4048  * directory offset may not be known until later.  The caller is responsible
4049  * adding the entry to the journal when this information is available.  nlink
4050  * should be the link count prior to the addition and mode is only required
4051  * to have the correct FMT.
4052  */
4053 static struct jaddref *
4054 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4055     uint16_t mode)
4056 {
4057 	struct jaddref *jaddref;
4058 
4059 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4060 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4061 	jaddref->ja_state = ATTACHED;
4062 	jaddref->ja_mkdir = NULL;
4063 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4064 
4065 	return (jaddref);
4066 }
4067 
4068 /*
4069  * Create a new free dependency for a freework.  The caller is responsible
4070  * for adjusting the reference count when it has the lock held.  The freedep
4071  * will track an outstanding bitmap write that will ultimately clear the
4072  * freework to continue.
4073  */
4074 static struct freedep *
4075 newfreedep(struct freework *freework)
4076 {
4077 	struct freedep *freedep;
4078 
4079 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4080 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4081 	freedep->fd_freework = freework;
4082 
4083 	return (freedep);
4084 }
4085 
4086 /*
4087  * Free a freedep structure once the buffer it is linked to is written.  If
4088  * this is the last reference to the freework schedule it for completion.
4089  */
4090 static void
4091 free_freedep(freedep)
4092 	struct freedep *freedep;
4093 {
4094 	struct freework *freework;
4095 
4096 	freework = freedep->fd_freework;
4097 	freework->fw_freeblks->fb_cgwait--;
4098 	if (--freework->fw_ref == 0)
4099 		freework_enqueue(freework);
4100 	WORKITEM_FREE(freedep, D_FREEDEP);
4101 }
4102 
4103 /*
4104  * Allocate a new freework structure that may be a level in an indirect
4105  * when parent is not NULL or a top level block when it is.  The top level
4106  * freework structures are allocated without the per-filesystem lock held
4107  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4108  */
4109 static struct freework *
4110 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4111 	struct ufsmount *ump;
4112 	struct freeblks *freeblks;
4113 	struct freework *parent;
4114 	ufs_lbn_t lbn;
4115 	ufs2_daddr_t nb;
4116 	int frags;
4117 	int off;
4118 	int journal;
4119 {
4120 	struct freework *freework;
4121 
4122 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4123 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4124 	freework->fw_state = ATTACHED;
4125 	freework->fw_jnewblk = NULL;
4126 	freework->fw_freeblks = freeblks;
4127 	freework->fw_parent = parent;
4128 	freework->fw_lbn = lbn;
4129 	freework->fw_blkno = nb;
4130 	freework->fw_frags = frags;
4131 	freework->fw_indir = NULL;
4132 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4133 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4134 	freework->fw_start = freework->fw_off = off;
4135 	if (journal)
4136 		newjfreeblk(freeblks, lbn, nb, frags);
4137 	if (parent == NULL) {
4138 		ACQUIRE_LOCK(ump);
4139 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4140 		freeblks->fb_ref++;
4141 		FREE_LOCK(ump);
4142 	}
4143 
4144 	return (freework);
4145 }
4146 
4147 /*
4148  * Eliminate a jfreeblk for a block that does not need journaling.
4149  */
4150 static void
4151 cancel_jfreeblk(freeblks, blkno)
4152 	struct freeblks *freeblks;
4153 	ufs2_daddr_t blkno;
4154 {
4155 	struct jfreeblk *jfreeblk;
4156 	struct jblkdep *jblkdep;
4157 
4158 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4159 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4160 			continue;
4161 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4162 		if (jfreeblk->jf_blkno == blkno)
4163 			break;
4164 	}
4165 	if (jblkdep == NULL)
4166 		return;
4167 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4168 	free_jsegdep(jblkdep->jb_jsegdep);
4169 	LIST_REMOVE(jblkdep, jb_deps);
4170 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4171 }
4172 
4173 /*
4174  * Allocate a new jfreeblk to journal top level block pointer when truncating
4175  * a file.  The caller must add this to the worklist when the per-filesystem
4176  * lock is held.
4177  */
4178 static struct jfreeblk *
4179 newjfreeblk(freeblks, lbn, blkno, frags)
4180 	struct freeblks *freeblks;
4181 	ufs_lbn_t lbn;
4182 	ufs2_daddr_t blkno;
4183 	int frags;
4184 {
4185 	struct jfreeblk *jfreeblk;
4186 
4187 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4188 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4189 	    freeblks->fb_list.wk_mp);
4190 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4191 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4192 	jfreeblk->jf_ino = freeblks->fb_inum;
4193 	jfreeblk->jf_lbn = lbn;
4194 	jfreeblk->jf_blkno = blkno;
4195 	jfreeblk->jf_frags = frags;
4196 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4197 
4198 	return (jfreeblk);
4199 }
4200 
4201 /*
4202  * The journal is only prepared to handle full-size block numbers, so we
4203  * have to adjust the record to reflect the change to a full-size block.
4204  * For example, suppose we have a block made up of fragments 8-15 and
4205  * want to free its last two fragments. We are given a request that says:
4206  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4207  * where frags are the number of fragments to free and oldfrags are the
4208  * number of fragments to keep. To block align it, we have to change it to
4209  * have a valid full-size blkno, so it becomes:
4210  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4211  */
4212 static void
4213 adjust_newfreework(freeblks, frag_offset)
4214 	struct freeblks *freeblks;
4215 	int frag_offset;
4216 {
4217 	struct jfreeblk *jfreeblk;
4218 
4219 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4220 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4221 	    ("adjust_newfreework: Missing freeblks dependency"));
4222 
4223 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4224 	jfreeblk->jf_blkno -= frag_offset;
4225 	jfreeblk->jf_frags += frag_offset;
4226 }
4227 
4228 /*
4229  * Allocate a new jtrunc to track a partial truncation.
4230  */
4231 static struct jtrunc *
4232 newjtrunc(freeblks, size, extsize)
4233 	struct freeblks *freeblks;
4234 	off_t size;
4235 	int extsize;
4236 {
4237 	struct jtrunc *jtrunc;
4238 
4239 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4240 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4241 	    freeblks->fb_list.wk_mp);
4242 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4243 	jtrunc->jt_dep.jb_freeblks = freeblks;
4244 	jtrunc->jt_ino = freeblks->fb_inum;
4245 	jtrunc->jt_size = size;
4246 	jtrunc->jt_extsize = extsize;
4247 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4248 
4249 	return (jtrunc);
4250 }
4251 
4252 /*
4253  * If we're canceling a new bitmap we have to search for another ref
4254  * to move into the bmsafemap dep.  This might be better expressed
4255  * with another structure.
4256  */
4257 static void
4258 move_newblock_dep(jaddref, inodedep)
4259 	struct jaddref *jaddref;
4260 	struct inodedep *inodedep;
4261 {
4262 	struct inoref *inoref;
4263 	struct jaddref *jaddrefn;
4264 
4265 	jaddrefn = NULL;
4266 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4267 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4268 		if ((jaddref->ja_state & NEWBLOCK) &&
4269 		    inoref->if_list.wk_type == D_JADDREF) {
4270 			jaddrefn = (struct jaddref *)inoref;
4271 			break;
4272 		}
4273 	}
4274 	if (jaddrefn == NULL)
4275 		return;
4276 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4277 	jaddrefn->ja_state |= jaddref->ja_state &
4278 	    (ATTACHED | UNDONE | NEWBLOCK);
4279 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4280 	jaddref->ja_state |= ATTACHED;
4281 	LIST_REMOVE(jaddref, ja_bmdeps);
4282 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4283 	    ja_bmdeps);
4284 }
4285 
4286 /*
4287  * Cancel a jaddref either before it has been written or while it is being
4288  * written.  This happens when a link is removed before the add reaches
4289  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4290  * and inode to prevent the link count or bitmap from reaching the disk
4291  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4292  * required.
4293  *
4294  * Returns 1 if the canceled addref requires journaling of the remove and
4295  * 0 otherwise.
4296  */
4297 static int
4298 cancel_jaddref(jaddref, inodedep, wkhd)
4299 	struct jaddref *jaddref;
4300 	struct inodedep *inodedep;
4301 	struct workhead *wkhd;
4302 {
4303 	struct inoref *inoref;
4304 	struct jsegdep *jsegdep;
4305 	int needsj;
4306 
4307 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4308 	    ("cancel_jaddref: Canceling complete jaddref"));
4309 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4310 		needsj = 1;
4311 	else
4312 		needsj = 0;
4313 	if (inodedep == NULL)
4314 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4315 		    0, &inodedep) == 0)
4316 			panic("cancel_jaddref: Lost inodedep");
4317 	/*
4318 	 * We must adjust the nlink of any reference operation that follows
4319 	 * us so that it is consistent with the in-memory reference.  This
4320 	 * ensures that inode nlink rollbacks always have the correct link.
4321 	 */
4322 	if (needsj == 0) {
4323 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4324 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4325 			if (inoref->if_state & GOINGAWAY)
4326 				break;
4327 			inoref->if_nlink--;
4328 		}
4329 	}
4330 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4331 	if (jaddref->ja_state & NEWBLOCK)
4332 		move_newblock_dep(jaddref, inodedep);
4333 	wake_worklist(&jaddref->ja_list);
4334 	jaddref->ja_mkdir = NULL;
4335 	if (jaddref->ja_state & INPROGRESS) {
4336 		jaddref->ja_state &= ~INPROGRESS;
4337 		WORKLIST_REMOVE(&jaddref->ja_list);
4338 		jwork_insert(wkhd, jsegdep);
4339 	} else {
4340 		free_jsegdep(jsegdep);
4341 		if (jaddref->ja_state & DEPCOMPLETE)
4342 			remove_from_journal(&jaddref->ja_list);
4343 	}
4344 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4345 	/*
4346 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4347 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4348 	 * no longer need this addref attached to the inoreflst and it
4349 	 * will incorrectly adjust nlink if we leave it.
4350 	 */
4351 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4352 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4353 		    if_deps);
4354 		jaddref->ja_state |= COMPLETE;
4355 		free_jaddref(jaddref);
4356 		return (needsj);
4357 	}
4358 	/*
4359 	 * Leave the head of the list for jsegdeps for fast merging.
4360 	 */
4361 	if (LIST_FIRST(wkhd) != NULL) {
4362 		jaddref->ja_state |= ONWORKLIST;
4363 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4364 	} else
4365 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4366 
4367 	return (needsj);
4368 }
4369 
4370 /*
4371  * Attempt to free a jaddref structure when some work completes.  This
4372  * should only succeed once the entry is written and all dependencies have
4373  * been notified.
4374  */
4375 static void
4376 free_jaddref(jaddref)
4377 	struct jaddref *jaddref;
4378 {
4379 
4380 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4381 		return;
4382 	if (jaddref->ja_ref.if_jsegdep)
4383 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4384 		    jaddref, jaddref->ja_state);
4385 	if (jaddref->ja_state & NEWBLOCK)
4386 		LIST_REMOVE(jaddref, ja_bmdeps);
4387 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4388 		panic("free_jaddref: Bad state %p(0x%X)",
4389 		    jaddref, jaddref->ja_state);
4390 	if (jaddref->ja_mkdir != NULL)
4391 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4392 	WORKITEM_FREE(jaddref, D_JADDREF);
4393 }
4394 
4395 /*
4396  * Free a jremref structure once it has been written or discarded.
4397  */
4398 static void
4399 free_jremref(jremref)
4400 	struct jremref *jremref;
4401 {
4402 
4403 	if (jremref->jr_ref.if_jsegdep)
4404 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4405 	if (jremref->jr_state & INPROGRESS)
4406 		panic("free_jremref: IO still pending");
4407 	WORKITEM_FREE(jremref, D_JREMREF);
4408 }
4409 
4410 /*
4411  * Free a jnewblk structure.
4412  */
4413 static void
4414 free_jnewblk(jnewblk)
4415 	struct jnewblk *jnewblk;
4416 {
4417 
4418 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4419 		return;
4420 	LIST_REMOVE(jnewblk, jn_deps);
4421 	if (jnewblk->jn_dep != NULL)
4422 		panic("free_jnewblk: Dependency still attached.");
4423 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4424 }
4425 
4426 /*
4427  * Cancel a jnewblk which has been been made redundant by frag extension.
4428  */
4429 static void
4430 cancel_jnewblk(jnewblk, wkhd)
4431 	struct jnewblk *jnewblk;
4432 	struct workhead *wkhd;
4433 {
4434 	struct jsegdep *jsegdep;
4435 
4436 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4437 	jsegdep = jnewblk->jn_jsegdep;
4438 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4439 		panic("cancel_jnewblk: Invalid state");
4440 	jnewblk->jn_jsegdep  = NULL;
4441 	jnewblk->jn_dep = NULL;
4442 	jnewblk->jn_state |= GOINGAWAY;
4443 	if (jnewblk->jn_state & INPROGRESS) {
4444 		jnewblk->jn_state &= ~INPROGRESS;
4445 		WORKLIST_REMOVE(&jnewblk->jn_list);
4446 		jwork_insert(wkhd, jsegdep);
4447 	} else {
4448 		free_jsegdep(jsegdep);
4449 		remove_from_journal(&jnewblk->jn_list);
4450 	}
4451 	wake_worklist(&jnewblk->jn_list);
4452 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4453 }
4454 
4455 static void
4456 free_jblkdep(jblkdep)
4457 	struct jblkdep *jblkdep;
4458 {
4459 
4460 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4461 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4462 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4463 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4464 	else
4465 		panic("free_jblkdep: Unexpected type %s",
4466 		    TYPENAME(jblkdep->jb_list.wk_type));
4467 }
4468 
4469 /*
4470  * Free a single jseg once it is no longer referenced in memory or on
4471  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4472  * to disappear.
4473  */
4474 static void
4475 free_jseg(jseg, jblocks)
4476 	struct jseg *jseg;
4477 	struct jblocks *jblocks;
4478 {
4479 	struct freework *freework;
4480 
4481 	/*
4482 	 * Free freework structures that were lingering to indicate freed
4483 	 * indirect blocks that forced journal write ordering on reallocate.
4484 	 */
4485 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4486 		indirblk_remove(freework);
4487 	if (jblocks->jb_oldestseg == jseg)
4488 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4489 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4490 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4491 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4492 	    ("free_jseg: Freed jseg has valid entries."));
4493 	WORKITEM_FREE(jseg, D_JSEG);
4494 }
4495 
4496 /*
4497  * Free all jsegs that meet the criteria for being reclaimed and update
4498  * oldestseg.
4499  */
4500 static void
4501 free_jsegs(jblocks)
4502 	struct jblocks *jblocks;
4503 {
4504 	struct jseg *jseg;
4505 
4506 	/*
4507 	 * Free only those jsegs which have none allocated before them to
4508 	 * preserve the journal space ordering.
4509 	 */
4510 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4511 		/*
4512 		 * Only reclaim space when nothing depends on this journal
4513 		 * set and another set has written that it is no longer
4514 		 * valid.
4515 		 */
4516 		if (jseg->js_refs != 0) {
4517 			jblocks->jb_oldestseg = jseg;
4518 			return;
4519 		}
4520 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4521 			break;
4522 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4523 			break;
4524 		/*
4525 		 * We can free jsegs that didn't write entries when
4526 		 * oldestwrseq == js_seq.
4527 		 */
4528 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4529 		    jseg->js_cnt != 0)
4530 			break;
4531 		free_jseg(jseg, jblocks);
4532 	}
4533 	/*
4534 	 * If we exited the loop above we still must discover the
4535 	 * oldest valid segment.
4536 	 */
4537 	if (jseg)
4538 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4539 		     jseg = TAILQ_NEXT(jseg, js_next))
4540 			if (jseg->js_refs != 0)
4541 				break;
4542 	jblocks->jb_oldestseg = jseg;
4543 	/*
4544 	 * The journal has no valid records but some jsegs may still be
4545 	 * waiting on oldestwrseq to advance.  We force a small record
4546 	 * out to permit these lingering records to be reclaimed.
4547 	 */
4548 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4549 		jblocks->jb_needseg = 1;
4550 }
4551 
4552 /*
4553  * Release one reference to a jseg and free it if the count reaches 0.  This
4554  * should eventually reclaim journal space as well.
4555  */
4556 static void
4557 rele_jseg(jseg)
4558 	struct jseg *jseg;
4559 {
4560 
4561 	KASSERT(jseg->js_refs > 0,
4562 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4563 	if (--jseg->js_refs != 0)
4564 		return;
4565 	free_jsegs(jseg->js_jblocks);
4566 }
4567 
4568 /*
4569  * Release a jsegdep and decrement the jseg count.
4570  */
4571 static void
4572 free_jsegdep(jsegdep)
4573 	struct jsegdep *jsegdep;
4574 {
4575 
4576 	if (jsegdep->jd_seg)
4577 		rele_jseg(jsegdep->jd_seg);
4578 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4579 }
4580 
4581 /*
4582  * Wait for a journal item to make it to disk.  Initiate journal processing
4583  * if required.
4584  */
4585 static int
4586 jwait(wk, waitfor)
4587 	struct worklist *wk;
4588 	int waitfor;
4589 {
4590 
4591 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4592 	/*
4593 	 * Blocking journal waits cause slow synchronous behavior.  Record
4594 	 * stats on the frequency of these blocking operations.
4595 	 */
4596 	if (waitfor == MNT_WAIT) {
4597 		stat_journal_wait++;
4598 		switch (wk->wk_type) {
4599 		case D_JREMREF:
4600 		case D_JMVREF:
4601 			stat_jwait_filepage++;
4602 			break;
4603 		case D_JTRUNC:
4604 		case D_JFREEBLK:
4605 			stat_jwait_freeblks++;
4606 			break;
4607 		case D_JNEWBLK:
4608 			stat_jwait_newblk++;
4609 			break;
4610 		case D_JADDREF:
4611 			stat_jwait_inode++;
4612 			break;
4613 		default:
4614 			break;
4615 		}
4616 	}
4617 	/*
4618 	 * If IO has not started we process the journal.  We can't mark the
4619 	 * worklist item as IOWAITING because we drop the lock while
4620 	 * processing the journal and the worklist entry may be freed after
4621 	 * this point.  The caller may call back in and re-issue the request.
4622 	 */
4623 	if ((wk->wk_state & INPROGRESS) == 0) {
4624 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4625 		if (waitfor != MNT_WAIT)
4626 			return (EBUSY);
4627 		return (0);
4628 	}
4629 	if (waitfor != MNT_WAIT)
4630 		return (EBUSY);
4631 	wait_worklist(wk, "jwait");
4632 	return (0);
4633 }
4634 
4635 /*
4636  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4637  * appropriate.  This is a convenience function to reduce duplicate code
4638  * for the setup and revert functions below.
4639  */
4640 static struct inodedep *
4641 inodedep_lookup_ip(ip)
4642 	struct inode *ip;
4643 {
4644 	struct inodedep *inodedep;
4645 
4646 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4647 	    ("inodedep_lookup_ip: bad delta"));
4648 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4649 	    &inodedep);
4650 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4651 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4652 
4653 	return (inodedep);
4654 }
4655 
4656 /*
4657  * Called prior to creating a new inode and linking it to a directory.  The
4658  * jaddref structure must already be allocated by softdep_setup_inomapdep
4659  * and it is discovered here so we can initialize the mode and update
4660  * nlinkdelta.
4661  */
4662 void
4663 softdep_setup_create(dp, ip)
4664 	struct inode *dp;
4665 	struct inode *ip;
4666 {
4667 	struct inodedep *inodedep;
4668 	struct jaddref *jaddref;
4669 	struct vnode *dvp;
4670 
4671 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4672 	    ("softdep_setup_create called on non-softdep filesystem"));
4673 	KASSERT(ip->i_nlink == 1,
4674 	    ("softdep_setup_create: Invalid link count."));
4675 	dvp = ITOV(dp);
4676 	ACQUIRE_LOCK(ITOUMP(dp));
4677 	inodedep = inodedep_lookup_ip(ip);
4678 	if (DOINGSUJ(dvp)) {
4679 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4680 		    inoreflst);
4681 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4682 		    ("softdep_setup_create: No addref structure present."));
4683 	}
4684 	softdep_prelink(dvp, NULL);
4685 	FREE_LOCK(ITOUMP(dp));
4686 }
4687 
4688 /*
4689  * Create a jaddref structure to track the addition of a DOTDOT link when
4690  * we are reparenting an inode as part of a rename.  This jaddref will be
4691  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4692  * non-journaling softdep.
4693  */
4694 void
4695 softdep_setup_dotdot_link(dp, ip)
4696 	struct inode *dp;
4697 	struct inode *ip;
4698 {
4699 	struct inodedep *inodedep;
4700 	struct jaddref *jaddref;
4701 	struct vnode *dvp;
4702 
4703 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4704 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4705 	dvp = ITOV(dp);
4706 	jaddref = NULL;
4707 	/*
4708 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4709 	 * is used as a normal link would be.
4710 	 */
4711 	if (DOINGSUJ(dvp))
4712 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4713 		    dp->i_effnlink - 1, dp->i_mode);
4714 	ACQUIRE_LOCK(ITOUMP(dp));
4715 	inodedep = inodedep_lookup_ip(dp);
4716 	if (jaddref)
4717 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4718 		    if_deps);
4719 	softdep_prelink(dvp, ITOV(ip));
4720 	FREE_LOCK(ITOUMP(dp));
4721 }
4722 
4723 /*
4724  * Create a jaddref structure to track a new link to an inode.  The directory
4725  * offset is not known until softdep_setup_directory_add or
4726  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4727  * softdep.
4728  */
4729 void
4730 softdep_setup_link(dp, ip)
4731 	struct inode *dp;
4732 	struct inode *ip;
4733 {
4734 	struct inodedep *inodedep;
4735 	struct jaddref *jaddref;
4736 	struct vnode *dvp;
4737 
4738 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4739 	    ("softdep_setup_link called on non-softdep filesystem"));
4740 	dvp = ITOV(dp);
4741 	jaddref = NULL;
4742 	if (DOINGSUJ(dvp))
4743 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4744 		    ip->i_mode);
4745 	ACQUIRE_LOCK(ITOUMP(dp));
4746 	inodedep = inodedep_lookup_ip(ip);
4747 	if (jaddref)
4748 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4749 		    if_deps);
4750 	softdep_prelink(dvp, ITOV(ip));
4751 	FREE_LOCK(ITOUMP(dp));
4752 }
4753 
4754 /*
4755  * Called to create the jaddref structures to track . and .. references as
4756  * well as lookup and further initialize the incomplete jaddref created
4757  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4758  * nlinkdelta for non-journaling softdep.
4759  */
4760 void
4761 softdep_setup_mkdir(dp, ip)
4762 	struct inode *dp;
4763 	struct inode *ip;
4764 {
4765 	struct inodedep *inodedep;
4766 	struct jaddref *dotdotaddref;
4767 	struct jaddref *dotaddref;
4768 	struct jaddref *jaddref;
4769 	struct vnode *dvp;
4770 
4771 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4772 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
4773 	dvp = ITOV(dp);
4774 	dotaddref = dotdotaddref = NULL;
4775 	if (DOINGSUJ(dvp)) {
4776 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4777 		    ip->i_mode);
4778 		dotaddref->ja_state |= MKDIR_BODY;
4779 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4780 		    dp->i_effnlink - 1, dp->i_mode);
4781 		dotdotaddref->ja_state |= MKDIR_PARENT;
4782 	}
4783 	ACQUIRE_LOCK(ITOUMP(dp));
4784 	inodedep = inodedep_lookup_ip(ip);
4785 	if (DOINGSUJ(dvp)) {
4786 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4787 		    inoreflst);
4788 		KASSERT(jaddref != NULL,
4789 		    ("softdep_setup_mkdir: No addref structure present."));
4790 		KASSERT(jaddref->ja_parent == dp->i_number,
4791 		    ("softdep_setup_mkdir: bad parent %ju",
4792 		    (uintmax_t)jaddref->ja_parent));
4793 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4794 		    if_deps);
4795 	}
4796 	inodedep = inodedep_lookup_ip(dp);
4797 	if (DOINGSUJ(dvp))
4798 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4799 		    &dotdotaddref->ja_ref, if_deps);
4800 	softdep_prelink(ITOV(dp), NULL);
4801 	FREE_LOCK(ITOUMP(dp));
4802 }
4803 
4804 /*
4805  * Called to track nlinkdelta of the inode and parent directories prior to
4806  * unlinking a directory.
4807  */
4808 void
4809 softdep_setup_rmdir(dp, ip)
4810 	struct inode *dp;
4811 	struct inode *ip;
4812 {
4813 	struct vnode *dvp;
4814 
4815 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4816 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4817 	dvp = ITOV(dp);
4818 	ACQUIRE_LOCK(ITOUMP(dp));
4819 	(void) inodedep_lookup_ip(ip);
4820 	(void) inodedep_lookup_ip(dp);
4821 	softdep_prelink(dvp, ITOV(ip));
4822 	FREE_LOCK(ITOUMP(dp));
4823 }
4824 
4825 /*
4826  * Called to track nlinkdelta of the inode and parent directories prior to
4827  * unlink.
4828  */
4829 void
4830 softdep_setup_unlink(dp, ip)
4831 	struct inode *dp;
4832 	struct inode *ip;
4833 {
4834 	struct vnode *dvp;
4835 
4836 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4837 	    ("softdep_setup_unlink called on non-softdep filesystem"));
4838 	dvp = ITOV(dp);
4839 	ACQUIRE_LOCK(ITOUMP(dp));
4840 	(void) inodedep_lookup_ip(ip);
4841 	(void) inodedep_lookup_ip(dp);
4842 	softdep_prelink(dvp, ITOV(ip));
4843 	FREE_LOCK(ITOUMP(dp));
4844 }
4845 
4846 /*
4847  * Called to release the journal structures created by a failed non-directory
4848  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4849  */
4850 void
4851 softdep_revert_create(dp, ip)
4852 	struct inode *dp;
4853 	struct inode *ip;
4854 {
4855 	struct inodedep *inodedep;
4856 	struct jaddref *jaddref;
4857 	struct vnode *dvp;
4858 
4859 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4860 	    ("softdep_revert_create called on non-softdep filesystem"));
4861 	dvp = ITOV(dp);
4862 	ACQUIRE_LOCK(ITOUMP(dp));
4863 	inodedep = inodedep_lookup_ip(ip);
4864 	if (DOINGSUJ(dvp)) {
4865 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4866 		    inoreflst);
4867 		KASSERT(jaddref->ja_parent == dp->i_number,
4868 		    ("softdep_revert_create: addref parent mismatch"));
4869 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4870 	}
4871 	FREE_LOCK(ITOUMP(dp));
4872 }
4873 
4874 /*
4875  * Called to release the journal structures created by a failed link
4876  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4877  */
4878 void
4879 softdep_revert_link(dp, ip)
4880 	struct inode *dp;
4881 	struct inode *ip;
4882 {
4883 	struct inodedep *inodedep;
4884 	struct jaddref *jaddref;
4885 	struct vnode *dvp;
4886 
4887 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4888 	    ("softdep_revert_link called on non-softdep filesystem"));
4889 	dvp = ITOV(dp);
4890 	ACQUIRE_LOCK(ITOUMP(dp));
4891 	inodedep = inodedep_lookup_ip(ip);
4892 	if (DOINGSUJ(dvp)) {
4893 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4894 		    inoreflst);
4895 		KASSERT(jaddref->ja_parent == dp->i_number,
4896 		    ("softdep_revert_link: addref parent mismatch"));
4897 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4898 	}
4899 	FREE_LOCK(ITOUMP(dp));
4900 }
4901 
4902 /*
4903  * Called to release the journal structures created by a failed mkdir
4904  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4905  */
4906 void
4907 softdep_revert_mkdir(dp, ip)
4908 	struct inode *dp;
4909 	struct inode *ip;
4910 {
4911 	struct inodedep *inodedep;
4912 	struct jaddref *jaddref;
4913 	struct jaddref *dotaddref;
4914 	struct vnode *dvp;
4915 
4916 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4917 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4918 	dvp = ITOV(dp);
4919 
4920 	ACQUIRE_LOCK(ITOUMP(dp));
4921 	inodedep = inodedep_lookup_ip(dp);
4922 	if (DOINGSUJ(dvp)) {
4923 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4924 		    inoreflst);
4925 		KASSERT(jaddref->ja_parent == ip->i_number,
4926 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4927 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4928 	}
4929 	inodedep = inodedep_lookup_ip(ip);
4930 	if (DOINGSUJ(dvp)) {
4931 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4932 		    inoreflst);
4933 		KASSERT(jaddref->ja_parent == dp->i_number,
4934 		    ("softdep_revert_mkdir: addref parent mismatch"));
4935 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4936 		    inoreflst, if_deps);
4937 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4938 		KASSERT(dotaddref->ja_parent == ip->i_number,
4939 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4940 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4941 	}
4942 	FREE_LOCK(ITOUMP(dp));
4943 }
4944 
4945 /*
4946  * Called to correct nlinkdelta after a failed rmdir.
4947  */
4948 void
4949 softdep_revert_rmdir(dp, ip)
4950 	struct inode *dp;
4951 	struct inode *ip;
4952 {
4953 
4954 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4955 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
4956 	ACQUIRE_LOCK(ITOUMP(dp));
4957 	(void) inodedep_lookup_ip(ip);
4958 	(void) inodedep_lookup_ip(dp);
4959 	FREE_LOCK(ITOUMP(dp));
4960 }
4961 
4962 /*
4963  * Protecting the freemaps (or bitmaps).
4964  *
4965  * To eliminate the need to execute fsck before mounting a filesystem
4966  * after a power failure, one must (conservatively) guarantee that the
4967  * on-disk copy of the bitmaps never indicate that a live inode or block is
4968  * free.  So, when a block or inode is allocated, the bitmap should be
4969  * updated (on disk) before any new pointers.  When a block or inode is
4970  * freed, the bitmap should not be updated until all pointers have been
4971  * reset.  The latter dependency is handled by the delayed de-allocation
4972  * approach described below for block and inode de-allocation.  The former
4973  * dependency is handled by calling the following procedure when a block or
4974  * inode is allocated. When an inode is allocated an "inodedep" is created
4975  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4976  * Each "inodedep" is also inserted into the hash indexing structure so
4977  * that any additional link additions can be made dependent on the inode
4978  * allocation.
4979  *
4980  * The ufs filesystem maintains a number of free block counts (e.g., per
4981  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4982  * in addition to the bitmaps.  These counts are used to improve efficiency
4983  * during allocation and therefore must be consistent with the bitmaps.
4984  * There is no convenient way to guarantee post-crash consistency of these
4985  * counts with simple update ordering, for two main reasons: (1) The counts
4986  * and bitmaps for a single cylinder group block are not in the same disk
4987  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4988  * be written and the other not.  (2) Some of the counts are located in the
4989  * superblock rather than the cylinder group block. So, we focus our soft
4990  * updates implementation on protecting the bitmaps. When mounting a
4991  * filesystem, we recompute the auxiliary counts from the bitmaps.
4992  */
4993 
4994 /*
4995  * Called just after updating the cylinder group block to allocate an inode.
4996  */
4997 void
4998 softdep_setup_inomapdep(bp, ip, newinum, mode)
4999 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5000 	struct inode *ip;	/* inode related to allocation */
5001 	ino_t newinum;		/* new inode number being allocated */
5002 	int mode;
5003 {
5004 	struct inodedep *inodedep;
5005 	struct bmsafemap *bmsafemap;
5006 	struct jaddref *jaddref;
5007 	struct mount *mp;
5008 	struct fs *fs;
5009 
5010 	mp = ITOVFS(ip);
5011 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5012 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5013 	fs = VFSTOUFS(mp)->um_fs;
5014 	jaddref = NULL;
5015 
5016 	/*
5017 	 * Allocate the journal reference add structure so that the bitmap
5018 	 * can be dependent on it.
5019 	 */
5020 	if (MOUNTEDSUJ(mp)) {
5021 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5022 		jaddref->ja_state |= NEWBLOCK;
5023 	}
5024 
5025 	/*
5026 	 * Create a dependency for the newly allocated inode.
5027 	 * Panic if it already exists as something is seriously wrong.
5028 	 * Otherwise add it to the dependency list for the buffer holding
5029 	 * the cylinder group map from which it was allocated.
5030 	 *
5031 	 * We have to preallocate a bmsafemap entry in case it is needed
5032 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5033 	 * have to finish initializing it before we can FREE_LOCK().
5034 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5035 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5036 	 * creating the inodedep as it can be freed during the time
5037 	 * that we FREE_LOCK() while allocating the inodedep. We must
5038 	 * call workitem_alloc() before entering the locked section as
5039 	 * it also acquires the lock and we must avoid trying doing so
5040 	 * recursively.
5041 	 */
5042 	bmsafemap = malloc(sizeof(struct bmsafemap),
5043 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5044 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5045 	ACQUIRE_LOCK(ITOUMP(ip));
5046 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5047 		panic("softdep_setup_inomapdep: dependency %p for new"
5048 		    "inode already exists", inodedep);
5049 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5050 	if (jaddref) {
5051 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5052 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5053 		    if_deps);
5054 	} else {
5055 		inodedep->id_state |= ONDEPLIST;
5056 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5057 	}
5058 	inodedep->id_bmsafemap = bmsafemap;
5059 	inodedep->id_state &= ~DEPCOMPLETE;
5060 	FREE_LOCK(ITOUMP(ip));
5061 }
5062 
5063 /*
5064  * Called just after updating the cylinder group block to
5065  * allocate block or fragment.
5066  */
5067 void
5068 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5069 	struct buf *bp;		/* buffer for cylgroup block with block map */
5070 	struct mount *mp;	/* filesystem doing allocation */
5071 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5072 	int frags;		/* Number of fragments. */
5073 	int oldfrags;		/* Previous number of fragments for extend. */
5074 {
5075 	struct newblk *newblk;
5076 	struct bmsafemap *bmsafemap;
5077 	struct jnewblk *jnewblk;
5078 	struct ufsmount *ump;
5079 	struct fs *fs;
5080 
5081 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5082 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5083 	ump = VFSTOUFS(mp);
5084 	fs = ump->um_fs;
5085 	jnewblk = NULL;
5086 	/*
5087 	 * Create a dependency for the newly allocated block.
5088 	 * Add it to the dependency list for the buffer holding
5089 	 * the cylinder group map from which it was allocated.
5090 	 */
5091 	if (MOUNTEDSUJ(mp)) {
5092 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5093 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5094 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5095 		jnewblk->jn_state = ATTACHED;
5096 		jnewblk->jn_blkno = newblkno;
5097 		jnewblk->jn_frags = frags;
5098 		jnewblk->jn_oldfrags = oldfrags;
5099 #ifdef SUJ_DEBUG
5100 		{
5101 			struct cg *cgp;
5102 			uint8_t *blksfree;
5103 			long bno;
5104 			int i;
5105 
5106 			cgp = (struct cg *)bp->b_data;
5107 			blksfree = cg_blksfree(cgp);
5108 			bno = dtogd(fs, jnewblk->jn_blkno);
5109 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5110 			    i++) {
5111 				if (isset(blksfree, bno + i))
5112 					panic("softdep_setup_blkmapdep: "
5113 					    "free fragment %d from %d-%d "
5114 					    "state 0x%X dep %p", i,
5115 					    jnewblk->jn_oldfrags,
5116 					    jnewblk->jn_frags,
5117 					    jnewblk->jn_state,
5118 					    jnewblk->jn_dep);
5119 			}
5120 		}
5121 #endif
5122 	}
5123 
5124 	CTR3(KTR_SUJ,
5125 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5126 	    newblkno, frags, oldfrags);
5127 	ACQUIRE_LOCK(ump);
5128 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5129 		panic("softdep_setup_blkmapdep: found block");
5130 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5131 	    dtog(fs, newblkno), NULL);
5132 	if (jnewblk) {
5133 		jnewblk->jn_dep = (struct worklist *)newblk;
5134 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5135 	} else {
5136 		newblk->nb_state |= ONDEPLIST;
5137 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5138 	}
5139 	newblk->nb_bmsafemap = bmsafemap;
5140 	newblk->nb_jnewblk = jnewblk;
5141 	FREE_LOCK(ump);
5142 }
5143 
5144 #define	BMSAFEMAP_HASH(ump, cg) \
5145       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5146 
5147 static int
5148 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5149 	struct bmsafemap_hashhead *bmsafemaphd;
5150 	int cg;
5151 	struct bmsafemap **bmsafemapp;
5152 {
5153 	struct bmsafemap *bmsafemap;
5154 
5155 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5156 		if (bmsafemap->sm_cg == cg)
5157 			break;
5158 	if (bmsafemap) {
5159 		*bmsafemapp = bmsafemap;
5160 		return (1);
5161 	}
5162 	*bmsafemapp = NULL;
5163 
5164 	return (0);
5165 }
5166 
5167 /*
5168  * Find the bmsafemap associated with a cylinder group buffer.
5169  * If none exists, create one. The buffer must be locked when
5170  * this routine is called and this routine must be called with
5171  * the softdep lock held. To avoid giving up the lock while
5172  * allocating a new bmsafemap, a preallocated bmsafemap may be
5173  * provided. If it is provided but not needed, it is freed.
5174  */
5175 static struct bmsafemap *
5176 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5177 	struct mount *mp;
5178 	struct buf *bp;
5179 	int cg;
5180 	struct bmsafemap *newbmsafemap;
5181 {
5182 	struct bmsafemap_hashhead *bmsafemaphd;
5183 	struct bmsafemap *bmsafemap, *collision;
5184 	struct worklist *wk;
5185 	struct ufsmount *ump;
5186 
5187 	ump = VFSTOUFS(mp);
5188 	LOCK_OWNED(ump);
5189 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5190 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5191 		if (wk->wk_type == D_BMSAFEMAP) {
5192 			if (newbmsafemap)
5193 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5194 			return (WK_BMSAFEMAP(wk));
5195 		}
5196 	}
5197 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5198 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5199 		if (newbmsafemap)
5200 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5201 		return (bmsafemap);
5202 	}
5203 	if (newbmsafemap) {
5204 		bmsafemap = newbmsafemap;
5205 	} else {
5206 		FREE_LOCK(ump);
5207 		bmsafemap = malloc(sizeof(struct bmsafemap),
5208 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5209 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5210 		ACQUIRE_LOCK(ump);
5211 	}
5212 	bmsafemap->sm_buf = bp;
5213 	LIST_INIT(&bmsafemap->sm_inodedephd);
5214 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5215 	LIST_INIT(&bmsafemap->sm_newblkhd);
5216 	LIST_INIT(&bmsafemap->sm_newblkwr);
5217 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5218 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5219 	LIST_INIT(&bmsafemap->sm_freehd);
5220 	LIST_INIT(&bmsafemap->sm_freewr);
5221 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5222 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5223 		return (collision);
5224 	}
5225 	bmsafemap->sm_cg = cg;
5226 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5227 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5228 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5229 	return (bmsafemap);
5230 }
5231 
5232 /*
5233  * Direct block allocation dependencies.
5234  *
5235  * When a new block is allocated, the corresponding disk locations must be
5236  * initialized (with zeros or new data) before the on-disk inode points to
5237  * them.  Also, the freemap from which the block was allocated must be
5238  * updated (on disk) before the inode's pointer. These two dependencies are
5239  * independent of each other and are needed for all file blocks and indirect
5240  * blocks that are pointed to directly by the inode.  Just before the
5241  * "in-core" version of the inode is updated with a newly allocated block
5242  * number, a procedure (below) is called to setup allocation dependency
5243  * structures.  These structures are removed when the corresponding
5244  * dependencies are satisfied or when the block allocation becomes obsolete
5245  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5246  * fragment that gets upgraded).  All of these cases are handled in
5247  * procedures described later.
5248  *
5249  * When a file extension causes a fragment to be upgraded, either to a larger
5250  * fragment or to a full block, the on-disk location may change (if the
5251  * previous fragment could not simply be extended). In this case, the old
5252  * fragment must be de-allocated, but not until after the inode's pointer has
5253  * been updated. In most cases, this is handled by later procedures, which
5254  * will construct a "freefrag" structure to be added to the workitem queue
5255  * when the inode update is complete (or obsolete).  The main exception to
5256  * this is when an allocation occurs while a pending allocation dependency
5257  * (for the same block pointer) remains.  This case is handled in the main
5258  * allocation dependency setup procedure by immediately freeing the
5259  * unreferenced fragments.
5260  */
5261 void
5262 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5263 	struct inode *ip;	/* inode to which block is being added */
5264 	ufs_lbn_t off;		/* block pointer within inode */
5265 	ufs2_daddr_t newblkno;	/* disk block number being added */
5266 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5267 	long newsize;		/* size of new block */
5268 	long oldsize;		/* size of new block */
5269 	struct buf *bp;		/* bp for allocated block */
5270 {
5271 	struct allocdirect *adp, *oldadp;
5272 	struct allocdirectlst *adphead;
5273 	struct freefrag *freefrag;
5274 	struct inodedep *inodedep;
5275 	struct pagedep *pagedep;
5276 	struct jnewblk *jnewblk;
5277 	struct newblk *newblk;
5278 	struct mount *mp;
5279 	ufs_lbn_t lbn;
5280 
5281 	lbn = bp->b_lblkno;
5282 	mp = ITOVFS(ip);
5283 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5284 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5285 	if (oldblkno && oldblkno != newblkno)
5286 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5287 	else
5288 		freefrag = NULL;
5289 
5290 	CTR6(KTR_SUJ,
5291 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5292 	    "off %jd newsize %ld oldsize %d",
5293 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5294 	ACQUIRE_LOCK(ITOUMP(ip));
5295 	if (off >= UFS_NDADDR) {
5296 		if (lbn > 0)
5297 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5298 			    lbn, off);
5299 		/* allocating an indirect block */
5300 		if (oldblkno != 0)
5301 			panic("softdep_setup_allocdirect: non-zero indir");
5302 	} else {
5303 		if (off != lbn)
5304 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5305 			    lbn, off);
5306 		/*
5307 		 * Allocating a direct block.
5308 		 *
5309 		 * If we are allocating a directory block, then we must
5310 		 * allocate an associated pagedep to track additions and
5311 		 * deletions.
5312 		 */
5313 		if ((ip->i_mode & IFMT) == IFDIR)
5314 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5315 			    &pagedep);
5316 	}
5317 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5318 		panic("softdep_setup_allocdirect: lost block");
5319 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5320 	    ("softdep_setup_allocdirect: newblk already initialized"));
5321 	/*
5322 	 * Convert the newblk to an allocdirect.
5323 	 */
5324 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5325 	adp = (struct allocdirect *)newblk;
5326 	newblk->nb_freefrag = freefrag;
5327 	adp->ad_offset = off;
5328 	adp->ad_oldblkno = oldblkno;
5329 	adp->ad_newsize = newsize;
5330 	adp->ad_oldsize = oldsize;
5331 
5332 	/*
5333 	 * Finish initializing the journal.
5334 	 */
5335 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5336 		jnewblk->jn_ino = ip->i_number;
5337 		jnewblk->jn_lbn = lbn;
5338 		add_to_journal(&jnewblk->jn_list);
5339 	}
5340 	if (freefrag && freefrag->ff_jdep != NULL &&
5341 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5342 		add_to_journal(freefrag->ff_jdep);
5343 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5344 	adp->ad_inodedep = inodedep;
5345 
5346 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5347 	/*
5348 	 * The list of allocdirects must be kept in sorted and ascending
5349 	 * order so that the rollback routines can quickly determine the
5350 	 * first uncommitted block (the size of the file stored on disk
5351 	 * ends at the end of the lowest committed fragment, or if there
5352 	 * are no fragments, at the end of the highest committed block).
5353 	 * Since files generally grow, the typical case is that the new
5354 	 * block is to be added at the end of the list. We speed this
5355 	 * special case by checking against the last allocdirect in the
5356 	 * list before laboriously traversing the list looking for the
5357 	 * insertion point.
5358 	 */
5359 	adphead = &inodedep->id_newinoupdt;
5360 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5361 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5362 		/* insert at end of list */
5363 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5364 		if (oldadp != NULL && oldadp->ad_offset == off)
5365 			allocdirect_merge(adphead, adp, oldadp);
5366 		FREE_LOCK(ITOUMP(ip));
5367 		return;
5368 	}
5369 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5370 		if (oldadp->ad_offset >= off)
5371 			break;
5372 	}
5373 	if (oldadp == NULL)
5374 		panic("softdep_setup_allocdirect: lost entry");
5375 	/* insert in middle of list */
5376 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5377 	if (oldadp->ad_offset == off)
5378 		allocdirect_merge(adphead, adp, oldadp);
5379 
5380 	FREE_LOCK(ITOUMP(ip));
5381 }
5382 
5383 /*
5384  * Merge a newer and older journal record to be stored either in a
5385  * newblock or freefrag.  This handles aggregating journal records for
5386  * fragment allocation into a second record as well as replacing a
5387  * journal free with an aborted journal allocation.  A segment for the
5388  * oldest record will be placed on wkhd if it has been written.  If not
5389  * the segment for the newer record will suffice.
5390  */
5391 static struct worklist *
5392 jnewblk_merge(new, old, wkhd)
5393 	struct worklist *new;
5394 	struct worklist *old;
5395 	struct workhead *wkhd;
5396 {
5397 	struct jnewblk *njnewblk;
5398 	struct jnewblk *jnewblk;
5399 
5400 	/* Handle NULLs to simplify callers. */
5401 	if (new == NULL)
5402 		return (old);
5403 	if (old == NULL)
5404 		return (new);
5405 	/* Replace a jfreefrag with a jnewblk. */
5406 	if (new->wk_type == D_JFREEFRAG) {
5407 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5408 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5409 			    old, new);
5410 		cancel_jfreefrag(WK_JFREEFRAG(new));
5411 		return (old);
5412 	}
5413 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5414 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5415 		    old->wk_type, new->wk_type);
5416 	/*
5417 	 * Handle merging of two jnewblk records that describe
5418 	 * different sets of fragments in the same block.
5419 	 */
5420 	jnewblk = WK_JNEWBLK(old);
5421 	njnewblk = WK_JNEWBLK(new);
5422 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5423 		panic("jnewblk_merge: Merging disparate blocks.");
5424 	/*
5425 	 * The record may be rolled back in the cg.
5426 	 */
5427 	if (jnewblk->jn_state & UNDONE) {
5428 		jnewblk->jn_state &= ~UNDONE;
5429 		njnewblk->jn_state |= UNDONE;
5430 		njnewblk->jn_state &= ~ATTACHED;
5431 	}
5432 	/*
5433 	 * We modify the newer addref and free the older so that if neither
5434 	 * has been written the most up-to-date copy will be on disk.  If
5435 	 * both have been written but rolled back we only temporarily need
5436 	 * one of them to fix the bits when the cg write completes.
5437 	 */
5438 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5439 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5440 	cancel_jnewblk(jnewblk, wkhd);
5441 	WORKLIST_REMOVE(&jnewblk->jn_list);
5442 	free_jnewblk(jnewblk);
5443 	return (new);
5444 }
5445 
5446 /*
5447  * Replace an old allocdirect dependency with a newer one.
5448  * This routine must be called with splbio interrupts blocked.
5449  */
5450 static void
5451 allocdirect_merge(adphead, newadp, oldadp)
5452 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5453 	struct allocdirect *newadp;	/* allocdirect being added */
5454 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5455 {
5456 	struct worklist *wk;
5457 	struct freefrag *freefrag;
5458 
5459 	freefrag = NULL;
5460 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5461 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5462 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5463 	    newadp->ad_offset >= UFS_NDADDR)
5464 		panic("%s %jd != new %jd || old size %ld != new %ld",
5465 		    "allocdirect_merge: old blkno",
5466 		    (intmax_t)newadp->ad_oldblkno,
5467 		    (intmax_t)oldadp->ad_newblkno,
5468 		    newadp->ad_oldsize, oldadp->ad_newsize);
5469 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5470 	newadp->ad_oldsize = oldadp->ad_oldsize;
5471 	/*
5472 	 * If the old dependency had a fragment to free or had never
5473 	 * previously had a block allocated, then the new dependency
5474 	 * can immediately post its freefrag and adopt the old freefrag.
5475 	 * This action is done by swapping the freefrag dependencies.
5476 	 * The new dependency gains the old one's freefrag, and the
5477 	 * old one gets the new one and then immediately puts it on
5478 	 * the worklist when it is freed by free_newblk. It is
5479 	 * not possible to do this swap when the old dependency had a
5480 	 * non-zero size but no previous fragment to free. This condition
5481 	 * arises when the new block is an extension of the old block.
5482 	 * Here, the first part of the fragment allocated to the new
5483 	 * dependency is part of the block currently claimed on disk by
5484 	 * the old dependency, so cannot legitimately be freed until the
5485 	 * conditions for the new dependency are fulfilled.
5486 	 */
5487 	freefrag = newadp->ad_freefrag;
5488 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5489 		newadp->ad_freefrag = oldadp->ad_freefrag;
5490 		oldadp->ad_freefrag = freefrag;
5491 	}
5492 	/*
5493 	 * If we are tracking a new directory-block allocation,
5494 	 * move it from the old allocdirect to the new allocdirect.
5495 	 */
5496 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5497 		WORKLIST_REMOVE(wk);
5498 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5499 			panic("allocdirect_merge: extra newdirblk");
5500 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5501 	}
5502 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5503 	/*
5504 	 * We need to move any journal dependencies over to the freefrag
5505 	 * that releases this block if it exists.  Otherwise we are
5506 	 * extending an existing block and we'll wait until that is
5507 	 * complete to release the journal space and extend the
5508 	 * new journal to cover this old space as well.
5509 	 */
5510 	if (freefrag == NULL) {
5511 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5512 			panic("allocdirect_merge: %jd != %jd",
5513 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5514 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5515 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5516 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5517 		    &newadp->ad_block.nb_jwork);
5518 		oldadp->ad_block.nb_jnewblk = NULL;
5519 		cancel_newblk(&oldadp->ad_block, NULL,
5520 		    &newadp->ad_block.nb_jwork);
5521 	} else {
5522 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5523 		    &freefrag->ff_list, &freefrag->ff_jwork);
5524 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5525 		    &freefrag->ff_jwork);
5526 	}
5527 	free_newblk(&oldadp->ad_block);
5528 }
5529 
5530 /*
5531  * Allocate a jfreefrag structure to journal a single block free.
5532  */
5533 static struct jfreefrag *
5534 newjfreefrag(freefrag, ip, blkno, size, lbn)
5535 	struct freefrag *freefrag;
5536 	struct inode *ip;
5537 	ufs2_daddr_t blkno;
5538 	long size;
5539 	ufs_lbn_t lbn;
5540 {
5541 	struct jfreefrag *jfreefrag;
5542 	struct fs *fs;
5543 
5544 	fs = ITOFS(ip);
5545 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5546 	    M_SOFTDEP_FLAGS);
5547 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5548 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5549 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5550 	jfreefrag->fr_ino = ip->i_number;
5551 	jfreefrag->fr_lbn = lbn;
5552 	jfreefrag->fr_blkno = blkno;
5553 	jfreefrag->fr_frags = numfrags(fs, size);
5554 	jfreefrag->fr_freefrag = freefrag;
5555 
5556 	return (jfreefrag);
5557 }
5558 
5559 /*
5560  * Allocate a new freefrag structure.
5561  */
5562 static struct freefrag *
5563 newfreefrag(ip, blkno, size, lbn)
5564 	struct inode *ip;
5565 	ufs2_daddr_t blkno;
5566 	long size;
5567 	ufs_lbn_t lbn;
5568 {
5569 	struct freefrag *freefrag;
5570 	struct ufsmount *ump;
5571 	struct fs *fs;
5572 
5573 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5574 	    ip->i_number, blkno, size, lbn);
5575 	ump = ITOUMP(ip);
5576 	fs = ump->um_fs;
5577 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5578 		panic("newfreefrag: frag size");
5579 	freefrag = malloc(sizeof(struct freefrag),
5580 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5581 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5582 	freefrag->ff_state = ATTACHED;
5583 	LIST_INIT(&freefrag->ff_jwork);
5584 	freefrag->ff_inum = ip->i_number;
5585 	freefrag->ff_vtype = ITOV(ip)->v_type;
5586 	freefrag->ff_blkno = blkno;
5587 	freefrag->ff_fragsize = size;
5588 
5589 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5590 		freefrag->ff_jdep = (struct worklist *)
5591 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5592 	} else {
5593 		freefrag->ff_state |= DEPCOMPLETE;
5594 		freefrag->ff_jdep = NULL;
5595 	}
5596 
5597 	return (freefrag);
5598 }
5599 
5600 /*
5601  * This workitem de-allocates fragments that were replaced during
5602  * file block allocation.
5603  */
5604 static void
5605 handle_workitem_freefrag(freefrag)
5606 	struct freefrag *freefrag;
5607 {
5608 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5609 	struct workhead wkhd;
5610 
5611 	CTR3(KTR_SUJ,
5612 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5613 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5614 	/*
5615 	 * It would be illegal to add new completion items to the
5616 	 * freefrag after it was schedule to be done so it must be
5617 	 * safe to modify the list head here.
5618 	 */
5619 	LIST_INIT(&wkhd);
5620 	ACQUIRE_LOCK(ump);
5621 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5622 	/*
5623 	 * If the journal has not been written we must cancel it here.
5624 	 */
5625 	if (freefrag->ff_jdep) {
5626 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5627 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5628 			    freefrag->ff_jdep->wk_type);
5629 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5630 	}
5631 	FREE_LOCK(ump);
5632 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5633 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5634 	ACQUIRE_LOCK(ump);
5635 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5636 	FREE_LOCK(ump);
5637 }
5638 
5639 /*
5640  * Set up a dependency structure for an external attributes data block.
5641  * This routine follows much of the structure of softdep_setup_allocdirect.
5642  * See the description of softdep_setup_allocdirect above for details.
5643  */
5644 void
5645 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5646 	struct inode *ip;
5647 	ufs_lbn_t off;
5648 	ufs2_daddr_t newblkno;
5649 	ufs2_daddr_t oldblkno;
5650 	long newsize;
5651 	long oldsize;
5652 	struct buf *bp;
5653 {
5654 	struct allocdirect *adp, *oldadp;
5655 	struct allocdirectlst *adphead;
5656 	struct freefrag *freefrag;
5657 	struct inodedep *inodedep;
5658 	struct jnewblk *jnewblk;
5659 	struct newblk *newblk;
5660 	struct mount *mp;
5661 	struct ufsmount *ump;
5662 	ufs_lbn_t lbn;
5663 
5664 	mp = ITOVFS(ip);
5665 	ump = VFSTOUFS(mp);
5666 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5667 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5668 	KASSERT(off < UFS_NXADDR,
5669 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5670 
5671 	lbn = bp->b_lblkno;
5672 	if (oldblkno && oldblkno != newblkno)
5673 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5674 	else
5675 		freefrag = NULL;
5676 
5677 	ACQUIRE_LOCK(ump);
5678 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5679 		panic("softdep_setup_allocext: lost block");
5680 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5681 	    ("softdep_setup_allocext: newblk already initialized"));
5682 	/*
5683 	 * Convert the newblk to an allocdirect.
5684 	 */
5685 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5686 	adp = (struct allocdirect *)newblk;
5687 	newblk->nb_freefrag = freefrag;
5688 	adp->ad_offset = off;
5689 	adp->ad_oldblkno = oldblkno;
5690 	adp->ad_newsize = newsize;
5691 	adp->ad_oldsize = oldsize;
5692 	adp->ad_state |=  EXTDATA;
5693 
5694 	/*
5695 	 * Finish initializing the journal.
5696 	 */
5697 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5698 		jnewblk->jn_ino = ip->i_number;
5699 		jnewblk->jn_lbn = lbn;
5700 		add_to_journal(&jnewblk->jn_list);
5701 	}
5702 	if (freefrag && freefrag->ff_jdep != NULL &&
5703 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5704 		add_to_journal(freefrag->ff_jdep);
5705 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5706 	adp->ad_inodedep = inodedep;
5707 
5708 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5709 	/*
5710 	 * The list of allocdirects must be kept in sorted and ascending
5711 	 * order so that the rollback routines can quickly determine the
5712 	 * first uncommitted block (the size of the file stored on disk
5713 	 * ends at the end of the lowest committed fragment, or if there
5714 	 * are no fragments, at the end of the highest committed block).
5715 	 * Since files generally grow, the typical case is that the new
5716 	 * block is to be added at the end of the list. We speed this
5717 	 * special case by checking against the last allocdirect in the
5718 	 * list before laboriously traversing the list looking for the
5719 	 * insertion point.
5720 	 */
5721 	adphead = &inodedep->id_newextupdt;
5722 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5723 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5724 		/* insert at end of list */
5725 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5726 		if (oldadp != NULL && oldadp->ad_offset == off)
5727 			allocdirect_merge(adphead, adp, oldadp);
5728 		FREE_LOCK(ump);
5729 		return;
5730 	}
5731 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5732 		if (oldadp->ad_offset >= off)
5733 			break;
5734 	}
5735 	if (oldadp == NULL)
5736 		panic("softdep_setup_allocext: lost entry");
5737 	/* insert in middle of list */
5738 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5739 	if (oldadp->ad_offset == off)
5740 		allocdirect_merge(adphead, adp, oldadp);
5741 	FREE_LOCK(ump);
5742 }
5743 
5744 /*
5745  * Indirect block allocation dependencies.
5746  *
5747  * The same dependencies that exist for a direct block also exist when
5748  * a new block is allocated and pointed to by an entry in a block of
5749  * indirect pointers. The undo/redo states described above are also
5750  * used here. Because an indirect block contains many pointers that
5751  * may have dependencies, a second copy of the entire in-memory indirect
5752  * block is kept. The buffer cache copy is always completely up-to-date.
5753  * The second copy, which is used only as a source for disk writes,
5754  * contains only the safe pointers (i.e., those that have no remaining
5755  * update dependencies). The second copy is freed when all pointers
5756  * are safe. The cache is not allowed to replace indirect blocks with
5757  * pending update dependencies. If a buffer containing an indirect
5758  * block with dependencies is written, these routines will mark it
5759  * dirty again. It can only be successfully written once all the
5760  * dependencies are removed. The ffs_fsync routine in conjunction with
5761  * softdep_sync_metadata work together to get all the dependencies
5762  * removed so that a file can be successfully written to disk. Three
5763  * procedures are used when setting up indirect block pointer
5764  * dependencies. The division is necessary because of the organization
5765  * of the "balloc" routine and because of the distinction between file
5766  * pages and file metadata blocks.
5767  */
5768 
5769 /*
5770  * Allocate a new allocindir structure.
5771  */
5772 static struct allocindir *
5773 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5774 	struct inode *ip;	/* inode for file being extended */
5775 	int ptrno;		/* offset of pointer in indirect block */
5776 	ufs2_daddr_t newblkno;	/* disk block number being added */
5777 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5778 	ufs_lbn_t lbn;
5779 {
5780 	struct newblk *newblk;
5781 	struct allocindir *aip;
5782 	struct freefrag *freefrag;
5783 	struct jnewblk *jnewblk;
5784 
5785 	if (oldblkno)
5786 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn);
5787 	else
5788 		freefrag = NULL;
5789 	ACQUIRE_LOCK(ITOUMP(ip));
5790 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5791 		panic("new_allocindir: lost block");
5792 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5793 	    ("newallocindir: newblk already initialized"));
5794 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5795 	newblk->nb_freefrag = freefrag;
5796 	aip = (struct allocindir *)newblk;
5797 	aip->ai_offset = ptrno;
5798 	aip->ai_oldblkno = oldblkno;
5799 	aip->ai_lbn = lbn;
5800 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5801 		jnewblk->jn_ino = ip->i_number;
5802 		jnewblk->jn_lbn = lbn;
5803 		add_to_journal(&jnewblk->jn_list);
5804 	}
5805 	if (freefrag && freefrag->ff_jdep != NULL &&
5806 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5807 		add_to_journal(freefrag->ff_jdep);
5808 	return (aip);
5809 }
5810 
5811 /*
5812  * Called just before setting an indirect block pointer
5813  * to a newly allocated file page.
5814  */
5815 void
5816 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5817 	struct inode *ip;	/* inode for file being extended */
5818 	ufs_lbn_t lbn;		/* allocated block number within file */
5819 	struct buf *bp;		/* buffer with indirect blk referencing page */
5820 	int ptrno;		/* offset of pointer in indirect block */
5821 	ufs2_daddr_t newblkno;	/* disk block number being added */
5822 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5823 	struct buf *nbp;	/* buffer holding allocated page */
5824 {
5825 	struct inodedep *inodedep;
5826 	struct freefrag *freefrag;
5827 	struct allocindir *aip;
5828 	struct pagedep *pagedep;
5829 	struct mount *mp;
5830 	struct ufsmount *ump;
5831 
5832 	mp = ITOVFS(ip);
5833 	ump = VFSTOUFS(mp);
5834 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5835 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5836 	KASSERT(lbn == nbp->b_lblkno,
5837 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5838 	    lbn, bp->b_lblkno));
5839 	CTR4(KTR_SUJ,
5840 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5841 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5842 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5843 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5844 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5845 	/*
5846 	 * If we are allocating a directory page, then we must
5847 	 * allocate an associated pagedep to track additions and
5848 	 * deletions.
5849 	 */
5850 	if ((ip->i_mode & IFMT) == IFDIR)
5851 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5852 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5853 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5854 	FREE_LOCK(ump);
5855 	if (freefrag)
5856 		handle_workitem_freefrag(freefrag);
5857 }
5858 
5859 /*
5860  * Called just before setting an indirect block pointer to a
5861  * newly allocated indirect block.
5862  */
5863 void
5864 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5865 	struct buf *nbp;	/* newly allocated indirect block */
5866 	struct inode *ip;	/* inode for file being extended */
5867 	struct buf *bp;		/* indirect block referencing allocated block */
5868 	int ptrno;		/* offset of pointer in indirect block */
5869 	ufs2_daddr_t newblkno;	/* disk block number being added */
5870 {
5871 	struct inodedep *inodedep;
5872 	struct allocindir *aip;
5873 	struct ufsmount *ump;
5874 	ufs_lbn_t lbn;
5875 
5876 	ump = ITOUMP(ip);
5877 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5878 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5879 	CTR3(KTR_SUJ,
5880 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5881 	    ip->i_number, newblkno, ptrno);
5882 	lbn = nbp->b_lblkno;
5883 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5884 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5885 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5886 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5887 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5888 		panic("softdep_setup_allocindir_meta: Block already existed");
5889 	FREE_LOCK(ump);
5890 }
5891 
5892 static void
5893 indirdep_complete(indirdep)
5894 	struct indirdep *indirdep;
5895 {
5896 	struct allocindir *aip;
5897 
5898 	LIST_REMOVE(indirdep, ir_next);
5899 	indirdep->ir_state |= DEPCOMPLETE;
5900 
5901 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5902 		LIST_REMOVE(aip, ai_next);
5903 		free_newblk(&aip->ai_block);
5904 	}
5905 	/*
5906 	 * If this indirdep is not attached to a buf it was simply waiting
5907 	 * on completion to clear completehd.  free_indirdep() asserts
5908 	 * that nothing is dangling.
5909 	 */
5910 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5911 		free_indirdep(indirdep);
5912 }
5913 
5914 static struct indirdep *
5915 indirdep_lookup(mp, ip, bp)
5916 	struct mount *mp;
5917 	struct inode *ip;
5918 	struct buf *bp;
5919 {
5920 	struct indirdep *indirdep, *newindirdep;
5921 	struct newblk *newblk;
5922 	struct ufsmount *ump;
5923 	struct worklist *wk;
5924 	struct fs *fs;
5925 	ufs2_daddr_t blkno;
5926 
5927 	ump = VFSTOUFS(mp);
5928 	LOCK_OWNED(ump);
5929 	indirdep = NULL;
5930 	newindirdep = NULL;
5931 	fs = ump->um_fs;
5932 	for (;;) {
5933 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5934 			if (wk->wk_type != D_INDIRDEP)
5935 				continue;
5936 			indirdep = WK_INDIRDEP(wk);
5937 			break;
5938 		}
5939 		/* Found on the buffer worklist, no new structure to free. */
5940 		if (indirdep != NULL && newindirdep == NULL)
5941 			return (indirdep);
5942 		if (indirdep != NULL && newindirdep != NULL)
5943 			panic("indirdep_lookup: simultaneous create");
5944 		/* None found on the buffer and a new structure is ready. */
5945 		if (indirdep == NULL && newindirdep != NULL)
5946 			break;
5947 		/* None found and no new structure available. */
5948 		FREE_LOCK(ump);
5949 		newindirdep = malloc(sizeof(struct indirdep),
5950 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
5951 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5952 		newindirdep->ir_state = ATTACHED;
5953 		if (I_IS_UFS1(ip))
5954 			newindirdep->ir_state |= UFS1FMT;
5955 		TAILQ_INIT(&newindirdep->ir_trunc);
5956 		newindirdep->ir_saveddata = NULL;
5957 		LIST_INIT(&newindirdep->ir_deplisthd);
5958 		LIST_INIT(&newindirdep->ir_donehd);
5959 		LIST_INIT(&newindirdep->ir_writehd);
5960 		LIST_INIT(&newindirdep->ir_completehd);
5961 		if (bp->b_blkno == bp->b_lblkno) {
5962 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5963 			    NULL, NULL);
5964 			bp->b_blkno = blkno;
5965 		}
5966 		newindirdep->ir_freeblks = NULL;
5967 		newindirdep->ir_savebp =
5968 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5969 		newindirdep->ir_bp = bp;
5970 		BUF_KERNPROC(newindirdep->ir_savebp);
5971 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5972 		ACQUIRE_LOCK(ump);
5973 	}
5974 	indirdep = newindirdep;
5975 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5976 	/*
5977 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
5978 	 * that we don't free dependencies until the pointers are valid.
5979 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5980 	 * than using the hash.
5981 	 */
5982 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5983 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5984 	else
5985 		indirdep->ir_state |= DEPCOMPLETE;
5986 	return (indirdep);
5987 }
5988 
5989 /*
5990  * Called to finish the allocation of the "aip" allocated
5991  * by one of the two routines above.
5992  */
5993 static struct freefrag *
5994 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
5995 	struct buf *bp;		/* in-memory copy of the indirect block */
5996 	struct inode *ip;	/* inode for file being extended */
5997 	struct inodedep *inodedep; /* Inodedep for ip */
5998 	struct allocindir *aip;	/* allocindir allocated by the above routines */
5999 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6000 {
6001 	struct fs *fs;
6002 	struct indirdep *indirdep;
6003 	struct allocindir *oldaip;
6004 	struct freefrag *freefrag;
6005 	struct mount *mp;
6006 	struct ufsmount *ump;
6007 
6008 	mp = ITOVFS(ip);
6009 	ump = VFSTOUFS(mp);
6010 	LOCK_OWNED(ump);
6011 	fs = ump->um_fs;
6012 	if (bp->b_lblkno >= 0)
6013 		panic("setup_allocindir_phase2: not indir blk");
6014 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6015 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6016 	indirdep = indirdep_lookup(mp, ip, bp);
6017 	KASSERT(indirdep->ir_savebp != NULL,
6018 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6019 	aip->ai_indirdep = indirdep;
6020 	/*
6021 	 * Check for an unwritten dependency for this indirect offset.  If
6022 	 * there is, merge the old dependency into the new one.  This happens
6023 	 * as a result of reallocblk only.
6024 	 */
6025 	freefrag = NULL;
6026 	if (aip->ai_oldblkno != 0) {
6027 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6028 			if (oldaip->ai_offset == aip->ai_offset) {
6029 				freefrag = allocindir_merge(aip, oldaip);
6030 				goto done;
6031 			}
6032 		}
6033 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6034 			if (oldaip->ai_offset == aip->ai_offset) {
6035 				freefrag = allocindir_merge(aip, oldaip);
6036 				goto done;
6037 			}
6038 		}
6039 	}
6040 done:
6041 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6042 	return (freefrag);
6043 }
6044 
6045 /*
6046  * Merge two allocindirs which refer to the same block.  Move newblock
6047  * dependencies and setup the freefrags appropriately.
6048  */
6049 static struct freefrag *
6050 allocindir_merge(aip, oldaip)
6051 	struct allocindir *aip;
6052 	struct allocindir *oldaip;
6053 {
6054 	struct freefrag *freefrag;
6055 	struct worklist *wk;
6056 
6057 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6058 		panic("allocindir_merge: blkno");
6059 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6060 	freefrag = aip->ai_freefrag;
6061 	aip->ai_freefrag = oldaip->ai_freefrag;
6062 	oldaip->ai_freefrag = NULL;
6063 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6064 	/*
6065 	 * If we are tracking a new directory-block allocation,
6066 	 * move it from the old allocindir to the new allocindir.
6067 	 */
6068 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6069 		WORKLIST_REMOVE(wk);
6070 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6071 			panic("allocindir_merge: extra newdirblk");
6072 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6073 	}
6074 	/*
6075 	 * We can skip journaling for this freefrag and just complete
6076 	 * any pending journal work for the allocindir that is being
6077 	 * removed after the freefrag completes.
6078 	 */
6079 	if (freefrag->ff_jdep)
6080 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6081 	LIST_REMOVE(oldaip, ai_next);
6082 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6083 	    &freefrag->ff_list, &freefrag->ff_jwork);
6084 	free_newblk(&oldaip->ai_block);
6085 
6086 	return (freefrag);
6087 }
6088 
6089 static inline void
6090 setup_freedirect(freeblks, ip, i, needj)
6091 	struct freeblks *freeblks;
6092 	struct inode *ip;
6093 	int i;
6094 	int needj;
6095 {
6096 	struct ufsmount *ump;
6097 	ufs2_daddr_t blkno;
6098 	int frags;
6099 
6100 	blkno = DIP(ip, i_db[i]);
6101 	if (blkno == 0)
6102 		return;
6103 	DIP_SET(ip, i_db[i], 0);
6104 	ump = ITOUMP(ip);
6105 	frags = sblksize(ump->um_fs, ip->i_size, i);
6106 	frags = numfrags(ump->um_fs, frags);
6107 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6108 }
6109 
6110 static inline void
6111 setup_freeext(freeblks, ip, i, needj)
6112 	struct freeblks *freeblks;
6113 	struct inode *ip;
6114 	int i;
6115 	int needj;
6116 {
6117 	struct ufsmount *ump;
6118 	ufs2_daddr_t blkno;
6119 	int frags;
6120 
6121 	blkno = ip->i_din2->di_extb[i];
6122 	if (blkno == 0)
6123 		return;
6124 	ip->i_din2->di_extb[i] = 0;
6125 	ump = ITOUMP(ip);
6126 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6127 	frags = numfrags(ump->um_fs, frags);
6128 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6129 }
6130 
6131 static inline void
6132 setup_freeindir(freeblks, ip, i, lbn, needj)
6133 	struct freeblks *freeblks;
6134 	struct inode *ip;
6135 	int i;
6136 	ufs_lbn_t lbn;
6137 	int needj;
6138 {
6139 	struct ufsmount *ump;
6140 	ufs2_daddr_t blkno;
6141 
6142 	blkno = DIP(ip, i_ib[i]);
6143 	if (blkno == 0)
6144 		return;
6145 	DIP_SET(ip, i_ib[i], 0);
6146 	ump = ITOUMP(ip);
6147 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6148 	    0, needj);
6149 }
6150 
6151 static inline struct freeblks *
6152 newfreeblks(mp, ip)
6153 	struct mount *mp;
6154 	struct inode *ip;
6155 {
6156 	struct freeblks *freeblks;
6157 
6158 	freeblks = malloc(sizeof(struct freeblks),
6159 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6160 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6161 	LIST_INIT(&freeblks->fb_jblkdephd);
6162 	LIST_INIT(&freeblks->fb_jwork);
6163 	freeblks->fb_ref = 0;
6164 	freeblks->fb_cgwait = 0;
6165 	freeblks->fb_state = ATTACHED;
6166 	freeblks->fb_uid = ip->i_uid;
6167 	freeblks->fb_inum = ip->i_number;
6168 	freeblks->fb_vtype = ITOV(ip)->v_type;
6169 	freeblks->fb_modrev = DIP(ip, i_modrev);
6170 	freeblks->fb_devvp = ITODEVVP(ip);
6171 	freeblks->fb_chkcnt = 0;
6172 	freeblks->fb_len = 0;
6173 
6174 	return (freeblks);
6175 }
6176 
6177 static void
6178 trunc_indirdep(indirdep, freeblks, bp, off)
6179 	struct indirdep *indirdep;
6180 	struct freeblks *freeblks;
6181 	struct buf *bp;
6182 	int off;
6183 {
6184 	struct allocindir *aip, *aipn;
6185 
6186 	/*
6187 	 * The first set of allocindirs won't be in savedbp.
6188 	 */
6189 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6190 		if (aip->ai_offset > off)
6191 			cancel_allocindir(aip, bp, freeblks, 1);
6192 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6193 		if (aip->ai_offset > off)
6194 			cancel_allocindir(aip, bp, freeblks, 1);
6195 	/*
6196 	 * These will exist in savedbp.
6197 	 */
6198 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6199 		if (aip->ai_offset > off)
6200 			cancel_allocindir(aip, NULL, freeblks, 0);
6201 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6202 		if (aip->ai_offset > off)
6203 			cancel_allocindir(aip, NULL, freeblks, 0);
6204 }
6205 
6206 /*
6207  * Follow the chain of indirects down to lastlbn creating a freework
6208  * structure for each.  This will be used to start indir_trunc() at
6209  * the right offset and create the journal records for the parrtial
6210  * truncation.  A second step will handle the truncated dependencies.
6211  */
6212 static int
6213 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6214 	struct freeblks *freeblks;
6215 	struct inode *ip;
6216 	ufs_lbn_t lbn;
6217 	ufs_lbn_t lastlbn;
6218 	ufs2_daddr_t blkno;
6219 {
6220 	struct indirdep *indirdep;
6221 	struct indirdep *indirn;
6222 	struct freework *freework;
6223 	struct newblk *newblk;
6224 	struct mount *mp;
6225 	struct ufsmount *ump;
6226 	struct buf *bp;
6227 	uint8_t *start;
6228 	uint8_t *end;
6229 	ufs_lbn_t lbnadd;
6230 	int level;
6231 	int error;
6232 	int off;
6233 
6234 
6235 	freework = NULL;
6236 	if (blkno == 0)
6237 		return (0);
6238 	mp = freeblks->fb_list.wk_mp;
6239 	ump = VFSTOUFS(mp);
6240 	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6241 	if ((bp->b_flags & B_CACHE) == 0) {
6242 		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6243 		bp->b_iocmd = BIO_READ;
6244 		bp->b_flags &= ~B_INVAL;
6245 		bp->b_ioflags &= ~BIO_ERROR;
6246 		vfs_busy_pages(bp, 0);
6247 		bp->b_iooffset = dbtob(bp->b_blkno);
6248 		bstrategy(bp);
6249 #ifdef RACCT
6250 		if (racct_enable) {
6251 			PROC_LOCK(curproc);
6252 			racct_add_buf(curproc, bp, 0);
6253 			PROC_UNLOCK(curproc);
6254 		}
6255 #endif /* RACCT */
6256 		curthread->td_ru.ru_inblock++;
6257 		error = bufwait(bp);
6258 		if (error) {
6259 			brelse(bp);
6260 			return (error);
6261 		}
6262 	}
6263 	level = lbn_level(lbn);
6264 	lbnadd = lbn_offset(ump->um_fs, level);
6265 	/*
6266 	 * Compute the offset of the last block we want to keep.  Store
6267 	 * in the freework the first block we want to completely free.
6268 	 */
6269 	off = (lastlbn - -(lbn + level)) / lbnadd;
6270 	if (off + 1 == NINDIR(ump->um_fs))
6271 		goto nowork;
6272 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6273 	/*
6274 	 * Link the freework into the indirdep.  This will prevent any new
6275 	 * allocations from proceeding until we are finished with the
6276 	 * truncate and the block is written.
6277 	 */
6278 	ACQUIRE_LOCK(ump);
6279 	indirdep = indirdep_lookup(mp, ip, bp);
6280 	if (indirdep->ir_freeblks)
6281 		panic("setup_trunc_indir: indirdep already truncated.");
6282 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6283 	freework->fw_indir = indirdep;
6284 	/*
6285 	 * Cancel any allocindirs that will not make it to disk.
6286 	 * We have to do this for all copies of the indirdep that
6287 	 * live on this newblk.
6288 	 */
6289 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6290 		newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0, &newblk);
6291 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6292 			trunc_indirdep(indirn, freeblks, bp, off);
6293 	} else
6294 		trunc_indirdep(indirdep, freeblks, bp, off);
6295 	FREE_LOCK(ump);
6296 	/*
6297 	 * Creation is protected by the buf lock. The saveddata is only
6298 	 * needed if a full truncation follows a partial truncation but it
6299 	 * is difficult to allocate in that case so we fetch it anyway.
6300 	 */
6301 	if (indirdep->ir_saveddata == NULL)
6302 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6303 		    M_SOFTDEP_FLAGS);
6304 nowork:
6305 	/* Fetch the blkno of the child and the zero start offset. */
6306 	if (I_IS_UFS1(ip)) {
6307 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6308 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6309 	} else {
6310 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6311 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6312 	}
6313 	if (freework) {
6314 		/* Zero the truncated pointers. */
6315 		end = bp->b_data + bp->b_bcount;
6316 		bzero(start, end - start);
6317 		bdwrite(bp);
6318 	} else
6319 		bqrelse(bp);
6320 	if (level == 0)
6321 		return (0);
6322 	lbn++; /* adjust level */
6323 	lbn -= (off * lbnadd);
6324 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6325 }
6326 
6327 /*
6328  * Complete the partial truncation of an indirect block setup by
6329  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6330  * copy and writes them to disk before the freeblks is allowed to complete.
6331  */
6332 static void
6333 complete_trunc_indir(freework)
6334 	struct freework *freework;
6335 {
6336 	struct freework *fwn;
6337 	struct indirdep *indirdep;
6338 	struct ufsmount *ump;
6339 	struct buf *bp;
6340 	uintptr_t start;
6341 	int count;
6342 
6343 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6344 	LOCK_OWNED(ump);
6345 	indirdep = freework->fw_indir;
6346 	for (;;) {
6347 		bp = indirdep->ir_bp;
6348 		/* See if the block was discarded. */
6349 		if (bp == NULL)
6350 			break;
6351 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6352 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6353 			break;
6354 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6355 		    LOCK_PTR(ump)) == 0)
6356 			BUF_UNLOCK(bp);
6357 		ACQUIRE_LOCK(ump);
6358 	}
6359 	freework->fw_state |= DEPCOMPLETE;
6360 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6361 	/*
6362 	 * Zero the pointers in the saved copy.
6363 	 */
6364 	if (indirdep->ir_state & UFS1FMT)
6365 		start = sizeof(ufs1_daddr_t);
6366 	else
6367 		start = sizeof(ufs2_daddr_t);
6368 	start *= freework->fw_start;
6369 	count = indirdep->ir_savebp->b_bcount - start;
6370 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6371 	bzero((char *)start, count);
6372 	/*
6373 	 * We need to start the next truncation in the list if it has not
6374 	 * been started yet.
6375 	 */
6376 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6377 	if (fwn != NULL) {
6378 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6379 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6380 		if ((fwn->fw_state & ONWORKLIST) == 0)
6381 			freework_enqueue(fwn);
6382 	}
6383 	/*
6384 	 * If bp is NULL the block was fully truncated, restore
6385 	 * the saved block list otherwise free it if it is no
6386 	 * longer needed.
6387 	 */
6388 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6389 		if (bp == NULL)
6390 			bcopy(indirdep->ir_saveddata,
6391 			    indirdep->ir_savebp->b_data,
6392 			    indirdep->ir_savebp->b_bcount);
6393 		free(indirdep->ir_saveddata, M_INDIRDEP);
6394 		indirdep->ir_saveddata = NULL;
6395 	}
6396 	/*
6397 	 * When bp is NULL there is a full truncation pending.  We
6398 	 * must wait for this full truncation to be journaled before
6399 	 * we can release this freework because the disk pointers will
6400 	 * never be written as zero.
6401 	 */
6402 	if (bp == NULL)  {
6403 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6404 			handle_written_freework(freework);
6405 		else
6406 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6407 			   &freework->fw_list);
6408 	} else {
6409 		/* Complete when the real copy is written. */
6410 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6411 		BUF_UNLOCK(bp);
6412 	}
6413 }
6414 
6415 /*
6416  * Calculate the number of blocks we are going to release where datablocks
6417  * is the current total and length is the new file size.
6418  */
6419 static ufs2_daddr_t
6420 blkcount(fs, datablocks, length)
6421 	struct fs *fs;
6422 	ufs2_daddr_t datablocks;
6423 	off_t length;
6424 {
6425 	off_t totblks, numblks;
6426 
6427 	totblks = 0;
6428 	numblks = howmany(length, fs->fs_bsize);
6429 	if (numblks <= UFS_NDADDR) {
6430 		totblks = howmany(length, fs->fs_fsize);
6431 		goto out;
6432 	}
6433         totblks = blkstofrags(fs, numblks);
6434 	numblks -= UFS_NDADDR;
6435 	/*
6436 	 * Count all single, then double, then triple indirects required.
6437 	 * Subtracting one indirects worth of blocks for each pass
6438 	 * acknowledges one of each pointed to by the inode.
6439 	 */
6440 	for (;;) {
6441 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6442 		numblks -= NINDIR(fs);
6443 		if (numblks <= 0)
6444 			break;
6445 		numblks = howmany(numblks, NINDIR(fs));
6446 	}
6447 out:
6448 	totblks = fsbtodb(fs, totblks);
6449 	/*
6450 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6451 	 * references.  We will correct it later in handle_complete_freeblks()
6452 	 * when we know the real count.
6453 	 */
6454 	if (totblks > datablocks)
6455 		return (0);
6456 	return (datablocks - totblks);
6457 }
6458 
6459 /*
6460  * Handle freeblocks for journaled softupdate filesystems.
6461  *
6462  * Contrary to normal softupdates, we must preserve the block pointers in
6463  * indirects until their subordinates are free.  This is to avoid journaling
6464  * every block that is freed which may consume more space than the journal
6465  * itself.  The recovery program will see the free block journals at the
6466  * base of the truncated area and traverse them to reclaim space.  The
6467  * pointers in the inode may be cleared immediately after the journal
6468  * records are written because each direct and indirect pointer in the
6469  * inode is recorded in a journal.  This permits full truncation to proceed
6470  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6471  *
6472  * The algorithm is as follows:
6473  * 1) Traverse the in-memory state and create journal entries to release
6474  *    the relevant blocks and full indirect trees.
6475  * 2) Traverse the indirect block chain adding partial truncation freework
6476  *    records to indirects in the path to lastlbn.  The freework will
6477  *    prevent new allocation dependencies from being satisfied in this
6478  *    indirect until the truncation completes.
6479  * 3) Read and lock the inode block, performing an update with the new size
6480  *    and pointers.  This prevents truncated data from becoming valid on
6481  *    disk through step 4.
6482  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6483  *    eliminate journal work for those records that do not require it.
6484  * 5) Schedule the journal records to be written followed by the inode block.
6485  * 6) Allocate any necessary frags for the end of file.
6486  * 7) Zero any partially truncated blocks.
6487  *
6488  * From this truncation proceeds asynchronously using the freework and
6489  * indir_trunc machinery.  The file will not be extended again into a
6490  * partially truncated indirect block until all work is completed but
6491  * the normal dependency mechanism ensures that it is rolled back/forward
6492  * as appropriate.  Further truncation may occur without delay and is
6493  * serialized in indir_trunc().
6494  */
6495 void
6496 softdep_journal_freeblocks(ip, cred, length, flags)
6497 	struct inode *ip;	/* The inode whose length is to be reduced */
6498 	struct ucred *cred;
6499 	off_t length;		/* The new length for the file */
6500 	int flags;		/* IO_EXT and/or IO_NORMAL */
6501 {
6502 	struct freeblks *freeblks, *fbn;
6503 	struct worklist *wk, *wkn;
6504 	struct inodedep *inodedep;
6505 	struct jblkdep *jblkdep;
6506 	struct allocdirect *adp, *adpn;
6507 	struct ufsmount *ump;
6508 	struct fs *fs;
6509 	struct buf *bp;
6510 	struct vnode *vp;
6511 	struct mount *mp;
6512 	ufs2_daddr_t extblocks, datablocks;
6513 	ufs_lbn_t tmpval, lbn, lastlbn;
6514 	int frags, lastoff, iboff, allocblock, needj, error, i;
6515 
6516 	ump = ITOUMP(ip);
6517 	mp = UFSTOVFS(ump);
6518 	fs = ump->um_fs;
6519 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6520 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6521 	vp = ITOV(ip);
6522 	needj = 1;
6523 	iboff = -1;
6524 	allocblock = 0;
6525 	extblocks = 0;
6526 	datablocks = 0;
6527 	frags = 0;
6528 	freeblks = newfreeblks(mp, ip);
6529 	ACQUIRE_LOCK(ump);
6530 	/*
6531 	 * If we're truncating a removed file that will never be written
6532 	 * we don't need to journal the block frees.  The canceled journals
6533 	 * for the allocations will suffice.
6534 	 */
6535 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6536 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6537 	    length == 0)
6538 		needj = 0;
6539 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6540 	    ip->i_number, length, needj);
6541 	FREE_LOCK(ump);
6542 	/*
6543 	 * Calculate the lbn that we are truncating to.  This results in -1
6544 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6545 	 * to keep, not the first lbn we want to truncate.
6546 	 */
6547 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6548 	lastoff = blkoff(fs, length);
6549 	/*
6550 	 * Compute frags we are keeping in lastlbn.  0 means all.
6551 	 */
6552 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6553 		frags = fragroundup(fs, lastoff);
6554 		/* adp offset of last valid allocdirect. */
6555 		iboff = lastlbn;
6556 	} else if (lastlbn > 0)
6557 		iboff = UFS_NDADDR;
6558 	if (fs->fs_magic == FS_UFS2_MAGIC)
6559 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6560 	/*
6561 	 * Handle normal data blocks and indirects.  This section saves
6562 	 * values used after the inode update to complete frag and indirect
6563 	 * truncation.
6564 	 */
6565 	if ((flags & IO_NORMAL) != 0) {
6566 		/*
6567 		 * Handle truncation of whole direct and indirect blocks.
6568 		 */
6569 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6570 			setup_freedirect(freeblks, ip, i, needj);
6571 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6572 		    i < UFS_NIADDR;
6573 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6574 			/* Release a whole indirect tree. */
6575 			if (lbn > lastlbn) {
6576 				setup_freeindir(freeblks, ip, i, -lbn -i,
6577 				    needj);
6578 				continue;
6579 			}
6580 			iboff = i + UFS_NDADDR;
6581 			/*
6582 			 * Traverse partially truncated indirect tree.
6583 			 */
6584 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6585 				setup_trunc_indir(freeblks, ip, -lbn - i,
6586 				    lastlbn, DIP(ip, i_ib[i]));
6587 		}
6588 		/*
6589 		 * Handle partial truncation to a frag boundary.
6590 		 */
6591 		if (frags) {
6592 			ufs2_daddr_t blkno;
6593 			long oldfrags;
6594 
6595 			oldfrags = blksize(fs, ip, lastlbn);
6596 			blkno = DIP(ip, i_db[lastlbn]);
6597 			if (blkno && oldfrags != frags) {
6598 				oldfrags -= frags;
6599 				oldfrags = numfrags(fs, oldfrags);
6600 				blkno += numfrags(fs, frags);
6601 				newfreework(ump, freeblks, NULL, lastlbn,
6602 				    blkno, oldfrags, 0, needj);
6603 				if (needj)
6604 					adjust_newfreework(freeblks,
6605 					    numfrags(fs, frags));
6606 			} else if (blkno == 0)
6607 				allocblock = 1;
6608 		}
6609 		/*
6610 		 * Add a journal record for partial truncate if we are
6611 		 * handling indirect blocks.  Non-indirects need no extra
6612 		 * journaling.
6613 		 */
6614 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6615 			ip->i_flag |= IN_TRUNCATED;
6616 			newjtrunc(freeblks, length, 0);
6617 		}
6618 		ip->i_size = length;
6619 		DIP_SET(ip, i_size, ip->i_size);
6620 		datablocks = DIP(ip, i_blocks) - extblocks;
6621 		if (length != 0)
6622 			datablocks = blkcount(fs, datablocks, length);
6623 		freeblks->fb_len = length;
6624 	}
6625 	if ((flags & IO_EXT) != 0) {
6626 		for (i = 0; i < UFS_NXADDR; i++)
6627 			setup_freeext(freeblks, ip, i, needj);
6628 		ip->i_din2->di_extsize = 0;
6629 		datablocks += extblocks;
6630 	}
6631 #ifdef QUOTA
6632 	/* Reference the quotas in case the block count is wrong in the end. */
6633 	quotaref(vp, freeblks->fb_quota);
6634 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6635 #endif
6636 	freeblks->fb_chkcnt = -datablocks;
6637 	UFS_LOCK(ump);
6638 	fs->fs_pendingblocks += datablocks;
6639 	UFS_UNLOCK(ump);
6640 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6641 	/*
6642 	 * Handle truncation of incomplete alloc direct dependencies.  We
6643 	 * hold the inode block locked to prevent incomplete dependencies
6644 	 * from reaching the disk while we are eliminating those that
6645 	 * have been truncated.  This is a partially inlined ffs_update().
6646 	 */
6647 	ufs_itimes(vp);
6648 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6649 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6650 	    (int)fs->fs_bsize, cred, &bp);
6651 	if (error) {
6652 		brelse(bp);
6653 		softdep_error("softdep_journal_freeblocks", error);
6654 		return;
6655 	}
6656 	if (bp->b_bufsize == fs->fs_bsize)
6657 		bp->b_flags |= B_CLUSTEROK;
6658 	softdep_update_inodeblock(ip, bp, 0);
6659 	if (ump->um_fstype == UFS1)
6660 		*((struct ufs1_dinode *)bp->b_data +
6661 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6662 	else
6663 		*((struct ufs2_dinode *)bp->b_data +
6664 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6665 	ACQUIRE_LOCK(ump);
6666 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6667 	if ((inodedep->id_state & IOSTARTED) != 0)
6668 		panic("softdep_setup_freeblocks: inode busy");
6669 	/*
6670 	 * Add the freeblks structure to the list of operations that
6671 	 * must await the zero'ed inode being written to disk. If we
6672 	 * still have a bitmap dependency (needj), then the inode
6673 	 * has never been written to disk, so we can process the
6674 	 * freeblks below once we have deleted the dependencies.
6675 	 */
6676 	if (needj)
6677 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6678 	else
6679 		freeblks->fb_state |= COMPLETE;
6680 	if ((flags & IO_NORMAL) != 0) {
6681 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6682 			if (adp->ad_offset > iboff)
6683 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6684 				    freeblks);
6685 			/*
6686 			 * Truncate the allocdirect.  We could eliminate
6687 			 * or modify journal records as well.
6688 			 */
6689 			else if (adp->ad_offset == iboff && frags)
6690 				adp->ad_newsize = frags;
6691 		}
6692 	}
6693 	if ((flags & IO_EXT) != 0)
6694 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6695 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6696 			    freeblks);
6697 	/*
6698 	 * Scan the bufwait list for newblock dependencies that will never
6699 	 * make it to disk.
6700 	 */
6701 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6702 		if (wk->wk_type != D_ALLOCDIRECT)
6703 			continue;
6704 		adp = WK_ALLOCDIRECT(wk);
6705 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6706 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6707 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6708 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6709 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6710 		}
6711 	}
6712 	/*
6713 	 * Add journal work.
6714 	 */
6715 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6716 		add_to_journal(&jblkdep->jb_list);
6717 	FREE_LOCK(ump);
6718 	bdwrite(bp);
6719 	/*
6720 	 * Truncate dependency structures beyond length.
6721 	 */
6722 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6723 	/*
6724 	 * This is only set when we need to allocate a fragment because
6725 	 * none existed at the end of a frag-sized file.  It handles only
6726 	 * allocating a new, zero filled block.
6727 	 */
6728 	if (allocblock) {
6729 		ip->i_size = length - lastoff;
6730 		DIP_SET(ip, i_size, ip->i_size);
6731 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6732 		if (error != 0) {
6733 			softdep_error("softdep_journal_freeblks", error);
6734 			return;
6735 		}
6736 		ip->i_size = length;
6737 		DIP_SET(ip, i_size, length);
6738 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6739 		allocbuf(bp, frags);
6740 		ffs_update(vp, 0);
6741 		bawrite(bp);
6742 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6743 		int size;
6744 
6745 		/*
6746 		 * Zero the end of a truncated frag or block.
6747 		 */
6748 		size = sblksize(fs, length, lastlbn);
6749 		error = bread(vp, lastlbn, size, cred, &bp);
6750 		if (error) {
6751 			softdep_error("softdep_journal_freeblks", error);
6752 			return;
6753 		}
6754 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6755 		bawrite(bp);
6756 
6757 	}
6758 	ACQUIRE_LOCK(ump);
6759 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6760 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6761 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6762 	/*
6763 	 * We zero earlier truncations so they don't erroneously
6764 	 * update i_blocks.
6765 	 */
6766 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6767 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6768 			fbn->fb_len = 0;
6769 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6770 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6771 		freeblks->fb_state |= INPROGRESS;
6772 	else
6773 		freeblks = NULL;
6774 	FREE_LOCK(ump);
6775 	if (freeblks)
6776 		handle_workitem_freeblocks(freeblks, 0);
6777 	trunc_pages(ip, length, extblocks, flags);
6778 
6779 }
6780 
6781 /*
6782  * Flush a JOP_SYNC to the journal.
6783  */
6784 void
6785 softdep_journal_fsync(ip)
6786 	struct inode *ip;
6787 {
6788 	struct jfsync *jfsync;
6789 	struct ufsmount *ump;
6790 
6791 	ump = ITOUMP(ip);
6792 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6793 	    ("softdep_journal_fsync called on non-softdep filesystem"));
6794 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6795 		return;
6796 	ip->i_flag &= ~IN_TRUNCATED;
6797 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6798 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6799 	jfsync->jfs_size = ip->i_size;
6800 	jfsync->jfs_ino = ip->i_number;
6801 	ACQUIRE_LOCK(ump);
6802 	add_to_journal(&jfsync->jfs_list);
6803 	jwait(&jfsync->jfs_list, MNT_WAIT);
6804 	FREE_LOCK(ump);
6805 }
6806 
6807 /*
6808  * Block de-allocation dependencies.
6809  *
6810  * When blocks are de-allocated, the on-disk pointers must be nullified before
6811  * the blocks are made available for use by other files.  (The true
6812  * requirement is that old pointers must be nullified before new on-disk
6813  * pointers are set.  We chose this slightly more stringent requirement to
6814  * reduce complexity.) Our implementation handles this dependency by updating
6815  * the inode (or indirect block) appropriately but delaying the actual block
6816  * de-allocation (i.e., freemap and free space count manipulation) until
6817  * after the updated versions reach stable storage.  After the disk is
6818  * updated, the blocks can be safely de-allocated whenever it is convenient.
6819  * This implementation handles only the common case of reducing a file's
6820  * length to zero. Other cases are handled by the conventional synchronous
6821  * write approach.
6822  *
6823  * The ffs implementation with which we worked double-checks
6824  * the state of the block pointers and file size as it reduces
6825  * a file's length.  Some of this code is replicated here in our
6826  * soft updates implementation.  The freeblks->fb_chkcnt field is
6827  * used to transfer a part of this information to the procedure
6828  * that eventually de-allocates the blocks.
6829  *
6830  * This routine should be called from the routine that shortens
6831  * a file's length, before the inode's size or block pointers
6832  * are modified. It will save the block pointer information for
6833  * later release and zero the inode so that the calling routine
6834  * can release it.
6835  */
6836 void
6837 softdep_setup_freeblocks(ip, length, flags)
6838 	struct inode *ip;	/* The inode whose length is to be reduced */
6839 	off_t length;		/* The new length for the file */
6840 	int flags;		/* IO_EXT and/or IO_NORMAL */
6841 {
6842 	struct ufs1_dinode *dp1;
6843 	struct ufs2_dinode *dp2;
6844 	struct freeblks *freeblks;
6845 	struct inodedep *inodedep;
6846 	struct allocdirect *adp;
6847 	struct ufsmount *ump;
6848 	struct buf *bp;
6849 	struct fs *fs;
6850 	ufs2_daddr_t extblocks, datablocks;
6851 	struct mount *mp;
6852 	int i, delay, error;
6853 	ufs_lbn_t tmpval;
6854 	ufs_lbn_t lbn;
6855 
6856 	ump = ITOUMP(ip);
6857 	mp = UFSTOVFS(ump);
6858 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6859 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6860 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6861 	    ip->i_number, length);
6862 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6863 	fs = ump->um_fs;
6864 	if ((error = bread(ump->um_devvp,
6865 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6866 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6867 		brelse(bp);
6868 		softdep_error("softdep_setup_freeblocks", error);
6869 		return;
6870 	}
6871 	freeblks = newfreeblks(mp, ip);
6872 	extblocks = 0;
6873 	datablocks = 0;
6874 	if (fs->fs_magic == FS_UFS2_MAGIC)
6875 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6876 	if ((flags & IO_NORMAL) != 0) {
6877 		for (i = 0; i < UFS_NDADDR; i++)
6878 			setup_freedirect(freeblks, ip, i, 0);
6879 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6880 		    i < UFS_NIADDR;
6881 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6882 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6883 		ip->i_size = 0;
6884 		DIP_SET(ip, i_size, 0);
6885 		datablocks = DIP(ip, i_blocks) - extblocks;
6886 	}
6887 	if ((flags & IO_EXT) != 0) {
6888 		for (i = 0; i < UFS_NXADDR; i++)
6889 			setup_freeext(freeblks, ip, i, 0);
6890 		ip->i_din2->di_extsize = 0;
6891 		datablocks += extblocks;
6892 	}
6893 #ifdef QUOTA
6894 	/* Reference the quotas in case the block count is wrong in the end. */
6895 	quotaref(ITOV(ip), freeblks->fb_quota);
6896 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6897 #endif
6898 	freeblks->fb_chkcnt = -datablocks;
6899 	UFS_LOCK(ump);
6900 	fs->fs_pendingblocks += datablocks;
6901 	UFS_UNLOCK(ump);
6902 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6903 	/*
6904 	 * Push the zero'ed inode to to its disk buffer so that we are free
6905 	 * to delete its dependencies below. Once the dependencies are gone
6906 	 * the buffer can be safely released.
6907 	 */
6908 	if (ump->um_fstype == UFS1) {
6909 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6910 		    ino_to_fsbo(fs, ip->i_number));
6911 		ip->i_din1->di_freelink = dp1->di_freelink;
6912 		*dp1 = *ip->i_din1;
6913 	} else {
6914 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6915 		    ino_to_fsbo(fs, ip->i_number));
6916 		ip->i_din2->di_freelink = dp2->di_freelink;
6917 		*dp2 = *ip->i_din2;
6918 	}
6919 	/*
6920 	 * Find and eliminate any inode dependencies.
6921 	 */
6922 	ACQUIRE_LOCK(ump);
6923 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6924 	if ((inodedep->id_state & IOSTARTED) != 0)
6925 		panic("softdep_setup_freeblocks: inode busy");
6926 	/*
6927 	 * Add the freeblks structure to the list of operations that
6928 	 * must await the zero'ed inode being written to disk. If we
6929 	 * still have a bitmap dependency (delay == 0), then the inode
6930 	 * has never been written to disk, so we can process the
6931 	 * freeblks below once we have deleted the dependencies.
6932 	 */
6933 	delay = (inodedep->id_state & DEPCOMPLETE);
6934 	if (delay)
6935 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6936 	else
6937 		freeblks->fb_state |= COMPLETE;
6938 	/*
6939 	 * Because the file length has been truncated to zero, any
6940 	 * pending block allocation dependency structures associated
6941 	 * with this inode are obsolete and can simply be de-allocated.
6942 	 * We must first merge the two dependency lists to get rid of
6943 	 * any duplicate freefrag structures, then purge the merged list.
6944 	 * If we still have a bitmap dependency, then the inode has never
6945 	 * been written to disk, so we can free any fragments without delay.
6946 	 */
6947 	if (flags & IO_NORMAL) {
6948 		merge_inode_lists(&inodedep->id_newinoupdt,
6949 		    &inodedep->id_inoupdt);
6950 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
6951 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
6952 			    freeblks);
6953 	}
6954 	if (flags & IO_EXT) {
6955 		merge_inode_lists(&inodedep->id_newextupdt,
6956 		    &inodedep->id_extupdt);
6957 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6958 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6959 			    freeblks);
6960 	}
6961 	FREE_LOCK(ump);
6962 	bdwrite(bp);
6963 	trunc_dependencies(ip, freeblks, -1, 0, flags);
6964 	ACQUIRE_LOCK(ump);
6965 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6966 		(void) free_inodedep(inodedep);
6967 	freeblks->fb_state |= DEPCOMPLETE;
6968 	/*
6969 	 * If the inode with zeroed block pointers is now on disk
6970 	 * we can start freeing blocks.
6971 	 */
6972 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6973 		freeblks->fb_state |= INPROGRESS;
6974 	else
6975 		freeblks = NULL;
6976 	FREE_LOCK(ump);
6977 	if (freeblks)
6978 		handle_workitem_freeblocks(freeblks, 0);
6979 	trunc_pages(ip, length, extblocks, flags);
6980 }
6981 
6982 /*
6983  * Eliminate pages from the page cache that back parts of this inode and
6984  * adjust the vnode pager's idea of our size.  This prevents stale data
6985  * from hanging around in the page cache.
6986  */
6987 static void
6988 trunc_pages(ip, length, extblocks, flags)
6989 	struct inode *ip;
6990 	off_t length;
6991 	ufs2_daddr_t extblocks;
6992 	int flags;
6993 {
6994 	struct vnode *vp;
6995 	struct fs *fs;
6996 	ufs_lbn_t lbn;
6997 	off_t end, extend;
6998 
6999 	vp = ITOV(ip);
7000 	fs = ITOFS(ip);
7001 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7002 	if ((flags & IO_EXT) != 0)
7003 		vn_pages_remove(vp, extend, 0);
7004 	if ((flags & IO_NORMAL) == 0)
7005 		return;
7006 	BO_LOCK(&vp->v_bufobj);
7007 	drain_output(vp);
7008 	BO_UNLOCK(&vp->v_bufobj);
7009 	/*
7010 	 * The vnode pager eliminates file pages we eliminate indirects
7011 	 * below.
7012 	 */
7013 	vnode_pager_setsize(vp, length);
7014 	/*
7015 	 * Calculate the end based on the last indirect we want to keep.  If
7016 	 * the block extends into indirects we can just use the negative of
7017 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7018 	 * be careful not to remove those, if they exist.  double and triple
7019 	 * indirect lbns do not overlap with others so it is not important
7020 	 * to verify how many levels are required.
7021 	 */
7022 	lbn = lblkno(fs, length);
7023 	if (lbn >= UFS_NDADDR) {
7024 		/* Calculate the virtual lbn of the triple indirect. */
7025 		lbn = -lbn - (UFS_NIADDR - 1);
7026 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7027 	} else
7028 		end = extend;
7029 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7030 }
7031 
7032 /*
7033  * See if the buf bp is in the range eliminated by truncation.
7034  */
7035 static int
7036 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7037 	struct buf *bp;
7038 	int *blkoffp;
7039 	ufs_lbn_t lastlbn;
7040 	int lastoff;
7041 	int flags;
7042 {
7043 	ufs_lbn_t lbn;
7044 
7045 	*blkoffp = 0;
7046 	/* Only match ext/normal blocks as appropriate. */
7047 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7048 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7049 		return (0);
7050 	/* ALTDATA is always a full truncation. */
7051 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7052 		return (1);
7053 	/* -1 is full truncation. */
7054 	if (lastlbn == -1)
7055 		return (1);
7056 	/*
7057 	 * If this is a partial truncate we only want those
7058 	 * blocks and indirect blocks that cover the range
7059 	 * we're after.
7060 	 */
7061 	lbn = bp->b_lblkno;
7062 	if (lbn < 0)
7063 		lbn = -(lbn + lbn_level(lbn));
7064 	if (lbn < lastlbn)
7065 		return (0);
7066 	/* Here we only truncate lblkno if it's partial. */
7067 	if (lbn == lastlbn) {
7068 		if (lastoff == 0)
7069 			return (0);
7070 		*blkoffp = lastoff;
7071 	}
7072 	return (1);
7073 }
7074 
7075 /*
7076  * Eliminate any dependencies that exist in memory beyond lblkno:off
7077  */
7078 static void
7079 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7080 	struct inode *ip;
7081 	struct freeblks *freeblks;
7082 	ufs_lbn_t lastlbn;
7083 	int lastoff;
7084 	int flags;
7085 {
7086 	struct bufobj *bo;
7087 	struct vnode *vp;
7088 	struct buf *bp;
7089 	int blkoff;
7090 
7091 	/*
7092 	 * We must wait for any I/O in progress to finish so that
7093 	 * all potential buffers on the dirty list will be visible.
7094 	 * Once they are all there, walk the list and get rid of
7095 	 * any dependencies.
7096 	 */
7097 	vp = ITOV(ip);
7098 	bo = &vp->v_bufobj;
7099 	BO_LOCK(bo);
7100 	drain_output(vp);
7101 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7102 		bp->b_vflags &= ~BV_SCANNED;
7103 restart:
7104 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7105 		if (bp->b_vflags & BV_SCANNED)
7106 			continue;
7107 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7108 			bp->b_vflags |= BV_SCANNED;
7109 			continue;
7110 		}
7111 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7112 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7113 			goto restart;
7114 		BO_UNLOCK(bo);
7115 		if (deallocate_dependencies(bp, freeblks, blkoff))
7116 			bqrelse(bp);
7117 		else
7118 			brelse(bp);
7119 		BO_LOCK(bo);
7120 		goto restart;
7121 	}
7122 	/*
7123 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7124 	 */
7125 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7126 		bp->b_vflags &= ~BV_SCANNED;
7127 cleanrestart:
7128 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7129 		if (bp->b_vflags & BV_SCANNED)
7130 			continue;
7131 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7132 			bp->b_vflags |= BV_SCANNED;
7133 			continue;
7134 		}
7135 		if (BUF_LOCK(bp,
7136 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7137 		    BO_LOCKPTR(bo)) == ENOLCK) {
7138 			BO_LOCK(bo);
7139 			goto cleanrestart;
7140 		}
7141 		bp->b_vflags |= BV_SCANNED;
7142 		bremfree(bp);
7143 		if (blkoff != 0) {
7144 			allocbuf(bp, blkoff);
7145 			bqrelse(bp);
7146 		} else {
7147 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7148 			brelse(bp);
7149 		}
7150 		BO_LOCK(bo);
7151 		goto cleanrestart;
7152 	}
7153 	drain_output(vp);
7154 	BO_UNLOCK(bo);
7155 }
7156 
7157 static int
7158 cancel_pagedep(pagedep, freeblks, blkoff)
7159 	struct pagedep *pagedep;
7160 	struct freeblks *freeblks;
7161 	int blkoff;
7162 {
7163 	struct jremref *jremref;
7164 	struct jmvref *jmvref;
7165 	struct dirrem *dirrem, *tmp;
7166 	int i;
7167 
7168 	/*
7169 	 * Copy any directory remove dependencies to the list
7170 	 * to be processed after the freeblks proceeds.  If
7171 	 * directory entry never made it to disk they
7172 	 * can be dumped directly onto the work list.
7173 	 */
7174 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7175 		/* Skip this directory removal if it is intended to remain. */
7176 		if (dirrem->dm_offset < blkoff)
7177 			continue;
7178 		/*
7179 		 * If there are any dirrems we wait for the journal write
7180 		 * to complete and then restart the buf scan as the lock
7181 		 * has been dropped.
7182 		 */
7183 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7184 			jwait(&jremref->jr_list, MNT_WAIT);
7185 			return (ERESTART);
7186 		}
7187 		LIST_REMOVE(dirrem, dm_next);
7188 		dirrem->dm_dirinum = pagedep->pd_ino;
7189 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7190 	}
7191 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7192 		jwait(&jmvref->jm_list, MNT_WAIT);
7193 		return (ERESTART);
7194 	}
7195 	/*
7196 	 * When we're partially truncating a pagedep we just want to flush
7197 	 * journal entries and return.  There can not be any adds in the
7198 	 * truncated portion of the directory and newblk must remain if
7199 	 * part of the block remains.
7200 	 */
7201 	if (blkoff != 0) {
7202 		struct diradd *dap;
7203 
7204 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7205 			if (dap->da_offset > blkoff)
7206 				panic("cancel_pagedep: diradd %p off %d > %d",
7207 				    dap, dap->da_offset, blkoff);
7208 		for (i = 0; i < DAHASHSZ; i++)
7209 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7210 				if (dap->da_offset > blkoff)
7211 					panic("cancel_pagedep: diradd %p off %d > %d",
7212 					    dap, dap->da_offset, blkoff);
7213 		return (0);
7214 	}
7215 	/*
7216 	 * There should be no directory add dependencies present
7217 	 * as the directory could not be truncated until all
7218 	 * children were removed.
7219 	 */
7220 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7221 	    ("deallocate_dependencies: pendinghd != NULL"));
7222 	for (i = 0; i < DAHASHSZ; i++)
7223 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7224 		    ("deallocate_dependencies: diraddhd != NULL"));
7225 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7226 		free_newdirblk(pagedep->pd_newdirblk);
7227 	if (free_pagedep(pagedep) == 0)
7228 		panic("Failed to free pagedep %p", pagedep);
7229 	return (0);
7230 }
7231 
7232 /*
7233  * Reclaim any dependency structures from a buffer that is about to
7234  * be reallocated to a new vnode. The buffer must be locked, thus,
7235  * no I/O completion operations can occur while we are manipulating
7236  * its associated dependencies. The mutex is held so that other I/O's
7237  * associated with related dependencies do not occur.
7238  */
7239 static int
7240 deallocate_dependencies(bp, freeblks, off)
7241 	struct buf *bp;
7242 	struct freeblks *freeblks;
7243 	int off;
7244 {
7245 	struct indirdep *indirdep;
7246 	struct pagedep *pagedep;
7247 	struct worklist *wk, *wkn;
7248 	struct ufsmount *ump;
7249 
7250 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
7251 		goto done;
7252 	ump = VFSTOUFS(wk->wk_mp);
7253 	ACQUIRE_LOCK(ump);
7254 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7255 		switch (wk->wk_type) {
7256 		case D_INDIRDEP:
7257 			indirdep = WK_INDIRDEP(wk);
7258 			if (bp->b_lblkno >= 0 ||
7259 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7260 				panic("deallocate_dependencies: not indir");
7261 			cancel_indirdep(indirdep, bp, freeblks);
7262 			continue;
7263 
7264 		case D_PAGEDEP:
7265 			pagedep = WK_PAGEDEP(wk);
7266 			if (cancel_pagedep(pagedep, freeblks, off)) {
7267 				FREE_LOCK(ump);
7268 				return (ERESTART);
7269 			}
7270 			continue;
7271 
7272 		case D_ALLOCINDIR:
7273 			/*
7274 			 * Simply remove the allocindir, we'll find it via
7275 			 * the indirdep where we can clear pointers if
7276 			 * needed.
7277 			 */
7278 			WORKLIST_REMOVE(wk);
7279 			continue;
7280 
7281 		case D_FREEWORK:
7282 			/*
7283 			 * A truncation is waiting for the zero'd pointers
7284 			 * to be written.  It can be freed when the freeblks
7285 			 * is journaled.
7286 			 */
7287 			WORKLIST_REMOVE(wk);
7288 			wk->wk_state |= ONDEPLIST;
7289 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7290 			break;
7291 
7292 		case D_ALLOCDIRECT:
7293 			if (off != 0)
7294 				continue;
7295 			/* FALLTHROUGH */
7296 		default:
7297 			panic("deallocate_dependencies: Unexpected type %s",
7298 			    TYPENAME(wk->wk_type));
7299 			/* NOTREACHED */
7300 		}
7301 	}
7302 	FREE_LOCK(ump);
7303 done:
7304 	/*
7305 	 * Don't throw away this buf, we were partially truncating and
7306 	 * some deps may always remain.
7307 	 */
7308 	if (off) {
7309 		allocbuf(bp, off);
7310 		bp->b_vflags |= BV_SCANNED;
7311 		return (EBUSY);
7312 	}
7313 	bp->b_flags |= B_INVAL | B_NOCACHE;
7314 
7315 	return (0);
7316 }
7317 
7318 /*
7319  * An allocdirect is being canceled due to a truncate.  We must make sure
7320  * the journal entry is released in concert with the blkfree that releases
7321  * the storage.  Completed journal entries must not be released until the
7322  * space is no longer pointed to by the inode or in the bitmap.
7323  */
7324 static void
7325 cancel_allocdirect(adphead, adp, freeblks)
7326 	struct allocdirectlst *adphead;
7327 	struct allocdirect *adp;
7328 	struct freeblks *freeblks;
7329 {
7330 	struct freework *freework;
7331 	struct newblk *newblk;
7332 	struct worklist *wk;
7333 
7334 	TAILQ_REMOVE(adphead, adp, ad_next);
7335 	newblk = (struct newblk *)adp;
7336 	freework = NULL;
7337 	/*
7338 	 * Find the correct freework structure.
7339 	 */
7340 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7341 		if (wk->wk_type != D_FREEWORK)
7342 			continue;
7343 		freework = WK_FREEWORK(wk);
7344 		if (freework->fw_blkno == newblk->nb_newblkno)
7345 			break;
7346 	}
7347 	if (freework == NULL)
7348 		panic("cancel_allocdirect: Freework not found");
7349 	/*
7350 	 * If a newblk exists at all we still have the journal entry that
7351 	 * initiated the allocation so we do not need to journal the free.
7352 	 */
7353 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7354 	/*
7355 	 * If the journal hasn't been written the jnewblk must be passed
7356 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7357 	 * this by linking the journal dependency into the freework to be
7358 	 * freed when freework_freeblock() is called.  If the journal has
7359 	 * been written we can simply reclaim the journal space when the
7360 	 * freeblks work is complete.
7361 	 */
7362 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7363 	    &freeblks->fb_jwork);
7364 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7365 }
7366 
7367 
7368 /*
7369  * Cancel a new block allocation.  May be an indirect or direct block.  We
7370  * remove it from various lists and return any journal record that needs to
7371  * be resolved by the caller.
7372  *
7373  * A special consideration is made for indirects which were never pointed
7374  * at on disk and will never be found once this block is released.
7375  */
7376 static struct jnewblk *
7377 cancel_newblk(newblk, wk, wkhd)
7378 	struct newblk *newblk;
7379 	struct worklist *wk;
7380 	struct workhead *wkhd;
7381 {
7382 	struct jnewblk *jnewblk;
7383 
7384 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7385 
7386 	newblk->nb_state |= GOINGAWAY;
7387 	/*
7388 	 * Previously we traversed the completedhd on each indirdep
7389 	 * attached to this newblk to cancel them and gather journal
7390 	 * work.  Since we need only the oldest journal segment and
7391 	 * the lowest point on the tree will always have the oldest
7392 	 * journal segment we are free to release the segments
7393 	 * of any subordinates and may leave the indirdep list to
7394 	 * indirdep_complete() when this newblk is freed.
7395 	 */
7396 	if (newblk->nb_state & ONDEPLIST) {
7397 		newblk->nb_state &= ~ONDEPLIST;
7398 		LIST_REMOVE(newblk, nb_deps);
7399 	}
7400 	if (newblk->nb_state & ONWORKLIST)
7401 		WORKLIST_REMOVE(&newblk->nb_list);
7402 	/*
7403 	 * If the journal entry hasn't been written we save a pointer to
7404 	 * the dependency that frees it until it is written or the
7405 	 * superseding operation completes.
7406 	 */
7407 	jnewblk = newblk->nb_jnewblk;
7408 	if (jnewblk != NULL && wk != NULL) {
7409 		newblk->nb_jnewblk = NULL;
7410 		jnewblk->jn_dep = wk;
7411 	}
7412 	if (!LIST_EMPTY(&newblk->nb_jwork))
7413 		jwork_move(wkhd, &newblk->nb_jwork);
7414 	/*
7415 	 * When truncating we must free the newdirblk early to remove
7416 	 * the pagedep from the hash before returning.
7417 	 */
7418 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7419 		free_newdirblk(WK_NEWDIRBLK(wk));
7420 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7421 		panic("cancel_newblk: extra newdirblk");
7422 
7423 	return (jnewblk);
7424 }
7425 
7426 /*
7427  * Schedule the freefrag associated with a newblk to be released once
7428  * the pointers are written and the previous block is no longer needed.
7429  */
7430 static void
7431 newblk_freefrag(newblk)
7432 	struct newblk *newblk;
7433 {
7434 	struct freefrag *freefrag;
7435 
7436 	if (newblk->nb_freefrag == NULL)
7437 		return;
7438 	freefrag = newblk->nb_freefrag;
7439 	newblk->nb_freefrag = NULL;
7440 	freefrag->ff_state |= COMPLETE;
7441 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7442 		add_to_worklist(&freefrag->ff_list, 0);
7443 }
7444 
7445 /*
7446  * Free a newblk. Generate a new freefrag work request if appropriate.
7447  * This must be called after the inode pointer and any direct block pointers
7448  * are valid or fully removed via truncate or frag extension.
7449  */
7450 static void
7451 free_newblk(newblk)
7452 	struct newblk *newblk;
7453 {
7454 	struct indirdep *indirdep;
7455 	struct worklist *wk;
7456 
7457 	KASSERT(newblk->nb_jnewblk == NULL,
7458 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7459 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7460 	    ("free_newblk: unclaimed newblk"));
7461 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7462 	newblk_freefrag(newblk);
7463 	if (newblk->nb_state & ONDEPLIST)
7464 		LIST_REMOVE(newblk, nb_deps);
7465 	if (newblk->nb_state & ONWORKLIST)
7466 		WORKLIST_REMOVE(&newblk->nb_list);
7467 	LIST_REMOVE(newblk, nb_hash);
7468 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7469 		free_newdirblk(WK_NEWDIRBLK(wk));
7470 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7471 		panic("free_newblk: extra newdirblk");
7472 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7473 		indirdep_complete(indirdep);
7474 	handle_jwork(&newblk->nb_jwork);
7475 	WORKITEM_FREE(newblk, D_NEWBLK);
7476 }
7477 
7478 /*
7479  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7480  * This routine must be called with splbio interrupts blocked.
7481  */
7482 static void
7483 free_newdirblk(newdirblk)
7484 	struct newdirblk *newdirblk;
7485 {
7486 	struct pagedep *pagedep;
7487 	struct diradd *dap;
7488 	struct worklist *wk;
7489 
7490 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7491 	WORKLIST_REMOVE(&newdirblk->db_list);
7492 	/*
7493 	 * If the pagedep is still linked onto the directory buffer
7494 	 * dependency chain, then some of the entries on the
7495 	 * pd_pendinghd list may not be committed to disk yet. In
7496 	 * this case, we will simply clear the NEWBLOCK flag and
7497 	 * let the pd_pendinghd list be processed when the pagedep
7498 	 * is next written. If the pagedep is no longer on the buffer
7499 	 * dependency chain, then all the entries on the pd_pending
7500 	 * list are committed to disk and we can free them here.
7501 	 */
7502 	pagedep = newdirblk->db_pagedep;
7503 	pagedep->pd_state &= ~NEWBLOCK;
7504 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7505 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7506 			free_diradd(dap, NULL);
7507 		/*
7508 		 * If no dependencies remain, the pagedep will be freed.
7509 		 */
7510 		free_pagedep(pagedep);
7511 	}
7512 	/* Should only ever be one item in the list. */
7513 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7514 		WORKLIST_REMOVE(wk);
7515 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7516 	}
7517 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7518 }
7519 
7520 /*
7521  * Prepare an inode to be freed. The actual free operation is not
7522  * done until the zero'ed inode has been written to disk.
7523  */
7524 void
7525 softdep_freefile(pvp, ino, mode)
7526 	struct vnode *pvp;
7527 	ino_t ino;
7528 	int mode;
7529 {
7530 	struct inode *ip = VTOI(pvp);
7531 	struct inodedep *inodedep;
7532 	struct freefile *freefile;
7533 	struct freeblks *freeblks;
7534 	struct ufsmount *ump;
7535 
7536 	ump = ITOUMP(ip);
7537 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7538 	    ("softdep_freefile called on non-softdep filesystem"));
7539 	/*
7540 	 * This sets up the inode de-allocation dependency.
7541 	 */
7542 	freefile = malloc(sizeof(struct freefile),
7543 		M_FREEFILE, M_SOFTDEP_FLAGS);
7544 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7545 	freefile->fx_mode = mode;
7546 	freefile->fx_oldinum = ino;
7547 	freefile->fx_devvp = ump->um_devvp;
7548 	LIST_INIT(&freefile->fx_jwork);
7549 	UFS_LOCK(ump);
7550 	ump->um_fs->fs_pendinginodes += 1;
7551 	UFS_UNLOCK(ump);
7552 
7553 	/*
7554 	 * If the inodedep does not exist, then the zero'ed inode has
7555 	 * been written to disk. If the allocated inode has never been
7556 	 * written to disk, then the on-disk inode is zero'ed. In either
7557 	 * case we can free the file immediately.  If the journal was
7558 	 * canceled before being written the inode will never make it to
7559 	 * disk and we must send the canceled journal entrys to
7560 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7561 	 * Any blocks waiting on the inode to write can be safely freed
7562 	 * here as it will never been written.
7563 	 */
7564 	ACQUIRE_LOCK(ump);
7565 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7566 	if (inodedep) {
7567 		/*
7568 		 * Clear out freeblks that no longer need to reference
7569 		 * this inode.
7570 		 */
7571 		while ((freeblks =
7572 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7573 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7574 			    fb_next);
7575 			freeblks->fb_state &= ~ONDEPLIST;
7576 		}
7577 		/*
7578 		 * Remove this inode from the unlinked list.
7579 		 */
7580 		if (inodedep->id_state & UNLINKED) {
7581 			/*
7582 			 * Save the journal work to be freed with the bitmap
7583 			 * before we clear UNLINKED.  Otherwise it can be lost
7584 			 * if the inode block is written.
7585 			 */
7586 			handle_bufwait(inodedep, &freefile->fx_jwork);
7587 			clear_unlinked_inodedep(inodedep);
7588 			/*
7589 			 * Re-acquire inodedep as we've dropped the
7590 			 * per-filesystem lock in clear_unlinked_inodedep().
7591 			 */
7592 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7593 		}
7594 	}
7595 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7596 		FREE_LOCK(ump);
7597 		handle_workitem_freefile(freefile);
7598 		return;
7599 	}
7600 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7601 		inodedep->id_state |= GOINGAWAY;
7602 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7603 	FREE_LOCK(ump);
7604 	if (ip->i_number == ino)
7605 		ip->i_flag |= IN_MODIFIED;
7606 }
7607 
7608 /*
7609  * Check to see if an inode has never been written to disk. If
7610  * so free the inodedep and return success, otherwise return failure.
7611  * This routine must be called with splbio interrupts blocked.
7612  *
7613  * If we still have a bitmap dependency, then the inode has never
7614  * been written to disk. Drop the dependency as it is no longer
7615  * necessary since the inode is being deallocated. We set the
7616  * ALLCOMPLETE flags since the bitmap now properly shows that the
7617  * inode is not allocated. Even if the inode is actively being
7618  * written, it has been rolled back to its zero'ed state, so we
7619  * are ensured that a zero inode is what is on the disk. For short
7620  * lived files, this change will usually result in removing all the
7621  * dependencies from the inode so that it can be freed immediately.
7622  */
7623 static int
7624 check_inode_unwritten(inodedep)
7625 	struct inodedep *inodedep;
7626 {
7627 
7628 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7629 
7630 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7631 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7632 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7633 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7634 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7635 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7636 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7637 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7638 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7639 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7640 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7641 	    inodedep->id_mkdiradd != NULL ||
7642 	    inodedep->id_nlinkdelta != 0)
7643 		return (0);
7644 	/*
7645 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7646 	 * trying to allocate memory without holding "Softdep Lock".
7647 	 */
7648 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7649 	    inodedep->id_savedino1 == NULL)
7650 		return (0);
7651 
7652 	if (inodedep->id_state & ONDEPLIST)
7653 		LIST_REMOVE(inodedep, id_deps);
7654 	inodedep->id_state &= ~ONDEPLIST;
7655 	inodedep->id_state |= ALLCOMPLETE;
7656 	inodedep->id_bmsafemap = NULL;
7657 	if (inodedep->id_state & ONWORKLIST)
7658 		WORKLIST_REMOVE(&inodedep->id_list);
7659 	if (inodedep->id_savedino1 != NULL) {
7660 		free(inodedep->id_savedino1, M_SAVEDINO);
7661 		inodedep->id_savedino1 = NULL;
7662 	}
7663 	if (free_inodedep(inodedep) == 0)
7664 		panic("check_inode_unwritten: busy inode");
7665 	return (1);
7666 }
7667 
7668 static int
7669 check_inodedep_free(inodedep)
7670 	struct inodedep *inodedep;
7671 {
7672 
7673 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7674 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7675 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7676 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7677 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7678 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7679 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7680 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7681 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7682 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7683 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7684 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7685 	    inodedep->id_mkdiradd != NULL ||
7686 	    inodedep->id_nlinkdelta != 0 ||
7687 	    inodedep->id_savedino1 != NULL)
7688 		return (0);
7689 	return (1);
7690 }
7691 
7692 /*
7693  * Try to free an inodedep structure. Return 1 if it could be freed.
7694  */
7695 static int
7696 free_inodedep(inodedep)
7697 	struct inodedep *inodedep;
7698 {
7699 
7700 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7701 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7702 	    !check_inodedep_free(inodedep))
7703 		return (0);
7704 	if (inodedep->id_state & ONDEPLIST)
7705 		LIST_REMOVE(inodedep, id_deps);
7706 	LIST_REMOVE(inodedep, id_hash);
7707 	WORKITEM_FREE(inodedep, D_INODEDEP);
7708 	return (1);
7709 }
7710 
7711 /*
7712  * Free the block referenced by a freework structure.  The parent freeblks
7713  * structure is released and completed when the final cg bitmap reaches
7714  * the disk.  This routine may be freeing a jnewblk which never made it to
7715  * disk in which case we do not have to wait as the operation is undone
7716  * in memory immediately.
7717  */
7718 static void
7719 freework_freeblock(freework)
7720 	struct freework *freework;
7721 {
7722 	struct freeblks *freeblks;
7723 	struct jnewblk *jnewblk;
7724 	struct ufsmount *ump;
7725 	struct workhead wkhd;
7726 	struct fs *fs;
7727 	int bsize;
7728 	int needj;
7729 
7730 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7731 	LOCK_OWNED(ump);
7732 	/*
7733 	 * Handle partial truncate separately.
7734 	 */
7735 	if (freework->fw_indir) {
7736 		complete_trunc_indir(freework);
7737 		return;
7738 	}
7739 	freeblks = freework->fw_freeblks;
7740 	fs = ump->um_fs;
7741 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7742 	bsize = lfragtosize(fs, freework->fw_frags);
7743 	LIST_INIT(&wkhd);
7744 	/*
7745 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7746 	 * on the indirblk hashtable and prevents premature freeing.
7747 	 */
7748 	freework->fw_state |= DEPCOMPLETE;
7749 	/*
7750 	 * SUJ needs to wait for the segment referencing freed indirect
7751 	 * blocks to expire so that we know the checker will not confuse
7752 	 * a re-allocated indirect block with its old contents.
7753 	 */
7754 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7755 		indirblk_insert(freework);
7756 	/*
7757 	 * If we are canceling an existing jnewblk pass it to the free
7758 	 * routine, otherwise pass the freeblk which will ultimately
7759 	 * release the freeblks.  If we're not journaling, we can just
7760 	 * free the freeblks immediately.
7761 	 */
7762 	jnewblk = freework->fw_jnewblk;
7763 	if (jnewblk != NULL) {
7764 		cancel_jnewblk(jnewblk, &wkhd);
7765 		needj = 0;
7766 	} else if (needj) {
7767 		freework->fw_state |= DELAYEDFREE;
7768 		freeblks->fb_cgwait++;
7769 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7770 	}
7771 	FREE_LOCK(ump);
7772 	freeblks_free(ump, freeblks, btodb(bsize));
7773 	CTR4(KTR_SUJ,
7774 	    "freework_freeblock: ino %d blkno %jd lbn %jd size %ld",
7775 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7776 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7777 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7778 	ACQUIRE_LOCK(ump);
7779 	/*
7780 	 * The jnewblk will be discarded and the bits in the map never
7781 	 * made it to disk.  We can immediately free the freeblk.
7782 	 */
7783 	if (needj == 0)
7784 		handle_written_freework(freework);
7785 }
7786 
7787 /*
7788  * We enqueue freework items that need processing back on the freeblks and
7789  * add the freeblks to the worklist.  This makes it easier to find all work
7790  * required to flush a truncation in process_truncates().
7791  */
7792 static void
7793 freework_enqueue(freework)
7794 	struct freework *freework;
7795 {
7796 	struct freeblks *freeblks;
7797 
7798 	freeblks = freework->fw_freeblks;
7799 	if ((freework->fw_state & INPROGRESS) == 0)
7800 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7801 	if ((freeblks->fb_state &
7802 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7803 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7804 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7805 }
7806 
7807 /*
7808  * Start, continue, or finish the process of freeing an indirect block tree.
7809  * The free operation may be paused at any point with fw_off containing the
7810  * offset to restart from.  This enables us to implement some flow control
7811  * for large truncates which may fan out and generate a huge number of
7812  * dependencies.
7813  */
7814 static void
7815 handle_workitem_indirblk(freework)
7816 	struct freework *freework;
7817 {
7818 	struct freeblks *freeblks;
7819 	struct ufsmount *ump;
7820 	struct fs *fs;
7821 
7822 	freeblks = freework->fw_freeblks;
7823 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7824 	fs = ump->um_fs;
7825 	if (freework->fw_state & DEPCOMPLETE) {
7826 		handle_written_freework(freework);
7827 		return;
7828 	}
7829 	if (freework->fw_off == NINDIR(fs)) {
7830 		freework_freeblock(freework);
7831 		return;
7832 	}
7833 	freework->fw_state |= INPROGRESS;
7834 	FREE_LOCK(ump);
7835 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7836 	    freework->fw_lbn);
7837 	ACQUIRE_LOCK(ump);
7838 }
7839 
7840 /*
7841  * Called when a freework structure attached to a cg buf is written.  The
7842  * ref on either the parent or the freeblks structure is released and
7843  * the freeblks is added back to the worklist if there is more work to do.
7844  */
7845 static void
7846 handle_written_freework(freework)
7847 	struct freework *freework;
7848 {
7849 	struct freeblks *freeblks;
7850 	struct freework *parent;
7851 
7852 	freeblks = freework->fw_freeblks;
7853 	parent = freework->fw_parent;
7854 	if (freework->fw_state & DELAYEDFREE)
7855 		freeblks->fb_cgwait--;
7856 	freework->fw_state |= COMPLETE;
7857 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7858 		WORKITEM_FREE(freework, D_FREEWORK);
7859 	if (parent) {
7860 		if (--parent->fw_ref == 0)
7861 			freework_enqueue(parent);
7862 		return;
7863 	}
7864 	if (--freeblks->fb_ref != 0)
7865 		return;
7866 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7867 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7868 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7869 }
7870 
7871 /*
7872  * This workitem routine performs the block de-allocation.
7873  * The workitem is added to the pending list after the updated
7874  * inode block has been written to disk.  As mentioned above,
7875  * checks regarding the number of blocks de-allocated (compared
7876  * to the number of blocks allocated for the file) are also
7877  * performed in this function.
7878  */
7879 static int
7880 handle_workitem_freeblocks(freeblks, flags)
7881 	struct freeblks *freeblks;
7882 	int flags;
7883 {
7884 	struct freework *freework;
7885 	struct newblk *newblk;
7886 	struct allocindir *aip;
7887 	struct ufsmount *ump;
7888 	struct worklist *wk;
7889 
7890 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7891 	    ("handle_workitem_freeblocks: Journal entries not written."));
7892 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7893 	ACQUIRE_LOCK(ump);
7894 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7895 		WORKLIST_REMOVE(wk);
7896 		switch (wk->wk_type) {
7897 		case D_DIRREM:
7898 			wk->wk_state |= COMPLETE;
7899 			add_to_worklist(wk, 0);
7900 			continue;
7901 
7902 		case D_ALLOCDIRECT:
7903 			free_newblk(WK_NEWBLK(wk));
7904 			continue;
7905 
7906 		case D_ALLOCINDIR:
7907 			aip = WK_ALLOCINDIR(wk);
7908 			freework = NULL;
7909 			if (aip->ai_state & DELAYEDFREE) {
7910 				FREE_LOCK(ump);
7911 				freework = newfreework(ump, freeblks, NULL,
7912 				    aip->ai_lbn, aip->ai_newblkno,
7913 				    ump->um_fs->fs_frag, 0, 0);
7914 				ACQUIRE_LOCK(ump);
7915 			}
7916 			newblk = WK_NEWBLK(wk);
7917 			if (newblk->nb_jnewblk) {
7918 				freework->fw_jnewblk = newblk->nb_jnewblk;
7919 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7920 				newblk->nb_jnewblk = NULL;
7921 			}
7922 			free_newblk(newblk);
7923 			continue;
7924 
7925 		case D_FREEWORK:
7926 			freework = WK_FREEWORK(wk);
7927 			if (freework->fw_lbn <= -UFS_NDADDR)
7928 				handle_workitem_indirblk(freework);
7929 			else
7930 				freework_freeblock(freework);
7931 			continue;
7932 		default:
7933 			panic("handle_workitem_freeblocks: Unknown type %s",
7934 			    TYPENAME(wk->wk_type));
7935 		}
7936 	}
7937 	if (freeblks->fb_ref != 0) {
7938 		freeblks->fb_state &= ~INPROGRESS;
7939 		wake_worklist(&freeblks->fb_list);
7940 		freeblks = NULL;
7941 	}
7942 	FREE_LOCK(ump);
7943 	if (freeblks)
7944 		return handle_complete_freeblocks(freeblks, flags);
7945 	return (0);
7946 }
7947 
7948 /*
7949  * Handle completion of block free via truncate.  This allows fs_pending
7950  * to track the actual free block count more closely than if we only updated
7951  * it at the end.  We must be careful to handle cases where the block count
7952  * on free was incorrect.
7953  */
7954 static void
7955 freeblks_free(ump, freeblks, blocks)
7956 	struct ufsmount *ump;
7957 	struct freeblks *freeblks;
7958 	int blocks;
7959 {
7960 	struct fs *fs;
7961 	ufs2_daddr_t remain;
7962 
7963 	UFS_LOCK(ump);
7964 	remain = -freeblks->fb_chkcnt;
7965 	freeblks->fb_chkcnt += blocks;
7966 	if (remain > 0) {
7967 		if (remain < blocks)
7968 			blocks = remain;
7969 		fs = ump->um_fs;
7970 		fs->fs_pendingblocks -= blocks;
7971 	}
7972 	UFS_UNLOCK(ump);
7973 }
7974 
7975 /*
7976  * Once all of the freework workitems are complete we can retire the
7977  * freeblocks dependency and any journal work awaiting completion.  This
7978  * can not be called until all other dependencies are stable on disk.
7979  */
7980 static int
7981 handle_complete_freeblocks(freeblks, flags)
7982 	struct freeblks *freeblks;
7983 	int flags;
7984 {
7985 	struct inodedep *inodedep;
7986 	struct inode *ip;
7987 	struct vnode *vp;
7988 	struct fs *fs;
7989 	struct ufsmount *ump;
7990 	ufs2_daddr_t spare;
7991 
7992 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7993 	fs = ump->um_fs;
7994 	flags = LK_EXCLUSIVE | flags;
7995 	spare = freeblks->fb_chkcnt;
7996 
7997 	/*
7998 	 * If we did not release the expected number of blocks we may have
7999 	 * to adjust the inode block count here.  Only do so if it wasn't
8000 	 * a truncation to zero and the modrev still matches.
8001 	 */
8002 	if (spare && freeblks->fb_len != 0) {
8003 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8004 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8005 			return (EBUSY);
8006 		ip = VTOI(vp);
8007 		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8008 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8009 			ip->i_flag |= IN_CHANGE;
8010 			/*
8011 			 * We must wait so this happens before the
8012 			 * journal is reclaimed.
8013 			 */
8014 			ffs_update(vp, 1);
8015 		}
8016 		vput(vp);
8017 	}
8018 	if (spare < 0) {
8019 		UFS_LOCK(ump);
8020 		fs->fs_pendingblocks += spare;
8021 		UFS_UNLOCK(ump);
8022 	}
8023 #ifdef QUOTA
8024 	/* Handle spare. */
8025 	if (spare)
8026 		quotaadj(freeblks->fb_quota, ump, -spare);
8027 	quotarele(freeblks->fb_quota);
8028 #endif
8029 	ACQUIRE_LOCK(ump);
8030 	if (freeblks->fb_state & ONDEPLIST) {
8031 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8032 		    0, &inodedep);
8033 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8034 		freeblks->fb_state &= ~ONDEPLIST;
8035 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8036 			free_inodedep(inodedep);
8037 	}
8038 	/*
8039 	 * All of the freeblock deps must be complete prior to this call
8040 	 * so it's now safe to complete earlier outstanding journal entries.
8041 	 */
8042 	handle_jwork(&freeblks->fb_jwork);
8043 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8044 	FREE_LOCK(ump);
8045 	return (0);
8046 }
8047 
8048 /*
8049  * Release blocks associated with the freeblks and stored in the indirect
8050  * block dbn. If level is greater than SINGLE, the block is an indirect block
8051  * and recursive calls to indirtrunc must be used to cleanse other indirect
8052  * blocks.
8053  *
8054  * This handles partial and complete truncation of blocks.  Partial is noted
8055  * with goingaway == 0.  In this case the freework is completed after the
8056  * zero'd indirects are written to disk.  For full truncation the freework
8057  * is completed after the block is freed.
8058  */
8059 static void
8060 indir_trunc(freework, dbn, lbn)
8061 	struct freework *freework;
8062 	ufs2_daddr_t dbn;
8063 	ufs_lbn_t lbn;
8064 {
8065 	struct freework *nfreework;
8066 	struct workhead wkhd;
8067 	struct freeblks *freeblks;
8068 	struct buf *bp;
8069 	struct fs *fs;
8070 	struct indirdep *indirdep;
8071 	struct ufsmount *ump;
8072 	ufs1_daddr_t *bap1;
8073 	ufs2_daddr_t nb, nnb, *bap2;
8074 	ufs_lbn_t lbnadd, nlbn;
8075 	int i, nblocks, ufs1fmt;
8076 	int freedblocks;
8077 	int goingaway;
8078 	int freedeps;
8079 	int needj;
8080 	int level;
8081 	int cnt;
8082 
8083 	freeblks = freework->fw_freeblks;
8084 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8085 	fs = ump->um_fs;
8086 	/*
8087 	 * Get buffer of block pointers to be freed.  There are three cases:
8088 	 *
8089 	 * 1) Partial truncate caches the indirdep pointer in the freework
8090 	 *    which provides us a back copy to the save bp which holds the
8091 	 *    pointers we want to clear.  When this completes the zero
8092 	 *    pointers are written to the real copy.
8093 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8094 	 *    eliminated the real copy and placed the indirdep on the saved
8095 	 *    copy.  The indirdep and buf are discarded when this completes.
8096 	 * 3) The indirect was not in memory, we read a copy off of the disk
8097 	 *    using the devvp and drop and invalidate the buffer when we're
8098 	 *    done.
8099 	 */
8100 	goingaway = 1;
8101 	indirdep = NULL;
8102 	if (freework->fw_indir != NULL) {
8103 		goingaway = 0;
8104 		indirdep = freework->fw_indir;
8105 		bp = indirdep->ir_savebp;
8106 		if (bp == NULL || bp->b_blkno != dbn)
8107 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8108 			    bp, (intmax_t)dbn);
8109 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8110 		/*
8111 		 * The lock prevents the buf dep list from changing and
8112 	 	 * indirects on devvp should only ever have one dependency.
8113 		 */
8114 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8115 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8116 			panic("indir_trunc: Bad indirdep %p from buf %p",
8117 			    indirdep, bp);
8118 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8119 	    NOCRED, &bp) != 0) {
8120 		brelse(bp);
8121 		return;
8122 	}
8123 	ACQUIRE_LOCK(ump);
8124 	/* Protects against a race with complete_trunc_indir(). */
8125 	freework->fw_state &= ~INPROGRESS;
8126 	/*
8127 	 * If we have an indirdep we need to enforce the truncation order
8128 	 * and discard it when it is complete.
8129 	 */
8130 	if (indirdep) {
8131 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8132 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8133 			/*
8134 			 * Add the complete truncate to the list on the
8135 			 * indirdep to enforce in-order processing.
8136 			 */
8137 			if (freework->fw_indir == NULL)
8138 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8139 				    freework, fw_next);
8140 			FREE_LOCK(ump);
8141 			return;
8142 		}
8143 		/*
8144 		 * If we're goingaway, free the indirdep.  Otherwise it will
8145 		 * linger until the write completes.
8146 		 */
8147 		if (goingaway)
8148 			free_indirdep(indirdep);
8149 	}
8150 	FREE_LOCK(ump);
8151 	/* Initialize pointers depending on block size. */
8152 	if (ump->um_fstype == UFS1) {
8153 		bap1 = (ufs1_daddr_t *)bp->b_data;
8154 		nb = bap1[freework->fw_off];
8155 		ufs1fmt = 1;
8156 		bap2 = NULL;
8157 	} else {
8158 		bap2 = (ufs2_daddr_t *)bp->b_data;
8159 		nb = bap2[freework->fw_off];
8160 		ufs1fmt = 0;
8161 		bap1 = NULL;
8162 	}
8163 	level = lbn_level(lbn);
8164 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8165 	lbnadd = lbn_offset(fs, level);
8166 	nblocks = btodb(fs->fs_bsize);
8167 	nfreework = freework;
8168 	freedeps = 0;
8169 	cnt = 0;
8170 	/*
8171 	 * Reclaim blocks.  Traverses into nested indirect levels and
8172 	 * arranges for the current level to be freed when subordinates
8173 	 * are free when journaling.
8174 	 */
8175 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8176 		if (i != NINDIR(fs) - 1) {
8177 			if (ufs1fmt)
8178 				nnb = bap1[i+1];
8179 			else
8180 				nnb = bap2[i+1];
8181 		} else
8182 			nnb = 0;
8183 		if (nb == 0)
8184 			continue;
8185 		cnt++;
8186 		if (level != 0) {
8187 			nlbn = (lbn + 1) - (i * lbnadd);
8188 			if (needj != 0) {
8189 				nfreework = newfreework(ump, freeblks, freework,
8190 				    nlbn, nb, fs->fs_frag, 0, 0);
8191 				freedeps++;
8192 			}
8193 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8194 		} else {
8195 			struct freedep *freedep;
8196 
8197 			/*
8198 			 * Attempt to aggregate freedep dependencies for
8199 			 * all blocks being released to the same CG.
8200 			 */
8201 			LIST_INIT(&wkhd);
8202 			if (needj != 0 &&
8203 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8204 				freedep = newfreedep(freework);
8205 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8206 				    &freedep->fd_list);
8207 				freedeps++;
8208 			}
8209 			CTR3(KTR_SUJ,
8210 			    "indir_trunc: ino %d blkno %jd size %ld",
8211 			    freeblks->fb_inum, nb, fs->fs_bsize);
8212 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8213 			    fs->fs_bsize, freeblks->fb_inum,
8214 			    freeblks->fb_vtype, &wkhd);
8215 		}
8216 	}
8217 	if (goingaway) {
8218 		bp->b_flags |= B_INVAL | B_NOCACHE;
8219 		brelse(bp);
8220 	}
8221 	freedblocks = 0;
8222 	if (level == 0)
8223 		freedblocks = (nblocks * cnt);
8224 	if (needj == 0)
8225 		freedblocks += nblocks;
8226 	freeblks_free(ump, freeblks, freedblocks);
8227 	/*
8228 	 * If we are journaling set up the ref counts and offset so this
8229 	 * indirect can be completed when its children are free.
8230 	 */
8231 	if (needj) {
8232 		ACQUIRE_LOCK(ump);
8233 		freework->fw_off = i;
8234 		freework->fw_ref += freedeps;
8235 		freework->fw_ref -= NINDIR(fs) + 1;
8236 		if (level == 0)
8237 			freeblks->fb_cgwait += freedeps;
8238 		if (freework->fw_ref == 0)
8239 			freework_freeblock(freework);
8240 		FREE_LOCK(ump);
8241 		return;
8242 	}
8243 	/*
8244 	 * If we're not journaling we can free the indirect now.
8245 	 */
8246 	dbn = dbtofsb(fs, dbn);
8247 	CTR3(KTR_SUJ,
8248 	    "indir_trunc 2: ino %d blkno %jd size %ld",
8249 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8250 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8251 	    freeblks->fb_inum, freeblks->fb_vtype, NULL);
8252 	/* Non SUJ softdep does single-threaded truncations. */
8253 	if (freework->fw_blkno == dbn) {
8254 		freework->fw_state |= ALLCOMPLETE;
8255 		ACQUIRE_LOCK(ump);
8256 		handle_written_freework(freework);
8257 		FREE_LOCK(ump);
8258 	}
8259 	return;
8260 }
8261 
8262 /*
8263  * Cancel an allocindir when it is removed via truncation.  When bp is not
8264  * NULL the indirect never appeared on disk and is scheduled to be freed
8265  * independently of the indir so we can more easily track journal work.
8266  */
8267 static void
8268 cancel_allocindir(aip, bp, freeblks, trunc)
8269 	struct allocindir *aip;
8270 	struct buf *bp;
8271 	struct freeblks *freeblks;
8272 	int trunc;
8273 {
8274 	struct indirdep *indirdep;
8275 	struct freefrag *freefrag;
8276 	struct newblk *newblk;
8277 
8278 	newblk = (struct newblk *)aip;
8279 	LIST_REMOVE(aip, ai_next);
8280 	/*
8281 	 * We must eliminate the pointer in bp if it must be freed on its
8282 	 * own due to partial truncate or pending journal work.
8283 	 */
8284 	if (bp && (trunc || newblk->nb_jnewblk)) {
8285 		/*
8286 		 * Clear the pointer and mark the aip to be freed
8287 		 * directly if it never existed on disk.
8288 		 */
8289 		aip->ai_state |= DELAYEDFREE;
8290 		indirdep = aip->ai_indirdep;
8291 		if (indirdep->ir_state & UFS1FMT)
8292 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8293 		else
8294 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8295 	}
8296 	/*
8297 	 * When truncating the previous pointer will be freed via
8298 	 * savedbp.  Eliminate the freefrag which would dup free.
8299 	 */
8300 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8301 		newblk->nb_freefrag = NULL;
8302 		if (freefrag->ff_jdep)
8303 			cancel_jfreefrag(
8304 			    WK_JFREEFRAG(freefrag->ff_jdep));
8305 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8306 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8307 	}
8308 	/*
8309 	 * If the journal hasn't been written the jnewblk must be passed
8310 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8311 	 * this by leaving the journal dependency on the newblk to be freed
8312 	 * when a freework is created in handle_workitem_freeblocks().
8313 	 */
8314 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8315 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8316 }
8317 
8318 /*
8319  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8320  * in to a newdirblk so any subsequent additions are tracked properly.  The
8321  * caller is responsible for adding the mkdir1 dependency to the journal
8322  * and updating id_mkdiradd.  This function returns with the per-filesystem
8323  * lock held.
8324  */
8325 static struct mkdir *
8326 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8327 	struct diradd *dap;
8328 	ino_t newinum;
8329 	ino_t dinum;
8330 	struct buf *newdirbp;
8331 	struct mkdir **mkdirp;
8332 {
8333 	struct newblk *newblk;
8334 	struct pagedep *pagedep;
8335 	struct inodedep *inodedep;
8336 	struct newdirblk *newdirblk;
8337 	struct mkdir *mkdir1, *mkdir2;
8338 	struct worklist *wk;
8339 	struct jaddref *jaddref;
8340 	struct ufsmount *ump;
8341 	struct mount *mp;
8342 
8343 	mp = dap->da_list.wk_mp;
8344 	ump = VFSTOUFS(mp);
8345 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8346 	    M_SOFTDEP_FLAGS);
8347 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8348 	LIST_INIT(&newdirblk->db_mkdir);
8349 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8350 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8351 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8352 	mkdir1->md_diradd = dap;
8353 	mkdir1->md_jaddref = NULL;
8354 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8355 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8356 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8357 	mkdir2->md_diradd = dap;
8358 	mkdir2->md_jaddref = NULL;
8359 	if (MOUNTEDSUJ(mp) == 0) {
8360 		mkdir1->md_state |= DEPCOMPLETE;
8361 		mkdir2->md_state |= DEPCOMPLETE;
8362 	}
8363 	/*
8364 	 * Dependency on "." and ".." being written to disk.
8365 	 */
8366 	mkdir1->md_buf = newdirbp;
8367 	ACQUIRE_LOCK(VFSTOUFS(mp));
8368 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8369 	/*
8370 	 * We must link the pagedep, allocdirect, and newdirblk for
8371 	 * the initial file page so the pointer to the new directory
8372 	 * is not written until the directory contents are live and
8373 	 * any subsequent additions are not marked live until the
8374 	 * block is reachable via the inode.
8375 	 */
8376 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8377 		panic("setup_newdir: lost pagedep");
8378 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8379 		if (wk->wk_type == D_ALLOCDIRECT)
8380 			break;
8381 	if (wk == NULL)
8382 		panic("setup_newdir: lost allocdirect");
8383 	if (pagedep->pd_state & NEWBLOCK)
8384 		panic("setup_newdir: NEWBLOCK already set");
8385 	newblk = WK_NEWBLK(wk);
8386 	pagedep->pd_state |= NEWBLOCK;
8387 	pagedep->pd_newdirblk = newdirblk;
8388 	newdirblk->db_pagedep = pagedep;
8389 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8390 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8391 	/*
8392 	 * Look up the inodedep for the parent directory so that we
8393 	 * can link mkdir2 into the pending dotdot jaddref or
8394 	 * the inode write if there is none.  If the inode is
8395 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8396 	 * been satisfied and mkdir2 can be freed.
8397 	 */
8398 	inodedep_lookup(mp, dinum, 0, &inodedep);
8399 	if (MOUNTEDSUJ(mp)) {
8400 		if (inodedep == NULL)
8401 			panic("setup_newdir: Lost parent.");
8402 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8403 		    inoreflst);
8404 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8405 		    (jaddref->ja_state & MKDIR_PARENT),
8406 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8407 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8408 		mkdir2->md_jaddref = jaddref;
8409 		jaddref->ja_mkdir = mkdir2;
8410 	} else if (inodedep == NULL ||
8411 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8412 		dap->da_state &= ~MKDIR_PARENT;
8413 		WORKITEM_FREE(mkdir2, D_MKDIR);
8414 		mkdir2 = NULL;
8415 	} else {
8416 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8417 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8418 	}
8419 	*mkdirp = mkdir2;
8420 
8421 	return (mkdir1);
8422 }
8423 
8424 /*
8425  * Directory entry addition dependencies.
8426  *
8427  * When adding a new directory entry, the inode (with its incremented link
8428  * count) must be written to disk before the directory entry's pointer to it.
8429  * Also, if the inode is newly allocated, the corresponding freemap must be
8430  * updated (on disk) before the directory entry's pointer. These requirements
8431  * are met via undo/redo on the directory entry's pointer, which consists
8432  * simply of the inode number.
8433  *
8434  * As directory entries are added and deleted, the free space within a
8435  * directory block can become fragmented.  The ufs filesystem will compact
8436  * a fragmented directory block to make space for a new entry. When this
8437  * occurs, the offsets of previously added entries change. Any "diradd"
8438  * dependency structures corresponding to these entries must be updated with
8439  * the new offsets.
8440  */
8441 
8442 /*
8443  * This routine is called after the in-memory inode's link
8444  * count has been incremented, but before the directory entry's
8445  * pointer to the inode has been set.
8446  */
8447 int
8448 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8449 	struct buf *bp;		/* buffer containing directory block */
8450 	struct inode *dp;	/* inode for directory */
8451 	off_t diroffset;	/* offset of new entry in directory */
8452 	ino_t newinum;		/* inode referenced by new directory entry */
8453 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8454 	int isnewblk;		/* entry is in a newly allocated block */
8455 {
8456 	int offset;		/* offset of new entry within directory block */
8457 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8458 	struct fs *fs;
8459 	struct diradd *dap;
8460 	struct newblk *newblk;
8461 	struct pagedep *pagedep;
8462 	struct inodedep *inodedep;
8463 	struct newdirblk *newdirblk;
8464 	struct mkdir *mkdir1, *mkdir2;
8465 	struct jaddref *jaddref;
8466 	struct ufsmount *ump;
8467 	struct mount *mp;
8468 	int isindir;
8469 
8470 	mp = ITOVFS(dp);
8471 	ump = VFSTOUFS(mp);
8472 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8473 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8474 	/*
8475 	 * Whiteouts have no dependencies.
8476 	 */
8477 	if (newinum == UFS_WINO) {
8478 		if (newdirbp != NULL)
8479 			bdwrite(newdirbp);
8480 		return (0);
8481 	}
8482 	jaddref = NULL;
8483 	mkdir1 = mkdir2 = NULL;
8484 	fs = ump->um_fs;
8485 	lbn = lblkno(fs, diroffset);
8486 	offset = blkoff(fs, diroffset);
8487 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8488 		M_SOFTDEP_FLAGS|M_ZERO);
8489 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8490 	dap->da_offset = offset;
8491 	dap->da_newinum = newinum;
8492 	dap->da_state = ATTACHED;
8493 	LIST_INIT(&dap->da_jwork);
8494 	isindir = bp->b_lblkno >= UFS_NDADDR;
8495 	newdirblk = NULL;
8496 	if (isnewblk &&
8497 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8498 		newdirblk = malloc(sizeof(struct newdirblk),
8499 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8500 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8501 		LIST_INIT(&newdirblk->db_mkdir);
8502 	}
8503 	/*
8504 	 * If we're creating a new directory setup the dependencies and set
8505 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8506 	 * we can move on.
8507 	 */
8508 	if (newdirbp == NULL) {
8509 		dap->da_state |= DEPCOMPLETE;
8510 		ACQUIRE_LOCK(ump);
8511 	} else {
8512 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8513 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8514 		    &mkdir2);
8515 	}
8516 	/*
8517 	 * Link into parent directory pagedep to await its being written.
8518 	 */
8519 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8520 #ifdef DEBUG
8521 	if (diradd_lookup(pagedep, offset) != NULL)
8522 		panic("softdep_setup_directory_add: %p already at off %d\n",
8523 		    diradd_lookup(pagedep, offset), offset);
8524 #endif
8525 	dap->da_pagedep = pagedep;
8526 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8527 	    da_pdlist);
8528 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8529 	/*
8530 	 * If we're journaling, link the diradd into the jaddref so it
8531 	 * may be completed after the journal entry is written.  Otherwise,
8532 	 * link the diradd into its inodedep.  If the inode is not yet
8533 	 * written place it on the bufwait list, otherwise do the post-inode
8534 	 * write processing to put it on the id_pendinghd list.
8535 	 */
8536 	if (MOUNTEDSUJ(mp)) {
8537 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8538 		    inoreflst);
8539 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8540 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8541 		jaddref->ja_diroff = diroffset;
8542 		jaddref->ja_diradd = dap;
8543 		add_to_journal(&jaddref->ja_list);
8544 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8545 		diradd_inode_written(dap, inodedep);
8546 	else
8547 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8548 	/*
8549 	 * Add the journal entries for . and .. links now that the primary
8550 	 * link is written.
8551 	 */
8552 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8553 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8554 		    inoreflst, if_deps);
8555 		KASSERT(jaddref != NULL &&
8556 		    jaddref->ja_ino == jaddref->ja_parent &&
8557 		    (jaddref->ja_state & MKDIR_BODY),
8558 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8559 		    jaddref));
8560 		mkdir1->md_jaddref = jaddref;
8561 		jaddref->ja_mkdir = mkdir1;
8562 		/*
8563 		 * It is important that the dotdot journal entry
8564 		 * is added prior to the dot entry since dot writes
8565 		 * both the dot and dotdot links.  These both must
8566 		 * be added after the primary link for the journal
8567 		 * to remain consistent.
8568 		 */
8569 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8570 		add_to_journal(&jaddref->ja_list);
8571 	}
8572 	/*
8573 	 * If we are adding a new directory remember this diradd so that if
8574 	 * we rename it we can keep the dot and dotdot dependencies.  If
8575 	 * we are adding a new name for an inode that has a mkdiradd we
8576 	 * must be in rename and we have to move the dot and dotdot
8577 	 * dependencies to this new name.  The old name is being orphaned
8578 	 * soon.
8579 	 */
8580 	if (mkdir1 != NULL) {
8581 		if (inodedep->id_mkdiradd != NULL)
8582 			panic("softdep_setup_directory_add: Existing mkdir");
8583 		inodedep->id_mkdiradd = dap;
8584 	} else if (inodedep->id_mkdiradd)
8585 		merge_diradd(inodedep, dap);
8586 	if (newdirblk != NULL) {
8587 		/*
8588 		 * There is nothing to do if we are already tracking
8589 		 * this block.
8590 		 */
8591 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8592 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8593 			FREE_LOCK(ump);
8594 			return (0);
8595 		}
8596 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8597 		    == 0)
8598 			panic("softdep_setup_directory_add: lost entry");
8599 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8600 		pagedep->pd_state |= NEWBLOCK;
8601 		pagedep->pd_newdirblk = newdirblk;
8602 		newdirblk->db_pagedep = pagedep;
8603 		FREE_LOCK(ump);
8604 		/*
8605 		 * If we extended into an indirect signal direnter to sync.
8606 		 */
8607 		if (isindir)
8608 			return (1);
8609 		return (0);
8610 	}
8611 	FREE_LOCK(ump);
8612 	return (0);
8613 }
8614 
8615 /*
8616  * This procedure is called to change the offset of a directory
8617  * entry when compacting a directory block which must be owned
8618  * exclusively by the caller. Note that the actual entry movement
8619  * must be done in this procedure to ensure that no I/O completions
8620  * occur while the move is in progress.
8621  */
8622 void
8623 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8624 	struct buf *bp;		/* Buffer holding directory block. */
8625 	struct inode *dp;	/* inode for directory */
8626 	caddr_t base;		/* address of dp->i_offset */
8627 	caddr_t oldloc;		/* address of old directory location */
8628 	caddr_t newloc;		/* address of new directory location */
8629 	int entrysize;		/* size of directory entry */
8630 {
8631 	int offset, oldoffset, newoffset;
8632 	struct pagedep *pagedep;
8633 	struct jmvref *jmvref;
8634 	struct diradd *dap;
8635 	struct direct *de;
8636 	struct mount *mp;
8637 	struct ufsmount *ump;
8638 	ufs_lbn_t lbn;
8639 	int flags;
8640 
8641 	mp = ITOVFS(dp);
8642 	ump = VFSTOUFS(mp);
8643 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8644 	    ("softdep_change_directoryentry_offset called on "
8645 	     "non-softdep filesystem"));
8646 	de = (struct direct *)oldloc;
8647 	jmvref = NULL;
8648 	flags = 0;
8649 	/*
8650 	 * Moves are always journaled as it would be too complex to
8651 	 * determine if any affected adds or removes are present in the
8652 	 * journal.
8653 	 */
8654 	if (MOUNTEDSUJ(mp)) {
8655 		flags = DEPALLOC;
8656 		jmvref = newjmvref(dp, de->d_ino,
8657 		    dp->i_offset + (oldloc - base),
8658 		    dp->i_offset + (newloc - base));
8659 	}
8660 	lbn = lblkno(ump->um_fs, dp->i_offset);
8661 	offset = blkoff(ump->um_fs, dp->i_offset);
8662 	oldoffset = offset + (oldloc - base);
8663 	newoffset = offset + (newloc - base);
8664 	ACQUIRE_LOCK(ump);
8665 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8666 		goto done;
8667 	dap = diradd_lookup(pagedep, oldoffset);
8668 	if (dap) {
8669 		dap->da_offset = newoffset;
8670 		newoffset = DIRADDHASH(newoffset);
8671 		oldoffset = DIRADDHASH(oldoffset);
8672 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8673 		    newoffset != oldoffset) {
8674 			LIST_REMOVE(dap, da_pdlist);
8675 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8676 			    dap, da_pdlist);
8677 		}
8678 	}
8679 done:
8680 	if (jmvref) {
8681 		jmvref->jm_pagedep = pagedep;
8682 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8683 		add_to_journal(&jmvref->jm_list);
8684 	}
8685 	bcopy(oldloc, newloc, entrysize);
8686 	FREE_LOCK(ump);
8687 }
8688 
8689 /*
8690  * Move the mkdir dependencies and journal work from one diradd to another
8691  * when renaming a directory.  The new name must depend on the mkdir deps
8692  * completing as the old name did.  Directories can only have one valid link
8693  * at a time so one must be canonical.
8694  */
8695 static void
8696 merge_diradd(inodedep, newdap)
8697 	struct inodedep *inodedep;
8698 	struct diradd *newdap;
8699 {
8700 	struct diradd *olddap;
8701 	struct mkdir *mkdir, *nextmd;
8702 	struct ufsmount *ump;
8703 	short state;
8704 
8705 	olddap = inodedep->id_mkdiradd;
8706 	inodedep->id_mkdiradd = newdap;
8707 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8708 		newdap->da_state &= ~DEPCOMPLETE;
8709 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8710 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8711 		     mkdir = nextmd) {
8712 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8713 			if (mkdir->md_diradd != olddap)
8714 				continue;
8715 			mkdir->md_diradd = newdap;
8716 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8717 			newdap->da_state |= state;
8718 			olddap->da_state &= ~state;
8719 			if ((olddap->da_state &
8720 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8721 				break;
8722 		}
8723 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8724 			panic("merge_diradd: unfound ref");
8725 	}
8726 	/*
8727 	 * Any mkdir related journal items are not safe to be freed until
8728 	 * the new name is stable.
8729 	 */
8730 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8731 	olddap->da_state |= DEPCOMPLETE;
8732 	complete_diradd(olddap);
8733 }
8734 
8735 /*
8736  * Move the diradd to the pending list when all diradd dependencies are
8737  * complete.
8738  */
8739 static void
8740 complete_diradd(dap)
8741 	struct diradd *dap;
8742 {
8743 	struct pagedep *pagedep;
8744 
8745 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8746 		if (dap->da_state & DIRCHG)
8747 			pagedep = dap->da_previous->dm_pagedep;
8748 		else
8749 			pagedep = dap->da_pagedep;
8750 		LIST_REMOVE(dap, da_pdlist);
8751 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8752 	}
8753 }
8754 
8755 /*
8756  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8757  * add entries and conditonally journal the remove.
8758  */
8759 static void
8760 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8761 	struct diradd *dap;
8762 	struct dirrem *dirrem;
8763 	struct jremref *jremref;
8764 	struct jremref *dotremref;
8765 	struct jremref *dotdotremref;
8766 {
8767 	struct inodedep *inodedep;
8768 	struct jaddref *jaddref;
8769 	struct inoref *inoref;
8770 	struct ufsmount *ump;
8771 	struct mkdir *mkdir;
8772 
8773 	/*
8774 	 * If no remove references were allocated we're on a non-journaled
8775 	 * filesystem and can skip the cancel step.
8776 	 */
8777 	if (jremref == NULL) {
8778 		free_diradd(dap, NULL);
8779 		return;
8780 	}
8781 	/*
8782 	 * Cancel the primary name an free it if it does not require
8783 	 * journaling.
8784 	 */
8785 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8786 	    0, &inodedep) != 0) {
8787 		/* Abort the addref that reference this diradd.  */
8788 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8789 			if (inoref->if_list.wk_type != D_JADDREF)
8790 				continue;
8791 			jaddref = (struct jaddref *)inoref;
8792 			if (jaddref->ja_diradd != dap)
8793 				continue;
8794 			if (cancel_jaddref(jaddref, inodedep,
8795 			    &dirrem->dm_jwork) == 0) {
8796 				free_jremref(jremref);
8797 				jremref = NULL;
8798 			}
8799 			break;
8800 		}
8801 	}
8802 	/*
8803 	 * Cancel subordinate names and free them if they do not require
8804 	 * journaling.
8805 	 */
8806 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8807 		ump = VFSTOUFS(dap->da_list.wk_mp);
8808 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8809 			if (mkdir->md_diradd != dap)
8810 				continue;
8811 			if ((jaddref = mkdir->md_jaddref) == NULL)
8812 				continue;
8813 			mkdir->md_jaddref = NULL;
8814 			if (mkdir->md_state & MKDIR_PARENT) {
8815 				if (cancel_jaddref(jaddref, NULL,
8816 				    &dirrem->dm_jwork) == 0) {
8817 					free_jremref(dotdotremref);
8818 					dotdotremref = NULL;
8819 				}
8820 			} else {
8821 				if (cancel_jaddref(jaddref, inodedep,
8822 				    &dirrem->dm_jwork) == 0) {
8823 					free_jremref(dotremref);
8824 					dotremref = NULL;
8825 				}
8826 			}
8827 		}
8828 	}
8829 
8830 	if (jremref)
8831 		journal_jremref(dirrem, jremref, inodedep);
8832 	if (dotremref)
8833 		journal_jremref(dirrem, dotremref, inodedep);
8834 	if (dotdotremref)
8835 		journal_jremref(dirrem, dotdotremref, NULL);
8836 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8837 	free_diradd(dap, &dirrem->dm_jwork);
8838 }
8839 
8840 /*
8841  * Free a diradd dependency structure. This routine must be called
8842  * with splbio interrupts blocked.
8843  */
8844 static void
8845 free_diradd(dap, wkhd)
8846 	struct diradd *dap;
8847 	struct workhead *wkhd;
8848 {
8849 	struct dirrem *dirrem;
8850 	struct pagedep *pagedep;
8851 	struct inodedep *inodedep;
8852 	struct mkdir *mkdir, *nextmd;
8853 	struct ufsmount *ump;
8854 
8855 	ump = VFSTOUFS(dap->da_list.wk_mp);
8856 	LOCK_OWNED(ump);
8857 	LIST_REMOVE(dap, da_pdlist);
8858 	if (dap->da_state & ONWORKLIST)
8859 		WORKLIST_REMOVE(&dap->da_list);
8860 	if ((dap->da_state & DIRCHG) == 0) {
8861 		pagedep = dap->da_pagedep;
8862 	} else {
8863 		dirrem = dap->da_previous;
8864 		pagedep = dirrem->dm_pagedep;
8865 		dirrem->dm_dirinum = pagedep->pd_ino;
8866 		dirrem->dm_state |= COMPLETE;
8867 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8868 			add_to_worklist(&dirrem->dm_list, 0);
8869 	}
8870 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8871 	    0, &inodedep) != 0)
8872 		if (inodedep->id_mkdiradd == dap)
8873 			inodedep->id_mkdiradd = NULL;
8874 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8875 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8876 		     mkdir = nextmd) {
8877 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8878 			if (mkdir->md_diradd != dap)
8879 				continue;
8880 			dap->da_state &=
8881 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8882 			LIST_REMOVE(mkdir, md_mkdirs);
8883 			if (mkdir->md_state & ONWORKLIST)
8884 				WORKLIST_REMOVE(&mkdir->md_list);
8885 			if (mkdir->md_jaddref != NULL)
8886 				panic("free_diradd: Unexpected jaddref");
8887 			WORKITEM_FREE(mkdir, D_MKDIR);
8888 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8889 				break;
8890 		}
8891 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8892 			panic("free_diradd: unfound ref");
8893 	}
8894 	if (inodedep)
8895 		free_inodedep(inodedep);
8896 	/*
8897 	 * Free any journal segments waiting for the directory write.
8898 	 */
8899 	handle_jwork(&dap->da_jwork);
8900 	WORKITEM_FREE(dap, D_DIRADD);
8901 }
8902 
8903 /*
8904  * Directory entry removal dependencies.
8905  *
8906  * When removing a directory entry, the entry's inode pointer must be
8907  * zero'ed on disk before the corresponding inode's link count is decremented
8908  * (possibly freeing the inode for re-use). This dependency is handled by
8909  * updating the directory entry but delaying the inode count reduction until
8910  * after the directory block has been written to disk. After this point, the
8911  * inode count can be decremented whenever it is convenient.
8912  */
8913 
8914 /*
8915  * This routine should be called immediately after removing
8916  * a directory entry.  The inode's link count should not be
8917  * decremented by the calling procedure -- the soft updates
8918  * code will do this task when it is safe.
8919  */
8920 void
8921 softdep_setup_remove(bp, dp, ip, isrmdir)
8922 	struct buf *bp;		/* buffer containing directory block */
8923 	struct inode *dp;	/* inode for the directory being modified */
8924 	struct inode *ip;	/* inode for directory entry being removed */
8925 	int isrmdir;		/* indicates if doing RMDIR */
8926 {
8927 	struct dirrem *dirrem, *prevdirrem;
8928 	struct inodedep *inodedep;
8929 	struct ufsmount *ump;
8930 	int direct;
8931 
8932 	ump = ITOUMP(ip);
8933 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8934 	    ("softdep_setup_remove called on non-softdep filesystem"));
8935 	/*
8936 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8937 	 * newdirrem() to setup the full directory remove which requires
8938 	 * isrmdir > 1.
8939 	 */
8940 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8941 	/*
8942 	 * Add the dirrem to the inodedep's pending remove list for quick
8943 	 * discovery later.
8944 	 */
8945 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
8946 		panic("softdep_setup_remove: Lost inodedep.");
8947 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8948 	dirrem->dm_state |= ONDEPLIST;
8949 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8950 
8951 	/*
8952 	 * If the COMPLETE flag is clear, then there were no active
8953 	 * entries and we want to roll back to a zeroed entry until
8954 	 * the new inode is committed to disk. If the COMPLETE flag is
8955 	 * set then we have deleted an entry that never made it to
8956 	 * disk. If the entry we deleted resulted from a name change,
8957 	 * then the old name still resides on disk. We cannot delete
8958 	 * its inode (returned to us in prevdirrem) until the zeroed
8959 	 * directory entry gets to disk. The new inode has never been
8960 	 * referenced on the disk, so can be deleted immediately.
8961 	 */
8962 	if ((dirrem->dm_state & COMPLETE) == 0) {
8963 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8964 		    dm_next);
8965 		FREE_LOCK(ump);
8966 	} else {
8967 		if (prevdirrem != NULL)
8968 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8969 			    prevdirrem, dm_next);
8970 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8971 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8972 		FREE_LOCK(ump);
8973 		if (direct)
8974 			handle_workitem_remove(dirrem, 0);
8975 	}
8976 }
8977 
8978 /*
8979  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8980  * pd_pendinghd list of a pagedep.
8981  */
8982 static struct diradd *
8983 diradd_lookup(pagedep, offset)
8984 	struct pagedep *pagedep;
8985 	int offset;
8986 {
8987 	struct diradd *dap;
8988 
8989 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8990 		if (dap->da_offset == offset)
8991 			return (dap);
8992 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8993 		if (dap->da_offset == offset)
8994 			return (dap);
8995 	return (NULL);
8996 }
8997 
8998 /*
8999  * Search for a .. diradd dependency in a directory that is being removed.
9000  * If the directory was renamed to a new parent we have a diradd rather
9001  * than a mkdir for the .. entry.  We need to cancel it now before
9002  * it is found in truncate().
9003  */
9004 static struct jremref *
9005 cancel_diradd_dotdot(ip, dirrem, jremref)
9006 	struct inode *ip;
9007 	struct dirrem *dirrem;
9008 	struct jremref *jremref;
9009 {
9010 	struct pagedep *pagedep;
9011 	struct diradd *dap;
9012 	struct worklist *wk;
9013 
9014 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9015 		return (jremref);
9016 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9017 	if (dap == NULL)
9018 		return (jremref);
9019 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9020 	/*
9021 	 * Mark any journal work as belonging to the parent so it is freed
9022 	 * with the .. reference.
9023 	 */
9024 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9025 		wk->wk_state |= MKDIR_PARENT;
9026 	return (NULL);
9027 }
9028 
9029 /*
9030  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9031  * replace it with a dirrem/diradd pair as a result of re-parenting a
9032  * directory.  This ensures that we don't simultaneously have a mkdir and
9033  * a diradd for the same .. entry.
9034  */
9035 static struct jremref *
9036 cancel_mkdir_dotdot(ip, dirrem, jremref)
9037 	struct inode *ip;
9038 	struct dirrem *dirrem;
9039 	struct jremref *jremref;
9040 {
9041 	struct inodedep *inodedep;
9042 	struct jaddref *jaddref;
9043 	struct ufsmount *ump;
9044 	struct mkdir *mkdir;
9045 	struct diradd *dap;
9046 	struct mount *mp;
9047 
9048 	mp = ITOVFS(ip);
9049 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9050 		return (jremref);
9051 	dap = inodedep->id_mkdiradd;
9052 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9053 		return (jremref);
9054 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9055 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9056 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9057 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9058 			break;
9059 	if (mkdir == NULL)
9060 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9061 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9062 		mkdir->md_jaddref = NULL;
9063 		jaddref->ja_state &= ~MKDIR_PARENT;
9064 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9065 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9066 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9067 			journal_jremref(dirrem, jremref, inodedep);
9068 			jremref = NULL;
9069 		}
9070 	}
9071 	if (mkdir->md_state & ONWORKLIST)
9072 		WORKLIST_REMOVE(&mkdir->md_list);
9073 	mkdir->md_state |= ALLCOMPLETE;
9074 	complete_mkdir(mkdir);
9075 	return (jremref);
9076 }
9077 
9078 static void
9079 journal_jremref(dirrem, jremref, inodedep)
9080 	struct dirrem *dirrem;
9081 	struct jremref *jremref;
9082 	struct inodedep *inodedep;
9083 {
9084 
9085 	if (inodedep == NULL)
9086 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9087 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9088 			panic("journal_jremref: Lost inodedep");
9089 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9090 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9091 	add_to_journal(&jremref->jr_list);
9092 }
9093 
9094 static void
9095 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9096 	struct dirrem *dirrem;
9097 	struct jremref *jremref;
9098 	struct jremref *dotremref;
9099 	struct jremref *dotdotremref;
9100 {
9101 	struct inodedep *inodedep;
9102 
9103 
9104 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9105 	    &inodedep) == 0)
9106 		panic("dirrem_journal: Lost inodedep");
9107 	journal_jremref(dirrem, jremref, inodedep);
9108 	if (dotremref)
9109 		journal_jremref(dirrem, dotremref, inodedep);
9110 	if (dotdotremref)
9111 		journal_jremref(dirrem, dotdotremref, NULL);
9112 }
9113 
9114 /*
9115  * Allocate a new dirrem if appropriate and return it along with
9116  * its associated pagedep. Called without a lock, returns with lock.
9117  */
9118 static struct dirrem *
9119 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9120 	struct buf *bp;		/* buffer containing directory block */
9121 	struct inode *dp;	/* inode for the directory being modified */
9122 	struct inode *ip;	/* inode for directory entry being removed */
9123 	int isrmdir;		/* indicates if doing RMDIR */
9124 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9125 {
9126 	int offset;
9127 	ufs_lbn_t lbn;
9128 	struct diradd *dap;
9129 	struct dirrem *dirrem;
9130 	struct pagedep *pagedep;
9131 	struct jremref *jremref;
9132 	struct jremref *dotremref;
9133 	struct jremref *dotdotremref;
9134 	struct vnode *dvp;
9135 	struct ufsmount *ump;
9136 
9137 	/*
9138 	 * Whiteouts have no deletion dependencies.
9139 	 */
9140 	if (ip == NULL)
9141 		panic("newdirrem: whiteout");
9142 	dvp = ITOV(dp);
9143 	ump = ITOUMP(dp);
9144 
9145 	/*
9146 	 * If the system is over its limit and our filesystem is
9147 	 * responsible for more than our share of that usage and
9148 	 * we are not a snapshot, request some inodedep cleanup.
9149 	 * Limiting the number of dirrem structures will also limit
9150 	 * the number of freefile and freeblks structures.
9151 	 */
9152 	ACQUIRE_LOCK(ump);
9153 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9154 		schedule_cleanup(UFSTOVFS(ump));
9155 	else
9156 		FREE_LOCK(ump);
9157 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9158 	    M_ZERO);
9159 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9160 	LIST_INIT(&dirrem->dm_jremrefhd);
9161 	LIST_INIT(&dirrem->dm_jwork);
9162 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9163 	dirrem->dm_oldinum = ip->i_number;
9164 	*prevdirremp = NULL;
9165 	/*
9166 	 * Allocate remove reference structures to track journal write
9167 	 * dependencies.  We will always have one for the link and
9168 	 * when doing directories we will always have one more for dot.
9169 	 * When renaming a directory we skip the dotdot link change so
9170 	 * this is not needed.
9171 	 */
9172 	jremref = dotremref = dotdotremref = NULL;
9173 	if (DOINGSUJ(dvp)) {
9174 		if (isrmdir) {
9175 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9176 			    ip->i_effnlink + 2);
9177 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9178 			    ip->i_effnlink + 1);
9179 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9180 			    dp->i_effnlink + 1);
9181 			dotdotremref->jr_state |= MKDIR_PARENT;
9182 		} else
9183 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9184 			    ip->i_effnlink + 1);
9185 	}
9186 	ACQUIRE_LOCK(ump);
9187 	lbn = lblkno(ump->um_fs, dp->i_offset);
9188 	offset = blkoff(ump->um_fs, dp->i_offset);
9189 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9190 	    &pagedep);
9191 	dirrem->dm_pagedep = pagedep;
9192 	dirrem->dm_offset = offset;
9193 	/*
9194 	 * If we're renaming a .. link to a new directory, cancel any
9195 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9196 	 * the jremref is preserved for any potential diradd in this
9197 	 * location.  This can not coincide with a rmdir.
9198 	 */
9199 	if (dp->i_offset == DOTDOT_OFFSET) {
9200 		if (isrmdir)
9201 			panic("newdirrem: .. directory change during remove?");
9202 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9203 	}
9204 	/*
9205 	 * If we're removing a directory search for the .. dependency now and
9206 	 * cancel it.  Any pending journal work will be added to the dirrem
9207 	 * to be completed when the workitem remove completes.
9208 	 */
9209 	if (isrmdir)
9210 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9211 	/*
9212 	 * Check for a diradd dependency for the same directory entry.
9213 	 * If present, then both dependencies become obsolete and can
9214 	 * be de-allocated.
9215 	 */
9216 	dap = diradd_lookup(pagedep, offset);
9217 	if (dap == NULL) {
9218 		/*
9219 		 * Link the jremref structures into the dirrem so they are
9220 		 * written prior to the pagedep.
9221 		 */
9222 		if (jremref)
9223 			dirrem_journal(dirrem, jremref, dotremref,
9224 			    dotdotremref);
9225 		return (dirrem);
9226 	}
9227 	/*
9228 	 * Must be ATTACHED at this point.
9229 	 */
9230 	if ((dap->da_state & ATTACHED) == 0)
9231 		panic("newdirrem: not ATTACHED");
9232 	if (dap->da_newinum != ip->i_number)
9233 		panic("newdirrem: inum %ju should be %ju",
9234 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9235 	/*
9236 	 * If we are deleting a changed name that never made it to disk,
9237 	 * then return the dirrem describing the previous inode (which
9238 	 * represents the inode currently referenced from this entry on disk).
9239 	 */
9240 	if ((dap->da_state & DIRCHG) != 0) {
9241 		*prevdirremp = dap->da_previous;
9242 		dap->da_state &= ~DIRCHG;
9243 		dap->da_pagedep = pagedep;
9244 	}
9245 	/*
9246 	 * We are deleting an entry that never made it to disk.
9247 	 * Mark it COMPLETE so we can delete its inode immediately.
9248 	 */
9249 	dirrem->dm_state |= COMPLETE;
9250 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9251 #ifdef SUJ_DEBUG
9252 	if (isrmdir == 0) {
9253 		struct worklist *wk;
9254 
9255 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9256 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9257 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9258 	}
9259 #endif
9260 
9261 	return (dirrem);
9262 }
9263 
9264 /*
9265  * Directory entry change dependencies.
9266  *
9267  * Changing an existing directory entry requires that an add operation
9268  * be completed first followed by a deletion. The semantics for the addition
9269  * are identical to the description of adding a new entry above except
9270  * that the rollback is to the old inode number rather than zero. Once
9271  * the addition dependency is completed, the removal is done as described
9272  * in the removal routine above.
9273  */
9274 
9275 /*
9276  * This routine should be called immediately after changing
9277  * a directory entry.  The inode's link count should not be
9278  * decremented by the calling procedure -- the soft updates
9279  * code will perform this task when it is safe.
9280  */
9281 void
9282 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9283 	struct buf *bp;		/* buffer containing directory block */
9284 	struct inode *dp;	/* inode for the directory being modified */
9285 	struct inode *ip;	/* inode for directory entry being removed */
9286 	ino_t newinum;		/* new inode number for changed entry */
9287 	int isrmdir;		/* indicates if doing RMDIR */
9288 {
9289 	int offset;
9290 	struct diradd *dap = NULL;
9291 	struct dirrem *dirrem, *prevdirrem;
9292 	struct pagedep *pagedep;
9293 	struct inodedep *inodedep;
9294 	struct jaddref *jaddref;
9295 	struct mount *mp;
9296 	struct ufsmount *ump;
9297 
9298 	mp = ITOVFS(dp);
9299 	ump = VFSTOUFS(mp);
9300 	offset = blkoff(ump->um_fs, dp->i_offset);
9301 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9302 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9303 
9304 	/*
9305 	 * Whiteouts do not need diradd dependencies.
9306 	 */
9307 	if (newinum != UFS_WINO) {
9308 		dap = malloc(sizeof(struct diradd),
9309 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9310 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9311 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9312 		dap->da_offset = offset;
9313 		dap->da_newinum = newinum;
9314 		LIST_INIT(&dap->da_jwork);
9315 	}
9316 
9317 	/*
9318 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9319 	 */
9320 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9321 	pagedep = dirrem->dm_pagedep;
9322 	/*
9323 	 * The possible values for isrmdir:
9324 	 *	0 - non-directory file rename
9325 	 *	1 - directory rename within same directory
9326 	 *   inum - directory rename to new directory of given inode number
9327 	 * When renaming to a new directory, we are both deleting and
9328 	 * creating a new directory entry, so the link count on the new
9329 	 * directory should not change. Thus we do not need the followup
9330 	 * dirrem which is usually done in handle_workitem_remove. We set
9331 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9332 	 * followup dirrem.
9333 	 */
9334 	if (isrmdir > 1)
9335 		dirrem->dm_state |= DIRCHG;
9336 
9337 	/*
9338 	 * Whiteouts have no additional dependencies,
9339 	 * so just put the dirrem on the correct list.
9340 	 */
9341 	if (newinum == UFS_WINO) {
9342 		if ((dirrem->dm_state & COMPLETE) == 0) {
9343 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9344 			    dm_next);
9345 		} else {
9346 			dirrem->dm_dirinum = pagedep->pd_ino;
9347 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9348 				add_to_worklist(&dirrem->dm_list, 0);
9349 		}
9350 		FREE_LOCK(ump);
9351 		return;
9352 	}
9353 	/*
9354 	 * Add the dirrem to the inodedep's pending remove list for quick
9355 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9356 	 * will not fail.
9357 	 */
9358 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9359 		panic("softdep_setup_directory_change: Lost inodedep.");
9360 	dirrem->dm_state |= ONDEPLIST;
9361 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9362 
9363 	/*
9364 	 * If the COMPLETE flag is clear, then there were no active
9365 	 * entries and we want to roll back to the previous inode until
9366 	 * the new inode is committed to disk. If the COMPLETE flag is
9367 	 * set, then we have deleted an entry that never made it to disk.
9368 	 * If the entry we deleted resulted from a name change, then the old
9369 	 * inode reference still resides on disk. Any rollback that we do
9370 	 * needs to be to that old inode (returned to us in prevdirrem). If
9371 	 * the entry we deleted resulted from a create, then there is
9372 	 * no entry on the disk, so we want to roll back to zero rather
9373 	 * than the uncommitted inode. In either of the COMPLETE cases we
9374 	 * want to immediately free the unwritten and unreferenced inode.
9375 	 */
9376 	if ((dirrem->dm_state & COMPLETE) == 0) {
9377 		dap->da_previous = dirrem;
9378 	} else {
9379 		if (prevdirrem != NULL) {
9380 			dap->da_previous = prevdirrem;
9381 		} else {
9382 			dap->da_state &= ~DIRCHG;
9383 			dap->da_pagedep = pagedep;
9384 		}
9385 		dirrem->dm_dirinum = pagedep->pd_ino;
9386 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9387 			add_to_worklist(&dirrem->dm_list, 0);
9388 	}
9389 	/*
9390 	 * Lookup the jaddref for this journal entry.  We must finish
9391 	 * initializing it and make the diradd write dependent on it.
9392 	 * If we're not journaling, put it on the id_bufwait list if the
9393 	 * inode is not yet written. If it is written, do the post-inode
9394 	 * write processing to put it on the id_pendinghd list.
9395 	 */
9396 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9397 	if (MOUNTEDSUJ(mp)) {
9398 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9399 		    inoreflst);
9400 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9401 		    ("softdep_setup_directory_change: bad jaddref %p",
9402 		    jaddref));
9403 		jaddref->ja_diroff = dp->i_offset;
9404 		jaddref->ja_diradd = dap;
9405 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9406 		    dap, da_pdlist);
9407 		add_to_journal(&jaddref->ja_list);
9408 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9409 		dap->da_state |= COMPLETE;
9410 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9411 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9412 	} else {
9413 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9414 		    dap, da_pdlist);
9415 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9416 	}
9417 	/*
9418 	 * If we're making a new name for a directory that has not been
9419 	 * committed when need to move the dot and dotdot references to
9420 	 * this new name.
9421 	 */
9422 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9423 		merge_diradd(inodedep, dap);
9424 	FREE_LOCK(ump);
9425 }
9426 
9427 /*
9428  * Called whenever the link count on an inode is changed.
9429  * It creates an inode dependency so that the new reference(s)
9430  * to the inode cannot be committed to disk until the updated
9431  * inode has been written.
9432  */
9433 void
9434 softdep_change_linkcnt(ip)
9435 	struct inode *ip;	/* the inode with the increased link count */
9436 {
9437 	struct inodedep *inodedep;
9438 	struct ufsmount *ump;
9439 
9440 	ump = ITOUMP(ip);
9441 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9442 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9443 	ACQUIRE_LOCK(ump);
9444 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9445 	if (ip->i_nlink < ip->i_effnlink)
9446 		panic("softdep_change_linkcnt: bad delta");
9447 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9448 	FREE_LOCK(ump);
9449 }
9450 
9451 /*
9452  * Attach a sbdep dependency to the superblock buf so that we can keep
9453  * track of the head of the linked list of referenced but unlinked inodes.
9454  */
9455 void
9456 softdep_setup_sbupdate(ump, fs, bp)
9457 	struct ufsmount *ump;
9458 	struct fs *fs;
9459 	struct buf *bp;
9460 {
9461 	struct sbdep *sbdep;
9462 	struct worklist *wk;
9463 
9464 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9465 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9466 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9467 		if (wk->wk_type == D_SBDEP)
9468 			break;
9469 	if (wk != NULL)
9470 		return;
9471 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9472 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9473 	sbdep->sb_fs = fs;
9474 	sbdep->sb_ump = ump;
9475 	ACQUIRE_LOCK(ump);
9476 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9477 	FREE_LOCK(ump);
9478 }
9479 
9480 /*
9481  * Return the first unlinked inodedep which is ready to be the head of the
9482  * list.  The inodedep and all those after it must have valid next pointers.
9483  */
9484 static struct inodedep *
9485 first_unlinked_inodedep(ump)
9486 	struct ufsmount *ump;
9487 {
9488 	struct inodedep *inodedep;
9489 	struct inodedep *idp;
9490 
9491 	LOCK_OWNED(ump);
9492 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9493 	    inodedep; inodedep = idp) {
9494 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9495 			return (NULL);
9496 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9497 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9498 			break;
9499 		if ((inodedep->id_state & UNLINKPREV) == 0)
9500 			break;
9501 	}
9502 	return (inodedep);
9503 }
9504 
9505 /*
9506  * Set the sujfree unlinked head pointer prior to writing a superblock.
9507  */
9508 static void
9509 initiate_write_sbdep(sbdep)
9510 	struct sbdep *sbdep;
9511 {
9512 	struct inodedep *inodedep;
9513 	struct fs *bpfs;
9514 	struct fs *fs;
9515 
9516 	bpfs = sbdep->sb_fs;
9517 	fs = sbdep->sb_ump->um_fs;
9518 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9519 	if (inodedep) {
9520 		fs->fs_sujfree = inodedep->id_ino;
9521 		inodedep->id_state |= UNLINKPREV;
9522 	} else
9523 		fs->fs_sujfree = 0;
9524 	bpfs->fs_sujfree = fs->fs_sujfree;
9525 }
9526 
9527 /*
9528  * After a superblock is written determine whether it must be written again
9529  * due to a changing unlinked list head.
9530  */
9531 static int
9532 handle_written_sbdep(sbdep, bp)
9533 	struct sbdep *sbdep;
9534 	struct buf *bp;
9535 {
9536 	struct inodedep *inodedep;
9537 	struct fs *fs;
9538 
9539 	LOCK_OWNED(sbdep->sb_ump);
9540 	fs = sbdep->sb_fs;
9541 	/*
9542 	 * If the superblock doesn't match the in-memory list start over.
9543 	 */
9544 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9545 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9546 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9547 		bdirty(bp);
9548 		return (1);
9549 	}
9550 	WORKITEM_FREE(sbdep, D_SBDEP);
9551 	if (fs->fs_sujfree == 0)
9552 		return (0);
9553 	/*
9554 	 * Now that we have a record of this inode in stable store allow it
9555 	 * to be written to free up pending work.  Inodes may see a lot of
9556 	 * write activity after they are unlinked which we must not hold up.
9557 	 */
9558 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9559 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9560 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9561 			    inodedep, inodedep->id_state);
9562 		if (inodedep->id_state & UNLINKONLIST)
9563 			break;
9564 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9565 	}
9566 
9567 	return (0);
9568 }
9569 
9570 /*
9571  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9572  */
9573 static void
9574 unlinked_inodedep(mp, inodedep)
9575 	struct mount *mp;
9576 	struct inodedep *inodedep;
9577 {
9578 	struct ufsmount *ump;
9579 
9580 	ump = VFSTOUFS(mp);
9581 	LOCK_OWNED(ump);
9582 	if (MOUNTEDSUJ(mp) == 0)
9583 		return;
9584 	ump->um_fs->fs_fmod = 1;
9585 	if (inodedep->id_state & UNLINKED)
9586 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9587 	inodedep->id_state |= UNLINKED;
9588 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9589 }
9590 
9591 /*
9592  * Remove an inodedep from the unlinked inodedep list.  This may require
9593  * disk writes if the inode has made it that far.
9594  */
9595 static void
9596 clear_unlinked_inodedep(inodedep)
9597 	struct inodedep *inodedep;
9598 {
9599 	struct ufsmount *ump;
9600 	struct inodedep *idp;
9601 	struct inodedep *idn;
9602 	struct fs *fs;
9603 	struct buf *bp;
9604 	ino_t ino;
9605 	ino_t nino;
9606 	ino_t pino;
9607 	int error;
9608 
9609 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9610 	fs = ump->um_fs;
9611 	ino = inodedep->id_ino;
9612 	error = 0;
9613 	for (;;) {
9614 		LOCK_OWNED(ump);
9615 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9616 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9617 		    inodedep));
9618 		/*
9619 		 * If nothing has yet been written simply remove us from
9620 		 * the in memory list and return.  This is the most common
9621 		 * case where handle_workitem_remove() loses the final
9622 		 * reference.
9623 		 */
9624 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9625 			break;
9626 		/*
9627 		 * If we have a NEXT pointer and no PREV pointer we can simply
9628 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9629 		 * careful not to clear PREV if the superblock points at
9630 		 * next as well.
9631 		 */
9632 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9633 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9634 			if (idn && fs->fs_sujfree != idn->id_ino)
9635 				idn->id_state &= ~UNLINKPREV;
9636 			break;
9637 		}
9638 		/*
9639 		 * Here we have an inodedep which is actually linked into
9640 		 * the list.  We must remove it by forcing a write to the
9641 		 * link before us, whether it be the superblock or an inode.
9642 		 * Unfortunately the list may change while we're waiting
9643 		 * on the buf lock for either resource so we must loop until
9644 		 * we lock the right one.  If both the superblock and an
9645 		 * inode point to this inode we must clear the inode first
9646 		 * followed by the superblock.
9647 		 */
9648 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9649 		pino = 0;
9650 		if (idp && (idp->id_state & UNLINKNEXT))
9651 			pino = idp->id_ino;
9652 		FREE_LOCK(ump);
9653 		if (pino == 0) {
9654 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9655 			    (int)fs->fs_sbsize, 0, 0, 0);
9656 		} else {
9657 			error = bread(ump->um_devvp,
9658 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9659 			    (int)fs->fs_bsize, NOCRED, &bp);
9660 			if (error)
9661 				brelse(bp);
9662 		}
9663 		ACQUIRE_LOCK(ump);
9664 		if (error)
9665 			break;
9666 		/* If the list has changed restart the loop. */
9667 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9668 		nino = 0;
9669 		if (idp && (idp->id_state & UNLINKNEXT))
9670 			nino = idp->id_ino;
9671 		if (nino != pino ||
9672 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9673 			FREE_LOCK(ump);
9674 			brelse(bp);
9675 			ACQUIRE_LOCK(ump);
9676 			continue;
9677 		}
9678 		nino = 0;
9679 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9680 		if (idn)
9681 			nino = idn->id_ino;
9682 		/*
9683 		 * Remove us from the in memory list.  After this we cannot
9684 		 * access the inodedep.
9685 		 */
9686 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9687 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9688 		    inodedep));
9689 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9690 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9691 		FREE_LOCK(ump);
9692 		/*
9693 		 * The predecessor's next pointer is manually updated here
9694 		 * so that the NEXT flag is never cleared for an element
9695 		 * that is in the list.
9696 		 */
9697 		if (pino == 0) {
9698 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9699 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9700 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9701 			    bp);
9702 		} else if (fs->fs_magic == FS_UFS1_MAGIC)
9703 			((struct ufs1_dinode *)bp->b_data +
9704 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9705 		else
9706 			((struct ufs2_dinode *)bp->b_data +
9707 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9708 		/*
9709 		 * If the bwrite fails we have no recourse to recover.  The
9710 		 * filesystem is corrupted already.
9711 		 */
9712 		bwrite(bp);
9713 		ACQUIRE_LOCK(ump);
9714 		/*
9715 		 * If the superblock pointer still needs to be cleared force
9716 		 * a write here.
9717 		 */
9718 		if (fs->fs_sujfree == ino) {
9719 			FREE_LOCK(ump);
9720 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9721 			    (int)fs->fs_sbsize, 0, 0, 0);
9722 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9723 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9724 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9725 			    bp);
9726 			bwrite(bp);
9727 			ACQUIRE_LOCK(ump);
9728 		}
9729 
9730 		if (fs->fs_sujfree != ino)
9731 			return;
9732 		panic("clear_unlinked_inodedep: Failed to clear free head");
9733 	}
9734 	if (inodedep->id_ino == fs->fs_sujfree)
9735 		panic("clear_unlinked_inodedep: Freeing head of free list");
9736 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9737 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9738 	return;
9739 }
9740 
9741 /*
9742  * This workitem decrements the inode's link count.
9743  * If the link count reaches zero, the file is removed.
9744  */
9745 static int
9746 handle_workitem_remove(dirrem, flags)
9747 	struct dirrem *dirrem;
9748 	int flags;
9749 {
9750 	struct inodedep *inodedep;
9751 	struct workhead dotdotwk;
9752 	struct worklist *wk;
9753 	struct ufsmount *ump;
9754 	struct mount *mp;
9755 	struct vnode *vp;
9756 	struct inode *ip;
9757 	ino_t oldinum;
9758 
9759 	if (dirrem->dm_state & ONWORKLIST)
9760 		panic("handle_workitem_remove: dirrem %p still on worklist",
9761 		    dirrem);
9762 	oldinum = dirrem->dm_oldinum;
9763 	mp = dirrem->dm_list.wk_mp;
9764 	ump = VFSTOUFS(mp);
9765 	flags |= LK_EXCLUSIVE;
9766 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9767 		return (EBUSY);
9768 	ip = VTOI(vp);
9769 	ACQUIRE_LOCK(ump);
9770 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9771 		panic("handle_workitem_remove: lost inodedep");
9772 	if (dirrem->dm_state & ONDEPLIST)
9773 		LIST_REMOVE(dirrem, dm_inonext);
9774 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9775 	    ("handle_workitem_remove:  Journal entries not written."));
9776 
9777 	/*
9778 	 * Move all dependencies waiting on the remove to complete
9779 	 * from the dirrem to the inode inowait list to be completed
9780 	 * after the inode has been updated and written to disk.  Any
9781 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9782 	 * is removed.
9783 	 */
9784 	LIST_INIT(&dotdotwk);
9785 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9786 		WORKLIST_REMOVE(wk);
9787 		if (wk->wk_state & MKDIR_PARENT) {
9788 			wk->wk_state &= ~MKDIR_PARENT;
9789 			WORKLIST_INSERT(&dotdotwk, wk);
9790 			continue;
9791 		}
9792 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9793 	}
9794 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9795 	/*
9796 	 * Normal file deletion.
9797 	 */
9798 	if ((dirrem->dm_state & RMDIR) == 0) {
9799 		ip->i_nlink--;
9800 		DIP_SET(ip, i_nlink, ip->i_nlink);
9801 		ip->i_flag |= IN_CHANGE;
9802 		if (ip->i_nlink < ip->i_effnlink)
9803 			panic("handle_workitem_remove: bad file delta");
9804 		if (ip->i_nlink == 0)
9805 			unlinked_inodedep(mp, inodedep);
9806 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9807 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9808 		    ("handle_workitem_remove: worklist not empty. %s",
9809 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9810 		WORKITEM_FREE(dirrem, D_DIRREM);
9811 		FREE_LOCK(ump);
9812 		goto out;
9813 	}
9814 	/*
9815 	 * Directory deletion. Decrement reference count for both the
9816 	 * just deleted parent directory entry and the reference for ".".
9817 	 * Arrange to have the reference count on the parent decremented
9818 	 * to account for the loss of "..".
9819 	 */
9820 	ip->i_nlink -= 2;
9821 	DIP_SET(ip, i_nlink, ip->i_nlink);
9822 	ip->i_flag |= IN_CHANGE;
9823 	if (ip->i_nlink < ip->i_effnlink)
9824 		panic("handle_workitem_remove: bad dir delta");
9825 	if (ip->i_nlink == 0)
9826 		unlinked_inodedep(mp, inodedep);
9827 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9828 	/*
9829 	 * Rename a directory to a new parent. Since, we are both deleting
9830 	 * and creating a new directory entry, the link count on the new
9831 	 * directory should not change. Thus we skip the followup dirrem.
9832 	 */
9833 	if (dirrem->dm_state & DIRCHG) {
9834 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9835 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9836 		WORKITEM_FREE(dirrem, D_DIRREM);
9837 		FREE_LOCK(ump);
9838 		goto out;
9839 	}
9840 	dirrem->dm_state = ONDEPLIST;
9841 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9842 	/*
9843 	 * Place the dirrem on the parent's diremhd list.
9844 	 */
9845 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9846 		panic("handle_workitem_remove: lost dir inodedep");
9847 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9848 	/*
9849 	 * If the allocated inode has never been written to disk, then
9850 	 * the on-disk inode is zero'ed and we can remove the file
9851 	 * immediately.  When journaling if the inode has been marked
9852 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9853 	 */
9854 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9855 	if (inodedep == NULL ||
9856 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9857 	    check_inode_unwritten(inodedep)) {
9858 		FREE_LOCK(ump);
9859 		vput(vp);
9860 		return handle_workitem_remove(dirrem, flags);
9861 	}
9862 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9863 	FREE_LOCK(ump);
9864 	ip->i_flag |= IN_CHANGE;
9865 out:
9866 	ffs_update(vp, 0);
9867 	vput(vp);
9868 	return (0);
9869 }
9870 
9871 /*
9872  * Inode de-allocation dependencies.
9873  *
9874  * When an inode's link count is reduced to zero, it can be de-allocated. We
9875  * found it convenient to postpone de-allocation until after the inode is
9876  * written to disk with its new link count (zero).  At this point, all of the
9877  * on-disk inode's block pointers are nullified and, with careful dependency
9878  * list ordering, all dependencies related to the inode will be satisfied and
9879  * the corresponding dependency structures de-allocated.  So, if/when the
9880  * inode is reused, there will be no mixing of old dependencies with new
9881  * ones.  This artificial dependency is set up by the block de-allocation
9882  * procedure above (softdep_setup_freeblocks) and completed by the
9883  * following procedure.
9884  */
9885 static void
9886 handle_workitem_freefile(freefile)
9887 	struct freefile *freefile;
9888 {
9889 	struct workhead wkhd;
9890 	struct fs *fs;
9891 	struct inodedep *idp;
9892 	struct ufsmount *ump;
9893 	int error;
9894 
9895 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9896 	fs = ump->um_fs;
9897 #ifdef DEBUG
9898 	ACQUIRE_LOCK(ump);
9899 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9900 	FREE_LOCK(ump);
9901 	if (error)
9902 		panic("handle_workitem_freefile: inodedep %p survived", idp);
9903 #endif
9904 	UFS_LOCK(ump);
9905 	fs->fs_pendinginodes -= 1;
9906 	UFS_UNLOCK(ump);
9907 	LIST_INIT(&wkhd);
9908 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9909 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9910 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9911 		softdep_error("handle_workitem_freefile", error);
9912 	ACQUIRE_LOCK(ump);
9913 	WORKITEM_FREE(freefile, D_FREEFILE);
9914 	FREE_LOCK(ump);
9915 }
9916 
9917 
9918 /*
9919  * Helper function which unlinks marker element from work list and returns
9920  * the next element on the list.
9921  */
9922 static __inline struct worklist *
9923 markernext(struct worklist *marker)
9924 {
9925 	struct worklist *next;
9926 
9927 	next = LIST_NEXT(marker, wk_list);
9928 	LIST_REMOVE(marker, wk_list);
9929 	return next;
9930 }
9931 
9932 /*
9933  * Disk writes.
9934  *
9935  * The dependency structures constructed above are most actively used when file
9936  * system blocks are written to disk.  No constraints are placed on when a
9937  * block can be written, but unsatisfied update dependencies are made safe by
9938  * modifying (or replacing) the source memory for the duration of the disk
9939  * write.  When the disk write completes, the memory block is again brought
9940  * up-to-date.
9941  *
9942  * In-core inode structure reclamation.
9943  *
9944  * Because there are a finite number of "in-core" inode structures, they are
9945  * reused regularly.  By transferring all inode-related dependencies to the
9946  * in-memory inode block and indexing them separately (via "inodedep"s), we
9947  * can allow "in-core" inode structures to be reused at any time and avoid
9948  * any increase in contention.
9949  *
9950  * Called just before entering the device driver to initiate a new disk I/O.
9951  * The buffer must be locked, thus, no I/O completion operations can occur
9952  * while we are manipulating its associated dependencies.
9953  */
9954 static void
9955 softdep_disk_io_initiation(bp)
9956 	struct buf *bp;		/* structure describing disk write to occur */
9957 {
9958 	struct worklist *wk;
9959 	struct worklist marker;
9960 	struct inodedep *inodedep;
9961 	struct freeblks *freeblks;
9962 	struct jblkdep *jblkdep;
9963 	struct newblk *newblk;
9964 	struct ufsmount *ump;
9965 
9966 	/*
9967 	 * We only care about write operations. There should never
9968 	 * be dependencies for reads.
9969 	 */
9970 	if (bp->b_iocmd != BIO_WRITE)
9971 		panic("softdep_disk_io_initiation: not write");
9972 
9973 	if (bp->b_vflags & BV_BKGRDINPROG)
9974 		panic("softdep_disk_io_initiation: Writing buffer with "
9975 		    "background write in progress: %p", bp);
9976 
9977 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
9978 		return;
9979 	ump = VFSTOUFS(wk->wk_mp);
9980 
9981 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
9982 	PHOLD(curproc);			/* Don't swap out kernel stack */
9983 	ACQUIRE_LOCK(ump);
9984 	/*
9985 	 * Do any necessary pre-I/O processing.
9986 	 */
9987 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9988 	     wk = markernext(&marker)) {
9989 		LIST_INSERT_AFTER(wk, &marker, wk_list);
9990 		switch (wk->wk_type) {
9991 
9992 		case D_PAGEDEP:
9993 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
9994 			continue;
9995 
9996 		case D_INODEDEP:
9997 			inodedep = WK_INODEDEP(wk);
9998 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
9999 				initiate_write_inodeblock_ufs1(inodedep, bp);
10000 			else
10001 				initiate_write_inodeblock_ufs2(inodedep, bp);
10002 			continue;
10003 
10004 		case D_INDIRDEP:
10005 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10006 			continue;
10007 
10008 		case D_BMSAFEMAP:
10009 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10010 			continue;
10011 
10012 		case D_JSEG:
10013 			WK_JSEG(wk)->js_buf = NULL;
10014 			continue;
10015 
10016 		case D_FREEBLKS:
10017 			freeblks = WK_FREEBLKS(wk);
10018 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10019 			/*
10020 			 * We have to wait for the freeblks to be journaled
10021 			 * before we can write an inodeblock with updated
10022 			 * pointers.  Be careful to arrange the marker so
10023 			 * we revisit the freeblks if it's not removed by
10024 			 * the first jwait().
10025 			 */
10026 			if (jblkdep != NULL) {
10027 				LIST_REMOVE(&marker, wk_list);
10028 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10029 				jwait(&jblkdep->jb_list, MNT_WAIT);
10030 			}
10031 			continue;
10032 		case D_ALLOCDIRECT:
10033 		case D_ALLOCINDIR:
10034 			/*
10035 			 * We have to wait for the jnewblk to be journaled
10036 			 * before we can write to a block if the contents
10037 			 * may be confused with an earlier file's indirect
10038 			 * at recovery time.  Handle the marker as described
10039 			 * above.
10040 			 */
10041 			newblk = WK_NEWBLK(wk);
10042 			if (newblk->nb_jnewblk != NULL &&
10043 			    indirblk_lookup(newblk->nb_list.wk_mp,
10044 			    newblk->nb_newblkno)) {
10045 				LIST_REMOVE(&marker, wk_list);
10046 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10047 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10048 			}
10049 			continue;
10050 
10051 		case D_SBDEP:
10052 			initiate_write_sbdep(WK_SBDEP(wk));
10053 			continue;
10054 
10055 		case D_MKDIR:
10056 		case D_FREEWORK:
10057 		case D_FREEDEP:
10058 		case D_JSEGDEP:
10059 			continue;
10060 
10061 		default:
10062 			panic("handle_disk_io_initiation: Unexpected type %s",
10063 			    TYPENAME(wk->wk_type));
10064 			/* NOTREACHED */
10065 		}
10066 	}
10067 	FREE_LOCK(ump);
10068 	PRELE(curproc);			/* Allow swapout of kernel stack */
10069 }
10070 
10071 /*
10072  * Called from within the procedure above to deal with unsatisfied
10073  * allocation dependencies in a directory. The buffer must be locked,
10074  * thus, no I/O completion operations can occur while we are
10075  * manipulating its associated dependencies.
10076  */
10077 static void
10078 initiate_write_filepage(pagedep, bp)
10079 	struct pagedep *pagedep;
10080 	struct buf *bp;
10081 {
10082 	struct jremref *jremref;
10083 	struct jmvref *jmvref;
10084 	struct dirrem *dirrem;
10085 	struct diradd *dap;
10086 	struct direct *ep;
10087 	int i;
10088 
10089 	if (pagedep->pd_state & IOSTARTED) {
10090 		/*
10091 		 * This can only happen if there is a driver that does not
10092 		 * understand chaining. Here biodone will reissue the call
10093 		 * to strategy for the incomplete buffers.
10094 		 */
10095 		printf("initiate_write_filepage: already started\n");
10096 		return;
10097 	}
10098 	pagedep->pd_state |= IOSTARTED;
10099 	/*
10100 	 * Wait for all journal remove dependencies to hit the disk.
10101 	 * We can not allow any potentially conflicting directory adds
10102 	 * to be visible before removes and rollback is too difficult.
10103 	 * The per-filesystem lock may be dropped and re-acquired, however
10104 	 * we hold the buf locked so the dependency can not go away.
10105 	 */
10106 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10107 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10108 			jwait(&jremref->jr_list, MNT_WAIT);
10109 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10110 		jwait(&jmvref->jm_list, MNT_WAIT);
10111 	for (i = 0; i < DAHASHSZ; i++) {
10112 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10113 			ep = (struct direct *)
10114 			    ((char *)bp->b_data + dap->da_offset);
10115 			if (ep->d_ino != dap->da_newinum)
10116 				panic("%s: dir inum %ju != new %ju",
10117 				    "initiate_write_filepage",
10118 				    (uintmax_t)ep->d_ino,
10119 				    (uintmax_t)dap->da_newinum);
10120 			if (dap->da_state & DIRCHG)
10121 				ep->d_ino = dap->da_previous->dm_oldinum;
10122 			else
10123 				ep->d_ino = 0;
10124 			dap->da_state &= ~ATTACHED;
10125 			dap->da_state |= UNDONE;
10126 		}
10127 	}
10128 }
10129 
10130 /*
10131  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10132  * Note that any bug fixes made to this routine must be done in the
10133  * version found below.
10134  *
10135  * Called from within the procedure above to deal with unsatisfied
10136  * allocation dependencies in an inodeblock. The buffer must be
10137  * locked, thus, no I/O completion operations can occur while we
10138  * are manipulating its associated dependencies.
10139  */
10140 static void
10141 initiate_write_inodeblock_ufs1(inodedep, bp)
10142 	struct inodedep *inodedep;
10143 	struct buf *bp;			/* The inode block */
10144 {
10145 	struct allocdirect *adp, *lastadp;
10146 	struct ufs1_dinode *dp;
10147 	struct ufs1_dinode *sip;
10148 	struct inoref *inoref;
10149 	struct ufsmount *ump;
10150 	struct fs *fs;
10151 	ufs_lbn_t i;
10152 #ifdef INVARIANTS
10153 	ufs_lbn_t prevlbn = 0;
10154 #endif
10155 	int deplist;
10156 
10157 	if (inodedep->id_state & IOSTARTED)
10158 		panic("initiate_write_inodeblock_ufs1: already started");
10159 	inodedep->id_state |= IOSTARTED;
10160 	fs = inodedep->id_fs;
10161 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10162 	LOCK_OWNED(ump);
10163 	dp = (struct ufs1_dinode *)bp->b_data +
10164 	    ino_to_fsbo(fs, inodedep->id_ino);
10165 
10166 	/*
10167 	 * If we're on the unlinked list but have not yet written our
10168 	 * next pointer initialize it here.
10169 	 */
10170 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10171 		struct inodedep *inon;
10172 
10173 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10174 		dp->di_freelink = inon ? inon->id_ino : 0;
10175 	}
10176 	/*
10177 	 * If the bitmap is not yet written, then the allocated
10178 	 * inode cannot be written to disk.
10179 	 */
10180 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10181 		if (inodedep->id_savedino1 != NULL)
10182 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10183 		FREE_LOCK(ump);
10184 		sip = malloc(sizeof(struct ufs1_dinode),
10185 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10186 		ACQUIRE_LOCK(ump);
10187 		inodedep->id_savedino1 = sip;
10188 		*inodedep->id_savedino1 = *dp;
10189 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10190 		dp->di_gen = inodedep->id_savedino1->di_gen;
10191 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10192 		return;
10193 	}
10194 	/*
10195 	 * If no dependencies, then there is nothing to roll back.
10196 	 */
10197 	inodedep->id_savedsize = dp->di_size;
10198 	inodedep->id_savedextsize = 0;
10199 	inodedep->id_savednlink = dp->di_nlink;
10200 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10201 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10202 		return;
10203 	/*
10204 	 * Revert the link count to that of the first unwritten journal entry.
10205 	 */
10206 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10207 	if (inoref)
10208 		dp->di_nlink = inoref->if_nlink;
10209 	/*
10210 	 * Set the dependencies to busy.
10211 	 */
10212 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10213 	     adp = TAILQ_NEXT(adp, ad_next)) {
10214 #ifdef INVARIANTS
10215 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10216 			panic("softdep_write_inodeblock: lbn order");
10217 		prevlbn = adp->ad_offset;
10218 		if (adp->ad_offset < UFS_NDADDR &&
10219 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10220 			panic("%s: direct pointer #%jd mismatch %d != %jd",
10221 			    "softdep_write_inodeblock",
10222 			    (intmax_t)adp->ad_offset,
10223 			    dp->di_db[adp->ad_offset],
10224 			    (intmax_t)adp->ad_newblkno);
10225 		if (adp->ad_offset >= UFS_NDADDR &&
10226 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10227 			panic("%s: indirect pointer #%jd mismatch %d != %jd",
10228 			    "softdep_write_inodeblock",
10229 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10230 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10231 			    (intmax_t)adp->ad_newblkno);
10232 		deplist |= 1 << adp->ad_offset;
10233 		if ((adp->ad_state & ATTACHED) == 0)
10234 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10235 			    adp->ad_state);
10236 #endif /* INVARIANTS */
10237 		adp->ad_state &= ~ATTACHED;
10238 		adp->ad_state |= UNDONE;
10239 	}
10240 	/*
10241 	 * The on-disk inode cannot claim to be any larger than the last
10242 	 * fragment that has been written. Otherwise, the on-disk inode
10243 	 * might have fragments that were not the last block in the file
10244 	 * which would corrupt the filesystem.
10245 	 */
10246 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10247 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10248 		if (adp->ad_offset >= UFS_NDADDR)
10249 			break;
10250 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10251 		/* keep going until hitting a rollback to a frag */
10252 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10253 			continue;
10254 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10255 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10256 #ifdef INVARIANTS
10257 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10258 				panic("softdep_write_inodeblock: lost dep1");
10259 #endif /* INVARIANTS */
10260 			dp->di_db[i] = 0;
10261 		}
10262 		for (i = 0; i < UFS_NIADDR; i++) {
10263 #ifdef INVARIANTS
10264 			if (dp->di_ib[i] != 0 &&
10265 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10266 				panic("softdep_write_inodeblock: lost dep2");
10267 #endif /* INVARIANTS */
10268 			dp->di_ib[i] = 0;
10269 		}
10270 		return;
10271 	}
10272 	/*
10273 	 * If we have zero'ed out the last allocated block of the file,
10274 	 * roll back the size to the last currently allocated block.
10275 	 * We know that this last allocated block is a full-sized as
10276 	 * we already checked for fragments in the loop above.
10277 	 */
10278 	if (lastadp != NULL &&
10279 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10280 		for (i = lastadp->ad_offset; i >= 0; i--)
10281 			if (dp->di_db[i] != 0)
10282 				break;
10283 		dp->di_size = (i + 1) * fs->fs_bsize;
10284 	}
10285 	/*
10286 	 * The only dependencies are for indirect blocks.
10287 	 *
10288 	 * The file size for indirect block additions is not guaranteed.
10289 	 * Such a guarantee would be non-trivial to achieve. The conventional
10290 	 * synchronous write implementation also does not make this guarantee.
10291 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10292 	 * can be over-estimated without destroying integrity when the file
10293 	 * moves into the indirect blocks (i.e., is large). If we want to
10294 	 * postpone fsck, we are stuck with this argument.
10295 	 */
10296 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10297 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10298 }
10299 
10300 /*
10301  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10302  * Note that any bug fixes made to this routine must be done in the
10303  * version found above.
10304  *
10305  * Called from within the procedure above to deal with unsatisfied
10306  * allocation dependencies in an inodeblock. The buffer must be
10307  * locked, thus, no I/O completion operations can occur while we
10308  * are manipulating its associated dependencies.
10309  */
10310 static void
10311 initiate_write_inodeblock_ufs2(inodedep, bp)
10312 	struct inodedep *inodedep;
10313 	struct buf *bp;			/* The inode block */
10314 {
10315 	struct allocdirect *adp, *lastadp;
10316 	struct ufs2_dinode *dp;
10317 	struct ufs2_dinode *sip;
10318 	struct inoref *inoref;
10319 	struct ufsmount *ump;
10320 	struct fs *fs;
10321 	ufs_lbn_t i;
10322 #ifdef INVARIANTS
10323 	ufs_lbn_t prevlbn = 0;
10324 #endif
10325 	int deplist;
10326 
10327 	if (inodedep->id_state & IOSTARTED)
10328 		panic("initiate_write_inodeblock_ufs2: already started");
10329 	inodedep->id_state |= IOSTARTED;
10330 	fs = inodedep->id_fs;
10331 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10332 	LOCK_OWNED(ump);
10333 	dp = (struct ufs2_dinode *)bp->b_data +
10334 	    ino_to_fsbo(fs, inodedep->id_ino);
10335 
10336 	/*
10337 	 * If we're on the unlinked list but have not yet written our
10338 	 * next pointer initialize it here.
10339 	 */
10340 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10341 		struct inodedep *inon;
10342 
10343 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10344 		dp->di_freelink = inon ? inon->id_ino : 0;
10345 	}
10346 	/*
10347 	 * If the bitmap is not yet written, then the allocated
10348 	 * inode cannot be written to disk.
10349 	 */
10350 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10351 		if (inodedep->id_savedino2 != NULL)
10352 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10353 		FREE_LOCK(ump);
10354 		sip = malloc(sizeof(struct ufs2_dinode),
10355 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10356 		ACQUIRE_LOCK(ump);
10357 		inodedep->id_savedino2 = sip;
10358 		*inodedep->id_savedino2 = *dp;
10359 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10360 		dp->di_gen = inodedep->id_savedino2->di_gen;
10361 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10362 		return;
10363 	}
10364 	/*
10365 	 * If no dependencies, then there is nothing to roll back.
10366 	 */
10367 	inodedep->id_savedsize = dp->di_size;
10368 	inodedep->id_savedextsize = dp->di_extsize;
10369 	inodedep->id_savednlink = dp->di_nlink;
10370 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10371 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10372 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10373 		return;
10374 	/*
10375 	 * Revert the link count to that of the first unwritten journal entry.
10376 	 */
10377 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10378 	if (inoref)
10379 		dp->di_nlink = inoref->if_nlink;
10380 
10381 	/*
10382 	 * Set the ext data dependencies to busy.
10383 	 */
10384 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10385 	     adp = TAILQ_NEXT(adp, ad_next)) {
10386 #ifdef INVARIANTS
10387 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10388 			panic("softdep_write_inodeblock: lbn order");
10389 		prevlbn = adp->ad_offset;
10390 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10391 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10392 			    "softdep_write_inodeblock",
10393 			    (intmax_t)adp->ad_offset,
10394 			    (intmax_t)dp->di_extb[adp->ad_offset],
10395 			    (intmax_t)adp->ad_newblkno);
10396 		deplist |= 1 << adp->ad_offset;
10397 		if ((adp->ad_state & ATTACHED) == 0)
10398 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10399 			    adp->ad_state);
10400 #endif /* INVARIANTS */
10401 		adp->ad_state &= ~ATTACHED;
10402 		adp->ad_state |= UNDONE;
10403 	}
10404 	/*
10405 	 * The on-disk inode cannot claim to be any larger than the last
10406 	 * fragment that has been written. Otherwise, the on-disk inode
10407 	 * might have fragments that were not the last block in the ext
10408 	 * data which would corrupt the filesystem.
10409 	 */
10410 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10411 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10412 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10413 		/* keep going until hitting a rollback to a frag */
10414 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10415 			continue;
10416 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10417 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10418 #ifdef INVARIANTS
10419 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10420 				panic("softdep_write_inodeblock: lost dep1");
10421 #endif /* INVARIANTS */
10422 			dp->di_extb[i] = 0;
10423 		}
10424 		lastadp = NULL;
10425 		break;
10426 	}
10427 	/*
10428 	 * If we have zero'ed out the last allocated block of the ext
10429 	 * data, roll back the size to the last currently allocated block.
10430 	 * We know that this last allocated block is a full-sized as
10431 	 * we already checked for fragments in the loop above.
10432 	 */
10433 	if (lastadp != NULL &&
10434 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10435 		for (i = lastadp->ad_offset; i >= 0; i--)
10436 			if (dp->di_extb[i] != 0)
10437 				break;
10438 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10439 	}
10440 	/*
10441 	 * Set the file data dependencies to busy.
10442 	 */
10443 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10444 	     adp = TAILQ_NEXT(adp, ad_next)) {
10445 #ifdef INVARIANTS
10446 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10447 			panic("softdep_write_inodeblock: lbn order");
10448 		if ((adp->ad_state & ATTACHED) == 0)
10449 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10450 		prevlbn = adp->ad_offset;
10451 		if (adp->ad_offset < UFS_NDADDR &&
10452 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10453 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10454 			    "softdep_write_inodeblock",
10455 			    (intmax_t)adp->ad_offset,
10456 			    (intmax_t)dp->di_db[adp->ad_offset],
10457 			    (intmax_t)adp->ad_newblkno);
10458 		if (adp->ad_offset >= UFS_NDADDR &&
10459 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10460 			panic("%s indirect pointer #%jd mismatch %jd != %jd",
10461 			    "softdep_write_inodeblock:",
10462 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10463 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10464 			    (intmax_t)adp->ad_newblkno);
10465 		deplist |= 1 << adp->ad_offset;
10466 		if ((adp->ad_state & ATTACHED) == 0)
10467 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10468 			    adp->ad_state);
10469 #endif /* INVARIANTS */
10470 		adp->ad_state &= ~ATTACHED;
10471 		adp->ad_state |= UNDONE;
10472 	}
10473 	/*
10474 	 * The on-disk inode cannot claim to be any larger than the last
10475 	 * fragment that has been written. Otherwise, the on-disk inode
10476 	 * might have fragments that were not the last block in the file
10477 	 * which would corrupt the filesystem.
10478 	 */
10479 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10480 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10481 		if (adp->ad_offset >= UFS_NDADDR)
10482 			break;
10483 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10484 		/* keep going until hitting a rollback to a frag */
10485 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10486 			continue;
10487 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10488 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10489 #ifdef INVARIANTS
10490 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10491 				panic("softdep_write_inodeblock: lost dep2");
10492 #endif /* INVARIANTS */
10493 			dp->di_db[i] = 0;
10494 		}
10495 		for (i = 0; i < UFS_NIADDR; i++) {
10496 #ifdef INVARIANTS
10497 			if (dp->di_ib[i] != 0 &&
10498 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10499 				panic("softdep_write_inodeblock: lost dep3");
10500 #endif /* INVARIANTS */
10501 			dp->di_ib[i] = 0;
10502 		}
10503 		return;
10504 	}
10505 	/*
10506 	 * If we have zero'ed out the last allocated block of the file,
10507 	 * roll back the size to the last currently allocated block.
10508 	 * We know that this last allocated block is a full-sized as
10509 	 * we already checked for fragments in the loop above.
10510 	 */
10511 	if (lastadp != NULL &&
10512 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10513 		for (i = lastadp->ad_offset; i >= 0; i--)
10514 			if (dp->di_db[i] != 0)
10515 				break;
10516 		dp->di_size = (i + 1) * fs->fs_bsize;
10517 	}
10518 	/*
10519 	 * The only dependencies are for indirect blocks.
10520 	 *
10521 	 * The file size for indirect block additions is not guaranteed.
10522 	 * Such a guarantee would be non-trivial to achieve. The conventional
10523 	 * synchronous write implementation also does not make this guarantee.
10524 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10525 	 * can be over-estimated without destroying integrity when the file
10526 	 * moves into the indirect blocks (i.e., is large). If we want to
10527 	 * postpone fsck, we are stuck with this argument.
10528 	 */
10529 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10530 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10531 }
10532 
10533 /*
10534  * Cancel an indirdep as a result of truncation.  Release all of the
10535  * children allocindirs and place their journal work on the appropriate
10536  * list.
10537  */
10538 static void
10539 cancel_indirdep(indirdep, bp, freeblks)
10540 	struct indirdep *indirdep;
10541 	struct buf *bp;
10542 	struct freeblks *freeblks;
10543 {
10544 	struct allocindir *aip;
10545 
10546 	/*
10547 	 * None of the indirect pointers will ever be visible,
10548 	 * so they can simply be tossed. GOINGAWAY ensures
10549 	 * that allocated pointers will be saved in the buffer
10550 	 * cache until they are freed. Note that they will
10551 	 * only be able to be found by their physical address
10552 	 * since the inode mapping the logical address will
10553 	 * be gone. The save buffer used for the safe copy
10554 	 * was allocated in setup_allocindir_phase2 using
10555 	 * the physical address so it could be used for this
10556 	 * purpose. Hence we swap the safe copy with the real
10557 	 * copy, allowing the safe copy to be freed and holding
10558 	 * on to the real copy for later use in indir_trunc.
10559 	 */
10560 	if (indirdep->ir_state & GOINGAWAY)
10561 		panic("cancel_indirdep: already gone");
10562 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10563 		indirdep->ir_state |= DEPCOMPLETE;
10564 		LIST_REMOVE(indirdep, ir_next);
10565 	}
10566 	indirdep->ir_state |= GOINGAWAY;
10567 	/*
10568 	 * Pass in bp for blocks still have journal writes
10569 	 * pending so we can cancel them on their own.
10570 	 */
10571 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10572 		cancel_allocindir(aip, bp, freeblks, 0);
10573 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10574 		cancel_allocindir(aip, NULL, freeblks, 0);
10575 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10576 		cancel_allocindir(aip, NULL, freeblks, 0);
10577 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10578 		cancel_allocindir(aip, NULL, freeblks, 0);
10579 	/*
10580 	 * If there are pending partial truncations we need to keep the
10581 	 * old block copy around until they complete.  This is because
10582 	 * the current b_data is not a perfect superset of the available
10583 	 * blocks.
10584 	 */
10585 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10586 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10587 	else
10588 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10589 	WORKLIST_REMOVE(&indirdep->ir_list);
10590 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10591 	indirdep->ir_bp = NULL;
10592 	indirdep->ir_freeblks = freeblks;
10593 }
10594 
10595 /*
10596  * Free an indirdep once it no longer has new pointers to track.
10597  */
10598 static void
10599 free_indirdep(indirdep)
10600 	struct indirdep *indirdep;
10601 {
10602 
10603 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10604 	    ("free_indirdep: Indir trunc list not empty."));
10605 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10606 	    ("free_indirdep: Complete head not empty."));
10607 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10608 	    ("free_indirdep: write head not empty."));
10609 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10610 	    ("free_indirdep: done head not empty."));
10611 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10612 	    ("free_indirdep: deplist head not empty."));
10613 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10614 	    ("free_indirdep: %p still on newblk list.", indirdep));
10615 	KASSERT(indirdep->ir_saveddata == NULL,
10616 	    ("free_indirdep: %p still has saved data.", indirdep));
10617 	if (indirdep->ir_state & ONWORKLIST)
10618 		WORKLIST_REMOVE(&indirdep->ir_list);
10619 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10620 }
10621 
10622 /*
10623  * Called before a write to an indirdep.  This routine is responsible for
10624  * rolling back pointers to a safe state which includes only those
10625  * allocindirs which have been completed.
10626  */
10627 static void
10628 initiate_write_indirdep(indirdep, bp)
10629 	struct indirdep *indirdep;
10630 	struct buf *bp;
10631 {
10632 	struct ufsmount *ump;
10633 
10634 	indirdep->ir_state |= IOSTARTED;
10635 	if (indirdep->ir_state & GOINGAWAY)
10636 		panic("disk_io_initiation: indirdep gone");
10637 	/*
10638 	 * If there are no remaining dependencies, this will be writing
10639 	 * the real pointers.
10640 	 */
10641 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10642 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10643 		return;
10644 	/*
10645 	 * Replace up-to-date version with safe version.
10646 	 */
10647 	if (indirdep->ir_saveddata == NULL) {
10648 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10649 		LOCK_OWNED(ump);
10650 		FREE_LOCK(ump);
10651 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10652 		    M_SOFTDEP_FLAGS);
10653 		ACQUIRE_LOCK(ump);
10654 	}
10655 	indirdep->ir_state &= ~ATTACHED;
10656 	indirdep->ir_state |= UNDONE;
10657 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10658 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10659 	    bp->b_bcount);
10660 }
10661 
10662 /*
10663  * Called when an inode has been cleared in a cg bitmap.  This finally
10664  * eliminates any canceled jaddrefs
10665  */
10666 void
10667 softdep_setup_inofree(mp, bp, ino, wkhd)
10668 	struct mount *mp;
10669 	struct buf *bp;
10670 	ino_t ino;
10671 	struct workhead *wkhd;
10672 {
10673 	struct worklist *wk, *wkn;
10674 	struct inodedep *inodedep;
10675 	struct ufsmount *ump;
10676 	uint8_t *inosused;
10677 	struct cg *cgp;
10678 	struct fs *fs;
10679 
10680 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10681 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10682 	ump = VFSTOUFS(mp);
10683 	ACQUIRE_LOCK(ump);
10684 	fs = ump->um_fs;
10685 	cgp = (struct cg *)bp->b_data;
10686 	inosused = cg_inosused(cgp);
10687 	if (isset(inosused, ino % fs->fs_ipg))
10688 		panic("softdep_setup_inofree: inode %ju not freed.",
10689 		    (uintmax_t)ino);
10690 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10691 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10692 		    (uintmax_t)ino, inodedep);
10693 	if (wkhd) {
10694 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10695 			if (wk->wk_type != D_JADDREF)
10696 				continue;
10697 			WORKLIST_REMOVE(wk);
10698 			/*
10699 			 * We can free immediately even if the jaddref
10700 			 * isn't attached in a background write as now
10701 			 * the bitmaps are reconciled.
10702 			 */
10703 			wk->wk_state |= COMPLETE | ATTACHED;
10704 			free_jaddref(WK_JADDREF(wk));
10705 		}
10706 		jwork_move(&bp->b_dep, wkhd);
10707 	}
10708 	FREE_LOCK(ump);
10709 }
10710 
10711 
10712 /*
10713  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10714  * map.  Any dependencies waiting for the write to clear are added to the
10715  * buf's list and any jnewblks that are being canceled are discarded
10716  * immediately.
10717  */
10718 void
10719 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10720 	struct mount *mp;
10721 	struct buf *bp;
10722 	ufs2_daddr_t blkno;
10723 	int frags;
10724 	struct workhead *wkhd;
10725 {
10726 	struct bmsafemap *bmsafemap;
10727 	struct jnewblk *jnewblk;
10728 	struct ufsmount *ump;
10729 	struct worklist *wk;
10730 	struct fs *fs;
10731 #ifdef SUJ_DEBUG
10732 	uint8_t *blksfree;
10733 	struct cg *cgp;
10734 	ufs2_daddr_t jstart;
10735 	ufs2_daddr_t jend;
10736 	ufs2_daddr_t end;
10737 	long bno;
10738 	int i;
10739 #endif
10740 
10741 	CTR3(KTR_SUJ,
10742 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10743 	    blkno, frags, wkhd);
10744 
10745 	ump = VFSTOUFS(mp);
10746 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10747 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10748 	ACQUIRE_LOCK(ump);
10749 	/* Lookup the bmsafemap so we track when it is dirty. */
10750 	fs = ump->um_fs;
10751 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10752 	/*
10753 	 * Detach any jnewblks which have been canceled.  They must linger
10754 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10755 	 * an unjournaled allocation from hitting the disk.
10756 	 */
10757 	if (wkhd) {
10758 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10759 			CTR2(KTR_SUJ,
10760 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10761 			    blkno, wk->wk_type);
10762 			WORKLIST_REMOVE(wk);
10763 			if (wk->wk_type != D_JNEWBLK) {
10764 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10765 				continue;
10766 			}
10767 			jnewblk = WK_JNEWBLK(wk);
10768 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10769 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10770 #ifdef SUJ_DEBUG
10771 			/*
10772 			 * Assert that this block is free in the bitmap
10773 			 * before we discard the jnewblk.
10774 			 */
10775 			cgp = (struct cg *)bp->b_data;
10776 			blksfree = cg_blksfree(cgp);
10777 			bno = dtogd(fs, jnewblk->jn_blkno);
10778 			for (i = jnewblk->jn_oldfrags;
10779 			    i < jnewblk->jn_frags; i++) {
10780 				if (isset(blksfree, bno + i))
10781 					continue;
10782 				panic("softdep_setup_blkfree: not free");
10783 			}
10784 #endif
10785 			/*
10786 			 * Even if it's not attached we can free immediately
10787 			 * as the new bitmap is correct.
10788 			 */
10789 			wk->wk_state |= COMPLETE | ATTACHED;
10790 			free_jnewblk(jnewblk);
10791 		}
10792 	}
10793 
10794 #ifdef SUJ_DEBUG
10795 	/*
10796 	 * Assert that we are not freeing a block which has an outstanding
10797 	 * allocation dependency.
10798 	 */
10799 	fs = VFSTOUFS(mp)->um_fs;
10800 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10801 	end = blkno + frags;
10802 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10803 		/*
10804 		 * Don't match against blocks that will be freed when the
10805 		 * background write is done.
10806 		 */
10807 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10808 		    (COMPLETE | DEPCOMPLETE))
10809 			continue;
10810 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10811 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10812 		if ((blkno >= jstart && blkno < jend) ||
10813 		    (end > jstart && end <= jend)) {
10814 			printf("state 0x%X %jd - %d %d dep %p\n",
10815 			    jnewblk->jn_state, jnewblk->jn_blkno,
10816 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10817 			    jnewblk->jn_dep);
10818 			panic("softdep_setup_blkfree: "
10819 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10820 			    blkno, end, frags, jstart, jend);
10821 		}
10822 	}
10823 #endif
10824 	FREE_LOCK(ump);
10825 }
10826 
10827 /*
10828  * Revert a block allocation when the journal record that describes it
10829  * is not yet written.
10830  */
10831 static int
10832 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10833 	struct jnewblk *jnewblk;
10834 	struct fs *fs;
10835 	struct cg *cgp;
10836 	uint8_t *blksfree;
10837 {
10838 	ufs1_daddr_t fragno;
10839 	long cgbno, bbase;
10840 	int frags, blk;
10841 	int i;
10842 
10843 	frags = 0;
10844 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10845 	/*
10846 	 * We have to test which frags need to be rolled back.  We may
10847 	 * be operating on a stale copy when doing background writes.
10848 	 */
10849 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10850 		if (isclr(blksfree, cgbno + i))
10851 			frags++;
10852 	if (frags == 0)
10853 		return (0);
10854 	/*
10855 	 * This is mostly ffs_blkfree() sans some validation and
10856 	 * superblock updates.
10857 	 */
10858 	if (frags == fs->fs_frag) {
10859 		fragno = fragstoblks(fs, cgbno);
10860 		ffs_setblock(fs, blksfree, fragno);
10861 		ffs_clusteracct(fs, cgp, fragno, 1);
10862 		cgp->cg_cs.cs_nbfree++;
10863 	} else {
10864 		cgbno += jnewblk->jn_oldfrags;
10865 		bbase = cgbno - fragnum(fs, cgbno);
10866 		/* Decrement the old frags.  */
10867 		blk = blkmap(fs, blksfree, bbase);
10868 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10869 		/* Deallocate the fragment */
10870 		for (i = 0; i < frags; i++)
10871 			setbit(blksfree, cgbno + i);
10872 		cgp->cg_cs.cs_nffree += frags;
10873 		/* Add back in counts associated with the new frags */
10874 		blk = blkmap(fs, blksfree, bbase);
10875 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10876 		/* If a complete block has been reassembled, account for it. */
10877 		fragno = fragstoblks(fs, bbase);
10878 		if (ffs_isblock(fs, blksfree, fragno)) {
10879 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10880 			ffs_clusteracct(fs, cgp, fragno, 1);
10881 			cgp->cg_cs.cs_nbfree++;
10882 		}
10883 	}
10884 	stat_jnewblk++;
10885 	jnewblk->jn_state &= ~ATTACHED;
10886 	jnewblk->jn_state |= UNDONE;
10887 
10888 	return (frags);
10889 }
10890 
10891 static void
10892 initiate_write_bmsafemap(bmsafemap, bp)
10893 	struct bmsafemap *bmsafemap;
10894 	struct buf *bp;			/* The cg block. */
10895 {
10896 	struct jaddref *jaddref;
10897 	struct jnewblk *jnewblk;
10898 	uint8_t *inosused;
10899 	uint8_t *blksfree;
10900 	struct cg *cgp;
10901 	struct fs *fs;
10902 	ino_t ino;
10903 
10904 	/*
10905 	 * If this is a background write, we did this at the time that
10906 	 * the copy was made, so do not need to do it again.
10907 	 */
10908 	if (bmsafemap->sm_state & IOSTARTED)
10909 		return;
10910 	bmsafemap->sm_state |= IOSTARTED;
10911 	/*
10912 	 * Clear any inode allocations which are pending journal writes.
10913 	 */
10914 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10915 		cgp = (struct cg *)bp->b_data;
10916 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10917 		inosused = cg_inosused(cgp);
10918 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10919 			ino = jaddref->ja_ino % fs->fs_ipg;
10920 			if (isset(inosused, ino)) {
10921 				if ((jaddref->ja_mode & IFMT) == IFDIR)
10922 					cgp->cg_cs.cs_ndir--;
10923 				cgp->cg_cs.cs_nifree++;
10924 				clrbit(inosused, ino);
10925 				jaddref->ja_state &= ~ATTACHED;
10926 				jaddref->ja_state |= UNDONE;
10927 				stat_jaddref++;
10928 			} else
10929 				panic("initiate_write_bmsafemap: inode %ju "
10930 				    "marked free", (uintmax_t)jaddref->ja_ino);
10931 		}
10932 	}
10933 	/*
10934 	 * Clear any block allocations which are pending journal writes.
10935 	 */
10936 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10937 		cgp = (struct cg *)bp->b_data;
10938 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10939 		blksfree = cg_blksfree(cgp);
10940 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10941 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10942 				continue;
10943 			panic("initiate_write_bmsafemap: block %jd "
10944 			    "marked free", jnewblk->jn_blkno);
10945 		}
10946 	}
10947 	/*
10948 	 * Move allocation lists to the written lists so they can be
10949 	 * cleared once the block write is complete.
10950 	 */
10951 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10952 	    inodedep, id_deps);
10953 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10954 	    newblk, nb_deps);
10955 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10956 	    wk_list);
10957 }
10958 
10959 /*
10960  * This routine is called during the completion interrupt
10961  * service routine for a disk write (from the procedure called
10962  * by the device driver to inform the filesystem caches of
10963  * a request completion).  It should be called early in this
10964  * procedure, before the block is made available to other
10965  * processes or other routines are called.
10966  *
10967  */
10968 static void
10969 softdep_disk_write_complete(bp)
10970 	struct buf *bp;		/* describes the completed disk write */
10971 {
10972 	struct worklist *wk;
10973 	struct worklist *owk;
10974 	struct ufsmount *ump;
10975 	struct workhead reattach;
10976 	struct freeblks *freeblks;
10977 	struct buf *sbp;
10978 
10979 	/*
10980 	 * If an error occurred while doing the write, then the data
10981 	 * has not hit the disk and the dependencies cannot be processed.
10982 	 * But we do have to go through and roll forward any dependencies
10983 	 * that were rolled back before the disk write.
10984 	 */
10985 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
10986 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
10987 			switch (wk->wk_type) {
10988 
10989 			case D_PAGEDEP:
10990 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
10991 				continue;
10992 
10993 			case D_INODEDEP:
10994 				handle_written_inodeblock(WK_INODEDEP(wk),
10995 				    bp, 0);
10996 				continue;
10997 
10998 			case D_BMSAFEMAP:
10999 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11000 				    bp, 0);
11001 				continue;
11002 
11003 			case D_INDIRDEP:
11004 				handle_written_indirdep(WK_INDIRDEP(wk),
11005 				    bp, &sbp, 0);
11006 				continue;
11007 			default:
11008 				/* nothing to roll forward */
11009 				continue;
11010 			}
11011 		}
11012 		return;
11013 	}
11014 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
11015 		return;
11016 	ump = VFSTOUFS(wk->wk_mp);
11017 	LIST_INIT(&reattach);
11018 	/*
11019 	 * This lock must not be released anywhere in this code segment.
11020 	 */
11021 	sbp = NULL;
11022 	owk = NULL;
11023 	ACQUIRE_LOCK(ump);
11024 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11025 		WORKLIST_REMOVE(wk);
11026 		atomic_add_long(&dep_write[wk->wk_type], 1);
11027 		if (wk == owk)
11028 			panic("duplicate worklist: %p\n", wk);
11029 		owk = wk;
11030 		switch (wk->wk_type) {
11031 
11032 		case D_PAGEDEP:
11033 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11034 			    WRITESUCCEEDED))
11035 				WORKLIST_INSERT(&reattach, wk);
11036 			continue;
11037 
11038 		case D_INODEDEP:
11039 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11040 			    WRITESUCCEEDED))
11041 				WORKLIST_INSERT(&reattach, wk);
11042 			continue;
11043 
11044 		case D_BMSAFEMAP:
11045 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11046 			    WRITESUCCEEDED))
11047 				WORKLIST_INSERT(&reattach, wk);
11048 			continue;
11049 
11050 		case D_MKDIR:
11051 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11052 			continue;
11053 
11054 		case D_ALLOCDIRECT:
11055 			wk->wk_state |= COMPLETE;
11056 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11057 			continue;
11058 
11059 		case D_ALLOCINDIR:
11060 			wk->wk_state |= COMPLETE;
11061 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11062 			continue;
11063 
11064 		case D_INDIRDEP:
11065 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11066 			    WRITESUCCEEDED))
11067 				WORKLIST_INSERT(&reattach, wk);
11068 			continue;
11069 
11070 		case D_FREEBLKS:
11071 			wk->wk_state |= COMPLETE;
11072 			freeblks = WK_FREEBLKS(wk);
11073 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11074 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11075 				add_to_worklist(wk, WK_NODELAY);
11076 			continue;
11077 
11078 		case D_FREEWORK:
11079 			handle_written_freework(WK_FREEWORK(wk));
11080 			break;
11081 
11082 		case D_JSEGDEP:
11083 			free_jsegdep(WK_JSEGDEP(wk));
11084 			continue;
11085 
11086 		case D_JSEG:
11087 			handle_written_jseg(WK_JSEG(wk), bp);
11088 			continue;
11089 
11090 		case D_SBDEP:
11091 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11092 				WORKLIST_INSERT(&reattach, wk);
11093 			continue;
11094 
11095 		case D_FREEDEP:
11096 			free_freedep(WK_FREEDEP(wk));
11097 			continue;
11098 
11099 		default:
11100 			panic("handle_disk_write_complete: Unknown type %s",
11101 			    TYPENAME(wk->wk_type));
11102 			/* NOTREACHED */
11103 		}
11104 	}
11105 	/*
11106 	 * Reattach any requests that must be redone.
11107 	 */
11108 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11109 		WORKLIST_REMOVE(wk);
11110 		WORKLIST_INSERT(&bp->b_dep, wk);
11111 	}
11112 	FREE_LOCK(ump);
11113 	if (sbp)
11114 		brelse(sbp);
11115 }
11116 
11117 /*
11118  * Called from within softdep_disk_write_complete above. Note that
11119  * this routine is always called from interrupt level with further
11120  * splbio interrupts blocked.
11121  */
11122 static void
11123 handle_allocdirect_partdone(adp, wkhd)
11124 	struct allocdirect *adp;	/* the completed allocdirect */
11125 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11126 {
11127 	struct allocdirectlst *listhead;
11128 	struct allocdirect *listadp;
11129 	struct inodedep *inodedep;
11130 	long bsize;
11131 
11132 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11133 		return;
11134 	/*
11135 	 * The on-disk inode cannot claim to be any larger than the last
11136 	 * fragment that has been written. Otherwise, the on-disk inode
11137 	 * might have fragments that were not the last block in the file
11138 	 * which would corrupt the filesystem. Thus, we cannot free any
11139 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11140 	 * these blocks must be rolled back to zero before writing the inode.
11141 	 * We check the currently active set of allocdirects in id_inoupdt
11142 	 * or id_extupdt as appropriate.
11143 	 */
11144 	inodedep = adp->ad_inodedep;
11145 	bsize = inodedep->id_fs->fs_bsize;
11146 	if (adp->ad_state & EXTDATA)
11147 		listhead = &inodedep->id_extupdt;
11148 	else
11149 		listhead = &inodedep->id_inoupdt;
11150 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11151 		/* found our block */
11152 		if (listadp == adp)
11153 			break;
11154 		/* continue if ad_oldlbn is not a fragment */
11155 		if (listadp->ad_oldsize == 0 ||
11156 		    listadp->ad_oldsize == bsize)
11157 			continue;
11158 		/* hit a fragment */
11159 		return;
11160 	}
11161 	/*
11162 	 * If we have reached the end of the current list without
11163 	 * finding the just finished dependency, then it must be
11164 	 * on the future dependency list. Future dependencies cannot
11165 	 * be freed until they are moved to the current list.
11166 	 */
11167 	if (listadp == NULL) {
11168 #ifdef DEBUG
11169 		if (adp->ad_state & EXTDATA)
11170 			listhead = &inodedep->id_newextupdt;
11171 		else
11172 			listhead = &inodedep->id_newinoupdt;
11173 		TAILQ_FOREACH(listadp, listhead, ad_next)
11174 			/* found our block */
11175 			if (listadp == adp)
11176 				break;
11177 		if (listadp == NULL)
11178 			panic("handle_allocdirect_partdone: lost dep");
11179 #endif /* DEBUG */
11180 		return;
11181 	}
11182 	/*
11183 	 * If we have found the just finished dependency, then queue
11184 	 * it along with anything that follows it that is complete.
11185 	 * Since the pointer has not yet been written in the inode
11186 	 * as the dependency prevents it, place the allocdirect on the
11187 	 * bufwait list where it will be freed once the pointer is
11188 	 * valid.
11189 	 */
11190 	if (wkhd == NULL)
11191 		wkhd = &inodedep->id_bufwait;
11192 	for (; adp; adp = listadp) {
11193 		listadp = TAILQ_NEXT(adp, ad_next);
11194 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11195 			return;
11196 		TAILQ_REMOVE(listhead, adp, ad_next);
11197 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11198 	}
11199 }
11200 
11201 /*
11202  * Called from within softdep_disk_write_complete above.  This routine
11203  * completes successfully written allocindirs.
11204  */
11205 static void
11206 handle_allocindir_partdone(aip)
11207 	struct allocindir *aip;		/* the completed allocindir */
11208 {
11209 	struct indirdep *indirdep;
11210 
11211 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11212 		return;
11213 	indirdep = aip->ai_indirdep;
11214 	LIST_REMOVE(aip, ai_next);
11215 	/*
11216 	 * Don't set a pointer while the buffer is undergoing IO or while
11217 	 * we have active truncations.
11218 	 */
11219 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11220 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11221 		return;
11222 	}
11223 	if (indirdep->ir_state & UFS1FMT)
11224 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11225 		    aip->ai_newblkno;
11226 	else
11227 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11228 		    aip->ai_newblkno;
11229 	/*
11230 	 * Await the pointer write before freeing the allocindir.
11231 	 */
11232 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11233 }
11234 
11235 /*
11236  * Release segments held on a jwork list.
11237  */
11238 static void
11239 handle_jwork(wkhd)
11240 	struct workhead *wkhd;
11241 {
11242 	struct worklist *wk;
11243 
11244 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11245 		WORKLIST_REMOVE(wk);
11246 		switch (wk->wk_type) {
11247 		case D_JSEGDEP:
11248 			free_jsegdep(WK_JSEGDEP(wk));
11249 			continue;
11250 		case D_FREEDEP:
11251 			free_freedep(WK_FREEDEP(wk));
11252 			continue;
11253 		case D_FREEFRAG:
11254 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11255 			WORKITEM_FREE(wk, D_FREEFRAG);
11256 			continue;
11257 		case D_FREEWORK:
11258 			handle_written_freework(WK_FREEWORK(wk));
11259 			continue;
11260 		default:
11261 			panic("handle_jwork: Unknown type %s\n",
11262 			    TYPENAME(wk->wk_type));
11263 		}
11264 	}
11265 }
11266 
11267 /*
11268  * Handle the bufwait list on an inode when it is safe to release items
11269  * held there.  This normally happens after an inode block is written but
11270  * may be delayed and handled later if there are pending journal items that
11271  * are not yet safe to be released.
11272  */
11273 static struct freefile *
11274 handle_bufwait(inodedep, refhd)
11275 	struct inodedep *inodedep;
11276 	struct workhead *refhd;
11277 {
11278 	struct jaddref *jaddref;
11279 	struct freefile *freefile;
11280 	struct worklist *wk;
11281 
11282 	freefile = NULL;
11283 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11284 		WORKLIST_REMOVE(wk);
11285 		switch (wk->wk_type) {
11286 		case D_FREEFILE:
11287 			/*
11288 			 * We defer adding freefile to the worklist
11289 			 * until all other additions have been made to
11290 			 * ensure that it will be done after all the
11291 			 * old blocks have been freed.
11292 			 */
11293 			if (freefile != NULL)
11294 				panic("handle_bufwait: freefile");
11295 			freefile = WK_FREEFILE(wk);
11296 			continue;
11297 
11298 		case D_MKDIR:
11299 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11300 			continue;
11301 
11302 		case D_DIRADD:
11303 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11304 			continue;
11305 
11306 		case D_FREEFRAG:
11307 			wk->wk_state |= COMPLETE;
11308 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11309 				add_to_worklist(wk, 0);
11310 			continue;
11311 
11312 		case D_DIRREM:
11313 			wk->wk_state |= COMPLETE;
11314 			add_to_worklist(wk, 0);
11315 			continue;
11316 
11317 		case D_ALLOCDIRECT:
11318 		case D_ALLOCINDIR:
11319 			free_newblk(WK_NEWBLK(wk));
11320 			continue;
11321 
11322 		case D_JNEWBLK:
11323 			wk->wk_state |= COMPLETE;
11324 			free_jnewblk(WK_JNEWBLK(wk));
11325 			continue;
11326 
11327 		/*
11328 		 * Save freed journal segments and add references on
11329 		 * the supplied list which will delay their release
11330 		 * until the cg bitmap is cleared on disk.
11331 		 */
11332 		case D_JSEGDEP:
11333 			if (refhd == NULL)
11334 				free_jsegdep(WK_JSEGDEP(wk));
11335 			else
11336 				WORKLIST_INSERT(refhd, wk);
11337 			continue;
11338 
11339 		case D_JADDREF:
11340 			jaddref = WK_JADDREF(wk);
11341 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11342 			    if_deps);
11343 			/*
11344 			 * Transfer any jaddrefs to the list to be freed with
11345 			 * the bitmap if we're handling a removed file.
11346 			 */
11347 			if (refhd == NULL) {
11348 				wk->wk_state |= COMPLETE;
11349 				free_jaddref(jaddref);
11350 			} else
11351 				WORKLIST_INSERT(refhd, wk);
11352 			continue;
11353 
11354 		default:
11355 			panic("handle_bufwait: Unknown type %p(%s)",
11356 			    wk, TYPENAME(wk->wk_type));
11357 			/* NOTREACHED */
11358 		}
11359 	}
11360 	return (freefile);
11361 }
11362 /*
11363  * Called from within softdep_disk_write_complete above to restore
11364  * in-memory inode block contents to their most up-to-date state. Note
11365  * that this routine is always called from interrupt level with further
11366  * interrupts from this device blocked.
11367  *
11368  * If the write did not succeed, we will do all the roll-forward
11369  * operations, but we will not take the actions that will allow its
11370  * dependencies to be processed.
11371  */
11372 static int
11373 handle_written_inodeblock(inodedep, bp, flags)
11374 	struct inodedep *inodedep;
11375 	struct buf *bp;		/* buffer containing the inode block */
11376 	int flags;
11377 {
11378 	struct freefile *freefile;
11379 	struct allocdirect *adp, *nextadp;
11380 	struct ufs1_dinode *dp1 = NULL;
11381 	struct ufs2_dinode *dp2 = NULL;
11382 	struct workhead wkhd;
11383 	int hadchanges, fstype;
11384 	ino_t freelink;
11385 
11386 	LIST_INIT(&wkhd);
11387 	hadchanges = 0;
11388 	freefile = NULL;
11389 	if ((inodedep->id_state & IOSTARTED) == 0)
11390 		panic("handle_written_inodeblock: not started");
11391 	inodedep->id_state &= ~IOSTARTED;
11392 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11393 		fstype = UFS1;
11394 		dp1 = (struct ufs1_dinode *)bp->b_data +
11395 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11396 		freelink = dp1->di_freelink;
11397 	} else {
11398 		fstype = UFS2;
11399 		dp2 = (struct ufs2_dinode *)bp->b_data +
11400 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11401 		freelink = dp2->di_freelink;
11402 	}
11403 	/*
11404 	 * Leave this inodeblock dirty until it's in the list.
11405 	 */
11406 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11407 	    (flags & WRITESUCCEEDED)) {
11408 		struct inodedep *inon;
11409 
11410 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11411 		if ((inon == NULL && freelink == 0) ||
11412 		    (inon && inon->id_ino == freelink)) {
11413 			if (inon)
11414 				inon->id_state |= UNLINKPREV;
11415 			inodedep->id_state |= UNLINKNEXT;
11416 		}
11417 		hadchanges = 1;
11418 	}
11419 	/*
11420 	 * If we had to rollback the inode allocation because of
11421 	 * bitmaps being incomplete, then simply restore it.
11422 	 * Keep the block dirty so that it will not be reclaimed until
11423 	 * all associated dependencies have been cleared and the
11424 	 * corresponding updates written to disk.
11425 	 */
11426 	if (inodedep->id_savedino1 != NULL) {
11427 		hadchanges = 1;
11428 		if (fstype == UFS1)
11429 			*dp1 = *inodedep->id_savedino1;
11430 		else
11431 			*dp2 = *inodedep->id_savedino2;
11432 		free(inodedep->id_savedino1, M_SAVEDINO);
11433 		inodedep->id_savedino1 = NULL;
11434 		if ((bp->b_flags & B_DELWRI) == 0)
11435 			stat_inode_bitmap++;
11436 		bdirty(bp);
11437 		/*
11438 		 * If the inode is clear here and GOINGAWAY it will never
11439 		 * be written.  Process the bufwait and clear any pending
11440 		 * work which may include the freefile.
11441 		 */
11442 		if (inodedep->id_state & GOINGAWAY)
11443 			goto bufwait;
11444 		return (1);
11445 	}
11446 	if (flags & WRITESUCCEEDED)
11447 		inodedep->id_state |= COMPLETE;
11448 	/*
11449 	 * Roll forward anything that had to be rolled back before
11450 	 * the inode could be updated.
11451 	 */
11452 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11453 		nextadp = TAILQ_NEXT(adp, ad_next);
11454 		if (adp->ad_state & ATTACHED)
11455 			panic("handle_written_inodeblock: new entry");
11456 		if (fstype == UFS1) {
11457 			if (adp->ad_offset < UFS_NDADDR) {
11458 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11459 					panic("%s %s #%jd mismatch %d != %jd",
11460 					    "handle_written_inodeblock:",
11461 					    "direct pointer",
11462 					    (intmax_t)adp->ad_offset,
11463 					    dp1->di_db[adp->ad_offset],
11464 					    (intmax_t)adp->ad_oldblkno);
11465 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11466 			} else {
11467 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11468 				    0)
11469 					panic("%s: %s #%jd allocated as %d",
11470 					    "handle_written_inodeblock",
11471 					    "indirect pointer",
11472 					    (intmax_t)adp->ad_offset -
11473 					    UFS_NDADDR,
11474 					    dp1->di_ib[adp->ad_offset -
11475 					    UFS_NDADDR]);
11476 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11477 				    adp->ad_newblkno;
11478 			}
11479 		} else {
11480 			if (adp->ad_offset < UFS_NDADDR) {
11481 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11482 					panic("%s: %s #%jd %s %jd != %jd",
11483 					    "handle_written_inodeblock",
11484 					    "direct pointer",
11485 					    (intmax_t)adp->ad_offset, "mismatch",
11486 					    (intmax_t)dp2->di_db[adp->ad_offset],
11487 					    (intmax_t)adp->ad_oldblkno);
11488 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11489 			} else {
11490 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11491 				    0)
11492 					panic("%s: %s #%jd allocated as %jd",
11493 					    "handle_written_inodeblock",
11494 					    "indirect pointer",
11495 					    (intmax_t)adp->ad_offset -
11496 					    UFS_NDADDR,
11497 					    (intmax_t)
11498 					    dp2->di_ib[adp->ad_offset -
11499 					    UFS_NDADDR]);
11500 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11501 				    adp->ad_newblkno;
11502 			}
11503 		}
11504 		adp->ad_state &= ~UNDONE;
11505 		adp->ad_state |= ATTACHED;
11506 		hadchanges = 1;
11507 	}
11508 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11509 		nextadp = TAILQ_NEXT(adp, ad_next);
11510 		if (adp->ad_state & ATTACHED)
11511 			panic("handle_written_inodeblock: new entry");
11512 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11513 			panic("%s: direct pointers #%jd %s %jd != %jd",
11514 			    "handle_written_inodeblock",
11515 			    (intmax_t)adp->ad_offset, "mismatch",
11516 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11517 			    (intmax_t)adp->ad_oldblkno);
11518 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11519 		adp->ad_state &= ~UNDONE;
11520 		adp->ad_state |= ATTACHED;
11521 		hadchanges = 1;
11522 	}
11523 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11524 		stat_direct_blk_ptrs++;
11525 	/*
11526 	 * Reset the file size to its most up-to-date value.
11527 	 */
11528 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11529 		panic("handle_written_inodeblock: bad size");
11530 	if (inodedep->id_savednlink > UFS_LINK_MAX)
11531 		panic("handle_written_inodeblock: Invalid link count "
11532 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11533 		    inodedep);
11534 	if (fstype == UFS1) {
11535 		if (dp1->di_nlink != inodedep->id_savednlink) {
11536 			dp1->di_nlink = inodedep->id_savednlink;
11537 			hadchanges = 1;
11538 		}
11539 		if (dp1->di_size != inodedep->id_savedsize) {
11540 			dp1->di_size = inodedep->id_savedsize;
11541 			hadchanges = 1;
11542 		}
11543 	} else {
11544 		if (dp2->di_nlink != inodedep->id_savednlink) {
11545 			dp2->di_nlink = inodedep->id_savednlink;
11546 			hadchanges = 1;
11547 		}
11548 		if (dp2->di_size != inodedep->id_savedsize) {
11549 			dp2->di_size = inodedep->id_savedsize;
11550 			hadchanges = 1;
11551 		}
11552 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11553 			dp2->di_extsize = inodedep->id_savedextsize;
11554 			hadchanges = 1;
11555 		}
11556 	}
11557 	inodedep->id_savedsize = -1;
11558 	inodedep->id_savedextsize = -1;
11559 	inodedep->id_savednlink = -1;
11560 	/*
11561 	 * If there were any rollbacks in the inode block, then it must be
11562 	 * marked dirty so that its will eventually get written back in
11563 	 * its correct form.
11564 	 */
11565 	if (hadchanges)
11566 		bdirty(bp);
11567 bufwait:
11568 	/*
11569 	 * If the write did not succeed, we have done all the roll-forward
11570 	 * operations, but we cannot take the actions that will allow its
11571 	 * dependencies to be processed.
11572 	 */
11573 	if ((flags & WRITESUCCEEDED) == 0)
11574 		return (hadchanges);
11575 	/*
11576 	 * Process any allocdirects that completed during the update.
11577 	 */
11578 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11579 		handle_allocdirect_partdone(adp, &wkhd);
11580 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11581 		handle_allocdirect_partdone(adp, &wkhd);
11582 	/*
11583 	 * Process deallocations that were held pending until the
11584 	 * inode had been written to disk. Freeing of the inode
11585 	 * is delayed until after all blocks have been freed to
11586 	 * avoid creation of new <vfsid, inum, lbn> triples
11587 	 * before the old ones have been deleted.  Completely
11588 	 * unlinked inodes are not processed until the unlinked
11589 	 * inode list is written or the last reference is removed.
11590 	 */
11591 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11592 		freefile = handle_bufwait(inodedep, NULL);
11593 		if (freefile && !LIST_EMPTY(&wkhd)) {
11594 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11595 			freefile = NULL;
11596 		}
11597 	}
11598 	/*
11599 	 * Move rolled forward dependency completions to the bufwait list
11600 	 * now that those that were already written have been processed.
11601 	 */
11602 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11603 		panic("handle_written_inodeblock: bufwait but no changes");
11604 	jwork_move(&inodedep->id_bufwait, &wkhd);
11605 
11606 	if (freefile != NULL) {
11607 		/*
11608 		 * If the inode is goingaway it was never written.  Fake up
11609 		 * the state here so free_inodedep() can succeed.
11610 		 */
11611 		if (inodedep->id_state & GOINGAWAY)
11612 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11613 		if (free_inodedep(inodedep) == 0)
11614 			panic("handle_written_inodeblock: live inodedep %p",
11615 			    inodedep);
11616 		add_to_worklist(&freefile->fx_list, 0);
11617 		return (0);
11618 	}
11619 
11620 	/*
11621 	 * If no outstanding dependencies, free it.
11622 	 */
11623 	if (free_inodedep(inodedep) ||
11624 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11625 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11626 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11627 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11628 		return (0);
11629 	return (hadchanges);
11630 }
11631 
11632 /*
11633  * Perform needed roll-forwards and kick off any dependencies that
11634  * can now be processed.
11635  *
11636  * If the write did not succeed, we will do all the roll-forward
11637  * operations, but we will not take the actions that will allow its
11638  * dependencies to be processed.
11639  */
11640 static int
11641 handle_written_indirdep(indirdep, bp, bpp, flags)
11642 	struct indirdep *indirdep;
11643 	struct buf *bp;
11644 	struct buf **bpp;
11645 	int flags;
11646 {
11647 	struct allocindir *aip;
11648 	struct buf *sbp;
11649 	int chgs;
11650 
11651 	if (indirdep->ir_state & GOINGAWAY)
11652 		panic("handle_written_indirdep: indirdep gone");
11653 	if ((indirdep->ir_state & IOSTARTED) == 0)
11654 		panic("handle_written_indirdep: IO not started");
11655 	chgs = 0;
11656 	/*
11657 	 * If there were rollbacks revert them here.
11658 	 */
11659 	if (indirdep->ir_saveddata) {
11660 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11661 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11662 			free(indirdep->ir_saveddata, M_INDIRDEP);
11663 			indirdep->ir_saveddata = NULL;
11664 		}
11665 		chgs = 1;
11666 	}
11667 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11668 	indirdep->ir_state |= ATTACHED;
11669 	/*
11670 	 * If the write did not succeed, we have done all the roll-forward
11671 	 * operations, but we cannot take the actions that will allow its
11672 	 * dependencies to be processed.
11673 	 */
11674 	if ((flags & WRITESUCCEEDED) == 0) {
11675 		stat_indir_blk_ptrs++;
11676 		bdirty(bp);
11677 		return (1);
11678 	}
11679 	/*
11680 	 * Move allocindirs with written pointers to the completehd if
11681 	 * the indirdep's pointer is not yet written.  Otherwise
11682 	 * free them here.
11683 	 */
11684 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11685 		LIST_REMOVE(aip, ai_next);
11686 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11687 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11688 			    ai_next);
11689 			newblk_freefrag(&aip->ai_block);
11690 			continue;
11691 		}
11692 		free_newblk(&aip->ai_block);
11693 	}
11694 	/*
11695 	 * Move allocindirs that have finished dependency processing from
11696 	 * the done list to the write list after updating the pointers.
11697 	 */
11698 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11699 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11700 			handle_allocindir_partdone(aip);
11701 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11702 				panic("disk_write_complete: not gone");
11703 			chgs = 1;
11704 		}
11705 	}
11706 	/*
11707 	 * Preserve the indirdep if there were any changes or if it is not
11708 	 * yet valid on disk.
11709 	 */
11710 	if (chgs) {
11711 		stat_indir_blk_ptrs++;
11712 		bdirty(bp);
11713 		return (1);
11714 	}
11715 	/*
11716 	 * If there were no changes we can discard the savedbp and detach
11717 	 * ourselves from the buf.  We are only carrying completed pointers
11718 	 * in this case.
11719 	 */
11720 	sbp = indirdep->ir_savebp;
11721 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11722 	indirdep->ir_savebp = NULL;
11723 	indirdep->ir_bp = NULL;
11724 	if (*bpp != NULL)
11725 		panic("handle_written_indirdep: bp already exists.");
11726 	*bpp = sbp;
11727 	/*
11728 	 * The indirdep may not be freed until its parent points at it.
11729 	 */
11730 	if (indirdep->ir_state & DEPCOMPLETE)
11731 		free_indirdep(indirdep);
11732 
11733 	return (0);
11734 }
11735 
11736 /*
11737  * Process a diradd entry after its dependent inode has been written.
11738  * This routine must be called with splbio interrupts blocked.
11739  */
11740 static void
11741 diradd_inode_written(dap, inodedep)
11742 	struct diradd *dap;
11743 	struct inodedep *inodedep;
11744 {
11745 
11746 	dap->da_state |= COMPLETE;
11747 	complete_diradd(dap);
11748 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11749 }
11750 
11751 /*
11752  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11753  * be called with the per-filesystem lock and the buf lock on the cg held.
11754  */
11755 static int
11756 bmsafemap_backgroundwrite(bmsafemap, bp)
11757 	struct bmsafemap *bmsafemap;
11758 	struct buf *bp;
11759 {
11760 	int dirty;
11761 
11762 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11763 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11764 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11765 	/*
11766 	 * If we're initiating a background write we need to process the
11767 	 * rollbacks as they exist now, not as they exist when IO starts.
11768 	 * No other consumers will look at the contents of the shadowed
11769 	 * buf so this is safe to do here.
11770 	 */
11771 	if (bp->b_xflags & BX_BKGRDMARKER)
11772 		initiate_write_bmsafemap(bmsafemap, bp);
11773 
11774 	return (dirty);
11775 }
11776 
11777 /*
11778  * Re-apply an allocation when a cg write is complete.
11779  */
11780 static int
11781 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11782 	struct jnewblk *jnewblk;
11783 	struct fs *fs;
11784 	struct cg *cgp;
11785 	uint8_t *blksfree;
11786 {
11787 	ufs1_daddr_t fragno;
11788 	ufs2_daddr_t blkno;
11789 	long cgbno, bbase;
11790 	int frags, blk;
11791 	int i;
11792 
11793 	frags = 0;
11794 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11795 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11796 		if (isclr(blksfree, cgbno + i))
11797 			panic("jnewblk_rollforward: re-allocated fragment");
11798 		frags++;
11799 	}
11800 	if (frags == fs->fs_frag) {
11801 		blkno = fragstoblks(fs, cgbno);
11802 		ffs_clrblock(fs, blksfree, (long)blkno);
11803 		ffs_clusteracct(fs, cgp, blkno, -1);
11804 		cgp->cg_cs.cs_nbfree--;
11805 	} else {
11806 		bbase = cgbno - fragnum(fs, cgbno);
11807 		cgbno += jnewblk->jn_oldfrags;
11808                 /* If a complete block had been reassembled, account for it. */
11809 		fragno = fragstoblks(fs, bbase);
11810 		if (ffs_isblock(fs, blksfree, fragno)) {
11811 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11812 			ffs_clusteracct(fs, cgp, fragno, -1);
11813 			cgp->cg_cs.cs_nbfree--;
11814 		}
11815 		/* Decrement the old frags.  */
11816 		blk = blkmap(fs, blksfree, bbase);
11817 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11818 		/* Allocate the fragment */
11819 		for (i = 0; i < frags; i++)
11820 			clrbit(blksfree, cgbno + i);
11821 		cgp->cg_cs.cs_nffree -= frags;
11822 		/* Add back in counts associated with the new frags */
11823 		blk = blkmap(fs, blksfree, bbase);
11824 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11825 	}
11826 	return (frags);
11827 }
11828 
11829 /*
11830  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11831  * changes if it's not a background write.  Set all written dependencies
11832  * to DEPCOMPLETE and free the structure if possible.
11833  *
11834  * If the write did not succeed, we will do all the roll-forward
11835  * operations, but we will not take the actions that will allow its
11836  * dependencies to be processed.
11837  */
11838 static int
11839 handle_written_bmsafemap(bmsafemap, bp, flags)
11840 	struct bmsafemap *bmsafemap;
11841 	struct buf *bp;
11842 	int flags;
11843 {
11844 	struct newblk *newblk;
11845 	struct inodedep *inodedep;
11846 	struct jaddref *jaddref, *jatmp;
11847 	struct jnewblk *jnewblk, *jntmp;
11848 	struct ufsmount *ump;
11849 	uint8_t *inosused;
11850 	uint8_t *blksfree;
11851 	struct cg *cgp;
11852 	struct fs *fs;
11853 	ino_t ino;
11854 	int foreground;
11855 	int chgs;
11856 
11857 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11858 		panic("handle_written_bmsafemap: Not started\n");
11859 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11860 	chgs = 0;
11861 	bmsafemap->sm_state &= ~IOSTARTED;
11862 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11863 	/*
11864 	 * If write was successful, release journal work that was waiting
11865 	 * on the write. Otherwise move the work back.
11866 	 */
11867 	if (flags & WRITESUCCEEDED)
11868 		handle_jwork(&bmsafemap->sm_freewr);
11869 	else
11870 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11871 		    worklist, wk_list);
11872 
11873 	/*
11874 	 * Restore unwritten inode allocation pending jaddref writes.
11875 	 */
11876 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11877 		cgp = (struct cg *)bp->b_data;
11878 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11879 		inosused = cg_inosused(cgp);
11880 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11881 		    ja_bmdeps, jatmp) {
11882 			if ((jaddref->ja_state & UNDONE) == 0)
11883 				continue;
11884 			ino = jaddref->ja_ino % fs->fs_ipg;
11885 			if (isset(inosused, ino))
11886 				panic("handle_written_bmsafemap: "
11887 				    "re-allocated inode");
11888 			/* Do the roll-forward only if it's a real copy. */
11889 			if (foreground) {
11890 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11891 					cgp->cg_cs.cs_ndir++;
11892 				cgp->cg_cs.cs_nifree--;
11893 				setbit(inosused, ino);
11894 				chgs = 1;
11895 			}
11896 			jaddref->ja_state &= ~UNDONE;
11897 			jaddref->ja_state |= ATTACHED;
11898 			free_jaddref(jaddref);
11899 		}
11900 	}
11901 	/*
11902 	 * Restore any block allocations which are pending journal writes.
11903 	 */
11904 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11905 		cgp = (struct cg *)bp->b_data;
11906 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11907 		blksfree = cg_blksfree(cgp);
11908 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11909 		    jntmp) {
11910 			if ((jnewblk->jn_state & UNDONE) == 0)
11911 				continue;
11912 			/* Do the roll-forward only if it's a real copy. */
11913 			if (foreground &&
11914 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11915 				chgs = 1;
11916 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11917 			jnewblk->jn_state |= ATTACHED;
11918 			free_jnewblk(jnewblk);
11919 		}
11920 	}
11921 	/*
11922 	 * If the write did not succeed, we have done all the roll-forward
11923 	 * operations, but we cannot take the actions that will allow its
11924 	 * dependencies to be processed.
11925 	 */
11926 	if ((flags & WRITESUCCEEDED) == 0) {
11927 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11928 		    newblk, nb_deps);
11929 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11930 		    worklist, wk_list);
11931 		if (foreground)
11932 			bdirty(bp);
11933 		return (1);
11934 	}
11935 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11936 		newblk->nb_state |= DEPCOMPLETE;
11937 		newblk->nb_state &= ~ONDEPLIST;
11938 		newblk->nb_bmsafemap = NULL;
11939 		LIST_REMOVE(newblk, nb_deps);
11940 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11941 			handle_allocdirect_partdone(
11942 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11943 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11944 			handle_allocindir_partdone(
11945 			    WK_ALLOCINDIR(&newblk->nb_list));
11946 		else if (newblk->nb_list.wk_type != D_NEWBLK)
11947 			panic("handle_written_bmsafemap: Unexpected type: %s",
11948 			    TYPENAME(newblk->nb_list.wk_type));
11949 	}
11950 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11951 		inodedep->id_state |= DEPCOMPLETE;
11952 		inodedep->id_state &= ~ONDEPLIST;
11953 		LIST_REMOVE(inodedep, id_deps);
11954 		inodedep->id_bmsafemap = NULL;
11955 	}
11956 	LIST_REMOVE(bmsafemap, sm_next);
11957 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11958 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11959 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11960 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11961 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
11962 		LIST_REMOVE(bmsafemap, sm_hash);
11963 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11964 		return (0);
11965 	}
11966 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11967 	if (foreground)
11968 		bdirty(bp);
11969 	return (1);
11970 }
11971 
11972 /*
11973  * Try to free a mkdir dependency.
11974  */
11975 static void
11976 complete_mkdir(mkdir)
11977 	struct mkdir *mkdir;
11978 {
11979 	struct diradd *dap;
11980 
11981 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11982 		return;
11983 	LIST_REMOVE(mkdir, md_mkdirs);
11984 	dap = mkdir->md_diradd;
11985 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11986 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11987 		dap->da_state |= DEPCOMPLETE;
11988 		complete_diradd(dap);
11989 	}
11990 	WORKITEM_FREE(mkdir, D_MKDIR);
11991 }
11992 
11993 /*
11994  * Handle the completion of a mkdir dependency.
11995  */
11996 static void
11997 handle_written_mkdir(mkdir, type)
11998 	struct mkdir *mkdir;
11999 	int type;
12000 {
12001 
12002 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12003 		panic("handle_written_mkdir: bad type");
12004 	mkdir->md_state |= COMPLETE;
12005 	complete_mkdir(mkdir);
12006 }
12007 
12008 static int
12009 free_pagedep(pagedep)
12010 	struct pagedep *pagedep;
12011 {
12012 	int i;
12013 
12014 	if (pagedep->pd_state & NEWBLOCK)
12015 		return (0);
12016 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12017 		return (0);
12018 	for (i = 0; i < DAHASHSZ; i++)
12019 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12020 			return (0);
12021 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12022 		return (0);
12023 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12024 		return (0);
12025 	if (pagedep->pd_state & ONWORKLIST)
12026 		WORKLIST_REMOVE(&pagedep->pd_list);
12027 	LIST_REMOVE(pagedep, pd_hash);
12028 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12029 
12030 	return (1);
12031 }
12032 
12033 /*
12034  * Called from within softdep_disk_write_complete above.
12035  * A write operation was just completed. Removed inodes can
12036  * now be freed and associated block pointers may be committed.
12037  * Note that this routine is always called from interrupt level
12038  * with further interrupts from this device blocked.
12039  *
12040  * If the write did not succeed, we will do all the roll-forward
12041  * operations, but we will not take the actions that will allow its
12042  * dependencies to be processed.
12043  */
12044 static int
12045 handle_written_filepage(pagedep, bp, flags)
12046 	struct pagedep *pagedep;
12047 	struct buf *bp;		/* buffer containing the written page */
12048 	int flags;
12049 {
12050 	struct dirrem *dirrem;
12051 	struct diradd *dap, *nextdap;
12052 	struct direct *ep;
12053 	int i, chgs;
12054 
12055 	if ((pagedep->pd_state & IOSTARTED) == 0)
12056 		panic("handle_written_filepage: not started");
12057 	pagedep->pd_state &= ~IOSTARTED;
12058 	if ((flags & WRITESUCCEEDED) == 0)
12059 		goto rollforward;
12060 	/*
12061 	 * Process any directory removals that have been committed.
12062 	 */
12063 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12064 		LIST_REMOVE(dirrem, dm_next);
12065 		dirrem->dm_state |= COMPLETE;
12066 		dirrem->dm_dirinum = pagedep->pd_ino;
12067 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12068 		    ("handle_written_filepage: Journal entries not written."));
12069 		add_to_worklist(&dirrem->dm_list, 0);
12070 	}
12071 	/*
12072 	 * Free any directory additions that have been committed.
12073 	 * If it is a newly allocated block, we have to wait until
12074 	 * the on-disk directory inode claims the new block.
12075 	 */
12076 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12077 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12078 			free_diradd(dap, NULL);
12079 rollforward:
12080 	/*
12081 	 * Uncommitted directory entries must be restored.
12082 	 */
12083 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12084 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12085 		     dap = nextdap) {
12086 			nextdap = LIST_NEXT(dap, da_pdlist);
12087 			if (dap->da_state & ATTACHED)
12088 				panic("handle_written_filepage: attached");
12089 			ep = (struct direct *)
12090 			    ((char *)bp->b_data + dap->da_offset);
12091 			ep->d_ino = dap->da_newinum;
12092 			dap->da_state &= ~UNDONE;
12093 			dap->da_state |= ATTACHED;
12094 			chgs = 1;
12095 			/*
12096 			 * If the inode referenced by the directory has
12097 			 * been written out, then the dependency can be
12098 			 * moved to the pending list.
12099 			 */
12100 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12101 				LIST_REMOVE(dap, da_pdlist);
12102 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12103 				    da_pdlist);
12104 			}
12105 		}
12106 	}
12107 	/*
12108 	 * If there were any rollbacks in the directory, then it must be
12109 	 * marked dirty so that its will eventually get written back in
12110 	 * its correct form.
12111 	 */
12112 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12113 		if ((bp->b_flags & B_DELWRI) == 0)
12114 			stat_dir_entry++;
12115 		bdirty(bp);
12116 		return (1);
12117 	}
12118 	/*
12119 	 * If we are not waiting for a new directory block to be
12120 	 * claimed by its inode, then the pagedep will be freed.
12121 	 * Otherwise it will remain to track any new entries on
12122 	 * the page in case they are fsync'ed.
12123 	 */
12124 	free_pagedep(pagedep);
12125 	return (0);
12126 }
12127 
12128 /*
12129  * Writing back in-core inode structures.
12130  *
12131  * The filesystem only accesses an inode's contents when it occupies an
12132  * "in-core" inode structure.  These "in-core" structures are separate from
12133  * the page frames used to cache inode blocks.  Only the latter are
12134  * transferred to/from the disk.  So, when the updated contents of the
12135  * "in-core" inode structure are copied to the corresponding in-memory inode
12136  * block, the dependencies are also transferred.  The following procedure is
12137  * called when copying a dirty "in-core" inode to a cached inode block.
12138  */
12139 
12140 /*
12141  * Called when an inode is loaded from disk. If the effective link count
12142  * differed from the actual link count when it was last flushed, then we
12143  * need to ensure that the correct effective link count is put back.
12144  */
12145 void
12146 softdep_load_inodeblock(ip)
12147 	struct inode *ip;	/* the "in_core" copy of the inode */
12148 {
12149 	struct inodedep *inodedep;
12150 	struct ufsmount *ump;
12151 
12152 	ump = ITOUMP(ip);
12153 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12154 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12155 	/*
12156 	 * Check for alternate nlink count.
12157 	 */
12158 	ip->i_effnlink = ip->i_nlink;
12159 	ACQUIRE_LOCK(ump);
12160 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12161 		FREE_LOCK(ump);
12162 		return;
12163 	}
12164 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12165 	FREE_LOCK(ump);
12166 }
12167 
12168 /*
12169  * This routine is called just before the "in-core" inode
12170  * information is to be copied to the in-memory inode block.
12171  * Recall that an inode block contains several inodes. If
12172  * the force flag is set, then the dependencies will be
12173  * cleared so that the update can always be made. Note that
12174  * the buffer is locked when this routine is called, so we
12175  * will never be in the middle of writing the inode block
12176  * to disk.
12177  */
12178 void
12179 softdep_update_inodeblock(ip, bp, waitfor)
12180 	struct inode *ip;	/* the "in_core" copy of the inode */
12181 	struct buf *bp;		/* the buffer containing the inode block */
12182 	int waitfor;		/* nonzero => update must be allowed */
12183 {
12184 	struct inodedep *inodedep;
12185 	struct inoref *inoref;
12186 	struct ufsmount *ump;
12187 	struct worklist *wk;
12188 	struct mount *mp;
12189 	struct buf *ibp;
12190 	struct fs *fs;
12191 	int error;
12192 
12193 	ump = ITOUMP(ip);
12194 	mp = UFSTOVFS(ump);
12195 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12196 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12197 	fs = ump->um_fs;
12198 	/*
12199 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12200 	 * does not have access to the in-core ip so must write directly into
12201 	 * the inode block buffer when setting freelink.
12202 	 */
12203 	if (fs->fs_magic == FS_UFS1_MAGIC)
12204 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12205 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12206 	else
12207 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12208 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12209 	/*
12210 	 * If the effective link count is not equal to the actual link
12211 	 * count, then we must track the difference in an inodedep while
12212 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12213 	 * if there is no existing inodedep, then there are no dependencies
12214 	 * to track.
12215 	 */
12216 	ACQUIRE_LOCK(ump);
12217 again:
12218 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12219 		FREE_LOCK(ump);
12220 		if (ip->i_effnlink != ip->i_nlink)
12221 			panic("softdep_update_inodeblock: bad link count");
12222 		return;
12223 	}
12224 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12225 		panic("softdep_update_inodeblock: bad delta");
12226 	/*
12227 	 * If we're flushing all dependencies we must also move any waiting
12228 	 * for journal writes onto the bufwait list prior to I/O.
12229 	 */
12230 	if (waitfor) {
12231 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12232 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12233 			    == DEPCOMPLETE) {
12234 				jwait(&inoref->if_list, MNT_WAIT);
12235 				goto again;
12236 			}
12237 		}
12238 	}
12239 	/*
12240 	 * Changes have been initiated. Anything depending on these
12241 	 * changes cannot occur until this inode has been written.
12242 	 */
12243 	inodedep->id_state &= ~COMPLETE;
12244 	if ((inodedep->id_state & ONWORKLIST) == 0)
12245 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12246 	/*
12247 	 * Any new dependencies associated with the incore inode must
12248 	 * now be moved to the list associated with the buffer holding
12249 	 * the in-memory copy of the inode. Once merged process any
12250 	 * allocdirects that are completed by the merger.
12251 	 */
12252 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12253 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12254 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12255 		    NULL);
12256 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12257 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12258 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12259 		    NULL);
12260 	/*
12261 	 * Now that the inode has been pushed into the buffer, the
12262 	 * operations dependent on the inode being written to disk
12263 	 * can be moved to the id_bufwait so that they will be
12264 	 * processed when the buffer I/O completes.
12265 	 */
12266 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12267 		WORKLIST_REMOVE(wk);
12268 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12269 	}
12270 	/*
12271 	 * Newly allocated inodes cannot be written until the bitmap
12272 	 * that allocates them have been written (indicated by
12273 	 * DEPCOMPLETE being set in id_state). If we are doing a
12274 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12275 	 * to be written so that the update can be done.
12276 	 */
12277 	if (waitfor == 0) {
12278 		FREE_LOCK(ump);
12279 		return;
12280 	}
12281 retry:
12282 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12283 		FREE_LOCK(ump);
12284 		return;
12285 	}
12286 	ibp = inodedep->id_bmsafemap->sm_buf;
12287 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12288 	if (ibp == NULL) {
12289 		/*
12290 		 * If ibp came back as NULL, the dependency could have been
12291 		 * freed while we slept.  Look it up again, and check to see
12292 		 * that it has completed.
12293 		 */
12294 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12295 			goto retry;
12296 		FREE_LOCK(ump);
12297 		return;
12298 	}
12299 	FREE_LOCK(ump);
12300 	if ((error = bwrite(ibp)) != 0)
12301 		softdep_error("softdep_update_inodeblock: bwrite", error);
12302 }
12303 
12304 /*
12305  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12306  * old inode dependency list (such as id_inoupdt). This routine must be
12307  * called with splbio interrupts blocked.
12308  */
12309 static void
12310 merge_inode_lists(newlisthead, oldlisthead)
12311 	struct allocdirectlst *newlisthead;
12312 	struct allocdirectlst *oldlisthead;
12313 {
12314 	struct allocdirect *listadp, *newadp;
12315 
12316 	newadp = TAILQ_FIRST(newlisthead);
12317 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12318 		if (listadp->ad_offset < newadp->ad_offset) {
12319 			listadp = TAILQ_NEXT(listadp, ad_next);
12320 			continue;
12321 		}
12322 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12323 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12324 		if (listadp->ad_offset == newadp->ad_offset) {
12325 			allocdirect_merge(oldlisthead, newadp,
12326 			    listadp);
12327 			listadp = newadp;
12328 		}
12329 		newadp = TAILQ_FIRST(newlisthead);
12330 	}
12331 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12332 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12333 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12334 	}
12335 }
12336 
12337 /*
12338  * If we are doing an fsync, then we must ensure that any directory
12339  * entries for the inode have been written after the inode gets to disk.
12340  */
12341 int
12342 softdep_fsync(vp)
12343 	struct vnode *vp;	/* the "in_core" copy of the inode */
12344 {
12345 	struct inodedep *inodedep;
12346 	struct pagedep *pagedep;
12347 	struct inoref *inoref;
12348 	struct ufsmount *ump;
12349 	struct worklist *wk;
12350 	struct diradd *dap;
12351 	struct mount *mp;
12352 	struct vnode *pvp;
12353 	struct inode *ip;
12354 	struct buf *bp;
12355 	struct fs *fs;
12356 	struct thread *td = curthread;
12357 	int error, flushparent, pagedep_new_block;
12358 	ino_t parentino;
12359 	ufs_lbn_t lbn;
12360 
12361 	ip = VTOI(vp);
12362 	mp = vp->v_mount;
12363 	ump = VFSTOUFS(mp);
12364 	fs = ump->um_fs;
12365 	if (MOUNTEDSOFTDEP(mp) == 0)
12366 		return (0);
12367 	ACQUIRE_LOCK(ump);
12368 restart:
12369 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12370 		FREE_LOCK(ump);
12371 		return (0);
12372 	}
12373 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12374 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12375 		    == DEPCOMPLETE) {
12376 			jwait(&inoref->if_list, MNT_WAIT);
12377 			goto restart;
12378 		}
12379 	}
12380 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12381 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12382 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12383 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12384 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12385 		panic("softdep_fsync: pending ops %p", inodedep);
12386 	for (error = 0, flushparent = 0; ; ) {
12387 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12388 			break;
12389 		if (wk->wk_type != D_DIRADD)
12390 			panic("softdep_fsync: Unexpected type %s",
12391 			    TYPENAME(wk->wk_type));
12392 		dap = WK_DIRADD(wk);
12393 		/*
12394 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12395 		 * dependency or is contained in a newly allocated block.
12396 		 */
12397 		if (dap->da_state & DIRCHG)
12398 			pagedep = dap->da_previous->dm_pagedep;
12399 		else
12400 			pagedep = dap->da_pagedep;
12401 		parentino = pagedep->pd_ino;
12402 		lbn = pagedep->pd_lbn;
12403 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12404 			panic("softdep_fsync: dirty");
12405 		if ((dap->da_state & MKDIR_PARENT) ||
12406 		    (pagedep->pd_state & NEWBLOCK))
12407 			flushparent = 1;
12408 		else
12409 			flushparent = 0;
12410 		/*
12411 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12412 		 * then we will not be able to release and recover the
12413 		 * vnode below, so we just have to give up on writing its
12414 		 * directory entry out. It will eventually be written, just
12415 		 * not now, but then the user was not asking to have it
12416 		 * written, so we are not breaking any promises.
12417 		 */
12418 		if (vp->v_iflag & VI_DOOMED)
12419 			break;
12420 		/*
12421 		 * We prevent deadlock by always fetching inodes from the
12422 		 * root, moving down the directory tree. Thus, when fetching
12423 		 * our parent directory, we first try to get the lock. If
12424 		 * that fails, we must unlock ourselves before requesting
12425 		 * the lock on our parent. See the comment in ufs_lookup
12426 		 * for details on possible races.
12427 		 */
12428 		FREE_LOCK(ump);
12429 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12430 		    FFSV_FORCEINSMQ)) {
12431 			error = vfs_busy(mp, MBF_NOWAIT);
12432 			if (error != 0) {
12433 				vfs_ref(mp);
12434 				VOP_UNLOCK(vp, 0);
12435 				error = vfs_busy(mp, 0);
12436 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12437 				vfs_rel(mp);
12438 				if (error != 0)
12439 					return (ENOENT);
12440 				if (vp->v_iflag & VI_DOOMED) {
12441 					vfs_unbusy(mp);
12442 					return (ENOENT);
12443 				}
12444 			}
12445 			VOP_UNLOCK(vp, 0);
12446 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12447 			    &pvp, FFSV_FORCEINSMQ);
12448 			vfs_unbusy(mp);
12449 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12450 			if (vp->v_iflag & VI_DOOMED) {
12451 				if (error == 0)
12452 					vput(pvp);
12453 				error = ENOENT;
12454 			}
12455 			if (error != 0)
12456 				return (error);
12457 		}
12458 		/*
12459 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12460 		 * that are contained in direct blocks will be resolved by
12461 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12462 		 * may require a complete sync'ing of the directory. So, we
12463 		 * try the cheap and fast ffs_update first, and if that fails,
12464 		 * then we do the slower ffs_syncvnode of the directory.
12465 		 */
12466 		if (flushparent) {
12467 			int locked;
12468 
12469 			if ((error = ffs_update(pvp, 1)) != 0) {
12470 				vput(pvp);
12471 				return (error);
12472 			}
12473 			ACQUIRE_LOCK(ump);
12474 			locked = 1;
12475 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12476 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12477 					if (wk->wk_type != D_DIRADD)
12478 						panic("softdep_fsync: Unexpected type %s",
12479 						      TYPENAME(wk->wk_type));
12480 					dap = WK_DIRADD(wk);
12481 					if (dap->da_state & DIRCHG)
12482 						pagedep = dap->da_previous->dm_pagedep;
12483 					else
12484 						pagedep = dap->da_pagedep;
12485 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12486 					FREE_LOCK(ump);
12487 					locked = 0;
12488 					if (pagedep_new_block && (error =
12489 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12490 						vput(pvp);
12491 						return (error);
12492 					}
12493 				}
12494 			}
12495 			if (locked)
12496 				FREE_LOCK(ump);
12497 		}
12498 		/*
12499 		 * Flush directory page containing the inode's name.
12500 		 */
12501 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12502 		    &bp);
12503 		if (error == 0)
12504 			error = bwrite(bp);
12505 		else
12506 			brelse(bp);
12507 		vput(pvp);
12508 		if (error != 0)
12509 			return (error);
12510 		ACQUIRE_LOCK(ump);
12511 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12512 			break;
12513 	}
12514 	FREE_LOCK(ump);
12515 	return (0);
12516 }
12517 
12518 /*
12519  * Flush all the dirty bitmaps associated with the block device
12520  * before flushing the rest of the dirty blocks so as to reduce
12521  * the number of dependencies that will have to be rolled back.
12522  *
12523  * XXX Unused?
12524  */
12525 void
12526 softdep_fsync_mountdev(vp)
12527 	struct vnode *vp;
12528 {
12529 	struct buf *bp, *nbp;
12530 	struct worklist *wk;
12531 	struct bufobj *bo;
12532 
12533 	if (!vn_isdisk(vp, NULL))
12534 		panic("softdep_fsync_mountdev: vnode not a disk");
12535 	bo = &vp->v_bufobj;
12536 restart:
12537 	BO_LOCK(bo);
12538 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12539 		/*
12540 		 * If it is already scheduled, skip to the next buffer.
12541 		 */
12542 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12543 			continue;
12544 
12545 		if ((bp->b_flags & B_DELWRI) == 0)
12546 			panic("softdep_fsync_mountdev: not dirty");
12547 		/*
12548 		 * We are only interested in bitmaps with outstanding
12549 		 * dependencies.
12550 		 */
12551 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12552 		    wk->wk_type != D_BMSAFEMAP ||
12553 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12554 			BUF_UNLOCK(bp);
12555 			continue;
12556 		}
12557 		BO_UNLOCK(bo);
12558 		bremfree(bp);
12559 		(void) bawrite(bp);
12560 		goto restart;
12561 	}
12562 	drain_output(vp);
12563 	BO_UNLOCK(bo);
12564 }
12565 
12566 /*
12567  * Sync all cylinder groups that were dirty at the time this function is
12568  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12569  * is used to flush freedep activity that may be holding up writes to a
12570  * indirect block.
12571  */
12572 static int
12573 sync_cgs(mp, waitfor)
12574 	struct mount *mp;
12575 	int waitfor;
12576 {
12577 	struct bmsafemap *bmsafemap;
12578 	struct bmsafemap *sentinel;
12579 	struct ufsmount *ump;
12580 	struct buf *bp;
12581 	int error;
12582 
12583 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12584 	sentinel->sm_cg = -1;
12585 	ump = VFSTOUFS(mp);
12586 	error = 0;
12587 	ACQUIRE_LOCK(ump);
12588 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12589 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12590 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12591 		/* Skip sentinels and cgs with no work to release. */
12592 		if (bmsafemap->sm_cg == -1 ||
12593 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12594 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12595 			LIST_REMOVE(sentinel, sm_next);
12596 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12597 			continue;
12598 		}
12599 		/*
12600 		 * If we don't get the lock and we're waiting try again, if
12601 		 * not move on to the next buf and try to sync it.
12602 		 */
12603 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12604 		if (bp == NULL && waitfor == MNT_WAIT)
12605 			continue;
12606 		LIST_REMOVE(sentinel, sm_next);
12607 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12608 		if (bp == NULL)
12609 			continue;
12610 		FREE_LOCK(ump);
12611 		if (waitfor == MNT_NOWAIT)
12612 			bawrite(bp);
12613 		else
12614 			error = bwrite(bp);
12615 		ACQUIRE_LOCK(ump);
12616 		if (error)
12617 			break;
12618 	}
12619 	LIST_REMOVE(sentinel, sm_next);
12620 	FREE_LOCK(ump);
12621 	free(sentinel, M_BMSAFEMAP);
12622 	return (error);
12623 }
12624 
12625 /*
12626  * This routine is called when we are trying to synchronously flush a
12627  * file. This routine must eliminate any filesystem metadata dependencies
12628  * so that the syncing routine can succeed.
12629  */
12630 int
12631 softdep_sync_metadata(struct vnode *vp)
12632 {
12633 	struct inode *ip;
12634 	int error;
12635 
12636 	ip = VTOI(vp);
12637 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12638 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12639 	/*
12640 	 * Ensure that any direct block dependencies have been cleared,
12641 	 * truncations are started, and inode references are journaled.
12642 	 */
12643 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12644 	/*
12645 	 * Write all journal records to prevent rollbacks on devvp.
12646 	 */
12647 	if (vp->v_type == VCHR)
12648 		softdep_flushjournal(vp->v_mount);
12649 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12650 	/*
12651 	 * Ensure that all truncates are written so we won't find deps on
12652 	 * indirect blocks.
12653 	 */
12654 	process_truncates(vp);
12655 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12656 
12657 	return (error);
12658 }
12659 
12660 /*
12661  * This routine is called when we are attempting to sync a buf with
12662  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12663  * other IO it can but returns EBUSY if the buffer is not yet able to
12664  * be written.  Dependencies which will not cause rollbacks will always
12665  * return 0.
12666  */
12667 int
12668 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12669 {
12670 	struct indirdep *indirdep;
12671 	struct pagedep *pagedep;
12672 	struct allocindir *aip;
12673 	struct newblk *newblk;
12674 	struct ufsmount *ump;
12675 	struct buf *nbp;
12676 	struct worklist *wk;
12677 	int i, error;
12678 
12679 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12680 	    ("softdep_sync_buf called on non-softdep filesystem"));
12681 	/*
12682 	 * For VCHR we just don't want to force flush any dependencies that
12683 	 * will cause rollbacks.
12684 	 */
12685 	if (vp->v_type == VCHR) {
12686 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12687 			return (EBUSY);
12688 		return (0);
12689 	}
12690 	ump = VFSTOUFS(vp->v_mount);
12691 	ACQUIRE_LOCK(ump);
12692 	/*
12693 	 * As we hold the buffer locked, none of its dependencies
12694 	 * will disappear.
12695 	 */
12696 	error = 0;
12697 top:
12698 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12699 		switch (wk->wk_type) {
12700 
12701 		case D_ALLOCDIRECT:
12702 		case D_ALLOCINDIR:
12703 			newblk = WK_NEWBLK(wk);
12704 			if (newblk->nb_jnewblk != NULL) {
12705 				if (waitfor == MNT_NOWAIT) {
12706 					error = EBUSY;
12707 					goto out_unlock;
12708 				}
12709 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12710 				goto top;
12711 			}
12712 			if (newblk->nb_state & DEPCOMPLETE ||
12713 			    waitfor == MNT_NOWAIT)
12714 				continue;
12715 			nbp = newblk->nb_bmsafemap->sm_buf;
12716 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12717 			if (nbp == NULL)
12718 				goto top;
12719 			FREE_LOCK(ump);
12720 			if ((error = bwrite(nbp)) != 0)
12721 				goto out;
12722 			ACQUIRE_LOCK(ump);
12723 			continue;
12724 
12725 		case D_INDIRDEP:
12726 			indirdep = WK_INDIRDEP(wk);
12727 			if (waitfor == MNT_NOWAIT) {
12728 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12729 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12730 					error = EBUSY;
12731 					goto out_unlock;
12732 				}
12733 			}
12734 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12735 				panic("softdep_sync_buf: truncation pending.");
12736 		restart:
12737 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12738 				newblk = (struct newblk *)aip;
12739 				if (newblk->nb_jnewblk != NULL) {
12740 					jwait(&newblk->nb_jnewblk->jn_list,
12741 					    waitfor);
12742 					goto restart;
12743 				}
12744 				if (newblk->nb_state & DEPCOMPLETE)
12745 					continue;
12746 				nbp = newblk->nb_bmsafemap->sm_buf;
12747 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12748 				if (nbp == NULL)
12749 					goto restart;
12750 				FREE_LOCK(ump);
12751 				if ((error = bwrite(nbp)) != 0)
12752 					goto out;
12753 				ACQUIRE_LOCK(ump);
12754 				goto restart;
12755 			}
12756 			continue;
12757 
12758 		case D_PAGEDEP:
12759 			/*
12760 			 * Only flush directory entries in synchronous passes.
12761 			 */
12762 			if (waitfor != MNT_WAIT) {
12763 				error = EBUSY;
12764 				goto out_unlock;
12765 			}
12766 			/*
12767 			 * While syncing snapshots, we must allow recursive
12768 			 * lookups.
12769 			 */
12770 			BUF_AREC(bp);
12771 			/*
12772 			 * We are trying to sync a directory that may
12773 			 * have dependencies on both its own metadata
12774 			 * and/or dependencies on the inodes of any
12775 			 * recently allocated files. We walk its diradd
12776 			 * lists pushing out the associated inode.
12777 			 */
12778 			pagedep = WK_PAGEDEP(wk);
12779 			for (i = 0; i < DAHASHSZ; i++) {
12780 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12781 					continue;
12782 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12783 				    &pagedep->pd_diraddhd[i]))) {
12784 					BUF_NOREC(bp);
12785 					goto out_unlock;
12786 				}
12787 			}
12788 			BUF_NOREC(bp);
12789 			continue;
12790 
12791 		case D_FREEWORK:
12792 		case D_FREEDEP:
12793 		case D_JSEGDEP:
12794 		case D_JNEWBLK:
12795 			continue;
12796 
12797 		default:
12798 			panic("softdep_sync_buf: Unknown type %s",
12799 			    TYPENAME(wk->wk_type));
12800 			/* NOTREACHED */
12801 		}
12802 	}
12803 out_unlock:
12804 	FREE_LOCK(ump);
12805 out:
12806 	return (error);
12807 }
12808 
12809 /*
12810  * Flush the dependencies associated with an inodedep.
12811  * Called with splbio blocked.
12812  */
12813 static int
12814 flush_inodedep_deps(vp, mp, ino)
12815 	struct vnode *vp;
12816 	struct mount *mp;
12817 	ino_t ino;
12818 {
12819 	struct inodedep *inodedep;
12820 	struct inoref *inoref;
12821 	struct ufsmount *ump;
12822 	int error, waitfor;
12823 
12824 	/*
12825 	 * This work is done in two passes. The first pass grabs most
12826 	 * of the buffers and begins asynchronously writing them. The
12827 	 * only way to wait for these asynchronous writes is to sleep
12828 	 * on the filesystem vnode which may stay busy for a long time
12829 	 * if the filesystem is active. So, instead, we make a second
12830 	 * pass over the dependencies blocking on each write. In the
12831 	 * usual case we will be blocking against a write that we
12832 	 * initiated, so when it is done the dependency will have been
12833 	 * resolved. Thus the second pass is expected to end quickly.
12834 	 * We give a brief window at the top of the loop to allow
12835 	 * any pending I/O to complete.
12836 	 */
12837 	ump = VFSTOUFS(mp);
12838 	LOCK_OWNED(ump);
12839 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12840 		if (error)
12841 			return (error);
12842 		FREE_LOCK(ump);
12843 		ACQUIRE_LOCK(ump);
12844 restart:
12845 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12846 			return (0);
12847 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12848 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12849 			    == DEPCOMPLETE) {
12850 				jwait(&inoref->if_list, MNT_WAIT);
12851 				goto restart;
12852 			}
12853 		}
12854 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12855 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12856 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12857 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12858 			continue;
12859 		/*
12860 		 * If pass2, we are done, otherwise do pass 2.
12861 		 */
12862 		if (waitfor == MNT_WAIT)
12863 			break;
12864 		waitfor = MNT_WAIT;
12865 	}
12866 	/*
12867 	 * Try freeing inodedep in case all dependencies have been removed.
12868 	 */
12869 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12870 		(void) free_inodedep(inodedep);
12871 	return (0);
12872 }
12873 
12874 /*
12875  * Flush an inode dependency list.
12876  * Called with splbio blocked.
12877  */
12878 static int
12879 flush_deplist(listhead, waitfor, errorp)
12880 	struct allocdirectlst *listhead;
12881 	int waitfor;
12882 	int *errorp;
12883 {
12884 	struct allocdirect *adp;
12885 	struct newblk *newblk;
12886 	struct ufsmount *ump;
12887 	struct buf *bp;
12888 
12889 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
12890 		return (0);
12891 	ump = VFSTOUFS(adp->ad_list.wk_mp);
12892 	LOCK_OWNED(ump);
12893 	TAILQ_FOREACH(adp, listhead, ad_next) {
12894 		newblk = (struct newblk *)adp;
12895 		if (newblk->nb_jnewblk != NULL) {
12896 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12897 			return (1);
12898 		}
12899 		if (newblk->nb_state & DEPCOMPLETE)
12900 			continue;
12901 		bp = newblk->nb_bmsafemap->sm_buf;
12902 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12903 		if (bp == NULL) {
12904 			if (waitfor == MNT_NOWAIT)
12905 				continue;
12906 			return (1);
12907 		}
12908 		FREE_LOCK(ump);
12909 		if (waitfor == MNT_NOWAIT)
12910 			bawrite(bp);
12911 		else
12912 			*errorp = bwrite(bp);
12913 		ACQUIRE_LOCK(ump);
12914 		return (1);
12915 	}
12916 	return (0);
12917 }
12918 
12919 /*
12920  * Flush dependencies associated with an allocdirect block.
12921  */
12922 static int
12923 flush_newblk_dep(vp, mp, lbn)
12924 	struct vnode *vp;
12925 	struct mount *mp;
12926 	ufs_lbn_t lbn;
12927 {
12928 	struct newblk *newblk;
12929 	struct ufsmount *ump;
12930 	struct bufobj *bo;
12931 	struct inode *ip;
12932 	struct buf *bp;
12933 	ufs2_daddr_t blkno;
12934 	int error;
12935 
12936 	error = 0;
12937 	bo = &vp->v_bufobj;
12938 	ip = VTOI(vp);
12939 	blkno = DIP(ip, i_db[lbn]);
12940 	if (blkno == 0)
12941 		panic("flush_newblk_dep: Missing block");
12942 	ump = VFSTOUFS(mp);
12943 	ACQUIRE_LOCK(ump);
12944 	/*
12945 	 * Loop until all dependencies related to this block are satisfied.
12946 	 * We must be careful to restart after each sleep in case a write
12947 	 * completes some part of this process for us.
12948 	 */
12949 	for (;;) {
12950 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12951 			FREE_LOCK(ump);
12952 			break;
12953 		}
12954 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12955 			panic("flush_newblk_deps: Bad newblk %p", newblk);
12956 		/*
12957 		 * Flush the journal.
12958 		 */
12959 		if (newblk->nb_jnewblk != NULL) {
12960 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12961 			continue;
12962 		}
12963 		/*
12964 		 * Write the bitmap dependency.
12965 		 */
12966 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12967 			bp = newblk->nb_bmsafemap->sm_buf;
12968 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
12969 			if (bp == NULL)
12970 				continue;
12971 			FREE_LOCK(ump);
12972 			error = bwrite(bp);
12973 			if (error)
12974 				break;
12975 			ACQUIRE_LOCK(ump);
12976 			continue;
12977 		}
12978 		/*
12979 		 * Write the buffer.
12980 		 */
12981 		FREE_LOCK(ump);
12982 		BO_LOCK(bo);
12983 		bp = gbincore(bo, lbn);
12984 		if (bp != NULL) {
12985 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12986 			    LK_INTERLOCK, BO_LOCKPTR(bo));
12987 			if (error == ENOLCK) {
12988 				ACQUIRE_LOCK(ump);
12989 				error = 0;
12990 				continue; /* Slept, retry */
12991 			}
12992 			if (error != 0)
12993 				break;	/* Failed */
12994 			if (bp->b_flags & B_DELWRI) {
12995 				bremfree(bp);
12996 				error = bwrite(bp);
12997 				if (error)
12998 					break;
12999 			} else
13000 				BUF_UNLOCK(bp);
13001 		} else
13002 			BO_UNLOCK(bo);
13003 		/*
13004 		 * We have to wait for the direct pointers to
13005 		 * point at the newdirblk before the dependency
13006 		 * will go away.
13007 		 */
13008 		error = ffs_update(vp, 1);
13009 		if (error)
13010 			break;
13011 		ACQUIRE_LOCK(ump);
13012 	}
13013 	return (error);
13014 }
13015 
13016 /*
13017  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13018  * Called with splbio blocked.
13019  */
13020 static int
13021 flush_pagedep_deps(pvp, mp, diraddhdp)
13022 	struct vnode *pvp;
13023 	struct mount *mp;
13024 	struct diraddhd *diraddhdp;
13025 {
13026 	struct inodedep *inodedep;
13027 	struct inoref *inoref;
13028 	struct ufsmount *ump;
13029 	struct diradd *dap;
13030 	struct vnode *vp;
13031 	int error = 0;
13032 	struct buf *bp;
13033 	ino_t inum;
13034 	struct diraddhd unfinished;
13035 
13036 	LIST_INIT(&unfinished);
13037 	ump = VFSTOUFS(mp);
13038 	LOCK_OWNED(ump);
13039 restart:
13040 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13041 		/*
13042 		 * Flush ourselves if this directory entry
13043 		 * has a MKDIR_PARENT dependency.
13044 		 */
13045 		if (dap->da_state & MKDIR_PARENT) {
13046 			FREE_LOCK(ump);
13047 			if ((error = ffs_update(pvp, 1)) != 0)
13048 				break;
13049 			ACQUIRE_LOCK(ump);
13050 			/*
13051 			 * If that cleared dependencies, go on to next.
13052 			 */
13053 			if (dap != LIST_FIRST(diraddhdp))
13054 				continue;
13055 			/*
13056 			 * All MKDIR_PARENT dependencies and all the
13057 			 * NEWBLOCK pagedeps that are contained in direct
13058 			 * blocks were resolved by doing above ffs_update.
13059 			 * Pagedeps contained in indirect blocks may
13060 			 * require a complete sync'ing of the directory.
13061 			 * We are in the midst of doing a complete sync,
13062 			 * so if they are not resolved in this pass we
13063 			 * defer them for now as they will be sync'ed by
13064 			 * our caller shortly.
13065 			 */
13066 			LIST_REMOVE(dap, da_pdlist);
13067 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13068 			continue;
13069 		}
13070 		/*
13071 		 * A newly allocated directory must have its "." and
13072 		 * ".." entries written out before its name can be
13073 		 * committed in its parent.
13074 		 */
13075 		inum = dap->da_newinum;
13076 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13077 			panic("flush_pagedep_deps: lost inode1");
13078 		/*
13079 		 * Wait for any pending journal adds to complete so we don't
13080 		 * cause rollbacks while syncing.
13081 		 */
13082 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13083 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13084 			    == DEPCOMPLETE) {
13085 				jwait(&inoref->if_list, MNT_WAIT);
13086 				goto restart;
13087 			}
13088 		}
13089 		if (dap->da_state & MKDIR_BODY) {
13090 			FREE_LOCK(ump);
13091 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13092 			    FFSV_FORCEINSMQ)))
13093 				break;
13094 			error = flush_newblk_dep(vp, mp, 0);
13095 			/*
13096 			 * If we still have the dependency we might need to
13097 			 * update the vnode to sync the new link count to
13098 			 * disk.
13099 			 */
13100 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13101 				error = ffs_update(vp, 1);
13102 			vput(vp);
13103 			if (error != 0)
13104 				break;
13105 			ACQUIRE_LOCK(ump);
13106 			/*
13107 			 * If that cleared dependencies, go on to next.
13108 			 */
13109 			if (dap != LIST_FIRST(diraddhdp))
13110 				continue;
13111 			if (dap->da_state & MKDIR_BODY) {
13112 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13113 				    &inodedep);
13114 				panic("flush_pagedep_deps: MKDIR_BODY "
13115 				    "inodedep %p dap %p vp %p",
13116 				    inodedep, dap, vp);
13117 			}
13118 		}
13119 		/*
13120 		 * Flush the inode on which the directory entry depends.
13121 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13122 		 * the only remaining dependency is that the updated inode
13123 		 * count must get pushed to disk. The inode has already
13124 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13125 		 * the time of the reference count change. So we need only
13126 		 * locate that buffer, ensure that there will be no rollback
13127 		 * caused by a bitmap dependency, then write the inode buffer.
13128 		 */
13129 retry:
13130 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13131 			panic("flush_pagedep_deps: lost inode");
13132 		/*
13133 		 * If the inode still has bitmap dependencies,
13134 		 * push them to disk.
13135 		 */
13136 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13137 			bp = inodedep->id_bmsafemap->sm_buf;
13138 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13139 			if (bp == NULL)
13140 				goto retry;
13141 			FREE_LOCK(ump);
13142 			if ((error = bwrite(bp)) != 0)
13143 				break;
13144 			ACQUIRE_LOCK(ump);
13145 			if (dap != LIST_FIRST(diraddhdp))
13146 				continue;
13147 		}
13148 		/*
13149 		 * If the inode is still sitting in a buffer waiting
13150 		 * to be written or waiting for the link count to be
13151 		 * adjusted update it here to flush it to disk.
13152 		 */
13153 		if (dap == LIST_FIRST(diraddhdp)) {
13154 			FREE_LOCK(ump);
13155 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13156 			    FFSV_FORCEINSMQ)))
13157 				break;
13158 			error = ffs_update(vp, 1);
13159 			vput(vp);
13160 			if (error)
13161 				break;
13162 			ACQUIRE_LOCK(ump);
13163 		}
13164 		/*
13165 		 * If we have failed to get rid of all the dependencies
13166 		 * then something is seriously wrong.
13167 		 */
13168 		if (dap == LIST_FIRST(diraddhdp)) {
13169 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13170 			panic("flush_pagedep_deps: failed to flush "
13171 			    "inodedep %p ino %ju dap %p",
13172 			    inodedep, (uintmax_t)inum, dap);
13173 		}
13174 	}
13175 	if (error)
13176 		ACQUIRE_LOCK(ump);
13177 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13178 		LIST_REMOVE(dap, da_pdlist);
13179 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13180 	}
13181 	return (error);
13182 }
13183 
13184 /*
13185  * A large burst of file addition or deletion activity can drive the
13186  * memory load excessively high. First attempt to slow things down
13187  * using the techniques below. If that fails, this routine requests
13188  * the offending operations to fall back to running synchronously
13189  * until the memory load returns to a reasonable level.
13190  */
13191 int
13192 softdep_slowdown(vp)
13193 	struct vnode *vp;
13194 {
13195 	struct ufsmount *ump;
13196 	int jlow;
13197 	int max_softdeps_hard;
13198 
13199 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13200 	    ("softdep_slowdown called on non-softdep filesystem"));
13201 	ump = VFSTOUFS(vp->v_mount);
13202 	ACQUIRE_LOCK(ump);
13203 	jlow = 0;
13204 	/*
13205 	 * Check for journal space if needed.
13206 	 */
13207 	if (DOINGSUJ(vp)) {
13208 		if (journal_space(ump, 0) == 0)
13209 			jlow = 1;
13210 	}
13211 	/*
13212 	 * If the system is under its limits and our filesystem is
13213 	 * not responsible for more than our share of the usage and
13214 	 * we are not low on journal space, then no need to slow down.
13215 	 */
13216 	max_softdeps_hard = max_softdeps * 11 / 10;
13217 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13218 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13219 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13220 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13221 	    ump->softdep_curdeps[D_DIRREM] <
13222 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13223 	    ump->softdep_curdeps[D_INODEDEP] <
13224 	    max_softdeps_hard / stat_flush_threads &&
13225 	    ump->softdep_curdeps[D_INDIRDEP] <
13226 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13227 	    ump->softdep_curdeps[D_FREEBLKS] <
13228 	    max_softdeps_hard / stat_flush_threads) {
13229 		FREE_LOCK(ump);
13230   		return (0);
13231 	}
13232 	/*
13233 	 * If the journal is low or our filesystem is over its limit
13234 	 * then speedup the cleanup.
13235 	 */
13236 	if (ump->softdep_curdeps[D_INDIRDEP] <
13237 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13238 		softdep_speedup(ump);
13239 	stat_sync_limit_hit += 1;
13240 	FREE_LOCK(ump);
13241 	/*
13242 	 * We only slow down the rate at which new dependencies are
13243 	 * generated if we are not using journaling. With journaling,
13244 	 * the cleanup should always be sufficient to keep things
13245 	 * under control.
13246 	 */
13247 	if (DOINGSUJ(vp))
13248 		return (0);
13249 	return (1);
13250 }
13251 
13252 /*
13253  * Called by the allocation routines when they are about to fail
13254  * in the hope that we can free up the requested resource (inodes
13255  * or disk space).
13256  *
13257  * First check to see if the work list has anything on it. If it has,
13258  * clean up entries until we successfully free the requested resource.
13259  * Because this process holds inodes locked, we cannot handle any remove
13260  * requests that might block on a locked inode as that could lead to
13261  * deadlock. If the worklist yields none of the requested resource,
13262  * start syncing out vnodes to free up the needed space.
13263  */
13264 int
13265 softdep_request_cleanup(fs, vp, cred, resource)
13266 	struct fs *fs;
13267 	struct vnode *vp;
13268 	struct ucred *cred;
13269 	int resource;
13270 {
13271 	struct ufsmount *ump;
13272 	struct mount *mp;
13273 	long starttime;
13274 	ufs2_daddr_t needed;
13275 	int error, failed_vnode;
13276 
13277 	/*
13278 	 * If we are being called because of a process doing a
13279 	 * copy-on-write, then it is not safe to process any
13280 	 * worklist items as we will recurse into the copyonwrite
13281 	 * routine.  This will result in an incoherent snapshot.
13282 	 * If the vnode that we hold is a snapshot, we must avoid
13283 	 * handling other resources that could cause deadlock.
13284 	 */
13285 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13286 		return (0);
13287 
13288 	if (resource == FLUSH_BLOCKS_WAIT)
13289 		stat_cleanup_blkrequests += 1;
13290 	else
13291 		stat_cleanup_inorequests += 1;
13292 
13293 	mp = vp->v_mount;
13294 	ump = VFSTOUFS(mp);
13295 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13296 	UFS_UNLOCK(ump);
13297 	error = ffs_update(vp, 1);
13298 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13299 		UFS_LOCK(ump);
13300 		return (0);
13301 	}
13302 	/*
13303 	 * If we are in need of resources, start by cleaning up
13304 	 * any block removals associated with our inode.
13305 	 */
13306 	ACQUIRE_LOCK(ump);
13307 	process_removes(vp);
13308 	process_truncates(vp);
13309 	FREE_LOCK(ump);
13310 	/*
13311 	 * Now clean up at least as many resources as we will need.
13312 	 *
13313 	 * When requested to clean up inodes, the number that are needed
13314 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13315 	 * plus a bit of slop (2) in case some more writers show up while
13316 	 * we are cleaning.
13317 	 *
13318 	 * When requested to free up space, the amount of space that
13319 	 * we need is enough blocks to allocate a full-sized segment
13320 	 * (fs_contigsumsize). The number of such segments that will
13321 	 * be needed is set by the number of simultaneous writers
13322 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13323 	 * writers show up while we are cleaning.
13324 	 *
13325 	 * Additionally, if we are unpriviledged and allocating space,
13326 	 * we need to ensure that we clean up enough blocks to get the
13327 	 * needed number of blocks over the threshold of the minimum
13328 	 * number of blocks required to be kept free by the filesystem
13329 	 * (fs_minfree).
13330 	 */
13331 	if (resource == FLUSH_INODES_WAIT) {
13332 		needed = vp->v_mount->mnt_writeopcount + 2;
13333 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13334 		needed = (vp->v_mount->mnt_writeopcount + 2) *
13335 		    fs->fs_contigsumsize;
13336 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
13337 			needed += fragstoblks(fs,
13338 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13339 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13340 	} else {
13341 		UFS_LOCK(ump);
13342 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13343 		    resource);
13344 		return (0);
13345 	}
13346 	starttime = time_second;
13347 retry:
13348 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13349 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13350 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13351 	    fs->fs_cstotal.cs_nifree <= needed)) {
13352 		ACQUIRE_LOCK(ump);
13353 		if (ump->softdep_on_worklist > 0 &&
13354 		    process_worklist_item(UFSTOVFS(ump),
13355 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13356 			stat_worklist_push += 1;
13357 		FREE_LOCK(ump);
13358 	}
13359 	/*
13360 	 * If we still need resources and there are no more worklist
13361 	 * entries to process to obtain them, we have to start flushing
13362 	 * the dirty vnodes to force the release of additional requests
13363 	 * to the worklist that we can then process to reap addition
13364 	 * resources. We walk the vnodes associated with the mount point
13365 	 * until we get the needed worklist requests that we can reap.
13366 	 *
13367 	 * If there are several threads all needing to clean the same
13368 	 * mount point, only one is allowed to walk the mount list.
13369 	 * When several threads all try to walk the same mount list,
13370 	 * they end up competing with each other and often end up in
13371 	 * livelock. This approach ensures that forward progress is
13372 	 * made at the cost of occational ENOSPC errors being returned
13373 	 * that might otherwise have been avoided.
13374 	 */
13375 	error = 1;
13376 	if ((resource == FLUSH_BLOCKS_WAIT &&
13377 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13378 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13379 	     fs->fs_cstotal.cs_nifree <= needed)) {
13380 		ACQUIRE_LOCK(ump);
13381 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13382 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13383 			FREE_LOCK(ump);
13384 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13385 			ACQUIRE_LOCK(ump);
13386 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13387 			FREE_LOCK(ump);
13388 			if (ump->softdep_on_worklist > 0) {
13389 				stat_cleanup_retries += 1;
13390 				if (!failed_vnode)
13391 					goto retry;
13392 			}
13393 		} else {
13394 			FREE_LOCK(ump);
13395 			error = 0;
13396 		}
13397 		stat_cleanup_failures += 1;
13398 	}
13399 	if (time_second - starttime > stat_cleanup_high_delay)
13400 		stat_cleanup_high_delay = time_second - starttime;
13401 	UFS_LOCK(ump);
13402 	return (error);
13403 }
13404 
13405 /*
13406  * Scan the vnodes for the specified mount point flushing out any
13407  * vnodes that can be locked without waiting. Finally, try to flush
13408  * the device associated with the mount point if it can be locked
13409  * without waiting.
13410  *
13411  * We return 0 if we were able to lock every vnode in our scan.
13412  * If we had to skip one or more vnodes, we return 1.
13413  */
13414 static int
13415 softdep_request_cleanup_flush(mp, ump)
13416 	struct mount *mp;
13417 	struct ufsmount *ump;
13418 {
13419 	struct thread *td;
13420 	struct vnode *lvp, *mvp;
13421 	int failed_vnode;
13422 
13423 	failed_vnode = 0;
13424 	td = curthread;
13425 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13426 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13427 			VI_UNLOCK(lvp);
13428 			continue;
13429 		}
13430 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13431 		    td) != 0) {
13432 			failed_vnode = 1;
13433 			continue;
13434 		}
13435 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13436 			vput(lvp);
13437 			continue;
13438 		}
13439 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13440 		vput(lvp);
13441 	}
13442 	lvp = ump->um_devvp;
13443 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13444 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13445 		VOP_UNLOCK(lvp, 0);
13446 	}
13447 	return (failed_vnode);
13448 }
13449 
13450 static bool
13451 softdep_excess_items(struct ufsmount *ump, int item)
13452 {
13453 
13454 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13455 	return (dep_current[item] > max_softdeps &&
13456 	    ump->softdep_curdeps[item] > max_softdeps /
13457 	    stat_flush_threads);
13458 }
13459 
13460 static void
13461 schedule_cleanup(struct mount *mp)
13462 {
13463 	struct ufsmount *ump;
13464 	struct thread *td;
13465 
13466 	ump = VFSTOUFS(mp);
13467 	LOCK_OWNED(ump);
13468 	FREE_LOCK(ump);
13469 	td = curthread;
13470 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13471 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13472 		/*
13473 		 * No ast is delivered to kernel threads, so nobody
13474 		 * would deref the mp.  Some kernel threads
13475 		 * explicitely check for AST, e.g. NFS daemon does
13476 		 * this in the serving loop.
13477 		 */
13478 		return;
13479 	}
13480 	if (td->td_su != NULL)
13481 		vfs_rel(td->td_su);
13482 	vfs_ref(mp);
13483 	td->td_su = mp;
13484 	thread_lock(td);
13485 	td->td_flags |= TDF_ASTPENDING;
13486 	thread_unlock(td);
13487 }
13488 
13489 static void
13490 softdep_ast_cleanup_proc(struct thread *td)
13491 {
13492 	struct mount *mp;
13493 	struct ufsmount *ump;
13494 	int error;
13495 	bool req;
13496 
13497 	while ((mp = td->td_su) != NULL) {
13498 		td->td_su = NULL;
13499 		error = vfs_busy(mp, MBF_NOWAIT);
13500 		vfs_rel(mp);
13501 		if (error != 0)
13502 			return;
13503 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13504 			ump = VFSTOUFS(mp);
13505 			for (;;) {
13506 				req = false;
13507 				ACQUIRE_LOCK(ump);
13508 				if (softdep_excess_items(ump, D_INODEDEP)) {
13509 					req = true;
13510 					request_cleanup(mp, FLUSH_INODES);
13511 				}
13512 				if (softdep_excess_items(ump, D_DIRREM)) {
13513 					req = true;
13514 					request_cleanup(mp, FLUSH_BLOCKS);
13515 				}
13516 				FREE_LOCK(ump);
13517 				if (softdep_excess_items(ump, D_NEWBLK) ||
13518 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13519 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13520 					error = vn_start_write(NULL, &mp,
13521 					    V_WAIT);
13522 					if (error == 0) {
13523 						req = true;
13524 						VFS_SYNC(mp, MNT_WAIT);
13525 						vn_finished_write(mp);
13526 					}
13527 				}
13528 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13529 					break;
13530 			}
13531 		}
13532 		vfs_unbusy(mp);
13533 	}
13534 	if ((mp = td->td_su) != NULL) {
13535 		td->td_su = NULL;
13536 		vfs_rel(mp);
13537 	}
13538 }
13539 
13540 /*
13541  * If memory utilization has gotten too high, deliberately slow things
13542  * down and speed up the I/O processing.
13543  */
13544 static int
13545 request_cleanup(mp, resource)
13546 	struct mount *mp;
13547 	int resource;
13548 {
13549 	struct thread *td = curthread;
13550 	struct ufsmount *ump;
13551 
13552 	ump = VFSTOUFS(mp);
13553 	LOCK_OWNED(ump);
13554 	/*
13555 	 * We never hold up the filesystem syncer or buf daemon.
13556 	 */
13557 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13558 		return (0);
13559 	/*
13560 	 * First check to see if the work list has gotten backlogged.
13561 	 * If it has, co-opt this process to help clean up two entries.
13562 	 * Because this process may hold inodes locked, we cannot
13563 	 * handle any remove requests that might block on a locked
13564 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13565 	 * to avoid recursively processing the worklist.
13566 	 */
13567 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13568 		td->td_pflags |= TDP_SOFTDEP;
13569 		process_worklist_item(mp, 2, LK_NOWAIT);
13570 		td->td_pflags &= ~TDP_SOFTDEP;
13571 		stat_worklist_push += 2;
13572 		return(1);
13573 	}
13574 	/*
13575 	 * Next, we attempt to speed up the syncer process. If that
13576 	 * is successful, then we allow the process to continue.
13577 	 */
13578 	if (softdep_speedup(ump) &&
13579 	    resource != FLUSH_BLOCKS_WAIT &&
13580 	    resource != FLUSH_INODES_WAIT)
13581 		return(0);
13582 	/*
13583 	 * If we are resource constrained on inode dependencies, try
13584 	 * flushing some dirty inodes. Otherwise, we are constrained
13585 	 * by file deletions, so try accelerating flushes of directories
13586 	 * with removal dependencies. We would like to do the cleanup
13587 	 * here, but we probably hold an inode locked at this point and
13588 	 * that might deadlock against one that we try to clean. So,
13589 	 * the best that we can do is request the syncer daemon to do
13590 	 * the cleanup for us.
13591 	 */
13592 	switch (resource) {
13593 
13594 	case FLUSH_INODES:
13595 	case FLUSH_INODES_WAIT:
13596 		ACQUIRE_GBLLOCK(&lk);
13597 		stat_ino_limit_push += 1;
13598 		req_clear_inodedeps += 1;
13599 		FREE_GBLLOCK(&lk);
13600 		stat_countp = &stat_ino_limit_hit;
13601 		break;
13602 
13603 	case FLUSH_BLOCKS:
13604 	case FLUSH_BLOCKS_WAIT:
13605 		ACQUIRE_GBLLOCK(&lk);
13606 		stat_blk_limit_push += 1;
13607 		req_clear_remove += 1;
13608 		FREE_GBLLOCK(&lk);
13609 		stat_countp = &stat_blk_limit_hit;
13610 		break;
13611 
13612 	default:
13613 		panic("request_cleanup: unknown type");
13614 	}
13615 	/*
13616 	 * Hopefully the syncer daemon will catch up and awaken us.
13617 	 * We wait at most tickdelay before proceeding in any case.
13618 	 */
13619 	ACQUIRE_GBLLOCK(&lk);
13620 	FREE_LOCK(ump);
13621 	proc_waiting += 1;
13622 	if (callout_pending(&softdep_callout) == FALSE)
13623 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13624 		    pause_timer, 0);
13625 
13626 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13627 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13628 	proc_waiting -= 1;
13629 	FREE_GBLLOCK(&lk);
13630 	ACQUIRE_LOCK(ump);
13631 	return (1);
13632 }
13633 
13634 /*
13635  * Awaken processes pausing in request_cleanup and clear proc_waiting
13636  * to indicate that there is no longer a timer running. Pause_timer
13637  * will be called with the global softdep mutex (&lk) locked.
13638  */
13639 static void
13640 pause_timer(arg)
13641 	void *arg;
13642 {
13643 
13644 	GBLLOCK_OWNED(&lk);
13645 	/*
13646 	 * The callout_ API has acquired mtx and will hold it around this
13647 	 * function call.
13648 	 */
13649 	*stat_countp += proc_waiting;
13650 	wakeup(&proc_waiting);
13651 }
13652 
13653 /*
13654  * If requested, try removing inode or removal dependencies.
13655  */
13656 static void
13657 check_clear_deps(mp)
13658 	struct mount *mp;
13659 {
13660 
13661 	/*
13662 	 * If we are suspended, it may be because of our using
13663 	 * too many inodedeps, so help clear them out.
13664 	 */
13665 	if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13666 		clear_inodedeps(mp);
13667 	/*
13668 	 * General requests for cleanup of backed up dependencies
13669 	 */
13670 	ACQUIRE_GBLLOCK(&lk);
13671 	if (req_clear_inodedeps) {
13672 		req_clear_inodedeps -= 1;
13673 		FREE_GBLLOCK(&lk);
13674 		clear_inodedeps(mp);
13675 		ACQUIRE_GBLLOCK(&lk);
13676 		wakeup(&proc_waiting);
13677 	}
13678 	if (req_clear_remove) {
13679 		req_clear_remove -= 1;
13680 		FREE_GBLLOCK(&lk);
13681 		clear_remove(mp);
13682 		ACQUIRE_GBLLOCK(&lk);
13683 		wakeup(&proc_waiting);
13684 	}
13685 	FREE_GBLLOCK(&lk);
13686 }
13687 
13688 /*
13689  * Flush out a directory with at least one removal dependency in an effort to
13690  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13691  */
13692 static void
13693 clear_remove(mp)
13694 	struct mount *mp;
13695 {
13696 	struct pagedep_hashhead *pagedephd;
13697 	struct pagedep *pagedep;
13698 	struct ufsmount *ump;
13699 	struct vnode *vp;
13700 	struct bufobj *bo;
13701 	int error, cnt;
13702 	ino_t ino;
13703 
13704 	ump = VFSTOUFS(mp);
13705 	LOCK_OWNED(ump);
13706 
13707 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13708 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13709 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13710 			ump->pagedep_nextclean = 0;
13711 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13712 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13713 				continue;
13714 			ino = pagedep->pd_ino;
13715 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13716 				continue;
13717 			FREE_LOCK(ump);
13718 
13719 			/*
13720 			 * Let unmount clear deps
13721 			 */
13722 			error = vfs_busy(mp, MBF_NOWAIT);
13723 			if (error != 0)
13724 				goto finish_write;
13725 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13726 			     FFSV_FORCEINSMQ);
13727 			vfs_unbusy(mp);
13728 			if (error != 0) {
13729 				softdep_error("clear_remove: vget", error);
13730 				goto finish_write;
13731 			}
13732 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13733 				softdep_error("clear_remove: fsync", error);
13734 			bo = &vp->v_bufobj;
13735 			BO_LOCK(bo);
13736 			drain_output(vp);
13737 			BO_UNLOCK(bo);
13738 			vput(vp);
13739 		finish_write:
13740 			vn_finished_write(mp);
13741 			ACQUIRE_LOCK(ump);
13742 			return;
13743 		}
13744 	}
13745 }
13746 
13747 /*
13748  * Clear out a block of dirty inodes in an effort to reduce
13749  * the number of inodedep dependency structures.
13750  */
13751 static void
13752 clear_inodedeps(mp)
13753 	struct mount *mp;
13754 {
13755 	struct inodedep_hashhead *inodedephd;
13756 	struct inodedep *inodedep;
13757 	struct ufsmount *ump;
13758 	struct vnode *vp;
13759 	struct fs *fs;
13760 	int error, cnt;
13761 	ino_t firstino, lastino, ino;
13762 
13763 	ump = VFSTOUFS(mp);
13764 	fs = ump->um_fs;
13765 	LOCK_OWNED(ump);
13766 	/*
13767 	 * Pick a random inode dependency to be cleared.
13768 	 * We will then gather up all the inodes in its block
13769 	 * that have dependencies and flush them out.
13770 	 */
13771 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13772 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13773 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13774 			ump->inodedep_nextclean = 0;
13775 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13776 			break;
13777 	}
13778 	if (inodedep == NULL)
13779 		return;
13780 	/*
13781 	 * Find the last inode in the block with dependencies.
13782 	 */
13783 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13784 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13785 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13786 			break;
13787 	/*
13788 	 * Asynchronously push all but the last inode with dependencies.
13789 	 * Synchronously push the last inode with dependencies to ensure
13790 	 * that the inode block gets written to free up the inodedeps.
13791 	 */
13792 	for (ino = firstino; ino <= lastino; ino++) {
13793 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13794 			continue;
13795 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13796 			continue;
13797 		FREE_LOCK(ump);
13798 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13799 		if (error != 0) {
13800 			vn_finished_write(mp);
13801 			ACQUIRE_LOCK(ump);
13802 			return;
13803 		}
13804 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13805 		    FFSV_FORCEINSMQ)) != 0) {
13806 			softdep_error("clear_inodedeps: vget", error);
13807 			vfs_unbusy(mp);
13808 			vn_finished_write(mp);
13809 			ACQUIRE_LOCK(ump);
13810 			return;
13811 		}
13812 		vfs_unbusy(mp);
13813 		if (ino == lastino) {
13814 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13815 				softdep_error("clear_inodedeps: fsync1", error);
13816 		} else {
13817 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13818 				softdep_error("clear_inodedeps: fsync2", error);
13819 			BO_LOCK(&vp->v_bufobj);
13820 			drain_output(vp);
13821 			BO_UNLOCK(&vp->v_bufobj);
13822 		}
13823 		vput(vp);
13824 		vn_finished_write(mp);
13825 		ACQUIRE_LOCK(ump);
13826 	}
13827 }
13828 
13829 void
13830 softdep_buf_append(bp, wkhd)
13831 	struct buf *bp;
13832 	struct workhead *wkhd;
13833 {
13834 	struct worklist *wk;
13835 	struct ufsmount *ump;
13836 
13837 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13838 		return;
13839 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13840 	    ("softdep_buf_append called on non-softdep filesystem"));
13841 	ump = VFSTOUFS(wk->wk_mp);
13842 	ACQUIRE_LOCK(ump);
13843 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13844 		WORKLIST_REMOVE(wk);
13845 		WORKLIST_INSERT(&bp->b_dep, wk);
13846 	}
13847 	FREE_LOCK(ump);
13848 
13849 }
13850 
13851 void
13852 softdep_inode_append(ip, cred, wkhd)
13853 	struct inode *ip;
13854 	struct ucred *cred;
13855 	struct workhead *wkhd;
13856 {
13857 	struct buf *bp;
13858 	struct fs *fs;
13859 	struct ufsmount *ump;
13860 	int error;
13861 
13862 	ump = ITOUMP(ip);
13863 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13864 	    ("softdep_inode_append called on non-softdep filesystem"));
13865 	fs = ump->um_fs;
13866 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13867 	    (int)fs->fs_bsize, cred, &bp);
13868 	if (error) {
13869 		bqrelse(bp);
13870 		softdep_freework(wkhd);
13871 		return;
13872 	}
13873 	softdep_buf_append(bp, wkhd);
13874 	bqrelse(bp);
13875 }
13876 
13877 void
13878 softdep_freework(wkhd)
13879 	struct workhead *wkhd;
13880 {
13881 	struct worklist *wk;
13882 	struct ufsmount *ump;
13883 
13884 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13885 		return;
13886 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13887 	    ("softdep_freework called on non-softdep filesystem"));
13888 	ump = VFSTOUFS(wk->wk_mp);
13889 	ACQUIRE_LOCK(ump);
13890 	handle_jwork(wkhd);
13891 	FREE_LOCK(ump);
13892 }
13893 
13894 /*
13895  * Function to determine if the buffer has outstanding dependencies
13896  * that will cause a roll-back if the buffer is written. If wantcount
13897  * is set, return number of dependencies, otherwise just yes or no.
13898  */
13899 static int
13900 softdep_count_dependencies(bp, wantcount)
13901 	struct buf *bp;
13902 	int wantcount;
13903 {
13904 	struct worklist *wk;
13905 	struct ufsmount *ump;
13906 	struct bmsafemap *bmsafemap;
13907 	struct freework *freework;
13908 	struct inodedep *inodedep;
13909 	struct indirdep *indirdep;
13910 	struct freeblks *freeblks;
13911 	struct allocindir *aip;
13912 	struct pagedep *pagedep;
13913 	struct dirrem *dirrem;
13914 	struct newblk *newblk;
13915 	struct mkdir *mkdir;
13916 	struct diradd *dap;
13917 	struct vnode *vp;
13918 	struct mount *mp;
13919 	int i, retval;
13920 
13921 	retval = 0;
13922 	if (LIST_EMPTY(&bp->b_dep))
13923 		return (0);
13924 	vp = bp->b_vp;
13925 
13926 	/*
13927 	 * The ump mount point is stable after we get a correct
13928 	 * pointer, since bp is locked and this prevents unmount from
13929 	 * proceed.  But to get to it, we cannot dereference bp->b_dep
13930 	 * head wk_mp, because we do not yet own SU ump lock and
13931 	 * workitem might be freed while dereferenced.
13932 	 */
13933 retry:
13934 	if (vp->v_type == VCHR) {
13935 		VI_LOCK(vp);
13936 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
13937 		VI_UNLOCK(vp);
13938 		if (mp == NULL)
13939 			goto retry;
13940 	} else if (vp->v_type == VREG) {
13941 		mp = vp->v_mount;
13942 	} else {
13943 		return (0);
13944 	}
13945 	ump = VFSTOUFS(mp);
13946 
13947 	ACQUIRE_LOCK(ump);
13948 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13949 		switch (wk->wk_type) {
13950 
13951 		case D_INODEDEP:
13952 			inodedep = WK_INODEDEP(wk);
13953 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13954 				/* bitmap allocation dependency */
13955 				retval += 1;
13956 				if (!wantcount)
13957 					goto out;
13958 			}
13959 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13960 				/* direct block pointer dependency */
13961 				retval += 1;
13962 				if (!wantcount)
13963 					goto out;
13964 			}
13965 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13966 				/* direct block pointer dependency */
13967 				retval += 1;
13968 				if (!wantcount)
13969 					goto out;
13970 			}
13971 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13972 				/* Add reference dependency. */
13973 				retval += 1;
13974 				if (!wantcount)
13975 					goto out;
13976 			}
13977 			continue;
13978 
13979 		case D_INDIRDEP:
13980 			indirdep = WK_INDIRDEP(wk);
13981 
13982 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
13983 				/* indirect truncation dependency */
13984 				retval += 1;
13985 				if (!wantcount)
13986 					goto out;
13987 			}
13988 
13989 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13990 				/* indirect block pointer dependency */
13991 				retval += 1;
13992 				if (!wantcount)
13993 					goto out;
13994 			}
13995 			continue;
13996 
13997 		case D_PAGEDEP:
13998 			pagedep = WK_PAGEDEP(wk);
13999 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14000 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14001 					/* Journal remove ref dependency. */
14002 					retval += 1;
14003 					if (!wantcount)
14004 						goto out;
14005 				}
14006 			}
14007 			for (i = 0; i < DAHASHSZ; i++) {
14008 
14009 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14010 					/* directory entry dependency */
14011 					retval += 1;
14012 					if (!wantcount)
14013 						goto out;
14014 				}
14015 			}
14016 			continue;
14017 
14018 		case D_BMSAFEMAP:
14019 			bmsafemap = WK_BMSAFEMAP(wk);
14020 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14021 				/* Add reference dependency. */
14022 				retval += 1;
14023 				if (!wantcount)
14024 					goto out;
14025 			}
14026 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14027 				/* Allocate block dependency. */
14028 				retval += 1;
14029 				if (!wantcount)
14030 					goto out;
14031 			}
14032 			continue;
14033 
14034 		case D_FREEBLKS:
14035 			freeblks = WK_FREEBLKS(wk);
14036 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14037 				/* Freeblk journal dependency. */
14038 				retval += 1;
14039 				if (!wantcount)
14040 					goto out;
14041 			}
14042 			continue;
14043 
14044 		case D_ALLOCDIRECT:
14045 		case D_ALLOCINDIR:
14046 			newblk = WK_NEWBLK(wk);
14047 			if (newblk->nb_jnewblk) {
14048 				/* Journal allocate dependency. */
14049 				retval += 1;
14050 				if (!wantcount)
14051 					goto out;
14052 			}
14053 			continue;
14054 
14055 		case D_MKDIR:
14056 			mkdir = WK_MKDIR(wk);
14057 			if (mkdir->md_jaddref) {
14058 				/* Journal reference dependency. */
14059 				retval += 1;
14060 				if (!wantcount)
14061 					goto out;
14062 			}
14063 			continue;
14064 
14065 		case D_FREEWORK:
14066 		case D_FREEDEP:
14067 		case D_JSEGDEP:
14068 		case D_JSEG:
14069 		case D_SBDEP:
14070 			/* never a dependency on these blocks */
14071 			continue;
14072 
14073 		default:
14074 			panic("softdep_count_dependencies: Unexpected type %s",
14075 			    TYPENAME(wk->wk_type));
14076 			/* NOTREACHED */
14077 		}
14078 	}
14079 out:
14080 	FREE_LOCK(ump);
14081 	return (retval);
14082 }
14083 
14084 /*
14085  * Acquire exclusive access to a buffer.
14086  * Must be called with a locked mtx parameter.
14087  * Return acquired buffer or NULL on failure.
14088  */
14089 static struct buf *
14090 getdirtybuf(bp, lock, waitfor)
14091 	struct buf *bp;
14092 	struct rwlock *lock;
14093 	int waitfor;
14094 {
14095 	int error;
14096 
14097 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14098 		if (waitfor != MNT_WAIT)
14099 			return (NULL);
14100 		error = BUF_LOCK(bp,
14101 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14102 		/*
14103 		 * Even if we successfully acquire bp here, we have dropped
14104 		 * lock, which may violates our guarantee.
14105 		 */
14106 		if (error == 0)
14107 			BUF_UNLOCK(bp);
14108 		else if (error != ENOLCK)
14109 			panic("getdirtybuf: inconsistent lock: %d", error);
14110 		rw_wlock(lock);
14111 		return (NULL);
14112 	}
14113 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14114 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14115 			rw_wunlock(lock);
14116 			BO_LOCK(bp->b_bufobj);
14117 			BUF_UNLOCK(bp);
14118 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14119 				bp->b_vflags |= BV_BKGRDWAIT;
14120 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14121 				       PRIBIO | PDROP, "getbuf", 0);
14122 			} else
14123 				BO_UNLOCK(bp->b_bufobj);
14124 			rw_wlock(lock);
14125 			return (NULL);
14126 		}
14127 		BUF_UNLOCK(bp);
14128 		if (waitfor != MNT_WAIT)
14129 			return (NULL);
14130 #ifdef DEBUG_VFS_LOCKS
14131 		if (bp->b_vp->v_type != VCHR)
14132 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14133 #endif
14134 		bp->b_vflags |= BV_BKGRDWAIT;
14135 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14136 		return (NULL);
14137 	}
14138 	if ((bp->b_flags & B_DELWRI) == 0) {
14139 		BUF_UNLOCK(bp);
14140 		return (NULL);
14141 	}
14142 	bremfree(bp);
14143 	return (bp);
14144 }
14145 
14146 
14147 /*
14148  * Check if it is safe to suspend the file system now.  On entry,
14149  * the vnode interlock for devvp should be held.  Return 0 with
14150  * the mount interlock held if the file system can be suspended now,
14151  * otherwise return EAGAIN with the mount interlock held.
14152  */
14153 int
14154 softdep_check_suspend(struct mount *mp,
14155 		      struct vnode *devvp,
14156 		      int softdep_depcnt,
14157 		      int softdep_accdepcnt,
14158 		      int secondary_writes,
14159 		      int secondary_accwrites)
14160 {
14161 	struct bufobj *bo;
14162 	struct ufsmount *ump;
14163 	struct inodedep *inodedep;
14164 	int error, unlinked;
14165 
14166 	bo = &devvp->v_bufobj;
14167 	ASSERT_BO_WLOCKED(bo);
14168 
14169 	/*
14170 	 * If we are not running with soft updates, then we need only
14171 	 * deal with secondary writes as we try to suspend.
14172 	 */
14173 	if (MOUNTEDSOFTDEP(mp) == 0) {
14174 		MNT_ILOCK(mp);
14175 		while (mp->mnt_secondary_writes != 0) {
14176 			BO_UNLOCK(bo);
14177 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14178 			    (PUSER - 1) | PDROP, "secwr", 0);
14179 			BO_LOCK(bo);
14180 			MNT_ILOCK(mp);
14181 		}
14182 
14183 		/*
14184 		 * Reasons for needing more work before suspend:
14185 		 * - Dirty buffers on devvp.
14186 		 * - Secondary writes occurred after start of vnode sync loop
14187 		 */
14188 		error = 0;
14189 		if (bo->bo_numoutput > 0 ||
14190 		    bo->bo_dirty.bv_cnt > 0 ||
14191 		    secondary_writes != 0 ||
14192 		    mp->mnt_secondary_writes != 0 ||
14193 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14194 			error = EAGAIN;
14195 		BO_UNLOCK(bo);
14196 		return (error);
14197 	}
14198 
14199 	/*
14200 	 * If we are running with soft updates, then we need to coordinate
14201 	 * with them as we try to suspend.
14202 	 */
14203 	ump = VFSTOUFS(mp);
14204 	for (;;) {
14205 		if (!TRY_ACQUIRE_LOCK(ump)) {
14206 			BO_UNLOCK(bo);
14207 			ACQUIRE_LOCK(ump);
14208 			FREE_LOCK(ump);
14209 			BO_LOCK(bo);
14210 			continue;
14211 		}
14212 		MNT_ILOCK(mp);
14213 		if (mp->mnt_secondary_writes != 0) {
14214 			FREE_LOCK(ump);
14215 			BO_UNLOCK(bo);
14216 			msleep(&mp->mnt_secondary_writes,
14217 			       MNT_MTX(mp),
14218 			       (PUSER - 1) | PDROP, "secwr", 0);
14219 			BO_LOCK(bo);
14220 			continue;
14221 		}
14222 		break;
14223 	}
14224 
14225 	unlinked = 0;
14226 	if (MOUNTEDSUJ(mp)) {
14227 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14228 		    inodedep != NULL;
14229 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14230 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14231 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14232 			    UNLINKONLIST) ||
14233 			    !check_inodedep_free(inodedep))
14234 				continue;
14235 			unlinked++;
14236 		}
14237 	}
14238 
14239 	/*
14240 	 * Reasons for needing more work before suspend:
14241 	 * - Dirty buffers on devvp.
14242 	 * - Softdep activity occurred after start of vnode sync loop
14243 	 * - Secondary writes occurred after start of vnode sync loop
14244 	 */
14245 	error = 0;
14246 	if (bo->bo_numoutput > 0 ||
14247 	    bo->bo_dirty.bv_cnt > 0 ||
14248 	    softdep_depcnt != unlinked ||
14249 	    ump->softdep_deps != unlinked ||
14250 	    softdep_accdepcnt != ump->softdep_accdeps ||
14251 	    secondary_writes != 0 ||
14252 	    mp->mnt_secondary_writes != 0 ||
14253 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14254 		error = EAGAIN;
14255 	FREE_LOCK(ump);
14256 	BO_UNLOCK(bo);
14257 	return (error);
14258 }
14259 
14260 
14261 /*
14262  * Get the number of dependency structures for the file system, both
14263  * the current number and the total number allocated.  These will
14264  * later be used to detect that softdep processing has occurred.
14265  */
14266 void
14267 softdep_get_depcounts(struct mount *mp,
14268 		      int *softdep_depsp,
14269 		      int *softdep_accdepsp)
14270 {
14271 	struct ufsmount *ump;
14272 
14273 	if (MOUNTEDSOFTDEP(mp) == 0) {
14274 		*softdep_depsp = 0;
14275 		*softdep_accdepsp = 0;
14276 		return;
14277 	}
14278 	ump = VFSTOUFS(mp);
14279 	ACQUIRE_LOCK(ump);
14280 	*softdep_depsp = ump->softdep_deps;
14281 	*softdep_accdepsp = ump->softdep_accdeps;
14282 	FREE_LOCK(ump);
14283 }
14284 
14285 /*
14286  * Wait for pending output on a vnode to complete.
14287  */
14288 static void
14289 drain_output(vp)
14290 	struct vnode *vp;
14291 {
14292 
14293 	ASSERT_VOP_LOCKED(vp, "drain_output");
14294 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14295 }
14296 
14297 /*
14298  * Called whenever a buffer that is being invalidated or reallocated
14299  * contains dependencies. This should only happen if an I/O error has
14300  * occurred. The routine is called with the buffer locked.
14301  */
14302 static void
14303 softdep_deallocate_dependencies(bp)
14304 	struct buf *bp;
14305 {
14306 
14307 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14308 		panic("softdep_deallocate_dependencies: dangling deps");
14309 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14310 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14311 	else
14312 		printf("softdep_deallocate_dependencies: "
14313 		    "got error %d while accessing filesystem\n", bp->b_error);
14314 	if (bp->b_error != ENXIO)
14315 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14316 }
14317 
14318 /*
14319  * Function to handle asynchronous write errors in the filesystem.
14320  */
14321 static void
14322 softdep_error(func, error)
14323 	char *func;
14324 	int error;
14325 {
14326 
14327 	/* XXX should do something better! */
14328 	printf("%s: got error %d while accessing filesystem\n", func, error);
14329 }
14330 
14331 #ifdef DDB
14332 
14333 static void
14334 inodedep_print(struct inodedep *inodedep, int verbose)
14335 {
14336 	db_printf("%p fs %p st %x ino %jd inoblk %jd delta %jd nlink %jd"
14337 	    " saveino %p\n",
14338 	    inodedep, inodedep->id_fs, inodedep->id_state,
14339 	    (intmax_t)inodedep->id_ino,
14340 	    (intmax_t)fsbtodb(inodedep->id_fs,
14341 	    ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14342 	    (intmax_t)inodedep->id_nlinkdelta,
14343 	    (intmax_t)inodedep->id_savednlink,
14344 	    inodedep->id_savedino1);
14345 
14346 	if (verbose == 0)
14347 		return;
14348 
14349 	db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
14350 	    "mkdiradd %p\n",
14351 	    LIST_FIRST(&inodedep->id_pendinghd),
14352 	    LIST_FIRST(&inodedep->id_bufwait),
14353 	    LIST_FIRST(&inodedep->id_inowait),
14354 	    TAILQ_FIRST(&inodedep->id_inoreflst),
14355 	    inodedep->id_mkdiradd);
14356 	db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
14357 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14358 	    TAILQ_FIRST(&inodedep->id_newinoupdt),
14359 	    TAILQ_FIRST(&inodedep->id_extupdt),
14360 	    TAILQ_FIRST(&inodedep->id_newextupdt));
14361 }
14362 
14363 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
14364 {
14365 
14366 	if (have_addr == 0) {
14367 		db_printf("Address required\n");
14368 		return;
14369 	}
14370 	inodedep_print((struct inodedep*)addr, 1);
14371 }
14372 
14373 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
14374 {
14375 	struct inodedep_hashhead *inodedephd;
14376 	struct inodedep *inodedep;
14377 	struct ufsmount *ump;
14378 	int cnt;
14379 
14380 	if (have_addr == 0) {
14381 		db_printf("Address required\n");
14382 		return;
14383 	}
14384 	ump = (struct ufsmount *)addr;
14385 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14386 		inodedephd = &ump->inodedep_hashtbl[cnt];
14387 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14388 			inodedep_print(inodedep, 0);
14389 		}
14390 	}
14391 }
14392 
14393 DB_SHOW_COMMAND(worklist, db_show_worklist)
14394 {
14395 	struct worklist *wk;
14396 
14397 	if (have_addr == 0) {
14398 		db_printf("Address required\n");
14399 		return;
14400 	}
14401 	wk = (struct worklist *)addr;
14402 	printf("worklist: %p type %s state 0x%X\n",
14403 	    wk, TYPENAME(wk->wk_type), wk->wk_state);
14404 }
14405 
14406 DB_SHOW_COMMAND(workhead, db_show_workhead)
14407 {
14408 	struct workhead *wkhd;
14409 	struct worklist *wk;
14410 	int i;
14411 
14412 	if (have_addr == 0) {
14413 		db_printf("Address required\n");
14414 		return;
14415 	}
14416 	wkhd = (struct workhead *)addr;
14417 	wk = LIST_FIRST(wkhd);
14418 	for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
14419 		db_printf("worklist: %p type %s state 0x%X",
14420 		    wk, TYPENAME(wk->wk_type), wk->wk_state);
14421 	if (i == 100)
14422 		db_printf("workhead overflow");
14423 	printf("\n");
14424 }
14425 
14426 
14427 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
14428 {
14429 	struct mkdirlist *mkdirlisthd;
14430 	struct jaddref *jaddref;
14431 	struct diradd *diradd;
14432 	struct mkdir *mkdir;
14433 
14434 	if (have_addr == 0) {
14435 		db_printf("Address required\n");
14436 		return;
14437 	}
14438 	mkdirlisthd = (struct mkdirlist *)addr;
14439 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14440 		diradd = mkdir->md_diradd;
14441 		db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
14442 		    mkdir, mkdir->md_state, diradd, diradd->da_state);
14443 		if ((jaddref = mkdir->md_jaddref) != NULL)
14444 			db_printf(" jaddref %p jaddref state 0x%X",
14445 			    jaddref, jaddref->ja_state);
14446 		db_printf("\n");
14447 	}
14448 }
14449 
14450 /* exported to ffs_vfsops.c */
14451 extern void db_print_ffs(struct ufsmount *ump);
14452 void
14453 db_print_ffs(struct ufsmount *ump)
14454 {
14455 	db_printf("mp %p %s devvp %p fs %p su_wl %d su_deps %d su_req %d\n",
14456 	    ump->um_mountp, ump->um_mountp->mnt_stat.f_mntonname,
14457 	    ump->um_devvp, ump->um_fs, ump->softdep_on_worklist,
14458 	    ump->softdep_deps, ump->softdep_req);
14459 }
14460 
14461 #endif /* DDB */
14462 
14463 #endif /* SOFTUPDATES */
14464