xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 1f4bcc459a76b7aa664f3fd557684cd0ba6da352)
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/rwlock.h>
73 #include <sys/stat.h>
74 #include <sys/sysctl.h>
75 #include <sys/syslog.h>
76 #include <sys/vnode.h>
77 #include <sys/conf.h>
78 
79 #include <ufs/ufs/dir.h>
80 #include <ufs/ufs/extattr.h>
81 #include <ufs/ufs/quota.h>
82 #include <ufs/ufs/inode.h>
83 #include <ufs/ufs/ufsmount.h>
84 #include <ufs/ffs/fs.h>
85 #include <ufs/ffs/softdep.h>
86 #include <ufs/ffs/ffs_extern.h>
87 #include <ufs/ufs/ufs_extern.h>
88 
89 #include <vm/vm.h>
90 #include <vm/vm_extern.h>
91 #include <vm/vm_object.h>
92 
93 #include <geom/geom.h>
94 
95 #include <ddb/ddb.h>
96 
97 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
98 
99 #ifndef SOFTUPDATES
100 
101 int
102 softdep_flushfiles(oldmnt, flags, td)
103 	struct mount *oldmnt;
104 	int flags;
105 	struct thread *td;
106 {
107 
108 	panic("softdep_flushfiles called");
109 }
110 
111 int
112 softdep_mount(devvp, mp, fs, cred)
113 	struct vnode *devvp;
114 	struct mount *mp;
115 	struct fs *fs;
116 	struct ucred *cred;
117 {
118 
119 	return (0);
120 }
121 
122 void
123 softdep_initialize()
124 {
125 
126 	return;
127 }
128 
129 void
130 softdep_uninitialize()
131 {
132 
133 	return;
134 }
135 
136 void
137 softdep_unmount(mp)
138 	struct mount *mp;
139 {
140 
141 	panic("softdep_unmount called");
142 }
143 
144 void
145 softdep_setup_sbupdate(ump, fs, bp)
146 	struct ufsmount *ump;
147 	struct fs *fs;
148 	struct buf *bp;
149 {
150 
151 	panic("softdep_setup_sbupdate called");
152 }
153 
154 void
155 softdep_setup_inomapdep(bp, ip, newinum, mode)
156 	struct buf *bp;
157 	struct inode *ip;
158 	ino_t newinum;
159 	int mode;
160 {
161 
162 	panic("softdep_setup_inomapdep called");
163 }
164 
165 void
166 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
167 	struct buf *bp;
168 	struct mount *mp;
169 	ufs2_daddr_t newblkno;
170 	int frags;
171 	int oldfrags;
172 {
173 
174 	panic("softdep_setup_blkmapdep called");
175 }
176 
177 void
178 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
179 	struct inode *ip;
180 	ufs_lbn_t lbn;
181 	ufs2_daddr_t newblkno;
182 	ufs2_daddr_t oldblkno;
183 	long newsize;
184 	long oldsize;
185 	struct buf *bp;
186 {
187 
188 	panic("softdep_setup_allocdirect called");
189 }
190 
191 void
192 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
193 	struct inode *ip;
194 	ufs_lbn_t lbn;
195 	ufs2_daddr_t newblkno;
196 	ufs2_daddr_t oldblkno;
197 	long newsize;
198 	long oldsize;
199 	struct buf *bp;
200 {
201 
202 	panic("softdep_setup_allocext called");
203 }
204 
205 void
206 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
207 	struct inode *ip;
208 	ufs_lbn_t lbn;
209 	struct buf *bp;
210 	int ptrno;
211 	ufs2_daddr_t newblkno;
212 	ufs2_daddr_t oldblkno;
213 	struct buf *nbp;
214 {
215 
216 	panic("softdep_setup_allocindir_page called");
217 }
218 
219 void
220 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
221 	struct buf *nbp;
222 	struct inode *ip;
223 	struct buf *bp;
224 	int ptrno;
225 	ufs2_daddr_t newblkno;
226 {
227 
228 	panic("softdep_setup_allocindir_meta called");
229 }
230 
231 void
232 softdep_journal_freeblocks(ip, cred, length, flags)
233 	struct inode *ip;
234 	struct ucred *cred;
235 	off_t length;
236 	int flags;
237 {
238 
239 	panic("softdep_journal_freeblocks called");
240 }
241 
242 void
243 softdep_journal_fsync(ip)
244 	struct inode *ip;
245 {
246 
247 	panic("softdep_journal_fsync called");
248 }
249 
250 void
251 softdep_setup_freeblocks(ip, length, flags)
252 	struct inode *ip;
253 	off_t length;
254 	int flags;
255 {
256 
257 	panic("softdep_setup_freeblocks called");
258 }
259 
260 void
261 softdep_freefile(pvp, ino, mode)
262 		struct vnode *pvp;
263 		ino_t ino;
264 		int mode;
265 {
266 
267 	panic("softdep_freefile called");
268 }
269 
270 int
271 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
272 	struct buf *bp;
273 	struct inode *dp;
274 	off_t diroffset;
275 	ino_t newinum;
276 	struct buf *newdirbp;
277 	int isnewblk;
278 {
279 
280 	panic("softdep_setup_directory_add called");
281 }
282 
283 void
284 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
285 	struct buf *bp;
286 	struct inode *dp;
287 	caddr_t base;
288 	caddr_t oldloc;
289 	caddr_t newloc;
290 	int entrysize;
291 {
292 
293 	panic("softdep_change_directoryentry_offset called");
294 }
295 
296 void
297 softdep_setup_remove(bp, dp, ip, isrmdir)
298 	struct buf *bp;
299 	struct inode *dp;
300 	struct inode *ip;
301 	int isrmdir;
302 {
303 
304 	panic("softdep_setup_remove called");
305 }
306 
307 void
308 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
309 	struct buf *bp;
310 	struct inode *dp;
311 	struct inode *ip;
312 	ino_t newinum;
313 	int isrmdir;
314 {
315 
316 	panic("softdep_setup_directory_change called");
317 }
318 
319 void
320 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
321 	struct mount *mp;
322 	struct buf *bp;
323 	ufs2_daddr_t blkno;
324 	int frags;
325 	struct workhead *wkhd;
326 {
327 
328 	panic("%s called", __FUNCTION__);
329 }
330 
331 void
332 softdep_setup_inofree(mp, bp, ino, wkhd)
333 	struct mount *mp;
334 	struct buf *bp;
335 	ino_t ino;
336 	struct workhead *wkhd;
337 {
338 
339 	panic("%s called", __FUNCTION__);
340 }
341 
342 void
343 softdep_setup_unlink(dp, ip)
344 	struct inode *dp;
345 	struct inode *ip;
346 {
347 
348 	panic("%s called", __FUNCTION__);
349 }
350 
351 void
352 softdep_setup_link(dp, ip)
353 	struct inode *dp;
354 	struct inode *ip;
355 {
356 
357 	panic("%s called", __FUNCTION__);
358 }
359 
360 void
361 softdep_revert_link(dp, ip)
362 	struct inode *dp;
363 	struct inode *ip;
364 {
365 
366 	panic("%s called", __FUNCTION__);
367 }
368 
369 void
370 softdep_setup_rmdir(dp, ip)
371 	struct inode *dp;
372 	struct inode *ip;
373 {
374 
375 	panic("%s called", __FUNCTION__);
376 }
377 
378 void
379 softdep_revert_rmdir(dp, ip)
380 	struct inode *dp;
381 	struct inode *ip;
382 {
383 
384 	panic("%s called", __FUNCTION__);
385 }
386 
387 void
388 softdep_setup_create(dp, ip)
389 	struct inode *dp;
390 	struct inode *ip;
391 {
392 
393 	panic("%s called", __FUNCTION__);
394 }
395 
396 void
397 softdep_revert_create(dp, ip)
398 	struct inode *dp;
399 	struct inode *ip;
400 {
401 
402 	panic("%s called", __FUNCTION__);
403 }
404 
405 void
406 softdep_setup_mkdir(dp, ip)
407 	struct inode *dp;
408 	struct inode *ip;
409 {
410 
411 	panic("%s called", __FUNCTION__);
412 }
413 
414 void
415 softdep_revert_mkdir(dp, ip)
416 	struct inode *dp;
417 	struct inode *ip;
418 {
419 
420 	panic("%s called", __FUNCTION__);
421 }
422 
423 void
424 softdep_setup_dotdot_link(dp, ip)
425 	struct inode *dp;
426 	struct inode *ip;
427 {
428 
429 	panic("%s called", __FUNCTION__);
430 }
431 
432 int
433 softdep_prealloc(vp, waitok)
434 	struct vnode *vp;
435 	int waitok;
436 {
437 
438 	panic("%s called", __FUNCTION__);
439 }
440 
441 int
442 softdep_journal_lookup(mp, vpp)
443 	struct mount *mp;
444 	struct vnode **vpp;
445 {
446 
447 	return (ENOENT);
448 }
449 
450 void
451 softdep_change_linkcnt(ip)
452 	struct inode *ip;
453 {
454 
455 	panic("softdep_change_linkcnt called");
456 }
457 
458 void
459 softdep_load_inodeblock(ip)
460 	struct inode *ip;
461 {
462 
463 	panic("softdep_load_inodeblock called");
464 }
465 
466 void
467 softdep_update_inodeblock(ip, bp, waitfor)
468 	struct inode *ip;
469 	struct buf *bp;
470 	int waitfor;
471 {
472 
473 	panic("softdep_update_inodeblock called");
474 }
475 
476 int
477 softdep_fsync(vp)
478 	struct vnode *vp;	/* the "in_core" copy of the inode */
479 {
480 
481 	return (0);
482 }
483 
484 void
485 softdep_fsync_mountdev(vp)
486 	struct vnode *vp;
487 {
488 
489 	return;
490 }
491 
492 int
493 softdep_flushworklist(oldmnt, countp, td)
494 	struct mount *oldmnt;
495 	int *countp;
496 	struct thread *td;
497 {
498 
499 	*countp = 0;
500 	return (0);
501 }
502 
503 int
504 softdep_sync_metadata(struct vnode *vp)
505 {
506 
507 	panic("softdep_sync_metadata called");
508 }
509 
510 int
511 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
512 {
513 
514 	panic("softdep_sync_buf called");
515 }
516 
517 int
518 softdep_slowdown(vp)
519 	struct vnode *vp;
520 {
521 
522 	panic("softdep_slowdown called");
523 }
524 
525 int
526 softdep_request_cleanup(fs, vp, cred, resource)
527 	struct fs *fs;
528 	struct vnode *vp;
529 	struct ucred *cred;
530 	int resource;
531 {
532 
533 	return (0);
534 }
535 
536 int
537 softdep_check_suspend(struct mount *mp,
538 		      struct vnode *devvp,
539 		      int softdep_depcnt,
540 		      int softdep_accdepcnt,
541 		      int secondary_writes,
542 		      int secondary_accwrites)
543 {
544 	struct bufobj *bo;
545 	int error;
546 
547 	(void) softdep_depcnt,
548 	(void) softdep_accdepcnt;
549 
550 	bo = &devvp->v_bufobj;
551 	ASSERT_BO_WLOCKED(bo);
552 
553 	MNT_ILOCK(mp);
554 	while (mp->mnt_secondary_writes != 0) {
555 		BO_UNLOCK(bo);
556 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
557 		    (PUSER - 1) | PDROP, "secwr", 0);
558 		BO_LOCK(bo);
559 		MNT_ILOCK(mp);
560 	}
561 
562 	/*
563 	 * Reasons for needing more work before suspend:
564 	 * - Dirty buffers on devvp.
565 	 * - Secondary writes occurred after start of vnode sync loop
566 	 */
567 	error = 0;
568 	if (bo->bo_numoutput > 0 ||
569 	    bo->bo_dirty.bv_cnt > 0 ||
570 	    secondary_writes != 0 ||
571 	    mp->mnt_secondary_writes != 0 ||
572 	    secondary_accwrites != mp->mnt_secondary_accwrites)
573 		error = EAGAIN;
574 	BO_UNLOCK(bo);
575 	return (error);
576 }
577 
578 void
579 softdep_get_depcounts(struct mount *mp,
580 		      int *softdepactivep,
581 		      int *softdepactiveaccp)
582 {
583 	(void) mp;
584 	*softdepactivep = 0;
585 	*softdepactiveaccp = 0;
586 }
587 
588 void
589 softdep_buf_append(bp, wkhd)
590 	struct buf *bp;
591 	struct workhead *wkhd;
592 {
593 
594 	panic("softdep_buf_appendwork called");
595 }
596 
597 void
598 softdep_inode_append(ip, cred, wkhd)
599 	struct inode *ip;
600 	struct ucred *cred;
601 	struct workhead *wkhd;
602 {
603 
604 	panic("softdep_inode_appendwork called");
605 }
606 
607 void
608 softdep_freework(wkhd)
609 	struct workhead *wkhd;
610 {
611 
612 	panic("softdep_freework called");
613 }
614 
615 #else
616 
617 FEATURE(softupdates, "FFS soft-updates support");
618 
619 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
620     "soft updates stats");
621 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
622     "total dependencies allocated");
623 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
624     "high use dependencies allocated");
625 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
626     "current dependencies allocated");
627 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
628     "current dependencies written");
629 
630 unsigned long dep_current[D_LAST + 1];
631 unsigned long dep_highuse[D_LAST + 1];
632 unsigned long dep_total[D_LAST + 1];
633 unsigned long dep_write[D_LAST + 1];
634 
635 #define	SOFTDEP_TYPE(type, str, long)					\
636     static MALLOC_DEFINE(M_ ## type, #str, long);			\
637     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
638 	&dep_total[D_ ## type], 0, "");					\
639     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
640 	&dep_current[D_ ## type], 0, "");				\
641     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
642 	&dep_highuse[D_ ## type], 0, "");				\
643     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
644 	&dep_write[D_ ## type], 0, "");
645 
646 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
647 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
648 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
649     "Block or frag allocated from cyl group map");
650 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
651 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
652 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
653 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
654 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
655 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
656 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
657 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
658 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
659 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
660 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
661 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
662 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
663 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
664 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
665 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
666 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
667 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
668 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
669 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
670 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
671 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
672 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
673 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
674 
675 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
676 
677 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
678 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
679 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
680 
681 #define M_SOFTDEP_FLAGS	(M_WAITOK)
682 
683 /*
684  * translate from workitem type to memory type
685  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
686  */
687 static struct malloc_type *memtype[] = {
688 	M_PAGEDEP,
689 	M_INODEDEP,
690 	M_BMSAFEMAP,
691 	M_NEWBLK,
692 	M_ALLOCDIRECT,
693 	M_INDIRDEP,
694 	M_ALLOCINDIR,
695 	M_FREEFRAG,
696 	M_FREEBLKS,
697 	M_FREEFILE,
698 	M_DIRADD,
699 	M_MKDIR,
700 	M_DIRREM,
701 	M_NEWDIRBLK,
702 	M_FREEWORK,
703 	M_FREEDEP,
704 	M_JADDREF,
705 	M_JREMREF,
706 	M_JMVREF,
707 	M_JNEWBLK,
708 	M_JFREEBLK,
709 	M_JFREEFRAG,
710 	M_JSEG,
711 	M_JSEGDEP,
712 	M_SBDEP,
713 	M_JTRUNC,
714 	M_JFSYNC,
715 	M_SENTINEL
716 };
717 
718 #define DtoM(type) (memtype[type])
719 
720 /*
721  * Names of malloc types.
722  */
723 #define TYPENAME(type)  \
724 	((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
725 /*
726  * End system adaptation definitions.
727  */
728 
729 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
730 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
731 
732 /*
733  * Internal function prototypes.
734  */
735 static	void check_clear_deps(struct mount *);
736 static	void softdep_error(char *, int);
737 static	int softdep_process_worklist(struct mount *, int);
738 static	int softdep_waitidle(struct mount *, int);
739 static	void drain_output(struct vnode *);
740 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
741 static	int check_inodedep_free(struct inodedep *);
742 static	void clear_remove(struct mount *);
743 static	void clear_inodedeps(struct mount *);
744 static	void unlinked_inodedep(struct mount *, struct inodedep *);
745 static	void clear_unlinked_inodedep(struct inodedep *);
746 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
747 static	int flush_pagedep_deps(struct vnode *, struct mount *,
748 	    struct diraddhd *);
749 static	int free_pagedep(struct pagedep *);
750 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
751 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
752 static	int flush_deplist(struct allocdirectlst *, int, int *);
753 static	int sync_cgs(struct mount *, int);
754 static	int handle_written_filepage(struct pagedep *, struct buf *);
755 static	int handle_written_sbdep(struct sbdep *, struct buf *);
756 static	void initiate_write_sbdep(struct sbdep *);
757 static	void diradd_inode_written(struct diradd *, struct inodedep *);
758 static	int handle_written_indirdep(struct indirdep *, struct buf *,
759 	    struct buf**);
760 static	int handle_written_inodeblock(struct inodedep *, struct buf *);
761 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
762 	    uint8_t *);
763 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *);
764 static	void handle_written_jaddref(struct jaddref *);
765 static	void handle_written_jremref(struct jremref *);
766 static	void handle_written_jseg(struct jseg *, struct buf *);
767 static	void handle_written_jnewblk(struct jnewblk *);
768 static	void handle_written_jblkdep(struct jblkdep *);
769 static	void handle_written_jfreefrag(struct jfreefrag *);
770 static	void complete_jseg(struct jseg *);
771 static	void complete_jsegs(struct jseg *);
772 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
773 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
774 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
775 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
776 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
777 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
778 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
779 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
780 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
781 static	inline void inoref_write(struct inoref *, struct jseg *,
782 	    struct jrefrec *);
783 static	void handle_allocdirect_partdone(struct allocdirect *,
784 	    struct workhead *);
785 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
786 	    struct workhead *);
787 static	void indirdep_complete(struct indirdep *);
788 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
789 static	void indirblk_insert(struct freework *);
790 static	void indirblk_remove(struct freework *);
791 static	void handle_allocindir_partdone(struct allocindir *);
792 static	void initiate_write_filepage(struct pagedep *, struct buf *);
793 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
794 static	void handle_written_mkdir(struct mkdir *, int);
795 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
796 	    uint8_t *);
797 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
798 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
799 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
800 static	void handle_workitem_freefile(struct freefile *);
801 static	int handle_workitem_remove(struct dirrem *, int);
802 static	struct dirrem *newdirrem(struct buf *, struct inode *,
803 	    struct inode *, int, struct dirrem **);
804 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
805 	    struct buf *);
806 static	void cancel_indirdep(struct indirdep *, struct buf *,
807 	    struct freeblks *);
808 static	void free_indirdep(struct indirdep *);
809 static	void free_diradd(struct diradd *, struct workhead *);
810 static	void merge_diradd(struct inodedep *, struct diradd *);
811 static	void complete_diradd(struct diradd *);
812 static	struct diradd *diradd_lookup(struct pagedep *, int);
813 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
814 	    struct jremref *);
815 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
816 	    struct jremref *);
817 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
818 	    struct jremref *, struct jremref *);
819 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
820 	    struct jremref *);
821 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
822 	    struct freeblks *, int);
823 static	int setup_trunc_indir(struct freeblks *, struct inode *,
824 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
825 static	void complete_trunc_indir(struct freework *);
826 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
827 	    int);
828 static	void complete_mkdir(struct mkdir *);
829 static	void free_newdirblk(struct newdirblk *);
830 static	void free_jremref(struct jremref *);
831 static	void free_jaddref(struct jaddref *);
832 static	void free_jsegdep(struct jsegdep *);
833 static	void free_jsegs(struct jblocks *);
834 static	void rele_jseg(struct jseg *);
835 static	void free_jseg(struct jseg *, struct jblocks *);
836 static	void free_jnewblk(struct jnewblk *);
837 static	void free_jblkdep(struct jblkdep *);
838 static	void free_jfreefrag(struct jfreefrag *);
839 static	void free_freedep(struct freedep *);
840 static	void journal_jremref(struct dirrem *, struct jremref *,
841 	    struct inodedep *);
842 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
843 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
844 	    struct workhead *);
845 static	void cancel_jfreefrag(struct jfreefrag *);
846 static	inline void setup_freedirect(struct freeblks *, struct inode *,
847 	    int, int);
848 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
849 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
850 	    ufs_lbn_t, int);
851 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
852 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
853 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
854 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
855 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
856 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
857 	    int, int);
858 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
859 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
860 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
861 static	void newblk_freefrag(struct newblk*);
862 static	void free_newblk(struct newblk *);
863 static	void cancel_allocdirect(struct allocdirectlst *,
864 	    struct allocdirect *, struct freeblks *);
865 static	int check_inode_unwritten(struct inodedep *);
866 static	int free_inodedep(struct inodedep *);
867 static	void freework_freeblock(struct freework *);
868 static	void freework_enqueue(struct freework *);
869 static	int handle_workitem_freeblocks(struct freeblks *, int);
870 static	int handle_complete_freeblocks(struct freeblks *, int);
871 static	void handle_workitem_indirblk(struct freework *);
872 static	void handle_written_freework(struct freework *);
873 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
874 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
875 	    struct workhead *);
876 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
877 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
878 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
879 	    ufs2_daddr_t, ufs_lbn_t);
880 static	void handle_workitem_freefrag(struct freefrag *);
881 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
882 	    ufs_lbn_t);
883 static	void allocdirect_merge(struct allocdirectlst *,
884 	    struct allocdirect *, struct allocdirect *);
885 static	struct freefrag *allocindir_merge(struct allocindir *,
886 	    struct allocindir *);
887 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
888 	    struct bmsafemap **);
889 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
890 	    int cg, struct bmsafemap *);
891 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
892 	    struct newblk **);
893 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
894 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
895 	    struct inodedep **);
896 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
897 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
898 	    int, struct pagedep **);
899 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
900 	    struct pagedep **);
901 static	void pause_timer(void *);
902 static	int request_cleanup(struct mount *, int);
903 static	void schedule_cleanup(struct mount *);
904 static void softdep_ast_cleanup_proc(void);
905 static	int process_worklist_item(struct mount *, int, int);
906 static	void process_removes(struct vnode *);
907 static	void process_truncates(struct vnode *);
908 static	void jwork_move(struct workhead *, struct workhead *);
909 static	void jwork_insert(struct workhead *, struct jsegdep *);
910 static	void add_to_worklist(struct worklist *, int);
911 static	void wake_worklist(struct worklist *);
912 static	void wait_worklist(struct worklist *, char *);
913 static	void remove_from_worklist(struct worklist *);
914 static	void softdep_flush(void *);
915 static	void softdep_flushjournal(struct mount *);
916 static	int softdep_speedup(struct ufsmount *);
917 static	void worklist_speedup(struct mount *);
918 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
919 static	void journal_unmount(struct ufsmount *);
920 static	int journal_space(struct ufsmount *, int);
921 static	void journal_suspend(struct ufsmount *);
922 static	int journal_unsuspend(struct ufsmount *ump);
923 static	void softdep_prelink(struct vnode *, struct vnode *);
924 static	void add_to_journal(struct worklist *);
925 static	void remove_from_journal(struct worklist *);
926 static	bool softdep_excess_items(struct ufsmount *, int);
927 static	void softdep_process_journal(struct mount *, struct worklist *, int);
928 static	struct jremref *newjremref(struct dirrem *, struct inode *,
929 	    struct inode *ip, off_t, nlink_t);
930 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
931 	    uint16_t);
932 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
933 	    uint16_t);
934 static	inline struct jsegdep *inoref_jseg(struct inoref *);
935 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
936 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
937 	    ufs2_daddr_t, int);
938 static	void adjust_newfreework(struct freeblks *, int);
939 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
940 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
941 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
942 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
943 	    ufs2_daddr_t, long, ufs_lbn_t);
944 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
945 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
946 static	int jwait(struct worklist *, int);
947 static	struct inodedep *inodedep_lookup_ip(struct inode *);
948 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
949 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
950 static	void handle_jwork(struct workhead *);
951 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
952 	    struct mkdir **);
953 static	struct jblocks *jblocks_create(void);
954 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
955 static	void jblocks_free(struct jblocks *, struct mount *, int);
956 static	void jblocks_destroy(struct jblocks *);
957 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
958 
959 /*
960  * Exported softdep operations.
961  */
962 static	void softdep_disk_io_initiation(struct buf *);
963 static	void softdep_disk_write_complete(struct buf *);
964 static	void softdep_deallocate_dependencies(struct buf *);
965 static	int softdep_count_dependencies(struct buf *bp, int);
966 
967 /*
968  * Global lock over all of soft updates.
969  */
970 static struct mtx lk;
971 MTX_SYSINIT(softdep_lock, &lk, "Global Softdep Lock", MTX_DEF);
972 
973 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
974 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
975 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
976 
977 /*
978  * Per-filesystem soft-updates locking.
979  */
980 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
981 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
982 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
983 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
984 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
985 				    RA_WLOCKED)
986 
987 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
988 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
989 
990 /*
991  * Worklist queue management.
992  * These routines require that the lock be held.
993  */
994 #ifndef /* NOT */ DEBUG
995 #define WORKLIST_INSERT(head, item) do {	\
996 	(item)->wk_state |= ONWORKLIST;		\
997 	LIST_INSERT_HEAD(head, item, wk_list);	\
998 } while (0)
999 #define WORKLIST_REMOVE(item) do {		\
1000 	(item)->wk_state &= ~ONWORKLIST;	\
1001 	LIST_REMOVE(item, wk_list);		\
1002 } while (0)
1003 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1004 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1005 
1006 #else /* DEBUG */
1007 static	void worklist_insert(struct workhead *, struct worklist *, int);
1008 static	void worklist_remove(struct worklist *, int);
1009 
1010 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1011 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1012 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1013 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1014 
1015 static void
1016 worklist_insert(head, item, locked)
1017 	struct workhead *head;
1018 	struct worklist *item;
1019 	int locked;
1020 {
1021 
1022 	if (locked)
1023 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1024 	if (item->wk_state & ONWORKLIST)
1025 		panic("worklist_insert: %p %s(0x%X) already on list",
1026 		    item, TYPENAME(item->wk_type), item->wk_state);
1027 	item->wk_state |= ONWORKLIST;
1028 	LIST_INSERT_HEAD(head, item, wk_list);
1029 }
1030 
1031 static void
1032 worklist_remove(item, locked)
1033 	struct worklist *item;
1034 	int locked;
1035 {
1036 
1037 	if (locked)
1038 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1039 	if ((item->wk_state & ONWORKLIST) == 0)
1040 		panic("worklist_remove: %p %s(0x%X) not on list",
1041 		    item, TYPENAME(item->wk_type), item->wk_state);
1042 	item->wk_state &= ~ONWORKLIST;
1043 	LIST_REMOVE(item, wk_list);
1044 }
1045 #endif /* DEBUG */
1046 
1047 /*
1048  * Merge two jsegdeps keeping only the oldest one as newer references
1049  * can't be discarded until after older references.
1050  */
1051 static inline struct jsegdep *
1052 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1053 {
1054 	struct jsegdep *swp;
1055 
1056 	if (two == NULL)
1057 		return (one);
1058 
1059 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1060 		swp = one;
1061 		one = two;
1062 		two = swp;
1063 	}
1064 	WORKLIST_REMOVE(&two->jd_list);
1065 	free_jsegdep(two);
1066 
1067 	return (one);
1068 }
1069 
1070 /*
1071  * If two freedeps are compatible free one to reduce list size.
1072  */
1073 static inline struct freedep *
1074 freedep_merge(struct freedep *one, struct freedep *two)
1075 {
1076 	if (two == NULL)
1077 		return (one);
1078 
1079 	if (one->fd_freework == two->fd_freework) {
1080 		WORKLIST_REMOVE(&two->fd_list);
1081 		free_freedep(two);
1082 	}
1083 	return (one);
1084 }
1085 
1086 /*
1087  * Move journal work from one list to another.  Duplicate freedeps and
1088  * jsegdeps are coalesced to keep the lists as small as possible.
1089  */
1090 static void
1091 jwork_move(dst, src)
1092 	struct workhead *dst;
1093 	struct workhead *src;
1094 {
1095 	struct freedep *freedep;
1096 	struct jsegdep *jsegdep;
1097 	struct worklist *wkn;
1098 	struct worklist *wk;
1099 
1100 	KASSERT(dst != src,
1101 	    ("jwork_move: dst == src"));
1102 	freedep = NULL;
1103 	jsegdep = NULL;
1104 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1105 		if (wk->wk_type == D_JSEGDEP)
1106 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1107 		else if (wk->wk_type == D_FREEDEP)
1108 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1109 	}
1110 
1111 	while ((wk = LIST_FIRST(src)) != NULL) {
1112 		WORKLIST_REMOVE(wk);
1113 		WORKLIST_INSERT(dst, wk);
1114 		if (wk->wk_type == D_JSEGDEP) {
1115 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1116 			continue;
1117 		}
1118 		if (wk->wk_type == D_FREEDEP)
1119 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1120 	}
1121 }
1122 
1123 static void
1124 jwork_insert(dst, jsegdep)
1125 	struct workhead *dst;
1126 	struct jsegdep *jsegdep;
1127 {
1128 	struct jsegdep *jsegdepn;
1129 	struct worklist *wk;
1130 
1131 	LIST_FOREACH(wk, dst, wk_list)
1132 		if (wk->wk_type == D_JSEGDEP)
1133 			break;
1134 	if (wk == NULL) {
1135 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1136 		return;
1137 	}
1138 	jsegdepn = WK_JSEGDEP(wk);
1139 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1140 		WORKLIST_REMOVE(wk);
1141 		free_jsegdep(jsegdepn);
1142 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1143 	} else
1144 		free_jsegdep(jsegdep);
1145 }
1146 
1147 /*
1148  * Routines for tracking and managing workitems.
1149  */
1150 static	void workitem_free(struct worklist *, int);
1151 static	void workitem_alloc(struct worklist *, int, struct mount *);
1152 static	void workitem_reassign(struct worklist *, int);
1153 
1154 #define	WORKITEM_FREE(item, type) \
1155 	workitem_free((struct worklist *)(item), (type))
1156 #define	WORKITEM_REASSIGN(item, type) \
1157 	workitem_reassign((struct worklist *)(item), (type))
1158 
1159 static void
1160 workitem_free(item, type)
1161 	struct worklist *item;
1162 	int type;
1163 {
1164 	struct ufsmount *ump;
1165 
1166 #ifdef DEBUG
1167 	if (item->wk_state & ONWORKLIST)
1168 		panic("workitem_free: %s(0x%X) still on list",
1169 		    TYPENAME(item->wk_type), item->wk_state);
1170 	if (item->wk_type != type && type != D_NEWBLK)
1171 		panic("workitem_free: type mismatch %s != %s",
1172 		    TYPENAME(item->wk_type), TYPENAME(type));
1173 #endif
1174 	if (item->wk_state & IOWAITING)
1175 		wakeup(item);
1176 	ump = VFSTOUFS(item->wk_mp);
1177 	LOCK_OWNED(ump);
1178 	KASSERT(ump->softdep_deps > 0,
1179 	    ("workitem_free: %s: softdep_deps going negative",
1180 	    ump->um_fs->fs_fsmnt));
1181 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1182 		wakeup(&ump->softdep_deps);
1183 	KASSERT(dep_current[item->wk_type] > 0,
1184 	    ("workitem_free: %s: dep_current[%s] going negative",
1185 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1186 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1187 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1188 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1189 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1190 	ump->softdep_curdeps[item->wk_type] -= 1;
1191 	free(item, DtoM(type));
1192 }
1193 
1194 static void
1195 workitem_alloc(item, type, mp)
1196 	struct worklist *item;
1197 	int type;
1198 	struct mount *mp;
1199 {
1200 	struct ufsmount *ump;
1201 
1202 	item->wk_type = type;
1203 	item->wk_mp = mp;
1204 	item->wk_state = 0;
1205 
1206 	ump = VFSTOUFS(mp);
1207 	ACQUIRE_GBLLOCK(&lk);
1208 	dep_current[type]++;
1209 	if (dep_current[type] > dep_highuse[type])
1210 		dep_highuse[type] = dep_current[type];
1211 	dep_total[type]++;
1212 	FREE_GBLLOCK(&lk);
1213 	ACQUIRE_LOCK(ump);
1214 	ump->softdep_curdeps[type] += 1;
1215 	ump->softdep_deps++;
1216 	ump->softdep_accdeps++;
1217 	FREE_LOCK(ump);
1218 }
1219 
1220 static void
1221 workitem_reassign(item, newtype)
1222 	struct worklist *item;
1223 	int newtype;
1224 {
1225 	struct ufsmount *ump;
1226 
1227 	ump = VFSTOUFS(item->wk_mp);
1228 	LOCK_OWNED(ump);
1229 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1230 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1231 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1232 	ump->softdep_curdeps[item->wk_type] -= 1;
1233 	ump->softdep_curdeps[newtype] += 1;
1234 	KASSERT(dep_current[item->wk_type] > 0,
1235 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1236 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1237 	ACQUIRE_GBLLOCK(&lk);
1238 	dep_current[newtype]++;
1239 	dep_current[item->wk_type]--;
1240 	if (dep_current[newtype] > dep_highuse[newtype])
1241 		dep_highuse[newtype] = dep_current[newtype];
1242 	dep_total[newtype]++;
1243 	FREE_GBLLOCK(&lk);
1244 	item->wk_type = newtype;
1245 }
1246 
1247 /*
1248  * Workitem queue management
1249  */
1250 static int max_softdeps;	/* maximum number of structs before slowdown */
1251 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1252 static int proc_waiting;	/* tracks whether we have a timeout posted */
1253 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1254 static struct callout softdep_callout;
1255 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1256 static int req_clear_remove;	/* syncer process flush some freeblks */
1257 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1258 
1259 /*
1260  * runtime statistics
1261  */
1262 static int stat_flush_threads;	/* number of softdep flushing threads */
1263 static int stat_worklist_push;	/* number of worklist cleanups */
1264 static int stat_blk_limit_push;	/* number of times block limit neared */
1265 static int stat_ino_limit_push;	/* number of times inode limit neared */
1266 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1267 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1268 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1269 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1270 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1271 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1272 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1273 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1274 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1275 static int stat_journal_min;	/* Times hit journal min threshold */
1276 static int stat_journal_low;	/* Times hit journal low threshold */
1277 static int stat_journal_wait;	/* Times blocked in jwait(). */
1278 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1279 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1280 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1281 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1282 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1283 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1284 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1285 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1286 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1287 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1288 
1289 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1290     &max_softdeps, 0, "");
1291 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1292     &tickdelay, 0, "");
1293 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1294     &stat_flush_threads, 0, "");
1295 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1296     &stat_worklist_push, 0,"");
1297 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1298     &stat_blk_limit_push, 0,"");
1299 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1300     &stat_ino_limit_push, 0,"");
1301 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1302     &stat_blk_limit_hit, 0, "");
1303 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1304     &stat_ino_limit_hit, 0, "");
1305 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1306     &stat_sync_limit_hit, 0, "");
1307 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1308     &stat_indir_blk_ptrs, 0, "");
1309 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1310     &stat_inode_bitmap, 0, "");
1311 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1312     &stat_direct_blk_ptrs, 0, "");
1313 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1314     &stat_dir_entry, 0, "");
1315 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1316     &stat_jaddref, 0, "");
1317 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1318     &stat_jnewblk, 0, "");
1319 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1320     &stat_journal_low, 0, "");
1321 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1322     &stat_journal_min, 0, "");
1323 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1324     &stat_journal_wait, 0, "");
1325 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1326     &stat_jwait_filepage, 0, "");
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1328     &stat_jwait_freeblks, 0, "");
1329 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1330     &stat_jwait_inode, 0, "");
1331 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1332     &stat_jwait_newblk, 0, "");
1333 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1334     &stat_cleanup_blkrequests, 0, "");
1335 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1336     &stat_cleanup_inorequests, 0, "");
1337 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1338     &stat_cleanup_high_delay, 0, "");
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1340     &stat_cleanup_retries, 0, "");
1341 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1342     &stat_cleanup_failures, 0, "");
1343 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1344     &softdep_flushcache, 0, "");
1345 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1346     &stat_emptyjblocks, 0, "");
1347 
1348 SYSCTL_DECL(_vfs_ffs);
1349 
1350 /* Whether to recompute the summary at mount time */
1351 static int compute_summary_at_mount = 0;
1352 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1353 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1354 static int print_threads = 0;
1355 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1356     &print_threads, 0, "Notify flusher thread start/stop");
1357 
1358 /* List of all filesystems mounted with soft updates */
1359 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1360 
1361 /*
1362  * This function cleans the worklist for a filesystem.
1363  * Each filesystem running with soft dependencies gets its own
1364  * thread to run in this function. The thread is started up in
1365  * softdep_mount and shutdown in softdep_unmount. They show up
1366  * as part of the kernel "bufdaemon" process whose process
1367  * entry is available in bufdaemonproc.
1368  */
1369 static int searchfailed;
1370 extern struct proc *bufdaemonproc;
1371 static void
1372 softdep_flush(addr)
1373 	void *addr;
1374 {
1375 	struct mount *mp;
1376 	struct thread *td;
1377 	struct ufsmount *ump;
1378 
1379 	td = curthread;
1380 	td->td_pflags |= TDP_NORUNNINGBUF;
1381 	mp = (struct mount *)addr;
1382 	ump = VFSTOUFS(mp);
1383 	atomic_add_int(&stat_flush_threads, 1);
1384 	ACQUIRE_LOCK(ump);
1385 	ump->softdep_flags &= ~FLUSH_STARTING;
1386 	wakeup(&ump->softdep_flushtd);
1387 	FREE_LOCK(ump);
1388 	if (print_threads) {
1389 		if (stat_flush_threads == 1)
1390 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1391 			    bufdaemonproc->p_pid);
1392 		printf("Start thread %s\n", td->td_name);
1393 	}
1394 	for (;;) {
1395 		while (softdep_process_worklist(mp, 0) > 0 ||
1396 		    (MOUNTEDSUJ(mp) &&
1397 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1398 			kthread_suspend_check();
1399 		ACQUIRE_LOCK(ump);
1400 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1401 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1402 			    "sdflush", hz / 2);
1403 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1404 		/*
1405 		 * Check to see if we are done and need to exit.
1406 		 */
1407 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1408 			FREE_LOCK(ump);
1409 			continue;
1410 		}
1411 		ump->softdep_flags &= ~FLUSH_EXIT;
1412 		FREE_LOCK(ump);
1413 		wakeup(&ump->softdep_flags);
1414 		if (print_threads)
1415 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1416 		atomic_subtract_int(&stat_flush_threads, 1);
1417 		kthread_exit();
1418 		panic("kthread_exit failed\n");
1419 	}
1420 }
1421 
1422 static void
1423 worklist_speedup(mp)
1424 	struct mount *mp;
1425 {
1426 	struct ufsmount *ump;
1427 
1428 	ump = VFSTOUFS(mp);
1429 	LOCK_OWNED(ump);
1430 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1431 		ump->softdep_flags |= FLUSH_CLEANUP;
1432 	wakeup(&ump->softdep_flushtd);
1433 }
1434 
1435 static int
1436 softdep_speedup(ump)
1437 	struct ufsmount *ump;
1438 {
1439 	struct ufsmount *altump;
1440 	struct mount_softdeps *sdp;
1441 
1442 	LOCK_OWNED(ump);
1443 	worklist_speedup(ump->um_mountp);
1444 	bd_speedup();
1445 	/*
1446 	 * If we have global shortages, then we need other
1447 	 * filesystems to help with the cleanup. Here we wakeup a
1448 	 * flusher thread for a filesystem that is over its fair
1449 	 * share of resources.
1450 	 */
1451 	if (req_clear_inodedeps || req_clear_remove) {
1452 		ACQUIRE_GBLLOCK(&lk);
1453 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1454 			if ((altump = sdp->sd_ump) == ump)
1455 				continue;
1456 			if (((req_clear_inodedeps &&
1457 			    altump->softdep_curdeps[D_INODEDEP] >
1458 			    max_softdeps / stat_flush_threads) ||
1459 			    (req_clear_remove &&
1460 			    altump->softdep_curdeps[D_DIRREM] >
1461 			    (max_softdeps / 2) / stat_flush_threads)) &&
1462 			    TRY_ACQUIRE_LOCK(altump))
1463 				break;
1464 		}
1465 		if (sdp == NULL) {
1466 			searchfailed++;
1467 			FREE_GBLLOCK(&lk);
1468 		} else {
1469 			/*
1470 			 * Move to the end of the list so we pick a
1471 			 * different one on out next try.
1472 			 */
1473 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1474 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1475 			FREE_GBLLOCK(&lk);
1476 			if ((altump->softdep_flags &
1477 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1478 				altump->softdep_flags |= FLUSH_CLEANUP;
1479 			altump->um_softdep->sd_cleanups++;
1480 			wakeup(&altump->softdep_flushtd);
1481 			FREE_LOCK(altump);
1482 		}
1483 	}
1484 	return (speedup_syncer());
1485 }
1486 
1487 /*
1488  * Add an item to the end of the work queue.
1489  * This routine requires that the lock be held.
1490  * This is the only routine that adds items to the list.
1491  * The following routine is the only one that removes items
1492  * and does so in order from first to last.
1493  */
1494 
1495 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1496 #define	WK_NODELAY	0x0002	/* Process immediately. */
1497 
1498 static void
1499 add_to_worklist(wk, flags)
1500 	struct worklist *wk;
1501 	int flags;
1502 {
1503 	struct ufsmount *ump;
1504 
1505 	ump = VFSTOUFS(wk->wk_mp);
1506 	LOCK_OWNED(ump);
1507 	if (wk->wk_state & ONWORKLIST)
1508 		panic("add_to_worklist: %s(0x%X) already on list",
1509 		    TYPENAME(wk->wk_type), wk->wk_state);
1510 	wk->wk_state |= ONWORKLIST;
1511 	if (ump->softdep_on_worklist == 0) {
1512 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1513 		ump->softdep_worklist_tail = wk;
1514 	} else if (flags & WK_HEAD) {
1515 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1516 	} else {
1517 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1518 		ump->softdep_worklist_tail = wk;
1519 	}
1520 	ump->softdep_on_worklist += 1;
1521 	if (flags & WK_NODELAY)
1522 		worklist_speedup(wk->wk_mp);
1523 }
1524 
1525 /*
1526  * Remove the item to be processed. If we are removing the last
1527  * item on the list, we need to recalculate the tail pointer.
1528  */
1529 static void
1530 remove_from_worklist(wk)
1531 	struct worklist *wk;
1532 {
1533 	struct ufsmount *ump;
1534 
1535 	ump = VFSTOUFS(wk->wk_mp);
1536 	WORKLIST_REMOVE(wk);
1537 	if (ump->softdep_worklist_tail == wk)
1538 		ump->softdep_worklist_tail =
1539 		    (struct worklist *)wk->wk_list.le_prev;
1540 	ump->softdep_on_worklist -= 1;
1541 }
1542 
1543 static void
1544 wake_worklist(wk)
1545 	struct worklist *wk;
1546 {
1547 	if (wk->wk_state & IOWAITING) {
1548 		wk->wk_state &= ~IOWAITING;
1549 		wakeup(wk);
1550 	}
1551 }
1552 
1553 static void
1554 wait_worklist(wk, wmesg)
1555 	struct worklist *wk;
1556 	char *wmesg;
1557 {
1558 	struct ufsmount *ump;
1559 
1560 	ump = VFSTOUFS(wk->wk_mp);
1561 	wk->wk_state |= IOWAITING;
1562 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1563 }
1564 
1565 /*
1566  * Process that runs once per second to handle items in the background queue.
1567  *
1568  * Note that we ensure that everything is done in the order in which they
1569  * appear in the queue. The code below depends on this property to ensure
1570  * that blocks of a file are freed before the inode itself is freed. This
1571  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1572  * until all the old ones have been purged from the dependency lists.
1573  */
1574 static int
1575 softdep_process_worklist(mp, full)
1576 	struct mount *mp;
1577 	int full;
1578 {
1579 	int cnt, matchcnt;
1580 	struct ufsmount *ump;
1581 	long starttime;
1582 
1583 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1584 	if (MOUNTEDSOFTDEP(mp) == 0)
1585 		return (0);
1586 	matchcnt = 0;
1587 	ump = VFSTOUFS(mp);
1588 	ACQUIRE_LOCK(ump);
1589 	starttime = time_second;
1590 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1591 	check_clear_deps(mp);
1592 	while (ump->softdep_on_worklist > 0) {
1593 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1594 			break;
1595 		else
1596 			matchcnt += cnt;
1597 		check_clear_deps(mp);
1598 		/*
1599 		 * We do not generally want to stop for buffer space, but if
1600 		 * we are really being a buffer hog, we will stop and wait.
1601 		 */
1602 		if (should_yield()) {
1603 			FREE_LOCK(ump);
1604 			kern_yield(PRI_USER);
1605 			bwillwrite();
1606 			ACQUIRE_LOCK(ump);
1607 		}
1608 		/*
1609 		 * Never allow processing to run for more than one
1610 		 * second. This gives the syncer thread the opportunity
1611 		 * to pause if appropriate.
1612 		 */
1613 		if (!full && starttime != time_second)
1614 			break;
1615 	}
1616 	if (full == 0)
1617 		journal_unsuspend(ump);
1618 	FREE_LOCK(ump);
1619 	return (matchcnt);
1620 }
1621 
1622 /*
1623  * Process all removes associated with a vnode if we are running out of
1624  * journal space.  Any other process which attempts to flush these will
1625  * be unable as we have the vnodes locked.
1626  */
1627 static void
1628 process_removes(vp)
1629 	struct vnode *vp;
1630 {
1631 	struct inodedep *inodedep;
1632 	struct dirrem *dirrem;
1633 	struct ufsmount *ump;
1634 	struct mount *mp;
1635 	ino_t inum;
1636 
1637 	mp = vp->v_mount;
1638 	ump = VFSTOUFS(mp);
1639 	LOCK_OWNED(ump);
1640 	inum = VTOI(vp)->i_number;
1641 	for (;;) {
1642 top:
1643 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1644 			return;
1645 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1646 			/*
1647 			 * If another thread is trying to lock this vnode
1648 			 * it will fail but we must wait for it to do so
1649 			 * before we can proceed.
1650 			 */
1651 			if (dirrem->dm_state & INPROGRESS) {
1652 				wait_worklist(&dirrem->dm_list, "pwrwait");
1653 				goto top;
1654 			}
1655 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1656 			    (COMPLETE | ONWORKLIST))
1657 				break;
1658 		}
1659 		if (dirrem == NULL)
1660 			return;
1661 		remove_from_worklist(&dirrem->dm_list);
1662 		FREE_LOCK(ump);
1663 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1664 			panic("process_removes: suspended filesystem");
1665 		handle_workitem_remove(dirrem, 0);
1666 		vn_finished_secondary_write(mp);
1667 		ACQUIRE_LOCK(ump);
1668 	}
1669 }
1670 
1671 /*
1672  * Process all truncations associated with a vnode if we are running out
1673  * of journal space.  This is called when the vnode lock is already held
1674  * and no other process can clear the truncation.  This function returns
1675  * a value greater than zero if it did any work.
1676  */
1677 static void
1678 process_truncates(vp)
1679 	struct vnode *vp;
1680 {
1681 	struct inodedep *inodedep;
1682 	struct freeblks *freeblks;
1683 	struct ufsmount *ump;
1684 	struct mount *mp;
1685 	ino_t inum;
1686 	int cgwait;
1687 
1688 	mp = vp->v_mount;
1689 	ump = VFSTOUFS(mp);
1690 	LOCK_OWNED(ump);
1691 	inum = VTOI(vp)->i_number;
1692 	for (;;) {
1693 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1694 			return;
1695 		cgwait = 0;
1696 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1697 			/* Journal entries not yet written.  */
1698 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1699 				jwait(&LIST_FIRST(
1700 				    &freeblks->fb_jblkdephd)->jb_list,
1701 				    MNT_WAIT);
1702 				break;
1703 			}
1704 			/* Another thread is executing this item. */
1705 			if (freeblks->fb_state & INPROGRESS) {
1706 				wait_worklist(&freeblks->fb_list, "ptrwait");
1707 				break;
1708 			}
1709 			/* Freeblks is waiting on a inode write. */
1710 			if ((freeblks->fb_state & COMPLETE) == 0) {
1711 				FREE_LOCK(ump);
1712 				ffs_update(vp, 1);
1713 				ACQUIRE_LOCK(ump);
1714 				break;
1715 			}
1716 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1717 			    (ALLCOMPLETE | ONWORKLIST)) {
1718 				remove_from_worklist(&freeblks->fb_list);
1719 				freeblks->fb_state |= INPROGRESS;
1720 				FREE_LOCK(ump);
1721 				if (vn_start_secondary_write(NULL, &mp,
1722 				    V_NOWAIT))
1723 					panic("process_truncates: "
1724 					    "suspended filesystem");
1725 				handle_workitem_freeblocks(freeblks, 0);
1726 				vn_finished_secondary_write(mp);
1727 				ACQUIRE_LOCK(ump);
1728 				break;
1729 			}
1730 			if (freeblks->fb_cgwait)
1731 				cgwait++;
1732 		}
1733 		if (cgwait) {
1734 			FREE_LOCK(ump);
1735 			sync_cgs(mp, MNT_WAIT);
1736 			ffs_sync_snap(mp, MNT_WAIT);
1737 			ACQUIRE_LOCK(ump);
1738 			continue;
1739 		}
1740 		if (freeblks == NULL)
1741 			break;
1742 	}
1743 	return;
1744 }
1745 
1746 /*
1747  * Process one item on the worklist.
1748  */
1749 static int
1750 process_worklist_item(mp, target, flags)
1751 	struct mount *mp;
1752 	int target;
1753 	int flags;
1754 {
1755 	struct worklist sentinel;
1756 	struct worklist *wk;
1757 	struct ufsmount *ump;
1758 	int matchcnt;
1759 	int error;
1760 
1761 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1762 	/*
1763 	 * If we are being called because of a process doing a
1764 	 * copy-on-write, then it is not safe to write as we may
1765 	 * recurse into the copy-on-write routine.
1766 	 */
1767 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1768 		return (-1);
1769 	PHOLD(curproc);	/* Don't let the stack go away. */
1770 	ump = VFSTOUFS(mp);
1771 	LOCK_OWNED(ump);
1772 	matchcnt = 0;
1773 	sentinel.wk_mp = NULL;
1774 	sentinel.wk_type = D_SENTINEL;
1775 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1776 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1777 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1778 		if (wk->wk_type == D_SENTINEL) {
1779 			LIST_REMOVE(&sentinel, wk_list);
1780 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1781 			continue;
1782 		}
1783 		if (wk->wk_state & INPROGRESS)
1784 			panic("process_worklist_item: %p already in progress.",
1785 			    wk);
1786 		wk->wk_state |= INPROGRESS;
1787 		remove_from_worklist(wk);
1788 		FREE_LOCK(ump);
1789 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1790 			panic("process_worklist_item: suspended filesystem");
1791 		switch (wk->wk_type) {
1792 		case D_DIRREM:
1793 			/* removal of a directory entry */
1794 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1795 			break;
1796 
1797 		case D_FREEBLKS:
1798 			/* releasing blocks and/or fragments from a file */
1799 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1800 			    flags);
1801 			break;
1802 
1803 		case D_FREEFRAG:
1804 			/* releasing a fragment when replaced as a file grows */
1805 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1806 			error = 0;
1807 			break;
1808 
1809 		case D_FREEFILE:
1810 			/* releasing an inode when its link count drops to 0 */
1811 			handle_workitem_freefile(WK_FREEFILE(wk));
1812 			error = 0;
1813 			break;
1814 
1815 		default:
1816 			panic("%s_process_worklist: Unknown type %s",
1817 			    "softdep", TYPENAME(wk->wk_type));
1818 			/* NOTREACHED */
1819 		}
1820 		vn_finished_secondary_write(mp);
1821 		ACQUIRE_LOCK(ump);
1822 		if (error == 0) {
1823 			if (++matchcnt == target)
1824 				break;
1825 			continue;
1826 		}
1827 		/*
1828 		 * We have to retry the worklist item later.  Wake up any
1829 		 * waiters who may be able to complete it immediately and
1830 		 * add the item back to the head so we don't try to execute
1831 		 * it again.
1832 		 */
1833 		wk->wk_state &= ~INPROGRESS;
1834 		wake_worklist(wk);
1835 		add_to_worklist(wk, WK_HEAD);
1836 	}
1837 	LIST_REMOVE(&sentinel, wk_list);
1838 	/* Sentinal could've become the tail from remove_from_worklist. */
1839 	if (ump->softdep_worklist_tail == &sentinel)
1840 		ump->softdep_worklist_tail =
1841 		    (struct worklist *)sentinel.wk_list.le_prev;
1842 	PRELE(curproc);
1843 	return (matchcnt);
1844 }
1845 
1846 /*
1847  * Move dependencies from one buffer to another.
1848  */
1849 int
1850 softdep_move_dependencies(oldbp, newbp)
1851 	struct buf *oldbp;
1852 	struct buf *newbp;
1853 {
1854 	struct worklist *wk, *wktail;
1855 	struct ufsmount *ump;
1856 	int dirty;
1857 
1858 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1859 		return (0);
1860 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1861 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1862 	dirty = 0;
1863 	wktail = NULL;
1864 	ump = VFSTOUFS(wk->wk_mp);
1865 	ACQUIRE_LOCK(ump);
1866 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1867 		LIST_REMOVE(wk, wk_list);
1868 		if (wk->wk_type == D_BMSAFEMAP &&
1869 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1870 			dirty = 1;
1871 		if (wktail == 0)
1872 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1873 		else
1874 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1875 		wktail = wk;
1876 	}
1877 	FREE_LOCK(ump);
1878 
1879 	return (dirty);
1880 }
1881 
1882 /*
1883  * Purge the work list of all items associated with a particular mount point.
1884  */
1885 int
1886 softdep_flushworklist(oldmnt, countp, td)
1887 	struct mount *oldmnt;
1888 	int *countp;
1889 	struct thread *td;
1890 {
1891 	struct vnode *devvp;
1892 	struct ufsmount *ump;
1893 	int count, error;
1894 
1895 	/*
1896 	 * Alternately flush the block device associated with the mount
1897 	 * point and process any dependencies that the flushing
1898 	 * creates. We continue until no more worklist dependencies
1899 	 * are found.
1900 	 */
1901 	*countp = 0;
1902 	error = 0;
1903 	ump = VFSTOUFS(oldmnt);
1904 	devvp = ump->um_devvp;
1905 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1906 		*countp += count;
1907 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1908 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1909 		VOP_UNLOCK(devvp, 0);
1910 		if (error != 0)
1911 			break;
1912 	}
1913 	return (error);
1914 }
1915 
1916 #define	SU_WAITIDLE_RETRIES	20
1917 static int
1918 softdep_waitidle(struct mount *mp, int flags __unused)
1919 {
1920 	struct ufsmount *ump;
1921 	struct vnode *devvp;
1922 	struct thread *td;
1923 	int error, i;
1924 
1925 	ump = VFSTOUFS(mp);
1926 	devvp = ump->um_devvp;
1927 	td = curthread;
1928 	error = 0;
1929 	ACQUIRE_LOCK(ump);
1930 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1931 		ump->softdep_req = 1;
1932 		KASSERT((flags & FORCECLOSE) == 0 ||
1933 		    ump->softdep_on_worklist == 0,
1934 		    ("softdep_waitidle: work added after flush"));
1935 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1936 		    "softdeps", 10 * hz);
1937 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1938 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1939 		VOP_UNLOCK(devvp, 0);
1940 		if (error != 0)
1941 			break;
1942 		ACQUIRE_LOCK(ump);
1943 	}
1944 	ump->softdep_req = 0;
1945 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1946 		error = EBUSY;
1947 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1948 		    mp);
1949 	}
1950 	FREE_LOCK(ump);
1951 	return (error);
1952 }
1953 
1954 /*
1955  * Flush all vnodes and worklist items associated with a specified mount point.
1956  */
1957 int
1958 softdep_flushfiles(oldmnt, flags, td)
1959 	struct mount *oldmnt;
1960 	int flags;
1961 	struct thread *td;
1962 {
1963 #ifdef QUOTA
1964 	struct ufsmount *ump;
1965 	int i;
1966 #endif
1967 	int error, early, depcount, loopcnt, retry_flush_count, retry;
1968 	int morework;
1969 
1970 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1971 	    ("softdep_flushfiles called on non-softdep filesystem"));
1972 	loopcnt = 10;
1973 	retry_flush_count = 3;
1974 retry_flush:
1975 	error = 0;
1976 
1977 	/*
1978 	 * Alternately flush the vnodes associated with the mount
1979 	 * point and process any dependencies that the flushing
1980 	 * creates. In theory, this loop can happen at most twice,
1981 	 * but we give it a few extra just to be sure.
1982 	 */
1983 	for (; loopcnt > 0; loopcnt--) {
1984 		/*
1985 		 * Do another flush in case any vnodes were brought in
1986 		 * as part of the cleanup operations.
1987 		 */
1988 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
1989 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
1990 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
1991 			break;
1992 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1993 		    depcount == 0)
1994 			break;
1995 	}
1996 	/*
1997 	 * If we are unmounting then it is an error to fail. If we
1998 	 * are simply trying to downgrade to read-only, then filesystem
1999 	 * activity can keep us busy forever, so we just fail with EBUSY.
2000 	 */
2001 	if (loopcnt == 0) {
2002 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2003 			panic("softdep_flushfiles: looping");
2004 		error = EBUSY;
2005 	}
2006 	if (!error)
2007 		error = softdep_waitidle(oldmnt, flags);
2008 	if (!error) {
2009 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2010 			retry = 0;
2011 			MNT_ILOCK(oldmnt);
2012 			KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
2013 			    ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
2014 			morework = oldmnt->mnt_nvnodelistsize > 0;
2015 #ifdef QUOTA
2016 			ump = VFSTOUFS(oldmnt);
2017 			UFS_LOCK(ump);
2018 			for (i = 0; i < MAXQUOTAS; i++) {
2019 				if (ump->um_quotas[i] != NULLVP)
2020 					morework = 1;
2021 			}
2022 			UFS_UNLOCK(ump);
2023 #endif
2024 			if (morework) {
2025 				if (--retry_flush_count > 0) {
2026 					retry = 1;
2027 					loopcnt = 3;
2028 				} else
2029 					error = EBUSY;
2030 			}
2031 			MNT_IUNLOCK(oldmnt);
2032 			if (retry)
2033 				goto retry_flush;
2034 		}
2035 	}
2036 	return (error);
2037 }
2038 
2039 /*
2040  * Structure hashing.
2041  *
2042  * There are four types of structures that can be looked up:
2043  *	1) pagedep structures identified by mount point, inode number,
2044  *	   and logical block.
2045  *	2) inodedep structures identified by mount point and inode number.
2046  *	3) newblk structures identified by mount point and
2047  *	   physical block number.
2048  *	4) bmsafemap structures identified by mount point and
2049  *	   cylinder group number.
2050  *
2051  * The "pagedep" and "inodedep" dependency structures are hashed
2052  * separately from the file blocks and inodes to which they correspond.
2053  * This separation helps when the in-memory copy of an inode or
2054  * file block must be replaced. It also obviates the need to access
2055  * an inode or file page when simply updating (or de-allocating)
2056  * dependency structures. Lookup of newblk structures is needed to
2057  * find newly allocated blocks when trying to associate them with
2058  * their allocdirect or allocindir structure.
2059  *
2060  * The lookup routines optionally create and hash a new instance when
2061  * an existing entry is not found. The bmsafemap lookup routine always
2062  * allocates a new structure if an existing one is not found.
2063  */
2064 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2065 
2066 /*
2067  * Structures and routines associated with pagedep caching.
2068  */
2069 #define	PAGEDEP_HASH(ump, inum, lbn) \
2070 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2071 
2072 static int
2073 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2074 	struct pagedep_hashhead *pagedephd;
2075 	ino_t ino;
2076 	ufs_lbn_t lbn;
2077 	struct pagedep **pagedeppp;
2078 {
2079 	struct pagedep *pagedep;
2080 
2081 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2082 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2083 			*pagedeppp = pagedep;
2084 			return (1);
2085 		}
2086 	}
2087 	*pagedeppp = NULL;
2088 	return (0);
2089 }
2090 /*
2091  * Look up a pagedep. Return 1 if found, 0 otherwise.
2092  * If not found, allocate if DEPALLOC flag is passed.
2093  * Found or allocated entry is returned in pagedeppp.
2094  * This routine must be called with splbio interrupts blocked.
2095  */
2096 static int
2097 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2098 	struct mount *mp;
2099 	struct buf *bp;
2100 	ino_t ino;
2101 	ufs_lbn_t lbn;
2102 	int flags;
2103 	struct pagedep **pagedeppp;
2104 {
2105 	struct pagedep *pagedep;
2106 	struct pagedep_hashhead *pagedephd;
2107 	struct worklist *wk;
2108 	struct ufsmount *ump;
2109 	int ret;
2110 	int i;
2111 
2112 	ump = VFSTOUFS(mp);
2113 	LOCK_OWNED(ump);
2114 	if (bp) {
2115 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2116 			if (wk->wk_type == D_PAGEDEP) {
2117 				*pagedeppp = WK_PAGEDEP(wk);
2118 				return (1);
2119 			}
2120 		}
2121 	}
2122 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2123 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2124 	if (ret) {
2125 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2126 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2127 		return (1);
2128 	}
2129 	if ((flags & DEPALLOC) == 0)
2130 		return (0);
2131 	FREE_LOCK(ump);
2132 	pagedep = malloc(sizeof(struct pagedep),
2133 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2134 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2135 	ACQUIRE_LOCK(ump);
2136 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2137 	if (*pagedeppp) {
2138 		/*
2139 		 * This should never happen since we only create pagedeps
2140 		 * with the vnode lock held.  Could be an assert.
2141 		 */
2142 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2143 		return (ret);
2144 	}
2145 	pagedep->pd_ino = ino;
2146 	pagedep->pd_lbn = lbn;
2147 	LIST_INIT(&pagedep->pd_dirremhd);
2148 	LIST_INIT(&pagedep->pd_pendinghd);
2149 	for (i = 0; i < DAHASHSZ; i++)
2150 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2151 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2152 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2153 	*pagedeppp = pagedep;
2154 	return (0);
2155 }
2156 
2157 /*
2158  * Structures and routines associated with inodedep caching.
2159  */
2160 #define	INODEDEP_HASH(ump, inum) \
2161       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2162 
2163 static int
2164 inodedep_find(inodedephd, inum, inodedeppp)
2165 	struct inodedep_hashhead *inodedephd;
2166 	ino_t inum;
2167 	struct inodedep **inodedeppp;
2168 {
2169 	struct inodedep *inodedep;
2170 
2171 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2172 		if (inum == inodedep->id_ino)
2173 			break;
2174 	if (inodedep) {
2175 		*inodedeppp = inodedep;
2176 		return (1);
2177 	}
2178 	*inodedeppp = NULL;
2179 
2180 	return (0);
2181 }
2182 /*
2183  * Look up an inodedep. Return 1 if found, 0 if not found.
2184  * If not found, allocate if DEPALLOC flag is passed.
2185  * Found or allocated entry is returned in inodedeppp.
2186  * This routine must be called with splbio interrupts blocked.
2187  */
2188 static int
2189 inodedep_lookup(mp, inum, flags, inodedeppp)
2190 	struct mount *mp;
2191 	ino_t inum;
2192 	int flags;
2193 	struct inodedep **inodedeppp;
2194 {
2195 	struct inodedep *inodedep;
2196 	struct inodedep_hashhead *inodedephd;
2197 	struct ufsmount *ump;
2198 	struct fs *fs;
2199 
2200 	ump = VFSTOUFS(mp);
2201 	LOCK_OWNED(ump);
2202 	fs = ump->um_fs;
2203 	inodedephd = INODEDEP_HASH(ump, inum);
2204 
2205 	if (inodedep_find(inodedephd, inum, inodedeppp))
2206 		return (1);
2207 	if ((flags & DEPALLOC) == 0)
2208 		return (0);
2209 	/*
2210 	 * If the system is over its limit and our filesystem is
2211 	 * responsible for more than our share of that usage and
2212 	 * we are not in a rush, request some inodedep cleanup.
2213 	 */
2214 	if (softdep_excess_items(ump, D_INODEDEP))
2215 		schedule_cleanup(mp);
2216 	else
2217 		FREE_LOCK(ump);
2218 	inodedep = malloc(sizeof(struct inodedep),
2219 		M_INODEDEP, M_SOFTDEP_FLAGS);
2220 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2221 	ACQUIRE_LOCK(ump);
2222 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2223 		WORKITEM_FREE(inodedep, D_INODEDEP);
2224 		return (1);
2225 	}
2226 	inodedep->id_fs = fs;
2227 	inodedep->id_ino = inum;
2228 	inodedep->id_state = ALLCOMPLETE;
2229 	inodedep->id_nlinkdelta = 0;
2230 	inodedep->id_savedino1 = NULL;
2231 	inodedep->id_savedsize = -1;
2232 	inodedep->id_savedextsize = -1;
2233 	inodedep->id_savednlink = -1;
2234 	inodedep->id_bmsafemap = NULL;
2235 	inodedep->id_mkdiradd = NULL;
2236 	LIST_INIT(&inodedep->id_dirremhd);
2237 	LIST_INIT(&inodedep->id_pendinghd);
2238 	LIST_INIT(&inodedep->id_inowait);
2239 	LIST_INIT(&inodedep->id_bufwait);
2240 	TAILQ_INIT(&inodedep->id_inoreflst);
2241 	TAILQ_INIT(&inodedep->id_inoupdt);
2242 	TAILQ_INIT(&inodedep->id_newinoupdt);
2243 	TAILQ_INIT(&inodedep->id_extupdt);
2244 	TAILQ_INIT(&inodedep->id_newextupdt);
2245 	TAILQ_INIT(&inodedep->id_freeblklst);
2246 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2247 	*inodedeppp = inodedep;
2248 	return (0);
2249 }
2250 
2251 /*
2252  * Structures and routines associated with newblk caching.
2253  */
2254 #define	NEWBLK_HASH(ump, inum) \
2255 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2256 
2257 static int
2258 newblk_find(newblkhd, newblkno, flags, newblkpp)
2259 	struct newblk_hashhead *newblkhd;
2260 	ufs2_daddr_t newblkno;
2261 	int flags;
2262 	struct newblk **newblkpp;
2263 {
2264 	struct newblk *newblk;
2265 
2266 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2267 		if (newblkno != newblk->nb_newblkno)
2268 			continue;
2269 		/*
2270 		 * If we're creating a new dependency don't match those that
2271 		 * have already been converted to allocdirects.  This is for
2272 		 * a frag extend.
2273 		 */
2274 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2275 			continue;
2276 		break;
2277 	}
2278 	if (newblk) {
2279 		*newblkpp = newblk;
2280 		return (1);
2281 	}
2282 	*newblkpp = NULL;
2283 	return (0);
2284 }
2285 
2286 /*
2287  * Look up a newblk. Return 1 if found, 0 if not found.
2288  * If not found, allocate if DEPALLOC flag is passed.
2289  * Found or allocated entry is returned in newblkpp.
2290  */
2291 static int
2292 newblk_lookup(mp, newblkno, flags, newblkpp)
2293 	struct mount *mp;
2294 	ufs2_daddr_t newblkno;
2295 	int flags;
2296 	struct newblk **newblkpp;
2297 {
2298 	struct newblk *newblk;
2299 	struct newblk_hashhead *newblkhd;
2300 	struct ufsmount *ump;
2301 
2302 	ump = VFSTOUFS(mp);
2303 	LOCK_OWNED(ump);
2304 	newblkhd = NEWBLK_HASH(ump, newblkno);
2305 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2306 		return (1);
2307 	if ((flags & DEPALLOC) == 0)
2308 		return (0);
2309 	if (softdep_excess_items(ump, D_NEWBLK) ||
2310 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2311 	    softdep_excess_items(ump, D_ALLOCINDIR))
2312 		schedule_cleanup(mp);
2313 	else
2314 		FREE_LOCK(ump);
2315 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2316 	    M_SOFTDEP_FLAGS | M_ZERO);
2317 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2318 	ACQUIRE_LOCK(ump);
2319 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2320 		WORKITEM_FREE(newblk, D_NEWBLK);
2321 		return (1);
2322 	}
2323 	newblk->nb_freefrag = NULL;
2324 	LIST_INIT(&newblk->nb_indirdeps);
2325 	LIST_INIT(&newblk->nb_newdirblk);
2326 	LIST_INIT(&newblk->nb_jwork);
2327 	newblk->nb_state = ATTACHED;
2328 	newblk->nb_newblkno = newblkno;
2329 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2330 	*newblkpp = newblk;
2331 	return (0);
2332 }
2333 
2334 /*
2335  * Structures and routines associated with freed indirect block caching.
2336  */
2337 #define	INDIR_HASH(ump, blkno) \
2338 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2339 
2340 /*
2341  * Lookup an indirect block in the indir hash table.  The freework is
2342  * removed and potentially freed.  The caller must do a blocking journal
2343  * write before writing to the blkno.
2344  */
2345 static int
2346 indirblk_lookup(mp, blkno)
2347 	struct mount *mp;
2348 	ufs2_daddr_t blkno;
2349 {
2350 	struct freework *freework;
2351 	struct indir_hashhead *wkhd;
2352 	struct ufsmount *ump;
2353 
2354 	ump = VFSTOUFS(mp);
2355 	wkhd = INDIR_HASH(ump, blkno);
2356 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2357 		if (freework->fw_blkno != blkno)
2358 			continue;
2359 		indirblk_remove(freework);
2360 		return (1);
2361 	}
2362 	return (0);
2363 }
2364 
2365 /*
2366  * Insert an indirect block represented by freework into the indirblk
2367  * hash table so that it may prevent the block from being re-used prior
2368  * to the journal being written.
2369  */
2370 static void
2371 indirblk_insert(freework)
2372 	struct freework *freework;
2373 {
2374 	struct jblocks *jblocks;
2375 	struct jseg *jseg;
2376 	struct ufsmount *ump;
2377 
2378 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2379 	jblocks = ump->softdep_jblocks;
2380 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2381 	if (jseg == NULL)
2382 		return;
2383 
2384 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2385 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2386 	    fw_next);
2387 	freework->fw_state &= ~DEPCOMPLETE;
2388 }
2389 
2390 static void
2391 indirblk_remove(freework)
2392 	struct freework *freework;
2393 {
2394 	struct ufsmount *ump;
2395 
2396 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2397 	LIST_REMOVE(freework, fw_segs);
2398 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2399 	freework->fw_state |= DEPCOMPLETE;
2400 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2401 		WORKITEM_FREE(freework, D_FREEWORK);
2402 }
2403 
2404 /*
2405  * Executed during filesystem system initialization before
2406  * mounting any filesystems.
2407  */
2408 void
2409 softdep_initialize()
2410 {
2411 
2412 	TAILQ_INIT(&softdepmounts);
2413 #ifdef __LP64__
2414 	max_softdeps = desiredvnodes * 4;
2415 #else
2416 	max_softdeps = desiredvnodes * 2;
2417 #endif
2418 
2419 	/* initialise bioops hack */
2420 	bioops.io_start = softdep_disk_io_initiation;
2421 	bioops.io_complete = softdep_disk_write_complete;
2422 	bioops.io_deallocate = softdep_deallocate_dependencies;
2423 	bioops.io_countdeps = softdep_count_dependencies;
2424 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2425 
2426 	/* Initialize the callout with an mtx. */
2427 	callout_init_mtx(&softdep_callout, &lk, 0);
2428 }
2429 
2430 /*
2431  * Executed after all filesystems have been unmounted during
2432  * filesystem module unload.
2433  */
2434 void
2435 softdep_uninitialize()
2436 {
2437 
2438 	/* clear bioops hack */
2439 	bioops.io_start = NULL;
2440 	bioops.io_complete = NULL;
2441 	bioops.io_deallocate = NULL;
2442 	bioops.io_countdeps = NULL;
2443 	softdep_ast_cleanup = NULL;
2444 
2445 	callout_drain(&softdep_callout);
2446 }
2447 
2448 /*
2449  * Called at mount time to notify the dependency code that a
2450  * filesystem wishes to use it.
2451  */
2452 int
2453 softdep_mount(devvp, mp, fs, cred)
2454 	struct vnode *devvp;
2455 	struct mount *mp;
2456 	struct fs *fs;
2457 	struct ucred *cred;
2458 {
2459 	struct csum_total cstotal;
2460 	struct mount_softdeps *sdp;
2461 	struct ufsmount *ump;
2462 	struct cg *cgp;
2463 	struct buf *bp;
2464 	int i, error, cyl;
2465 
2466 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2467 	    M_WAITOK | M_ZERO);
2468 	MNT_ILOCK(mp);
2469 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2470 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2471 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2472 			MNTK_SOFTDEP | MNTK_NOASYNC;
2473 	}
2474 	ump = VFSTOUFS(mp);
2475 	ump->um_softdep = sdp;
2476 	MNT_IUNLOCK(mp);
2477 	rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2478 	sdp->sd_ump = ump;
2479 	LIST_INIT(&ump->softdep_workitem_pending);
2480 	LIST_INIT(&ump->softdep_journal_pending);
2481 	TAILQ_INIT(&ump->softdep_unlinked);
2482 	LIST_INIT(&ump->softdep_dirtycg);
2483 	ump->softdep_worklist_tail = NULL;
2484 	ump->softdep_on_worklist = 0;
2485 	ump->softdep_deps = 0;
2486 	LIST_INIT(&ump->softdep_mkdirlisthd);
2487 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2488 	    &ump->pagedep_hash_size);
2489 	ump->pagedep_nextclean = 0;
2490 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2491 	    &ump->inodedep_hash_size);
2492 	ump->inodedep_nextclean = 0;
2493 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2494 	    &ump->newblk_hash_size);
2495 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2496 	    &ump->bmsafemap_hash_size);
2497 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2498 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2499 	    M_FREEWORK, M_WAITOK);
2500 	ump->indir_hash_size = i - 1;
2501 	for (i = 0; i <= ump->indir_hash_size; i++)
2502 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2503 	ACQUIRE_GBLLOCK(&lk);
2504 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2505 	FREE_GBLLOCK(&lk);
2506 	if ((fs->fs_flags & FS_SUJ) &&
2507 	    (error = journal_mount(mp, fs, cred)) != 0) {
2508 		printf("Failed to start journal: %d\n", error);
2509 		softdep_unmount(mp);
2510 		return (error);
2511 	}
2512 	/*
2513 	 * Start our flushing thread in the bufdaemon process.
2514 	 */
2515 	ACQUIRE_LOCK(ump);
2516 	ump->softdep_flags |= FLUSH_STARTING;
2517 	FREE_LOCK(ump);
2518 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2519 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2520 	    mp->mnt_stat.f_mntonname);
2521 	ACQUIRE_LOCK(ump);
2522 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2523 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2524 		    hz / 2);
2525 	}
2526 	FREE_LOCK(ump);
2527 	/*
2528 	 * When doing soft updates, the counters in the
2529 	 * superblock may have gotten out of sync. Recomputation
2530 	 * can take a long time and can be deferred for background
2531 	 * fsck.  However, the old behavior of scanning the cylinder
2532 	 * groups and recalculating them at mount time is available
2533 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2534 	 */
2535 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2536 		return (0);
2537 	bzero(&cstotal, sizeof cstotal);
2538 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2539 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2540 		    fs->fs_cgsize, cred, &bp)) != 0) {
2541 			brelse(bp);
2542 			softdep_unmount(mp);
2543 			return (error);
2544 		}
2545 		cgp = (struct cg *)bp->b_data;
2546 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2547 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2548 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2549 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2550 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2551 		brelse(bp);
2552 	}
2553 #ifdef DEBUG
2554 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2555 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2556 #endif
2557 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2558 	return (0);
2559 }
2560 
2561 void
2562 softdep_unmount(mp)
2563 	struct mount *mp;
2564 {
2565 	struct ufsmount *ump;
2566 #ifdef INVARIANTS
2567 	int i;
2568 #endif
2569 
2570 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2571 	    ("softdep_unmount called on non-softdep filesystem"));
2572 	ump = VFSTOUFS(mp);
2573 	MNT_ILOCK(mp);
2574 	mp->mnt_flag &= ~MNT_SOFTDEP;
2575 	if (MOUNTEDSUJ(mp) == 0) {
2576 		MNT_IUNLOCK(mp);
2577 	} else {
2578 		mp->mnt_flag &= ~MNT_SUJ;
2579 		MNT_IUNLOCK(mp);
2580 		journal_unmount(ump);
2581 	}
2582 	/*
2583 	 * Shut down our flushing thread. Check for NULL is if
2584 	 * softdep_mount errors out before the thread has been created.
2585 	 */
2586 	if (ump->softdep_flushtd != NULL) {
2587 		ACQUIRE_LOCK(ump);
2588 		ump->softdep_flags |= FLUSH_EXIT;
2589 		wakeup(&ump->softdep_flushtd);
2590 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2591 		    "sdwait", 0);
2592 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2593 		    ("Thread shutdown failed"));
2594 	}
2595 	/*
2596 	 * Free up our resources.
2597 	 */
2598 	ACQUIRE_GBLLOCK(&lk);
2599 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2600 	FREE_GBLLOCK(&lk);
2601 	rw_destroy(LOCK_PTR(ump));
2602 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2603 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2604 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2605 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2606 	    ump->bmsafemap_hash_size);
2607 	free(ump->indir_hashtbl, M_FREEWORK);
2608 #ifdef INVARIANTS
2609 	for (i = 0; i <= D_LAST; i++)
2610 		KASSERT(ump->softdep_curdeps[i] == 0,
2611 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2612 		    TYPENAME(i), ump->softdep_curdeps[i]));
2613 #endif
2614 	free(ump->um_softdep, M_MOUNTDATA);
2615 }
2616 
2617 static struct jblocks *
2618 jblocks_create(void)
2619 {
2620 	struct jblocks *jblocks;
2621 
2622 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2623 	TAILQ_INIT(&jblocks->jb_segs);
2624 	jblocks->jb_avail = 10;
2625 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2626 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2627 
2628 	return (jblocks);
2629 }
2630 
2631 static ufs2_daddr_t
2632 jblocks_alloc(jblocks, bytes, actual)
2633 	struct jblocks *jblocks;
2634 	int bytes;
2635 	int *actual;
2636 {
2637 	ufs2_daddr_t daddr;
2638 	struct jextent *jext;
2639 	int freecnt;
2640 	int blocks;
2641 
2642 	blocks = bytes / DEV_BSIZE;
2643 	jext = &jblocks->jb_extent[jblocks->jb_head];
2644 	freecnt = jext->je_blocks - jblocks->jb_off;
2645 	if (freecnt == 0) {
2646 		jblocks->jb_off = 0;
2647 		if (++jblocks->jb_head > jblocks->jb_used)
2648 			jblocks->jb_head = 0;
2649 		jext = &jblocks->jb_extent[jblocks->jb_head];
2650 		freecnt = jext->je_blocks;
2651 	}
2652 	if (freecnt > blocks)
2653 		freecnt = blocks;
2654 	*actual = freecnt * DEV_BSIZE;
2655 	daddr = jext->je_daddr + jblocks->jb_off;
2656 	jblocks->jb_off += freecnt;
2657 	jblocks->jb_free -= freecnt;
2658 
2659 	return (daddr);
2660 }
2661 
2662 static void
2663 jblocks_free(jblocks, mp, bytes)
2664 	struct jblocks *jblocks;
2665 	struct mount *mp;
2666 	int bytes;
2667 {
2668 
2669 	LOCK_OWNED(VFSTOUFS(mp));
2670 	jblocks->jb_free += bytes / DEV_BSIZE;
2671 	if (jblocks->jb_suspended)
2672 		worklist_speedup(mp);
2673 	wakeup(jblocks);
2674 }
2675 
2676 static void
2677 jblocks_destroy(jblocks)
2678 	struct jblocks *jblocks;
2679 {
2680 
2681 	if (jblocks->jb_extent)
2682 		free(jblocks->jb_extent, M_JBLOCKS);
2683 	free(jblocks, M_JBLOCKS);
2684 }
2685 
2686 static void
2687 jblocks_add(jblocks, daddr, blocks)
2688 	struct jblocks *jblocks;
2689 	ufs2_daddr_t daddr;
2690 	int blocks;
2691 {
2692 	struct jextent *jext;
2693 
2694 	jblocks->jb_blocks += blocks;
2695 	jblocks->jb_free += blocks;
2696 	jext = &jblocks->jb_extent[jblocks->jb_used];
2697 	/* Adding the first block. */
2698 	if (jext->je_daddr == 0) {
2699 		jext->je_daddr = daddr;
2700 		jext->je_blocks = blocks;
2701 		return;
2702 	}
2703 	/* Extending the last extent. */
2704 	if (jext->je_daddr + jext->je_blocks == daddr) {
2705 		jext->je_blocks += blocks;
2706 		return;
2707 	}
2708 	/* Adding a new extent. */
2709 	if (++jblocks->jb_used == jblocks->jb_avail) {
2710 		jblocks->jb_avail *= 2;
2711 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2712 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2713 		memcpy(jext, jblocks->jb_extent,
2714 		    sizeof(struct jextent) * jblocks->jb_used);
2715 		free(jblocks->jb_extent, M_JBLOCKS);
2716 		jblocks->jb_extent = jext;
2717 	}
2718 	jext = &jblocks->jb_extent[jblocks->jb_used];
2719 	jext->je_daddr = daddr;
2720 	jext->je_blocks = blocks;
2721 	return;
2722 }
2723 
2724 int
2725 softdep_journal_lookup(mp, vpp)
2726 	struct mount *mp;
2727 	struct vnode **vpp;
2728 {
2729 	struct componentname cnp;
2730 	struct vnode *dvp;
2731 	ino_t sujournal;
2732 	int error;
2733 
2734 	error = VFS_VGET(mp, ROOTINO, LK_EXCLUSIVE, &dvp);
2735 	if (error)
2736 		return (error);
2737 	bzero(&cnp, sizeof(cnp));
2738 	cnp.cn_nameiop = LOOKUP;
2739 	cnp.cn_flags = ISLASTCN;
2740 	cnp.cn_thread = curthread;
2741 	cnp.cn_cred = curthread->td_ucred;
2742 	cnp.cn_pnbuf = SUJ_FILE;
2743 	cnp.cn_nameptr = SUJ_FILE;
2744 	cnp.cn_namelen = strlen(SUJ_FILE);
2745 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2746 	vput(dvp);
2747 	if (error != 0)
2748 		return (error);
2749 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2750 	return (error);
2751 }
2752 
2753 /*
2754  * Open and verify the journal file.
2755  */
2756 static int
2757 journal_mount(mp, fs, cred)
2758 	struct mount *mp;
2759 	struct fs *fs;
2760 	struct ucred *cred;
2761 {
2762 	struct jblocks *jblocks;
2763 	struct ufsmount *ump;
2764 	struct vnode *vp;
2765 	struct inode *ip;
2766 	ufs2_daddr_t blkno;
2767 	int bcount;
2768 	int error;
2769 	int i;
2770 
2771 	ump = VFSTOUFS(mp);
2772 	ump->softdep_journal_tail = NULL;
2773 	ump->softdep_on_journal = 0;
2774 	ump->softdep_accdeps = 0;
2775 	ump->softdep_req = 0;
2776 	ump->softdep_jblocks = NULL;
2777 	error = softdep_journal_lookup(mp, &vp);
2778 	if (error != 0) {
2779 		printf("Failed to find journal.  Use tunefs to create one\n");
2780 		return (error);
2781 	}
2782 	ip = VTOI(vp);
2783 	if (ip->i_size < SUJ_MIN) {
2784 		error = ENOSPC;
2785 		goto out;
2786 	}
2787 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2788 	jblocks = jblocks_create();
2789 	for (i = 0; i < bcount; i++) {
2790 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2791 		if (error)
2792 			break;
2793 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2794 	}
2795 	if (error) {
2796 		jblocks_destroy(jblocks);
2797 		goto out;
2798 	}
2799 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2800 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2801 	ump->softdep_jblocks = jblocks;
2802 out:
2803 	if (error == 0) {
2804 		MNT_ILOCK(mp);
2805 		mp->mnt_flag |= MNT_SUJ;
2806 		mp->mnt_flag &= ~MNT_SOFTDEP;
2807 		MNT_IUNLOCK(mp);
2808 		/*
2809 		 * Only validate the journal contents if the
2810 		 * filesystem is clean, otherwise we write the logs
2811 		 * but they'll never be used.  If the filesystem was
2812 		 * still dirty when we mounted it the journal is
2813 		 * invalid and a new journal can only be valid if it
2814 		 * starts from a clean mount.
2815 		 */
2816 		if (fs->fs_clean) {
2817 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2818 			ip->i_flags |= IN_MODIFIED;
2819 			ffs_update(vp, 1);
2820 		}
2821 	}
2822 	vput(vp);
2823 	return (error);
2824 }
2825 
2826 static void
2827 journal_unmount(ump)
2828 	struct ufsmount *ump;
2829 {
2830 
2831 	if (ump->softdep_jblocks)
2832 		jblocks_destroy(ump->softdep_jblocks);
2833 	ump->softdep_jblocks = NULL;
2834 }
2835 
2836 /*
2837  * Called when a journal record is ready to be written.  Space is allocated
2838  * and the journal entry is created when the journal is flushed to stable
2839  * store.
2840  */
2841 static void
2842 add_to_journal(wk)
2843 	struct worklist *wk;
2844 {
2845 	struct ufsmount *ump;
2846 
2847 	ump = VFSTOUFS(wk->wk_mp);
2848 	LOCK_OWNED(ump);
2849 	if (wk->wk_state & ONWORKLIST)
2850 		panic("add_to_journal: %s(0x%X) already on list",
2851 		    TYPENAME(wk->wk_type), wk->wk_state);
2852 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2853 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2854 		ump->softdep_jblocks->jb_age = ticks;
2855 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2856 	} else
2857 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2858 	ump->softdep_journal_tail = wk;
2859 	ump->softdep_on_journal += 1;
2860 }
2861 
2862 /*
2863  * Remove an arbitrary item for the journal worklist maintain the tail
2864  * pointer.  This happens when a new operation obviates the need to
2865  * journal an old operation.
2866  */
2867 static void
2868 remove_from_journal(wk)
2869 	struct worklist *wk;
2870 {
2871 	struct ufsmount *ump;
2872 
2873 	ump = VFSTOUFS(wk->wk_mp);
2874 	LOCK_OWNED(ump);
2875 #ifdef SUJ_DEBUG
2876 	{
2877 		struct worklist *wkn;
2878 
2879 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2880 			if (wkn == wk)
2881 				break;
2882 		if (wkn == NULL)
2883 			panic("remove_from_journal: %p is not in journal", wk);
2884 	}
2885 #endif
2886 	/*
2887 	 * We emulate a TAILQ to save space in most structures which do not
2888 	 * require TAILQ semantics.  Here we must update the tail position
2889 	 * when removing the tail which is not the final entry. This works
2890 	 * only if the worklist linkage are at the beginning of the structure.
2891 	 */
2892 	if (ump->softdep_journal_tail == wk)
2893 		ump->softdep_journal_tail =
2894 		    (struct worklist *)wk->wk_list.le_prev;
2895 
2896 	WORKLIST_REMOVE(wk);
2897 	ump->softdep_on_journal -= 1;
2898 }
2899 
2900 /*
2901  * Check for journal space as well as dependency limits so the prelink
2902  * code can throttle both journaled and non-journaled filesystems.
2903  * Threshold is 0 for low and 1 for min.
2904  */
2905 static int
2906 journal_space(ump, thresh)
2907 	struct ufsmount *ump;
2908 	int thresh;
2909 {
2910 	struct jblocks *jblocks;
2911 	int limit, avail;
2912 
2913 	jblocks = ump->softdep_jblocks;
2914 	if (jblocks == NULL)
2915 		return (1);
2916 	/*
2917 	 * We use a tighter restriction here to prevent request_cleanup()
2918 	 * running in threads from running into locks we currently hold.
2919 	 * We have to be over the limit and our filesystem has to be
2920 	 * responsible for more than our share of that usage.
2921 	 */
2922 	limit = (max_softdeps / 10) * 9;
2923 	if (dep_current[D_INODEDEP] > limit &&
2924 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2925 		return (0);
2926 	if (thresh)
2927 		thresh = jblocks->jb_min;
2928 	else
2929 		thresh = jblocks->jb_low;
2930 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2931 	avail = jblocks->jb_free - avail;
2932 
2933 	return (avail > thresh);
2934 }
2935 
2936 static void
2937 journal_suspend(ump)
2938 	struct ufsmount *ump;
2939 {
2940 	struct jblocks *jblocks;
2941 	struct mount *mp;
2942 
2943 	mp = UFSTOVFS(ump);
2944 	jblocks = ump->softdep_jblocks;
2945 	MNT_ILOCK(mp);
2946 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2947 		stat_journal_min++;
2948 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2949 		mp->mnt_susp_owner = ump->softdep_flushtd;
2950 	}
2951 	jblocks->jb_suspended = 1;
2952 	MNT_IUNLOCK(mp);
2953 }
2954 
2955 static int
2956 journal_unsuspend(struct ufsmount *ump)
2957 {
2958 	struct jblocks *jblocks;
2959 	struct mount *mp;
2960 
2961 	mp = UFSTOVFS(ump);
2962 	jblocks = ump->softdep_jblocks;
2963 
2964 	if (jblocks != NULL && jblocks->jb_suspended &&
2965 	    journal_space(ump, jblocks->jb_min)) {
2966 		jblocks->jb_suspended = 0;
2967 		FREE_LOCK(ump);
2968 		mp->mnt_susp_owner = curthread;
2969 		vfs_write_resume(mp, 0);
2970 		ACQUIRE_LOCK(ump);
2971 		return (1);
2972 	}
2973 	return (0);
2974 }
2975 
2976 /*
2977  * Called before any allocation function to be certain that there is
2978  * sufficient space in the journal prior to creating any new records.
2979  * Since in the case of block allocation we may have multiple locked
2980  * buffers at the time of the actual allocation we can not block
2981  * when the journal records are created.  Doing so would create a deadlock
2982  * if any of these buffers needed to be flushed to reclaim space.  Instead
2983  * we require a sufficiently large amount of available space such that
2984  * each thread in the system could have passed this allocation check and
2985  * still have sufficient free space.  With 20% of a minimum journal size
2986  * of 1MB we have 6553 records available.
2987  */
2988 int
2989 softdep_prealloc(vp, waitok)
2990 	struct vnode *vp;
2991 	int waitok;
2992 {
2993 	struct ufsmount *ump;
2994 
2995 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
2996 	    ("softdep_prealloc called on non-softdep filesystem"));
2997 	/*
2998 	 * Nothing to do if we are not running journaled soft updates.
2999 	 * If we currently hold the snapshot lock, we must avoid handling
3000 	 * other resources that could cause deadlock.
3001 	 */
3002 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)))
3003 		return (0);
3004 	ump = VFSTOUFS(vp->v_mount);
3005 	ACQUIRE_LOCK(ump);
3006 	if (journal_space(ump, 0)) {
3007 		FREE_LOCK(ump);
3008 		return (0);
3009 	}
3010 	stat_journal_low++;
3011 	FREE_LOCK(ump);
3012 	if (waitok == MNT_NOWAIT)
3013 		return (ENOSPC);
3014 	/*
3015 	 * Attempt to sync this vnode once to flush any journal
3016 	 * work attached to it.
3017 	 */
3018 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3019 		ffs_syncvnode(vp, waitok, 0);
3020 	ACQUIRE_LOCK(ump);
3021 	process_removes(vp);
3022 	process_truncates(vp);
3023 	if (journal_space(ump, 0) == 0) {
3024 		softdep_speedup(ump);
3025 		if (journal_space(ump, 1) == 0)
3026 			journal_suspend(ump);
3027 	}
3028 	FREE_LOCK(ump);
3029 
3030 	return (0);
3031 }
3032 
3033 /*
3034  * Before adjusting a link count on a vnode verify that we have sufficient
3035  * journal space.  If not, process operations that depend on the currently
3036  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3037  * and softdep flush threads can not acquire these locks to reclaim space.
3038  */
3039 static void
3040 softdep_prelink(dvp, vp)
3041 	struct vnode *dvp;
3042 	struct vnode *vp;
3043 {
3044 	struct ufsmount *ump;
3045 
3046 	ump = VFSTOUFS(dvp->v_mount);
3047 	LOCK_OWNED(ump);
3048 	/*
3049 	 * Nothing to do if we have sufficient journal space.
3050 	 * If we currently hold the snapshot lock, we must avoid
3051 	 * handling other resources that could cause deadlock.
3052 	 */
3053 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3054 		return;
3055 	stat_journal_low++;
3056 	FREE_LOCK(ump);
3057 	if (vp)
3058 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3059 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3060 	ACQUIRE_LOCK(ump);
3061 	/* Process vp before dvp as it may create .. removes. */
3062 	if (vp) {
3063 		process_removes(vp);
3064 		process_truncates(vp);
3065 	}
3066 	process_removes(dvp);
3067 	process_truncates(dvp);
3068 	softdep_speedup(ump);
3069 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3070 	if (journal_space(ump, 0) == 0) {
3071 		softdep_speedup(ump);
3072 		if (journal_space(ump, 1) == 0)
3073 			journal_suspend(ump);
3074 	}
3075 }
3076 
3077 static void
3078 jseg_write(ump, jseg, data)
3079 	struct ufsmount *ump;
3080 	struct jseg *jseg;
3081 	uint8_t *data;
3082 {
3083 	struct jsegrec *rec;
3084 
3085 	rec = (struct jsegrec *)data;
3086 	rec->jsr_seq = jseg->js_seq;
3087 	rec->jsr_oldest = jseg->js_oldseq;
3088 	rec->jsr_cnt = jseg->js_cnt;
3089 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3090 	rec->jsr_crc = 0;
3091 	rec->jsr_time = ump->um_fs->fs_mtime;
3092 }
3093 
3094 static inline void
3095 inoref_write(inoref, jseg, rec)
3096 	struct inoref *inoref;
3097 	struct jseg *jseg;
3098 	struct jrefrec *rec;
3099 {
3100 
3101 	inoref->if_jsegdep->jd_seg = jseg;
3102 	rec->jr_ino = inoref->if_ino;
3103 	rec->jr_parent = inoref->if_parent;
3104 	rec->jr_nlink = inoref->if_nlink;
3105 	rec->jr_mode = inoref->if_mode;
3106 	rec->jr_diroff = inoref->if_diroff;
3107 }
3108 
3109 static void
3110 jaddref_write(jaddref, jseg, data)
3111 	struct jaddref *jaddref;
3112 	struct jseg *jseg;
3113 	uint8_t *data;
3114 {
3115 	struct jrefrec *rec;
3116 
3117 	rec = (struct jrefrec *)data;
3118 	rec->jr_op = JOP_ADDREF;
3119 	inoref_write(&jaddref->ja_ref, jseg, rec);
3120 }
3121 
3122 static void
3123 jremref_write(jremref, jseg, data)
3124 	struct jremref *jremref;
3125 	struct jseg *jseg;
3126 	uint8_t *data;
3127 {
3128 	struct jrefrec *rec;
3129 
3130 	rec = (struct jrefrec *)data;
3131 	rec->jr_op = JOP_REMREF;
3132 	inoref_write(&jremref->jr_ref, jseg, rec);
3133 }
3134 
3135 static void
3136 jmvref_write(jmvref, jseg, data)
3137 	struct jmvref *jmvref;
3138 	struct jseg *jseg;
3139 	uint8_t *data;
3140 {
3141 	struct jmvrec *rec;
3142 
3143 	rec = (struct jmvrec *)data;
3144 	rec->jm_op = JOP_MVREF;
3145 	rec->jm_ino = jmvref->jm_ino;
3146 	rec->jm_parent = jmvref->jm_parent;
3147 	rec->jm_oldoff = jmvref->jm_oldoff;
3148 	rec->jm_newoff = jmvref->jm_newoff;
3149 }
3150 
3151 static void
3152 jnewblk_write(jnewblk, jseg, data)
3153 	struct jnewblk *jnewblk;
3154 	struct jseg *jseg;
3155 	uint8_t *data;
3156 {
3157 	struct jblkrec *rec;
3158 
3159 	jnewblk->jn_jsegdep->jd_seg = jseg;
3160 	rec = (struct jblkrec *)data;
3161 	rec->jb_op = JOP_NEWBLK;
3162 	rec->jb_ino = jnewblk->jn_ino;
3163 	rec->jb_blkno = jnewblk->jn_blkno;
3164 	rec->jb_lbn = jnewblk->jn_lbn;
3165 	rec->jb_frags = jnewblk->jn_frags;
3166 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3167 }
3168 
3169 static void
3170 jfreeblk_write(jfreeblk, jseg, data)
3171 	struct jfreeblk *jfreeblk;
3172 	struct jseg *jseg;
3173 	uint8_t *data;
3174 {
3175 	struct jblkrec *rec;
3176 
3177 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3178 	rec = (struct jblkrec *)data;
3179 	rec->jb_op = JOP_FREEBLK;
3180 	rec->jb_ino = jfreeblk->jf_ino;
3181 	rec->jb_blkno = jfreeblk->jf_blkno;
3182 	rec->jb_lbn = jfreeblk->jf_lbn;
3183 	rec->jb_frags = jfreeblk->jf_frags;
3184 	rec->jb_oldfrags = 0;
3185 }
3186 
3187 static void
3188 jfreefrag_write(jfreefrag, jseg, data)
3189 	struct jfreefrag *jfreefrag;
3190 	struct jseg *jseg;
3191 	uint8_t *data;
3192 {
3193 	struct jblkrec *rec;
3194 
3195 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3196 	rec = (struct jblkrec *)data;
3197 	rec->jb_op = JOP_FREEBLK;
3198 	rec->jb_ino = jfreefrag->fr_ino;
3199 	rec->jb_blkno = jfreefrag->fr_blkno;
3200 	rec->jb_lbn = jfreefrag->fr_lbn;
3201 	rec->jb_frags = jfreefrag->fr_frags;
3202 	rec->jb_oldfrags = 0;
3203 }
3204 
3205 static void
3206 jtrunc_write(jtrunc, jseg, data)
3207 	struct jtrunc *jtrunc;
3208 	struct jseg *jseg;
3209 	uint8_t *data;
3210 {
3211 	struct jtrncrec *rec;
3212 
3213 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3214 	rec = (struct jtrncrec *)data;
3215 	rec->jt_op = JOP_TRUNC;
3216 	rec->jt_ino = jtrunc->jt_ino;
3217 	rec->jt_size = jtrunc->jt_size;
3218 	rec->jt_extsize = jtrunc->jt_extsize;
3219 }
3220 
3221 static void
3222 jfsync_write(jfsync, jseg, data)
3223 	struct jfsync *jfsync;
3224 	struct jseg *jseg;
3225 	uint8_t *data;
3226 {
3227 	struct jtrncrec *rec;
3228 
3229 	rec = (struct jtrncrec *)data;
3230 	rec->jt_op = JOP_SYNC;
3231 	rec->jt_ino = jfsync->jfs_ino;
3232 	rec->jt_size = jfsync->jfs_size;
3233 	rec->jt_extsize = jfsync->jfs_extsize;
3234 }
3235 
3236 static void
3237 softdep_flushjournal(mp)
3238 	struct mount *mp;
3239 {
3240 	struct jblocks *jblocks;
3241 	struct ufsmount *ump;
3242 
3243 	if (MOUNTEDSUJ(mp) == 0)
3244 		return;
3245 	ump = VFSTOUFS(mp);
3246 	jblocks = ump->softdep_jblocks;
3247 	ACQUIRE_LOCK(ump);
3248 	while (ump->softdep_on_journal) {
3249 		jblocks->jb_needseg = 1;
3250 		softdep_process_journal(mp, NULL, MNT_WAIT);
3251 	}
3252 	FREE_LOCK(ump);
3253 }
3254 
3255 static void softdep_synchronize_completed(struct bio *);
3256 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3257 
3258 static void
3259 softdep_synchronize_completed(bp)
3260         struct bio *bp;
3261 {
3262 	struct jseg *oldest;
3263 	struct jseg *jseg;
3264 	struct ufsmount *ump;
3265 
3266 	/*
3267 	 * caller1 marks the last segment written before we issued the
3268 	 * synchronize cache.
3269 	 */
3270 	jseg = bp->bio_caller1;
3271 	if (jseg == NULL) {
3272 		g_destroy_bio(bp);
3273 		return;
3274 	}
3275 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3276 	ACQUIRE_LOCK(ump);
3277 	oldest = NULL;
3278 	/*
3279 	 * Mark all the journal entries waiting on the synchronize cache
3280 	 * as completed so they may continue on.
3281 	 */
3282 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3283 		jseg->js_state |= COMPLETE;
3284 		oldest = jseg;
3285 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3286 	}
3287 	/*
3288 	 * Restart deferred journal entry processing from the oldest
3289 	 * completed jseg.
3290 	 */
3291 	if (oldest)
3292 		complete_jsegs(oldest);
3293 
3294 	FREE_LOCK(ump);
3295 	g_destroy_bio(bp);
3296 }
3297 
3298 /*
3299  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3300  * barriers.  The journal must be written prior to any blocks that depend
3301  * on it and the journal can not be released until the blocks have be
3302  * written.  This code handles both barriers simultaneously.
3303  */
3304 static void
3305 softdep_synchronize(bp, ump, caller1)
3306 	struct bio *bp;
3307 	struct ufsmount *ump;
3308 	void *caller1;
3309 {
3310 
3311 	bp->bio_cmd = BIO_FLUSH;
3312 	bp->bio_flags |= BIO_ORDERED;
3313 	bp->bio_data = NULL;
3314 	bp->bio_offset = ump->um_cp->provider->mediasize;
3315 	bp->bio_length = 0;
3316 	bp->bio_done = softdep_synchronize_completed;
3317 	bp->bio_caller1 = caller1;
3318 	g_io_request(bp,
3319 	    (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3320 }
3321 
3322 /*
3323  * Flush some journal records to disk.
3324  */
3325 static void
3326 softdep_process_journal(mp, needwk, flags)
3327 	struct mount *mp;
3328 	struct worklist *needwk;
3329 	int flags;
3330 {
3331 	struct jblocks *jblocks;
3332 	struct ufsmount *ump;
3333 	struct worklist *wk;
3334 	struct jseg *jseg;
3335 	struct buf *bp;
3336 	struct bio *bio;
3337 	uint8_t *data;
3338 	struct fs *fs;
3339 	int shouldflush;
3340 	int segwritten;
3341 	int jrecmin;	/* Minimum records per block. */
3342 	int jrecmax;	/* Maximum records per block. */
3343 	int size;
3344 	int cnt;
3345 	int off;
3346 	int devbsize;
3347 
3348 	if (MOUNTEDSUJ(mp) == 0)
3349 		return;
3350 	shouldflush = softdep_flushcache;
3351 	bio = NULL;
3352 	jseg = NULL;
3353 	ump = VFSTOUFS(mp);
3354 	LOCK_OWNED(ump);
3355 	fs = ump->um_fs;
3356 	jblocks = ump->softdep_jblocks;
3357 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3358 	/*
3359 	 * We write anywhere between a disk block and fs block.  The upper
3360 	 * bound is picked to prevent buffer cache fragmentation and limit
3361 	 * processing time per I/O.
3362 	 */
3363 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3364 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3365 	segwritten = 0;
3366 	for (;;) {
3367 		cnt = ump->softdep_on_journal;
3368 		/*
3369 		 * Criteria for writing a segment:
3370 		 * 1) We have a full block.
3371 		 * 2) We're called from jwait() and haven't found the
3372 		 *    journal item yet.
3373 		 * 3) Always write if needseg is set.
3374 		 * 4) If we are called from process_worklist and have
3375 		 *    not yet written anything we write a partial block
3376 		 *    to enforce a 1 second maximum latency on journal
3377 		 *    entries.
3378 		 */
3379 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3380 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3381 			break;
3382 		cnt++;
3383 		/*
3384 		 * Verify some free journal space.  softdep_prealloc() should
3385 		 * guarantee that we don't run out so this is indicative of
3386 		 * a problem with the flow control.  Try to recover
3387 		 * gracefully in any event.
3388 		 */
3389 		while (jblocks->jb_free == 0) {
3390 			if (flags != MNT_WAIT)
3391 				break;
3392 			printf("softdep: Out of journal space!\n");
3393 			softdep_speedup(ump);
3394 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3395 		}
3396 		FREE_LOCK(ump);
3397 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3398 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3399 		LIST_INIT(&jseg->js_entries);
3400 		LIST_INIT(&jseg->js_indirs);
3401 		jseg->js_state = ATTACHED;
3402 		if (shouldflush == 0)
3403 			jseg->js_state |= COMPLETE;
3404 		else if (bio == NULL)
3405 			bio = g_alloc_bio();
3406 		jseg->js_jblocks = jblocks;
3407 		bp = geteblk(fs->fs_bsize, 0);
3408 		ACQUIRE_LOCK(ump);
3409 		/*
3410 		 * If there was a race while we were allocating the block
3411 		 * and jseg the entry we care about was likely written.
3412 		 * We bail out in both the WAIT and NOWAIT case and assume
3413 		 * the caller will loop if the entry it cares about is
3414 		 * not written.
3415 		 */
3416 		cnt = ump->softdep_on_journal;
3417 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3418 			bp->b_flags |= B_INVAL | B_NOCACHE;
3419 			WORKITEM_FREE(jseg, D_JSEG);
3420 			FREE_LOCK(ump);
3421 			brelse(bp);
3422 			ACQUIRE_LOCK(ump);
3423 			break;
3424 		}
3425 		/*
3426 		 * Calculate the disk block size required for the available
3427 		 * records rounded to the min size.
3428 		 */
3429 		if (cnt == 0)
3430 			size = devbsize;
3431 		else if (cnt < jrecmax)
3432 			size = howmany(cnt, jrecmin) * devbsize;
3433 		else
3434 			size = fs->fs_bsize;
3435 		/*
3436 		 * Allocate a disk block for this journal data and account
3437 		 * for truncation of the requested size if enough contiguous
3438 		 * space was not available.
3439 		 */
3440 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3441 		bp->b_lblkno = bp->b_blkno;
3442 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3443 		bp->b_bcount = size;
3444 		bp->b_flags &= ~B_INVAL;
3445 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3446 		/*
3447 		 * Initialize our jseg with cnt records.  Assign the next
3448 		 * sequence number to it and link it in-order.
3449 		 */
3450 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3451 		jseg->js_buf = bp;
3452 		jseg->js_cnt = cnt;
3453 		jseg->js_refs = cnt + 1;	/* Self ref. */
3454 		jseg->js_size = size;
3455 		jseg->js_seq = jblocks->jb_nextseq++;
3456 		if (jblocks->jb_oldestseg == NULL)
3457 			jblocks->jb_oldestseg = jseg;
3458 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3459 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3460 		if (jblocks->jb_writeseg == NULL)
3461 			jblocks->jb_writeseg = jseg;
3462 		/*
3463 		 * Start filling in records from the pending list.
3464 		 */
3465 		data = bp->b_data;
3466 		off = 0;
3467 
3468 		/*
3469 		 * Always put a header on the first block.
3470 		 * XXX As with below, there might not be a chance to get
3471 		 * into the loop.  Ensure that something valid is written.
3472 		 */
3473 		jseg_write(ump, jseg, data);
3474 		off += JREC_SIZE;
3475 		data = bp->b_data + off;
3476 
3477 		/*
3478 		 * XXX Something is wrong here.  There's no work to do,
3479 		 * but we need to perform and I/O and allow it to complete
3480 		 * anyways.
3481 		 */
3482 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3483 			stat_emptyjblocks++;
3484 
3485 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3486 		    != NULL) {
3487 			if (cnt == 0)
3488 				break;
3489 			/* Place a segment header on every device block. */
3490 			if ((off % devbsize) == 0) {
3491 				jseg_write(ump, jseg, data);
3492 				off += JREC_SIZE;
3493 				data = bp->b_data + off;
3494 			}
3495 			if (wk == needwk)
3496 				needwk = NULL;
3497 			remove_from_journal(wk);
3498 			wk->wk_state |= INPROGRESS;
3499 			WORKLIST_INSERT(&jseg->js_entries, wk);
3500 			switch (wk->wk_type) {
3501 			case D_JADDREF:
3502 				jaddref_write(WK_JADDREF(wk), jseg, data);
3503 				break;
3504 			case D_JREMREF:
3505 				jremref_write(WK_JREMREF(wk), jseg, data);
3506 				break;
3507 			case D_JMVREF:
3508 				jmvref_write(WK_JMVREF(wk), jseg, data);
3509 				break;
3510 			case D_JNEWBLK:
3511 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3512 				break;
3513 			case D_JFREEBLK:
3514 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3515 				break;
3516 			case D_JFREEFRAG:
3517 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3518 				break;
3519 			case D_JTRUNC:
3520 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3521 				break;
3522 			case D_JFSYNC:
3523 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3524 				break;
3525 			default:
3526 				panic("process_journal: Unknown type %s",
3527 				    TYPENAME(wk->wk_type));
3528 				/* NOTREACHED */
3529 			}
3530 			off += JREC_SIZE;
3531 			data = bp->b_data + off;
3532 			cnt--;
3533 		}
3534 
3535 		/* Clear any remaining space so we don't leak kernel data */
3536 		if (size > off)
3537 			bzero(data, size - off);
3538 
3539 		/*
3540 		 * Write this one buffer and continue.
3541 		 */
3542 		segwritten = 1;
3543 		jblocks->jb_needseg = 0;
3544 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3545 		FREE_LOCK(ump);
3546 		pbgetvp(ump->um_devvp, bp);
3547 		/*
3548 		 * We only do the blocking wait once we find the journal
3549 		 * entry we're looking for.
3550 		 */
3551 		if (needwk == NULL && flags == MNT_WAIT)
3552 			bwrite(bp);
3553 		else
3554 			bawrite(bp);
3555 		ACQUIRE_LOCK(ump);
3556 	}
3557 	/*
3558 	 * If we wrote a segment issue a synchronize cache so the journal
3559 	 * is reflected on disk before the data is written.  Since reclaiming
3560 	 * journal space also requires writing a journal record this
3561 	 * process also enforces a barrier before reclamation.
3562 	 */
3563 	if (segwritten && shouldflush) {
3564 		softdep_synchronize(bio, ump,
3565 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3566 	} else if (bio)
3567 		g_destroy_bio(bio);
3568 	/*
3569 	 * If we've suspended the filesystem because we ran out of journal
3570 	 * space either try to sync it here to make some progress or
3571 	 * unsuspend it if we already have.
3572 	 */
3573 	if (flags == 0 && jblocks->jb_suspended) {
3574 		if (journal_unsuspend(ump))
3575 			return;
3576 		FREE_LOCK(ump);
3577 		VFS_SYNC(mp, MNT_NOWAIT);
3578 		ffs_sbupdate(ump, MNT_WAIT, 0);
3579 		ACQUIRE_LOCK(ump);
3580 	}
3581 }
3582 
3583 /*
3584  * Complete a jseg, allowing all dependencies awaiting journal writes
3585  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3586  * structures so that the journal segment can be freed to reclaim space.
3587  */
3588 static void
3589 complete_jseg(jseg)
3590 	struct jseg *jseg;
3591 {
3592 	struct worklist *wk;
3593 	struct jmvref *jmvref;
3594 	int waiting;
3595 #ifdef INVARIANTS
3596 	int i = 0;
3597 #endif
3598 
3599 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3600 		WORKLIST_REMOVE(wk);
3601 		waiting = wk->wk_state & IOWAITING;
3602 		wk->wk_state &= ~(INPROGRESS | IOWAITING);
3603 		wk->wk_state |= COMPLETE;
3604 		KASSERT(i++ < jseg->js_cnt,
3605 		    ("handle_written_jseg: overflow %d >= %d",
3606 		    i - 1, jseg->js_cnt));
3607 		switch (wk->wk_type) {
3608 		case D_JADDREF:
3609 			handle_written_jaddref(WK_JADDREF(wk));
3610 			break;
3611 		case D_JREMREF:
3612 			handle_written_jremref(WK_JREMREF(wk));
3613 			break;
3614 		case D_JMVREF:
3615 			rele_jseg(jseg);	/* No jsegdep. */
3616 			jmvref = WK_JMVREF(wk);
3617 			LIST_REMOVE(jmvref, jm_deps);
3618 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3619 				free_pagedep(jmvref->jm_pagedep);
3620 			WORKITEM_FREE(jmvref, D_JMVREF);
3621 			break;
3622 		case D_JNEWBLK:
3623 			handle_written_jnewblk(WK_JNEWBLK(wk));
3624 			break;
3625 		case D_JFREEBLK:
3626 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3627 			break;
3628 		case D_JTRUNC:
3629 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3630 			break;
3631 		case D_JFSYNC:
3632 			rele_jseg(jseg);	/* No jsegdep. */
3633 			WORKITEM_FREE(wk, D_JFSYNC);
3634 			break;
3635 		case D_JFREEFRAG:
3636 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3637 			break;
3638 		default:
3639 			panic("handle_written_jseg: Unknown type %s",
3640 			    TYPENAME(wk->wk_type));
3641 			/* NOTREACHED */
3642 		}
3643 		if (waiting)
3644 			wakeup(wk);
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, UFSTOVFS(dp->i_ump));
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, UFSTOVFS(dp->i_ump));
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, UFSTOVFS(dp->i_ump));
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 || lbn >= -NXADDR)
4133 		? 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(UFSTOVFS(ip->i_ump), 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(UFSTOVFS(dp->i_ump)) != 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(dp->i_ump);
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(dp->i_ump);
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(UFSTOVFS(dp->i_ump)) != 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(dp->i_ump);
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(dp->i_ump);
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(UFSTOVFS(dp->i_ump)) != 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(dp->i_ump);
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(dp->i_ump);
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(UFSTOVFS(dp->i_ump)) != 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(dp->i_ump);
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(dp->i_ump);
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(UFSTOVFS(dp->i_ump)) != 0,
4816 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4817 	dvp = ITOV(dp);
4818 	ACQUIRE_LOCK(dp->i_ump);
4819 	(void) inodedep_lookup_ip(ip);
4820 	(void) inodedep_lookup_ip(dp);
4821 	softdep_prelink(dvp, ITOV(ip));
4822 	FREE_LOCK(dp->i_ump);
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(UFSTOVFS(dp->i_ump)) != 0,
4837 	    ("softdep_setup_unlink called on non-softdep filesystem"));
4838 	dvp = ITOV(dp);
4839 	ACQUIRE_LOCK(dp->i_ump);
4840 	(void) inodedep_lookup_ip(ip);
4841 	(void) inodedep_lookup_ip(dp);
4842 	softdep_prelink(dvp, ITOV(ip));
4843 	FREE_LOCK(dp->i_ump);
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(UFSTOVFS(dp->i_ump)) != 0,
4860 	    ("softdep_revert_create called on non-softdep filesystem"));
4861 	dvp = ITOV(dp);
4862 	ACQUIRE_LOCK(dp->i_ump);
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(dp->i_ump);
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(UFSTOVFS(dp->i_ump)) != 0,
4888 	    ("softdep_revert_link called on non-softdep filesystem"));
4889 	dvp = ITOV(dp);
4890 	ACQUIRE_LOCK(dp->i_ump);
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(dp->i_ump);
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(UFSTOVFS(dp->i_ump)) != 0,
4917 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4918 	dvp = ITOV(dp);
4919 
4920 	ACQUIRE_LOCK(dp->i_ump);
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(dp->i_ump);
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(UFSTOVFS(dp->i_ump)) != 0,
4955 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
4956 	ACQUIRE_LOCK(dp->i_ump);
4957 	(void) inodedep_lookup_ip(ip);
4958 	(void) inodedep_lookup_ip(dp);
4959 	FREE_LOCK(dp->i_ump);
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 = UFSTOVFS(ip->i_ump);
5011 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5012 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5013 	fs = ip->i_ump->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(ip->i_ump);
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(ip->i_ump);
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 = UFSTOVFS(ip->i_ump);
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(ip->i_ump);
5295 	if (off >= 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(ip->i_ump);
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(ip->i_ump);
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 >= 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 = ip->i_fs;
5545 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5546 	    M_SOFTDEP_FLAGS);
5547 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, UFSTOVFS(ip->i_ump));
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 fs *fs;
5571 
5572 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5573 	    ip->i_number, blkno, size, lbn);
5574 	fs = ip->i_fs;
5575 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5576 		panic("newfreefrag: frag size");
5577 	freefrag = malloc(sizeof(struct freefrag),
5578 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5579 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ip->i_ump));
5580 	freefrag->ff_state = ATTACHED;
5581 	LIST_INIT(&freefrag->ff_jwork);
5582 	freefrag->ff_inum = ip->i_number;
5583 	freefrag->ff_vtype = ITOV(ip)->v_type;
5584 	freefrag->ff_blkno = blkno;
5585 	freefrag->ff_fragsize = size;
5586 
5587 	if (MOUNTEDSUJ(UFSTOVFS(ip->i_ump))) {
5588 		freefrag->ff_jdep = (struct worklist *)
5589 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5590 	} else {
5591 		freefrag->ff_state |= DEPCOMPLETE;
5592 		freefrag->ff_jdep = NULL;
5593 	}
5594 
5595 	return (freefrag);
5596 }
5597 
5598 /*
5599  * This workitem de-allocates fragments that were replaced during
5600  * file block allocation.
5601  */
5602 static void
5603 handle_workitem_freefrag(freefrag)
5604 	struct freefrag *freefrag;
5605 {
5606 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5607 	struct workhead wkhd;
5608 
5609 	CTR3(KTR_SUJ,
5610 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5611 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5612 	/*
5613 	 * It would be illegal to add new completion items to the
5614 	 * freefrag after it was schedule to be done so it must be
5615 	 * safe to modify the list head here.
5616 	 */
5617 	LIST_INIT(&wkhd);
5618 	ACQUIRE_LOCK(ump);
5619 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5620 	/*
5621 	 * If the journal has not been written we must cancel it here.
5622 	 */
5623 	if (freefrag->ff_jdep) {
5624 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5625 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5626 			    freefrag->ff_jdep->wk_type);
5627 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5628 	}
5629 	FREE_LOCK(ump);
5630 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5631 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5632 	ACQUIRE_LOCK(ump);
5633 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5634 	FREE_LOCK(ump);
5635 }
5636 
5637 /*
5638  * Set up a dependency structure for an external attributes data block.
5639  * This routine follows much of the structure of softdep_setup_allocdirect.
5640  * See the description of softdep_setup_allocdirect above for details.
5641  */
5642 void
5643 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5644 	struct inode *ip;
5645 	ufs_lbn_t off;
5646 	ufs2_daddr_t newblkno;
5647 	ufs2_daddr_t oldblkno;
5648 	long newsize;
5649 	long oldsize;
5650 	struct buf *bp;
5651 {
5652 	struct allocdirect *adp, *oldadp;
5653 	struct allocdirectlst *adphead;
5654 	struct freefrag *freefrag;
5655 	struct inodedep *inodedep;
5656 	struct jnewblk *jnewblk;
5657 	struct newblk *newblk;
5658 	struct mount *mp;
5659 	ufs_lbn_t lbn;
5660 
5661 	mp = UFSTOVFS(ip->i_ump);
5662 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5663 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5664 	KASSERT(off < NXADDR, ("softdep_setup_allocext: lbn %lld > NXADDR",
5665 		    (long long)off));
5666 
5667 	lbn = bp->b_lblkno;
5668 	if (oldblkno && oldblkno != newblkno)
5669 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5670 	else
5671 		freefrag = NULL;
5672 
5673 	ACQUIRE_LOCK(ip->i_ump);
5674 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5675 		panic("softdep_setup_allocext: lost block");
5676 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5677 	    ("softdep_setup_allocext: newblk already initialized"));
5678 	/*
5679 	 * Convert the newblk to an allocdirect.
5680 	 */
5681 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5682 	adp = (struct allocdirect *)newblk;
5683 	newblk->nb_freefrag = freefrag;
5684 	adp->ad_offset = off;
5685 	adp->ad_oldblkno = oldblkno;
5686 	adp->ad_newsize = newsize;
5687 	adp->ad_oldsize = oldsize;
5688 	adp->ad_state |=  EXTDATA;
5689 
5690 	/*
5691 	 * Finish initializing the journal.
5692 	 */
5693 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5694 		jnewblk->jn_ino = ip->i_number;
5695 		jnewblk->jn_lbn = lbn;
5696 		add_to_journal(&jnewblk->jn_list);
5697 	}
5698 	if (freefrag && freefrag->ff_jdep != NULL &&
5699 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5700 		add_to_journal(freefrag->ff_jdep);
5701 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5702 	adp->ad_inodedep = inodedep;
5703 
5704 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5705 	/*
5706 	 * The list of allocdirects must be kept in sorted and ascending
5707 	 * order so that the rollback routines can quickly determine the
5708 	 * first uncommitted block (the size of the file stored on disk
5709 	 * ends at the end of the lowest committed fragment, or if there
5710 	 * are no fragments, at the end of the highest committed block).
5711 	 * Since files generally grow, the typical case is that the new
5712 	 * block is to be added at the end of the list. We speed this
5713 	 * special case by checking against the last allocdirect in the
5714 	 * list before laboriously traversing the list looking for the
5715 	 * insertion point.
5716 	 */
5717 	adphead = &inodedep->id_newextupdt;
5718 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5719 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5720 		/* insert at end of list */
5721 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5722 		if (oldadp != NULL && oldadp->ad_offset == off)
5723 			allocdirect_merge(adphead, adp, oldadp);
5724 		FREE_LOCK(ip->i_ump);
5725 		return;
5726 	}
5727 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5728 		if (oldadp->ad_offset >= off)
5729 			break;
5730 	}
5731 	if (oldadp == NULL)
5732 		panic("softdep_setup_allocext: lost entry");
5733 	/* insert in middle of list */
5734 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5735 	if (oldadp->ad_offset == off)
5736 		allocdirect_merge(adphead, adp, oldadp);
5737 	FREE_LOCK(ip->i_ump);
5738 }
5739 
5740 /*
5741  * Indirect block allocation dependencies.
5742  *
5743  * The same dependencies that exist for a direct block also exist when
5744  * a new block is allocated and pointed to by an entry in a block of
5745  * indirect pointers. The undo/redo states described above are also
5746  * used here. Because an indirect block contains many pointers that
5747  * may have dependencies, a second copy of the entire in-memory indirect
5748  * block is kept. The buffer cache copy is always completely up-to-date.
5749  * The second copy, which is used only as a source for disk writes,
5750  * contains only the safe pointers (i.e., those that have no remaining
5751  * update dependencies). The second copy is freed when all pointers
5752  * are safe. The cache is not allowed to replace indirect blocks with
5753  * pending update dependencies. If a buffer containing an indirect
5754  * block with dependencies is written, these routines will mark it
5755  * dirty again. It can only be successfully written once all the
5756  * dependencies are removed. The ffs_fsync routine in conjunction with
5757  * softdep_sync_metadata work together to get all the dependencies
5758  * removed so that a file can be successfully written to disk. Three
5759  * procedures are used when setting up indirect block pointer
5760  * dependencies. The division is necessary because of the organization
5761  * of the "balloc" routine and because of the distinction between file
5762  * pages and file metadata blocks.
5763  */
5764 
5765 /*
5766  * Allocate a new allocindir structure.
5767  */
5768 static struct allocindir *
5769 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5770 	struct inode *ip;	/* inode for file being extended */
5771 	int ptrno;		/* offset of pointer in indirect block */
5772 	ufs2_daddr_t newblkno;	/* disk block number being added */
5773 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5774 	ufs_lbn_t lbn;
5775 {
5776 	struct newblk *newblk;
5777 	struct allocindir *aip;
5778 	struct freefrag *freefrag;
5779 	struct jnewblk *jnewblk;
5780 
5781 	if (oldblkno)
5782 		freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize, lbn);
5783 	else
5784 		freefrag = NULL;
5785 	ACQUIRE_LOCK(ip->i_ump);
5786 	if (newblk_lookup(UFSTOVFS(ip->i_ump), newblkno, 0, &newblk) == 0)
5787 		panic("new_allocindir: lost block");
5788 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5789 	    ("newallocindir: newblk already initialized"));
5790 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5791 	newblk->nb_freefrag = freefrag;
5792 	aip = (struct allocindir *)newblk;
5793 	aip->ai_offset = ptrno;
5794 	aip->ai_oldblkno = oldblkno;
5795 	aip->ai_lbn = lbn;
5796 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5797 		jnewblk->jn_ino = ip->i_number;
5798 		jnewblk->jn_lbn = lbn;
5799 		add_to_journal(&jnewblk->jn_list);
5800 	}
5801 	if (freefrag && freefrag->ff_jdep != NULL &&
5802 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5803 		add_to_journal(freefrag->ff_jdep);
5804 	return (aip);
5805 }
5806 
5807 /*
5808  * Called just before setting an indirect block pointer
5809  * to a newly allocated file page.
5810  */
5811 void
5812 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5813 	struct inode *ip;	/* inode for file being extended */
5814 	ufs_lbn_t lbn;		/* allocated block number within file */
5815 	struct buf *bp;		/* buffer with indirect blk referencing page */
5816 	int ptrno;		/* offset of pointer in indirect block */
5817 	ufs2_daddr_t newblkno;	/* disk block number being added */
5818 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5819 	struct buf *nbp;	/* buffer holding allocated page */
5820 {
5821 	struct inodedep *inodedep;
5822 	struct freefrag *freefrag;
5823 	struct allocindir *aip;
5824 	struct pagedep *pagedep;
5825 	struct mount *mp;
5826 
5827 	mp = UFSTOVFS(ip->i_ump);
5828 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5829 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5830 	KASSERT(lbn == nbp->b_lblkno,
5831 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5832 	    lbn, bp->b_lblkno));
5833 	CTR4(KTR_SUJ,
5834 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5835 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5836 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5837 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5838 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5839 	/*
5840 	 * If we are allocating a directory page, then we must
5841 	 * allocate an associated pagedep to track additions and
5842 	 * deletions.
5843 	 */
5844 	if ((ip->i_mode & IFMT) == IFDIR)
5845 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5846 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5847 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5848 	FREE_LOCK(ip->i_ump);
5849 	if (freefrag)
5850 		handle_workitem_freefrag(freefrag);
5851 }
5852 
5853 /*
5854  * Called just before setting an indirect block pointer to a
5855  * newly allocated indirect block.
5856  */
5857 void
5858 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5859 	struct buf *nbp;	/* newly allocated indirect block */
5860 	struct inode *ip;	/* inode for file being extended */
5861 	struct buf *bp;		/* indirect block referencing allocated block */
5862 	int ptrno;		/* offset of pointer in indirect block */
5863 	ufs2_daddr_t newblkno;	/* disk block number being added */
5864 {
5865 	struct inodedep *inodedep;
5866 	struct allocindir *aip;
5867 	ufs_lbn_t lbn;
5868 
5869 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
5870 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5871 	CTR3(KTR_SUJ,
5872 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5873 	    ip->i_number, newblkno, ptrno);
5874 	lbn = nbp->b_lblkno;
5875 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5876 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5877 	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, DEPALLOC,
5878 	    &inodedep);
5879 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5880 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5881 		panic("softdep_setup_allocindir_meta: Block already existed");
5882 	FREE_LOCK(ip->i_ump);
5883 }
5884 
5885 static void
5886 indirdep_complete(indirdep)
5887 	struct indirdep *indirdep;
5888 {
5889 	struct allocindir *aip;
5890 
5891 	LIST_REMOVE(indirdep, ir_next);
5892 	indirdep->ir_state |= DEPCOMPLETE;
5893 
5894 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5895 		LIST_REMOVE(aip, ai_next);
5896 		free_newblk(&aip->ai_block);
5897 	}
5898 	/*
5899 	 * If this indirdep is not attached to a buf it was simply waiting
5900 	 * on completion to clear completehd.  free_indirdep() asserts
5901 	 * that nothing is dangling.
5902 	 */
5903 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5904 		free_indirdep(indirdep);
5905 }
5906 
5907 static struct indirdep *
5908 indirdep_lookup(mp, ip, bp)
5909 	struct mount *mp;
5910 	struct inode *ip;
5911 	struct buf *bp;
5912 {
5913 	struct indirdep *indirdep, *newindirdep;
5914 	struct newblk *newblk;
5915 	struct ufsmount *ump;
5916 	struct worklist *wk;
5917 	struct fs *fs;
5918 	ufs2_daddr_t blkno;
5919 
5920 	ump = VFSTOUFS(mp);
5921 	LOCK_OWNED(ump);
5922 	indirdep = NULL;
5923 	newindirdep = NULL;
5924 	fs = ip->i_fs;
5925 	for (;;) {
5926 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5927 			if (wk->wk_type != D_INDIRDEP)
5928 				continue;
5929 			indirdep = WK_INDIRDEP(wk);
5930 			break;
5931 		}
5932 		/* Found on the buffer worklist, no new structure to free. */
5933 		if (indirdep != NULL && newindirdep == NULL)
5934 			return (indirdep);
5935 		if (indirdep != NULL && newindirdep != NULL)
5936 			panic("indirdep_lookup: simultaneous create");
5937 		/* None found on the buffer and a new structure is ready. */
5938 		if (indirdep == NULL && newindirdep != NULL)
5939 			break;
5940 		/* None found and no new structure available. */
5941 		FREE_LOCK(ump);
5942 		newindirdep = malloc(sizeof(struct indirdep),
5943 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
5944 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5945 		newindirdep->ir_state = ATTACHED;
5946 		if (ip->i_ump->um_fstype == UFS1)
5947 			newindirdep->ir_state |= UFS1FMT;
5948 		TAILQ_INIT(&newindirdep->ir_trunc);
5949 		newindirdep->ir_saveddata = NULL;
5950 		LIST_INIT(&newindirdep->ir_deplisthd);
5951 		LIST_INIT(&newindirdep->ir_donehd);
5952 		LIST_INIT(&newindirdep->ir_writehd);
5953 		LIST_INIT(&newindirdep->ir_completehd);
5954 		if (bp->b_blkno == bp->b_lblkno) {
5955 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5956 			    NULL, NULL);
5957 			bp->b_blkno = blkno;
5958 		}
5959 		newindirdep->ir_freeblks = NULL;
5960 		newindirdep->ir_savebp =
5961 		    getblk(ip->i_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5962 		newindirdep->ir_bp = bp;
5963 		BUF_KERNPROC(newindirdep->ir_savebp);
5964 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5965 		ACQUIRE_LOCK(ump);
5966 	}
5967 	indirdep = newindirdep;
5968 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5969 	/*
5970 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
5971 	 * that we don't free dependencies until the pointers are valid.
5972 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5973 	 * than using the hash.
5974 	 */
5975 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5976 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5977 	else
5978 		indirdep->ir_state |= DEPCOMPLETE;
5979 	return (indirdep);
5980 }
5981 
5982 /*
5983  * Called to finish the allocation of the "aip" allocated
5984  * by one of the two routines above.
5985  */
5986 static struct freefrag *
5987 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
5988 	struct buf *bp;		/* in-memory copy of the indirect block */
5989 	struct inode *ip;	/* inode for file being extended */
5990 	struct inodedep *inodedep; /* Inodedep for ip */
5991 	struct allocindir *aip;	/* allocindir allocated by the above routines */
5992 	ufs_lbn_t lbn;		/* Logical block number for this block. */
5993 {
5994 	struct fs *fs;
5995 	struct indirdep *indirdep;
5996 	struct allocindir *oldaip;
5997 	struct freefrag *freefrag;
5998 	struct mount *mp;
5999 
6000 	LOCK_OWNED(ip->i_ump);
6001 	mp = UFSTOVFS(ip->i_ump);
6002 	fs = ip->i_fs;
6003 	if (bp->b_lblkno >= 0)
6004 		panic("setup_allocindir_phase2: not indir blk");
6005 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6006 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6007 	indirdep = indirdep_lookup(mp, ip, bp);
6008 	KASSERT(indirdep->ir_savebp != NULL,
6009 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6010 	aip->ai_indirdep = indirdep;
6011 	/*
6012 	 * Check for an unwritten dependency for this indirect offset.  If
6013 	 * there is, merge the old dependency into the new one.  This happens
6014 	 * as a result of reallocblk only.
6015 	 */
6016 	freefrag = NULL;
6017 	if (aip->ai_oldblkno != 0) {
6018 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6019 			if (oldaip->ai_offset == aip->ai_offset) {
6020 				freefrag = allocindir_merge(aip, oldaip);
6021 				goto done;
6022 			}
6023 		}
6024 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6025 			if (oldaip->ai_offset == aip->ai_offset) {
6026 				freefrag = allocindir_merge(aip, oldaip);
6027 				goto done;
6028 			}
6029 		}
6030 	}
6031 done:
6032 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6033 	return (freefrag);
6034 }
6035 
6036 /*
6037  * Merge two allocindirs which refer to the same block.  Move newblock
6038  * dependencies and setup the freefrags appropriately.
6039  */
6040 static struct freefrag *
6041 allocindir_merge(aip, oldaip)
6042 	struct allocindir *aip;
6043 	struct allocindir *oldaip;
6044 {
6045 	struct freefrag *freefrag;
6046 	struct worklist *wk;
6047 
6048 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6049 		panic("allocindir_merge: blkno");
6050 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6051 	freefrag = aip->ai_freefrag;
6052 	aip->ai_freefrag = oldaip->ai_freefrag;
6053 	oldaip->ai_freefrag = NULL;
6054 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6055 	/*
6056 	 * If we are tracking a new directory-block allocation,
6057 	 * move it from the old allocindir to the new allocindir.
6058 	 */
6059 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6060 		WORKLIST_REMOVE(wk);
6061 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6062 			panic("allocindir_merge: extra newdirblk");
6063 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6064 	}
6065 	/*
6066 	 * We can skip journaling for this freefrag and just complete
6067 	 * any pending journal work for the allocindir that is being
6068 	 * removed after the freefrag completes.
6069 	 */
6070 	if (freefrag->ff_jdep)
6071 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6072 	LIST_REMOVE(oldaip, ai_next);
6073 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6074 	    &freefrag->ff_list, &freefrag->ff_jwork);
6075 	free_newblk(&oldaip->ai_block);
6076 
6077 	return (freefrag);
6078 }
6079 
6080 static inline void
6081 setup_freedirect(freeblks, ip, i, needj)
6082 	struct freeblks *freeblks;
6083 	struct inode *ip;
6084 	int i;
6085 	int needj;
6086 {
6087 	ufs2_daddr_t blkno;
6088 	int frags;
6089 
6090 	blkno = DIP(ip, i_db[i]);
6091 	if (blkno == 0)
6092 		return;
6093 	DIP_SET(ip, i_db[i], 0);
6094 	frags = sblksize(ip->i_fs, ip->i_size, i);
6095 	frags = numfrags(ip->i_fs, frags);
6096 	newfreework(ip->i_ump, freeblks, NULL, i, blkno, frags, 0, needj);
6097 }
6098 
6099 static inline void
6100 setup_freeext(freeblks, ip, i, needj)
6101 	struct freeblks *freeblks;
6102 	struct inode *ip;
6103 	int i;
6104 	int needj;
6105 {
6106 	ufs2_daddr_t blkno;
6107 	int frags;
6108 
6109 	blkno = ip->i_din2->di_extb[i];
6110 	if (blkno == 0)
6111 		return;
6112 	ip->i_din2->di_extb[i] = 0;
6113 	frags = sblksize(ip->i_fs, ip->i_din2->di_extsize, i);
6114 	frags = numfrags(ip->i_fs, frags);
6115 	newfreework(ip->i_ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6116 }
6117 
6118 static inline void
6119 setup_freeindir(freeblks, ip, i, lbn, needj)
6120 	struct freeblks *freeblks;
6121 	struct inode *ip;
6122 	int i;
6123 	ufs_lbn_t lbn;
6124 	int needj;
6125 {
6126 	ufs2_daddr_t blkno;
6127 
6128 	blkno = DIP(ip, i_ib[i]);
6129 	if (blkno == 0)
6130 		return;
6131 	DIP_SET(ip, i_ib[i], 0);
6132 	newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, ip->i_fs->fs_frag,
6133 	    0, needj);
6134 }
6135 
6136 static inline struct freeblks *
6137 newfreeblks(mp, ip)
6138 	struct mount *mp;
6139 	struct inode *ip;
6140 {
6141 	struct freeblks *freeblks;
6142 
6143 	freeblks = malloc(sizeof(struct freeblks),
6144 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6145 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6146 	LIST_INIT(&freeblks->fb_jblkdephd);
6147 	LIST_INIT(&freeblks->fb_jwork);
6148 	freeblks->fb_ref = 0;
6149 	freeblks->fb_cgwait = 0;
6150 	freeblks->fb_state = ATTACHED;
6151 	freeblks->fb_uid = ip->i_uid;
6152 	freeblks->fb_inum = ip->i_number;
6153 	freeblks->fb_vtype = ITOV(ip)->v_type;
6154 	freeblks->fb_modrev = DIP(ip, i_modrev);
6155 	freeblks->fb_devvp = ip->i_devvp;
6156 	freeblks->fb_chkcnt = 0;
6157 	freeblks->fb_len = 0;
6158 
6159 	return (freeblks);
6160 }
6161 
6162 static void
6163 trunc_indirdep(indirdep, freeblks, bp, off)
6164 	struct indirdep *indirdep;
6165 	struct freeblks *freeblks;
6166 	struct buf *bp;
6167 	int off;
6168 {
6169 	struct allocindir *aip, *aipn;
6170 
6171 	/*
6172 	 * The first set of allocindirs won't be in savedbp.
6173 	 */
6174 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6175 		if (aip->ai_offset > off)
6176 			cancel_allocindir(aip, bp, freeblks, 1);
6177 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6178 		if (aip->ai_offset > off)
6179 			cancel_allocindir(aip, bp, freeblks, 1);
6180 	/*
6181 	 * These will exist in savedbp.
6182 	 */
6183 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6184 		if (aip->ai_offset > off)
6185 			cancel_allocindir(aip, NULL, freeblks, 0);
6186 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6187 		if (aip->ai_offset > off)
6188 			cancel_allocindir(aip, NULL, freeblks, 0);
6189 }
6190 
6191 /*
6192  * Follow the chain of indirects down to lastlbn creating a freework
6193  * structure for each.  This will be used to start indir_trunc() at
6194  * the right offset and create the journal records for the parrtial
6195  * truncation.  A second step will handle the truncated dependencies.
6196  */
6197 static int
6198 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6199 	struct freeblks *freeblks;
6200 	struct inode *ip;
6201 	ufs_lbn_t lbn;
6202 	ufs_lbn_t lastlbn;
6203 	ufs2_daddr_t blkno;
6204 {
6205 	struct indirdep *indirdep;
6206 	struct indirdep *indirn;
6207 	struct freework *freework;
6208 	struct newblk *newblk;
6209 	struct mount *mp;
6210 	struct buf *bp;
6211 	uint8_t *start;
6212 	uint8_t *end;
6213 	ufs_lbn_t lbnadd;
6214 	int level;
6215 	int error;
6216 	int off;
6217 
6218 
6219 	freework = NULL;
6220 	if (blkno == 0)
6221 		return (0);
6222 	mp = freeblks->fb_list.wk_mp;
6223 	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6224 	if ((bp->b_flags & B_CACHE) == 0) {
6225 		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6226 		bp->b_iocmd = BIO_READ;
6227 		bp->b_flags &= ~B_INVAL;
6228 		bp->b_ioflags &= ~BIO_ERROR;
6229 		vfs_busy_pages(bp, 0);
6230 		bp->b_iooffset = dbtob(bp->b_blkno);
6231 		bstrategy(bp);
6232 		curthread->td_ru.ru_inblock++;
6233 		error = bufwait(bp);
6234 		if (error) {
6235 			brelse(bp);
6236 			return (error);
6237 		}
6238 	}
6239 	level = lbn_level(lbn);
6240 	lbnadd = lbn_offset(ip->i_fs, level);
6241 	/*
6242 	 * Compute the offset of the last block we want to keep.  Store
6243 	 * in the freework the first block we want to completely free.
6244 	 */
6245 	off = (lastlbn - -(lbn + level)) / lbnadd;
6246 	if (off + 1 == NINDIR(ip->i_fs))
6247 		goto nowork;
6248 	freework = newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, 0, off+1,
6249 	    0);
6250 	/*
6251 	 * Link the freework into the indirdep.  This will prevent any new
6252 	 * allocations from proceeding until we are finished with the
6253 	 * truncate and the block is written.
6254 	 */
6255 	ACQUIRE_LOCK(ip->i_ump);
6256 	indirdep = indirdep_lookup(mp, ip, bp);
6257 	if (indirdep->ir_freeblks)
6258 		panic("setup_trunc_indir: indirdep already truncated.");
6259 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6260 	freework->fw_indir = indirdep;
6261 	/*
6262 	 * Cancel any allocindirs that will not make it to disk.
6263 	 * We have to do this for all copies of the indirdep that
6264 	 * live on this newblk.
6265 	 */
6266 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6267 		newblk_lookup(mp, dbtofsb(ip->i_fs, bp->b_blkno), 0, &newblk);
6268 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6269 			trunc_indirdep(indirn, freeblks, bp, off);
6270 	} else
6271 		trunc_indirdep(indirdep, freeblks, bp, off);
6272 	FREE_LOCK(ip->i_ump);
6273 	/*
6274 	 * Creation is protected by the buf lock. The saveddata is only
6275 	 * needed if a full truncation follows a partial truncation but it
6276 	 * is difficult to allocate in that case so we fetch it anyway.
6277 	 */
6278 	if (indirdep->ir_saveddata == NULL)
6279 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6280 		    M_SOFTDEP_FLAGS);
6281 nowork:
6282 	/* Fetch the blkno of the child and the zero start offset. */
6283 	if (ip->i_ump->um_fstype == UFS1) {
6284 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6285 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6286 	} else {
6287 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6288 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6289 	}
6290 	if (freework) {
6291 		/* Zero the truncated pointers. */
6292 		end = bp->b_data + bp->b_bcount;
6293 		bzero(start, end - start);
6294 		bdwrite(bp);
6295 	} else
6296 		bqrelse(bp);
6297 	if (level == 0)
6298 		return (0);
6299 	lbn++; /* adjust level */
6300 	lbn -= (off * lbnadd);
6301 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6302 }
6303 
6304 /*
6305  * Complete the partial truncation of an indirect block setup by
6306  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6307  * copy and writes them to disk before the freeblks is allowed to complete.
6308  */
6309 static void
6310 complete_trunc_indir(freework)
6311 	struct freework *freework;
6312 {
6313 	struct freework *fwn;
6314 	struct indirdep *indirdep;
6315 	struct ufsmount *ump;
6316 	struct buf *bp;
6317 	uintptr_t start;
6318 	int count;
6319 
6320 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6321 	LOCK_OWNED(ump);
6322 	indirdep = freework->fw_indir;
6323 	for (;;) {
6324 		bp = indirdep->ir_bp;
6325 		/* See if the block was discarded. */
6326 		if (bp == NULL)
6327 			break;
6328 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6329 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6330 			break;
6331 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6332 		    LOCK_PTR(ump)) == 0)
6333 			BUF_UNLOCK(bp);
6334 		ACQUIRE_LOCK(ump);
6335 	}
6336 	freework->fw_state |= DEPCOMPLETE;
6337 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6338 	/*
6339 	 * Zero the pointers in the saved copy.
6340 	 */
6341 	if (indirdep->ir_state & UFS1FMT)
6342 		start = sizeof(ufs1_daddr_t);
6343 	else
6344 		start = sizeof(ufs2_daddr_t);
6345 	start *= freework->fw_start;
6346 	count = indirdep->ir_savebp->b_bcount - start;
6347 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6348 	bzero((char *)start, count);
6349 	/*
6350 	 * We need to start the next truncation in the list if it has not
6351 	 * been started yet.
6352 	 */
6353 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6354 	if (fwn != NULL) {
6355 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6356 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6357 		if ((fwn->fw_state & ONWORKLIST) == 0)
6358 			freework_enqueue(fwn);
6359 	}
6360 	/*
6361 	 * If bp is NULL the block was fully truncated, restore
6362 	 * the saved block list otherwise free it if it is no
6363 	 * longer needed.
6364 	 */
6365 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6366 		if (bp == NULL)
6367 			bcopy(indirdep->ir_saveddata,
6368 			    indirdep->ir_savebp->b_data,
6369 			    indirdep->ir_savebp->b_bcount);
6370 		free(indirdep->ir_saveddata, M_INDIRDEP);
6371 		indirdep->ir_saveddata = NULL;
6372 	}
6373 	/*
6374 	 * When bp is NULL there is a full truncation pending.  We
6375 	 * must wait for this full truncation to be journaled before
6376 	 * we can release this freework because the disk pointers will
6377 	 * never be written as zero.
6378 	 */
6379 	if (bp == NULL)  {
6380 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6381 			handle_written_freework(freework);
6382 		else
6383 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6384 			   &freework->fw_list);
6385 	} else {
6386 		/* Complete when the real copy is written. */
6387 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6388 		BUF_UNLOCK(bp);
6389 	}
6390 }
6391 
6392 /*
6393  * Calculate the number of blocks we are going to release where datablocks
6394  * is the current total and length is the new file size.
6395  */
6396 static ufs2_daddr_t
6397 blkcount(fs, datablocks, length)
6398 	struct fs *fs;
6399 	ufs2_daddr_t datablocks;
6400 	off_t length;
6401 {
6402 	off_t totblks, numblks;
6403 
6404 	totblks = 0;
6405 	numblks = howmany(length, fs->fs_bsize);
6406 	if (numblks <= NDADDR) {
6407 		totblks = howmany(length, fs->fs_fsize);
6408 		goto out;
6409 	}
6410         totblks = blkstofrags(fs, numblks);
6411 	numblks -= NDADDR;
6412 	/*
6413 	 * Count all single, then double, then triple indirects required.
6414 	 * Subtracting one indirects worth of blocks for each pass
6415 	 * acknowledges one of each pointed to by the inode.
6416 	 */
6417 	for (;;) {
6418 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6419 		numblks -= NINDIR(fs);
6420 		if (numblks <= 0)
6421 			break;
6422 		numblks = howmany(numblks, NINDIR(fs));
6423 	}
6424 out:
6425 	totblks = fsbtodb(fs, totblks);
6426 	/*
6427 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6428 	 * references.  We will correct it later in handle_complete_freeblks()
6429 	 * when we know the real count.
6430 	 */
6431 	if (totblks > datablocks)
6432 		return (0);
6433 	return (datablocks - totblks);
6434 }
6435 
6436 /*
6437  * Handle freeblocks for journaled softupdate filesystems.
6438  *
6439  * Contrary to normal softupdates, we must preserve the block pointers in
6440  * indirects until their subordinates are free.  This is to avoid journaling
6441  * every block that is freed which may consume more space than the journal
6442  * itself.  The recovery program will see the free block journals at the
6443  * base of the truncated area and traverse them to reclaim space.  The
6444  * pointers in the inode may be cleared immediately after the journal
6445  * records are written because each direct and indirect pointer in the
6446  * inode is recorded in a journal.  This permits full truncation to proceed
6447  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6448  *
6449  * The algorithm is as follows:
6450  * 1) Traverse the in-memory state and create journal entries to release
6451  *    the relevant blocks and full indirect trees.
6452  * 2) Traverse the indirect block chain adding partial truncation freework
6453  *    records to indirects in the path to lastlbn.  The freework will
6454  *    prevent new allocation dependencies from being satisfied in this
6455  *    indirect until the truncation completes.
6456  * 3) Read and lock the inode block, performing an update with the new size
6457  *    and pointers.  This prevents truncated data from becoming valid on
6458  *    disk through step 4.
6459  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6460  *    eliminate journal work for those records that do not require it.
6461  * 5) Schedule the journal records to be written followed by the inode block.
6462  * 6) Allocate any necessary frags for the end of file.
6463  * 7) Zero any partially truncated blocks.
6464  *
6465  * From this truncation proceeds asynchronously using the freework and
6466  * indir_trunc machinery.  The file will not be extended again into a
6467  * partially truncated indirect block until all work is completed but
6468  * the normal dependency mechanism ensures that it is rolled back/forward
6469  * as appropriate.  Further truncation may occur without delay and is
6470  * serialized in indir_trunc().
6471  */
6472 void
6473 softdep_journal_freeblocks(ip, cred, length, flags)
6474 	struct inode *ip;	/* The inode whose length is to be reduced */
6475 	struct ucred *cred;
6476 	off_t length;		/* The new length for the file */
6477 	int flags;		/* IO_EXT and/or IO_NORMAL */
6478 {
6479 	struct freeblks *freeblks, *fbn;
6480 	struct worklist *wk, *wkn;
6481 	struct inodedep *inodedep;
6482 	struct jblkdep *jblkdep;
6483 	struct allocdirect *adp, *adpn;
6484 	struct ufsmount *ump;
6485 	struct fs *fs;
6486 	struct buf *bp;
6487 	struct vnode *vp;
6488 	struct mount *mp;
6489 	ufs2_daddr_t extblocks, datablocks;
6490 	ufs_lbn_t tmpval, lbn, lastlbn;
6491 	int frags, lastoff, iboff, allocblock, needj, error, i;
6492 
6493 	fs = ip->i_fs;
6494 	ump = ip->i_ump;
6495 	mp = UFSTOVFS(ump);
6496 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6497 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6498 	vp = ITOV(ip);
6499 	needj = 1;
6500 	iboff = -1;
6501 	allocblock = 0;
6502 	extblocks = 0;
6503 	datablocks = 0;
6504 	frags = 0;
6505 	freeblks = newfreeblks(mp, ip);
6506 	ACQUIRE_LOCK(ump);
6507 	/*
6508 	 * If we're truncating a removed file that will never be written
6509 	 * we don't need to journal the block frees.  The canceled journals
6510 	 * for the allocations will suffice.
6511 	 */
6512 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6513 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6514 	    length == 0)
6515 		needj = 0;
6516 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6517 	    ip->i_number, length, needj);
6518 	FREE_LOCK(ump);
6519 	/*
6520 	 * Calculate the lbn that we are truncating to.  This results in -1
6521 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6522 	 * to keep, not the first lbn we want to truncate.
6523 	 */
6524 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6525 	lastoff = blkoff(fs, length);
6526 	/*
6527 	 * Compute frags we are keeping in lastlbn.  0 means all.
6528 	 */
6529 	if (lastlbn >= 0 && lastlbn < NDADDR) {
6530 		frags = fragroundup(fs, lastoff);
6531 		/* adp offset of last valid allocdirect. */
6532 		iboff = lastlbn;
6533 	} else if (lastlbn > 0)
6534 		iboff = NDADDR;
6535 	if (fs->fs_magic == FS_UFS2_MAGIC)
6536 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6537 	/*
6538 	 * Handle normal data blocks and indirects.  This section saves
6539 	 * values used after the inode update to complete frag and indirect
6540 	 * truncation.
6541 	 */
6542 	if ((flags & IO_NORMAL) != 0) {
6543 		/*
6544 		 * Handle truncation of whole direct and indirect blocks.
6545 		 */
6546 		for (i = iboff + 1; i < NDADDR; i++)
6547 			setup_freedirect(freeblks, ip, i, needj);
6548 		for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6549 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6550 			/* Release a whole indirect tree. */
6551 			if (lbn > lastlbn) {
6552 				setup_freeindir(freeblks, ip, i, -lbn -i,
6553 				    needj);
6554 				continue;
6555 			}
6556 			iboff = i + NDADDR;
6557 			/*
6558 			 * Traverse partially truncated indirect tree.
6559 			 */
6560 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6561 				setup_trunc_indir(freeblks, ip, -lbn - i,
6562 				    lastlbn, DIP(ip, i_ib[i]));
6563 		}
6564 		/*
6565 		 * Handle partial truncation to a frag boundary.
6566 		 */
6567 		if (frags) {
6568 			ufs2_daddr_t blkno;
6569 			long oldfrags;
6570 
6571 			oldfrags = blksize(fs, ip, lastlbn);
6572 			blkno = DIP(ip, i_db[lastlbn]);
6573 			if (blkno && oldfrags != frags) {
6574 				oldfrags -= frags;
6575 				oldfrags = numfrags(ip->i_fs, oldfrags);
6576 				blkno += numfrags(ip->i_fs, frags);
6577 				newfreework(ump, freeblks, NULL, lastlbn,
6578 				    blkno, oldfrags, 0, needj);
6579 				if (needj)
6580 					adjust_newfreework(freeblks,
6581 					    numfrags(ip->i_fs, frags));
6582 			} else if (blkno == 0)
6583 				allocblock = 1;
6584 		}
6585 		/*
6586 		 * Add a journal record for partial truncate if we are
6587 		 * handling indirect blocks.  Non-indirects need no extra
6588 		 * journaling.
6589 		 */
6590 		if (length != 0 && lastlbn >= NDADDR) {
6591 			ip->i_flag |= IN_TRUNCATED;
6592 			newjtrunc(freeblks, length, 0);
6593 		}
6594 		ip->i_size = length;
6595 		DIP_SET(ip, i_size, ip->i_size);
6596 		datablocks = DIP(ip, i_blocks) - extblocks;
6597 		if (length != 0)
6598 			datablocks = blkcount(ip->i_fs, datablocks, length);
6599 		freeblks->fb_len = length;
6600 	}
6601 	if ((flags & IO_EXT) != 0) {
6602 		for (i = 0; i < NXADDR; i++)
6603 			setup_freeext(freeblks, ip, i, needj);
6604 		ip->i_din2->di_extsize = 0;
6605 		datablocks += extblocks;
6606 	}
6607 #ifdef QUOTA
6608 	/* Reference the quotas in case the block count is wrong in the end. */
6609 	quotaref(vp, freeblks->fb_quota);
6610 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6611 #endif
6612 	freeblks->fb_chkcnt = -datablocks;
6613 	UFS_LOCK(ump);
6614 	fs->fs_pendingblocks += datablocks;
6615 	UFS_UNLOCK(ump);
6616 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6617 	/*
6618 	 * Handle truncation of incomplete alloc direct dependencies.  We
6619 	 * hold the inode block locked to prevent incomplete dependencies
6620 	 * from reaching the disk while we are eliminating those that
6621 	 * have been truncated.  This is a partially inlined ffs_update().
6622 	 */
6623 	ufs_itimes(vp);
6624 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6625 	error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6626 	    (int)fs->fs_bsize, cred, &bp);
6627 	if (error) {
6628 		brelse(bp);
6629 		softdep_error("softdep_journal_freeblocks", error);
6630 		return;
6631 	}
6632 	if (bp->b_bufsize == fs->fs_bsize)
6633 		bp->b_flags |= B_CLUSTEROK;
6634 	softdep_update_inodeblock(ip, bp, 0);
6635 	if (ump->um_fstype == UFS1)
6636 		*((struct ufs1_dinode *)bp->b_data +
6637 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6638 	else
6639 		*((struct ufs2_dinode *)bp->b_data +
6640 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6641 	ACQUIRE_LOCK(ump);
6642 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6643 	if ((inodedep->id_state & IOSTARTED) != 0)
6644 		panic("softdep_setup_freeblocks: inode busy");
6645 	/*
6646 	 * Add the freeblks structure to the list of operations that
6647 	 * must await the zero'ed inode being written to disk. If we
6648 	 * still have a bitmap dependency (needj), then the inode
6649 	 * has never been written to disk, so we can process the
6650 	 * freeblks below once we have deleted the dependencies.
6651 	 */
6652 	if (needj)
6653 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6654 	else
6655 		freeblks->fb_state |= COMPLETE;
6656 	if ((flags & IO_NORMAL) != 0) {
6657 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6658 			if (adp->ad_offset > iboff)
6659 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6660 				    freeblks);
6661 			/*
6662 			 * Truncate the allocdirect.  We could eliminate
6663 			 * or modify journal records as well.
6664 			 */
6665 			else if (adp->ad_offset == iboff && frags)
6666 				adp->ad_newsize = frags;
6667 		}
6668 	}
6669 	if ((flags & IO_EXT) != 0)
6670 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6671 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6672 			    freeblks);
6673 	/*
6674 	 * Scan the bufwait list for newblock dependencies that will never
6675 	 * make it to disk.
6676 	 */
6677 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6678 		if (wk->wk_type != D_ALLOCDIRECT)
6679 			continue;
6680 		adp = WK_ALLOCDIRECT(wk);
6681 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6682 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6683 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6684 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6685 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6686 		}
6687 	}
6688 	/*
6689 	 * Add journal work.
6690 	 */
6691 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6692 		add_to_journal(&jblkdep->jb_list);
6693 	FREE_LOCK(ump);
6694 	bdwrite(bp);
6695 	/*
6696 	 * Truncate dependency structures beyond length.
6697 	 */
6698 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6699 	/*
6700 	 * This is only set when we need to allocate a fragment because
6701 	 * none existed at the end of a frag-sized file.  It handles only
6702 	 * allocating a new, zero filled block.
6703 	 */
6704 	if (allocblock) {
6705 		ip->i_size = length - lastoff;
6706 		DIP_SET(ip, i_size, ip->i_size);
6707 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6708 		if (error != 0) {
6709 			softdep_error("softdep_journal_freeblks", error);
6710 			return;
6711 		}
6712 		ip->i_size = length;
6713 		DIP_SET(ip, i_size, length);
6714 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6715 		allocbuf(bp, frags);
6716 		ffs_update(vp, 0);
6717 		bawrite(bp);
6718 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6719 		int size;
6720 
6721 		/*
6722 		 * Zero the end of a truncated frag or block.
6723 		 */
6724 		size = sblksize(fs, length, lastlbn);
6725 		error = bread(vp, lastlbn, size, cred, &bp);
6726 		if (error) {
6727 			softdep_error("softdep_journal_freeblks", error);
6728 			return;
6729 		}
6730 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6731 		bawrite(bp);
6732 
6733 	}
6734 	ACQUIRE_LOCK(ump);
6735 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6736 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6737 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6738 	/*
6739 	 * We zero earlier truncations so they don't erroneously
6740 	 * update i_blocks.
6741 	 */
6742 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6743 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6744 			fbn->fb_len = 0;
6745 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6746 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6747 		freeblks->fb_state |= INPROGRESS;
6748 	else
6749 		freeblks = NULL;
6750 	FREE_LOCK(ump);
6751 	if (freeblks)
6752 		handle_workitem_freeblocks(freeblks, 0);
6753 	trunc_pages(ip, length, extblocks, flags);
6754 
6755 }
6756 
6757 /*
6758  * Flush a JOP_SYNC to the journal.
6759  */
6760 void
6761 softdep_journal_fsync(ip)
6762 	struct inode *ip;
6763 {
6764 	struct jfsync *jfsync;
6765 
6766 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
6767 	    ("softdep_journal_fsync called on non-softdep filesystem"));
6768 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6769 		return;
6770 	ip->i_flag &= ~IN_TRUNCATED;
6771 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6772 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ip->i_ump));
6773 	jfsync->jfs_size = ip->i_size;
6774 	jfsync->jfs_ino = ip->i_number;
6775 	ACQUIRE_LOCK(ip->i_ump);
6776 	add_to_journal(&jfsync->jfs_list);
6777 	jwait(&jfsync->jfs_list, MNT_WAIT);
6778 	FREE_LOCK(ip->i_ump);
6779 }
6780 
6781 /*
6782  * Block de-allocation dependencies.
6783  *
6784  * When blocks are de-allocated, the on-disk pointers must be nullified before
6785  * the blocks are made available for use by other files.  (The true
6786  * requirement is that old pointers must be nullified before new on-disk
6787  * pointers are set.  We chose this slightly more stringent requirement to
6788  * reduce complexity.) Our implementation handles this dependency by updating
6789  * the inode (or indirect block) appropriately but delaying the actual block
6790  * de-allocation (i.e., freemap and free space count manipulation) until
6791  * after the updated versions reach stable storage.  After the disk is
6792  * updated, the blocks can be safely de-allocated whenever it is convenient.
6793  * This implementation handles only the common case of reducing a file's
6794  * length to zero. Other cases are handled by the conventional synchronous
6795  * write approach.
6796  *
6797  * The ffs implementation with which we worked double-checks
6798  * the state of the block pointers and file size as it reduces
6799  * a file's length.  Some of this code is replicated here in our
6800  * soft updates implementation.  The freeblks->fb_chkcnt field is
6801  * used to transfer a part of this information to the procedure
6802  * that eventually de-allocates the blocks.
6803  *
6804  * This routine should be called from the routine that shortens
6805  * a file's length, before the inode's size or block pointers
6806  * are modified. It will save the block pointer information for
6807  * later release and zero the inode so that the calling routine
6808  * can release it.
6809  */
6810 void
6811 softdep_setup_freeblocks(ip, length, flags)
6812 	struct inode *ip;	/* The inode whose length is to be reduced */
6813 	off_t length;		/* The new length for the file */
6814 	int flags;		/* IO_EXT and/or IO_NORMAL */
6815 {
6816 	struct ufs1_dinode *dp1;
6817 	struct ufs2_dinode *dp2;
6818 	struct freeblks *freeblks;
6819 	struct inodedep *inodedep;
6820 	struct allocdirect *adp;
6821 	struct ufsmount *ump;
6822 	struct buf *bp;
6823 	struct fs *fs;
6824 	ufs2_daddr_t extblocks, datablocks;
6825 	struct mount *mp;
6826 	int i, delay, error;
6827 	ufs_lbn_t tmpval;
6828 	ufs_lbn_t lbn;
6829 
6830 	ump = ip->i_ump;
6831 	mp = UFSTOVFS(ump);
6832 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6833 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6834 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6835 	    ip->i_number, length);
6836 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6837 	fs = ip->i_fs;
6838 	if ((error = bread(ip->i_devvp,
6839 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6840 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6841 		brelse(bp);
6842 		softdep_error("softdep_setup_freeblocks", error);
6843 		return;
6844 	}
6845 	freeblks = newfreeblks(mp, ip);
6846 	extblocks = 0;
6847 	datablocks = 0;
6848 	if (fs->fs_magic == FS_UFS2_MAGIC)
6849 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6850 	if ((flags & IO_NORMAL) != 0) {
6851 		for (i = 0; i < NDADDR; i++)
6852 			setup_freedirect(freeblks, ip, i, 0);
6853 		for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6854 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6855 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6856 		ip->i_size = 0;
6857 		DIP_SET(ip, i_size, 0);
6858 		datablocks = DIP(ip, i_blocks) - extblocks;
6859 	}
6860 	if ((flags & IO_EXT) != 0) {
6861 		for (i = 0; i < NXADDR; i++)
6862 			setup_freeext(freeblks, ip, i, 0);
6863 		ip->i_din2->di_extsize = 0;
6864 		datablocks += extblocks;
6865 	}
6866 #ifdef QUOTA
6867 	/* Reference the quotas in case the block count is wrong in the end. */
6868 	quotaref(ITOV(ip), freeblks->fb_quota);
6869 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6870 #endif
6871 	freeblks->fb_chkcnt = -datablocks;
6872 	UFS_LOCK(ump);
6873 	fs->fs_pendingblocks += datablocks;
6874 	UFS_UNLOCK(ump);
6875 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6876 	/*
6877 	 * Push the zero'ed inode to to its disk buffer so that we are free
6878 	 * to delete its dependencies below. Once the dependencies are gone
6879 	 * the buffer can be safely released.
6880 	 */
6881 	if (ump->um_fstype == UFS1) {
6882 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6883 		    ino_to_fsbo(fs, ip->i_number));
6884 		ip->i_din1->di_freelink = dp1->di_freelink;
6885 		*dp1 = *ip->i_din1;
6886 	} else {
6887 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6888 		    ino_to_fsbo(fs, ip->i_number));
6889 		ip->i_din2->di_freelink = dp2->di_freelink;
6890 		*dp2 = *ip->i_din2;
6891 	}
6892 	/*
6893 	 * Find and eliminate any inode dependencies.
6894 	 */
6895 	ACQUIRE_LOCK(ump);
6896 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6897 	if ((inodedep->id_state & IOSTARTED) != 0)
6898 		panic("softdep_setup_freeblocks: inode busy");
6899 	/*
6900 	 * Add the freeblks structure to the list of operations that
6901 	 * must await the zero'ed inode being written to disk. If we
6902 	 * still have a bitmap dependency (delay == 0), then the inode
6903 	 * has never been written to disk, so we can process the
6904 	 * freeblks below once we have deleted the dependencies.
6905 	 */
6906 	delay = (inodedep->id_state & DEPCOMPLETE);
6907 	if (delay)
6908 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6909 	else
6910 		freeblks->fb_state |= COMPLETE;
6911 	/*
6912 	 * Because the file length has been truncated to zero, any
6913 	 * pending block allocation dependency structures associated
6914 	 * with this inode are obsolete and can simply be de-allocated.
6915 	 * We must first merge the two dependency lists to get rid of
6916 	 * any duplicate freefrag structures, then purge the merged list.
6917 	 * If we still have a bitmap dependency, then the inode has never
6918 	 * been written to disk, so we can free any fragments without delay.
6919 	 */
6920 	if (flags & IO_NORMAL) {
6921 		merge_inode_lists(&inodedep->id_newinoupdt,
6922 		    &inodedep->id_inoupdt);
6923 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
6924 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
6925 			    freeblks);
6926 	}
6927 	if (flags & IO_EXT) {
6928 		merge_inode_lists(&inodedep->id_newextupdt,
6929 		    &inodedep->id_extupdt);
6930 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6931 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6932 			    freeblks);
6933 	}
6934 	FREE_LOCK(ump);
6935 	bdwrite(bp);
6936 	trunc_dependencies(ip, freeblks, -1, 0, flags);
6937 	ACQUIRE_LOCK(ump);
6938 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6939 		(void) free_inodedep(inodedep);
6940 	freeblks->fb_state |= DEPCOMPLETE;
6941 	/*
6942 	 * If the inode with zeroed block pointers is now on disk
6943 	 * we can start freeing blocks.
6944 	 */
6945 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6946 		freeblks->fb_state |= INPROGRESS;
6947 	else
6948 		freeblks = NULL;
6949 	FREE_LOCK(ump);
6950 	if (freeblks)
6951 		handle_workitem_freeblocks(freeblks, 0);
6952 	trunc_pages(ip, length, extblocks, flags);
6953 }
6954 
6955 /*
6956  * Eliminate pages from the page cache that back parts of this inode and
6957  * adjust the vnode pager's idea of our size.  This prevents stale data
6958  * from hanging around in the page cache.
6959  */
6960 static void
6961 trunc_pages(ip, length, extblocks, flags)
6962 	struct inode *ip;
6963 	off_t length;
6964 	ufs2_daddr_t extblocks;
6965 	int flags;
6966 {
6967 	struct vnode *vp;
6968 	struct fs *fs;
6969 	ufs_lbn_t lbn;
6970 	off_t end, extend;
6971 
6972 	vp = ITOV(ip);
6973 	fs = ip->i_fs;
6974 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
6975 	if ((flags & IO_EXT) != 0)
6976 		vn_pages_remove(vp, extend, 0);
6977 	if ((flags & IO_NORMAL) == 0)
6978 		return;
6979 	BO_LOCK(&vp->v_bufobj);
6980 	drain_output(vp);
6981 	BO_UNLOCK(&vp->v_bufobj);
6982 	/*
6983 	 * The vnode pager eliminates file pages we eliminate indirects
6984 	 * below.
6985 	 */
6986 	vnode_pager_setsize(vp, length);
6987 	/*
6988 	 * Calculate the end based on the last indirect we want to keep.  If
6989 	 * the block extends into indirects we can just use the negative of
6990 	 * its lbn.  Doubles and triples exist at lower numbers so we must
6991 	 * be careful not to remove those, if they exist.  double and triple
6992 	 * indirect lbns do not overlap with others so it is not important
6993 	 * to verify how many levels are required.
6994 	 */
6995 	lbn = lblkno(fs, length);
6996 	if (lbn >= NDADDR) {
6997 		/* Calculate the virtual lbn of the triple indirect. */
6998 		lbn = -lbn - (NIADDR - 1);
6999 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7000 	} else
7001 		end = extend;
7002 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7003 }
7004 
7005 /*
7006  * See if the buf bp is in the range eliminated by truncation.
7007  */
7008 static int
7009 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7010 	struct buf *bp;
7011 	int *blkoffp;
7012 	ufs_lbn_t lastlbn;
7013 	int lastoff;
7014 	int flags;
7015 {
7016 	ufs_lbn_t lbn;
7017 
7018 	*blkoffp = 0;
7019 	/* Only match ext/normal blocks as appropriate. */
7020 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7021 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7022 		return (0);
7023 	/* ALTDATA is always a full truncation. */
7024 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7025 		return (1);
7026 	/* -1 is full truncation. */
7027 	if (lastlbn == -1)
7028 		return (1);
7029 	/*
7030 	 * If this is a partial truncate we only want those
7031 	 * blocks and indirect blocks that cover the range
7032 	 * we're after.
7033 	 */
7034 	lbn = bp->b_lblkno;
7035 	if (lbn < 0)
7036 		lbn = -(lbn + lbn_level(lbn));
7037 	if (lbn < lastlbn)
7038 		return (0);
7039 	/* Here we only truncate lblkno if it's partial. */
7040 	if (lbn == lastlbn) {
7041 		if (lastoff == 0)
7042 			return (0);
7043 		*blkoffp = lastoff;
7044 	}
7045 	return (1);
7046 }
7047 
7048 /*
7049  * Eliminate any dependencies that exist in memory beyond lblkno:off
7050  */
7051 static void
7052 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7053 	struct inode *ip;
7054 	struct freeblks *freeblks;
7055 	ufs_lbn_t lastlbn;
7056 	int lastoff;
7057 	int flags;
7058 {
7059 	struct bufobj *bo;
7060 	struct vnode *vp;
7061 	struct buf *bp;
7062 	int blkoff;
7063 
7064 	/*
7065 	 * We must wait for any I/O in progress to finish so that
7066 	 * all potential buffers on the dirty list will be visible.
7067 	 * Once they are all there, walk the list and get rid of
7068 	 * any dependencies.
7069 	 */
7070 	vp = ITOV(ip);
7071 	bo = &vp->v_bufobj;
7072 	BO_LOCK(bo);
7073 	drain_output(vp);
7074 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7075 		bp->b_vflags &= ~BV_SCANNED;
7076 restart:
7077 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7078 		if (bp->b_vflags & BV_SCANNED)
7079 			continue;
7080 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7081 			bp->b_vflags |= BV_SCANNED;
7082 			continue;
7083 		}
7084 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7085 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7086 			goto restart;
7087 		BO_UNLOCK(bo);
7088 		if (deallocate_dependencies(bp, freeblks, blkoff))
7089 			bqrelse(bp);
7090 		else
7091 			brelse(bp);
7092 		BO_LOCK(bo);
7093 		goto restart;
7094 	}
7095 	/*
7096 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7097 	 */
7098 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7099 		bp->b_vflags &= ~BV_SCANNED;
7100 cleanrestart:
7101 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7102 		if (bp->b_vflags & BV_SCANNED)
7103 			continue;
7104 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7105 			bp->b_vflags |= BV_SCANNED;
7106 			continue;
7107 		}
7108 		if (BUF_LOCK(bp,
7109 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7110 		    BO_LOCKPTR(bo)) == ENOLCK) {
7111 			BO_LOCK(bo);
7112 			goto cleanrestart;
7113 		}
7114 		bp->b_vflags |= BV_SCANNED;
7115 		bremfree(bp);
7116 		if (blkoff != 0) {
7117 			allocbuf(bp, blkoff);
7118 			bqrelse(bp);
7119 		} else {
7120 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7121 			brelse(bp);
7122 		}
7123 		BO_LOCK(bo);
7124 		goto cleanrestart;
7125 	}
7126 	drain_output(vp);
7127 	BO_UNLOCK(bo);
7128 }
7129 
7130 static int
7131 cancel_pagedep(pagedep, freeblks, blkoff)
7132 	struct pagedep *pagedep;
7133 	struct freeblks *freeblks;
7134 	int blkoff;
7135 {
7136 	struct jremref *jremref;
7137 	struct jmvref *jmvref;
7138 	struct dirrem *dirrem, *tmp;
7139 	int i;
7140 
7141 	/*
7142 	 * Copy any directory remove dependencies to the list
7143 	 * to be processed after the freeblks proceeds.  If
7144 	 * directory entry never made it to disk they
7145 	 * can be dumped directly onto the work list.
7146 	 */
7147 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7148 		/* Skip this directory removal if it is intended to remain. */
7149 		if (dirrem->dm_offset < blkoff)
7150 			continue;
7151 		/*
7152 		 * If there are any dirrems we wait for the journal write
7153 		 * to complete and then restart the buf scan as the lock
7154 		 * has been dropped.
7155 		 */
7156 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7157 			jwait(&jremref->jr_list, MNT_WAIT);
7158 			return (ERESTART);
7159 		}
7160 		LIST_REMOVE(dirrem, dm_next);
7161 		dirrem->dm_dirinum = pagedep->pd_ino;
7162 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7163 	}
7164 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7165 		jwait(&jmvref->jm_list, MNT_WAIT);
7166 		return (ERESTART);
7167 	}
7168 	/*
7169 	 * When we're partially truncating a pagedep we just want to flush
7170 	 * journal entries and return.  There can not be any adds in the
7171 	 * truncated portion of the directory and newblk must remain if
7172 	 * part of the block remains.
7173 	 */
7174 	if (blkoff != 0) {
7175 		struct diradd *dap;
7176 
7177 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7178 			if (dap->da_offset > blkoff)
7179 				panic("cancel_pagedep: diradd %p off %d > %d",
7180 				    dap, dap->da_offset, blkoff);
7181 		for (i = 0; i < DAHASHSZ; i++)
7182 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7183 				if (dap->da_offset > blkoff)
7184 					panic("cancel_pagedep: diradd %p off %d > %d",
7185 					    dap, dap->da_offset, blkoff);
7186 		return (0);
7187 	}
7188 	/*
7189 	 * There should be no directory add dependencies present
7190 	 * as the directory could not be truncated until all
7191 	 * children were removed.
7192 	 */
7193 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7194 	    ("deallocate_dependencies: pendinghd != NULL"));
7195 	for (i = 0; i < DAHASHSZ; i++)
7196 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7197 		    ("deallocate_dependencies: diraddhd != NULL"));
7198 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7199 		free_newdirblk(pagedep->pd_newdirblk);
7200 	if (free_pagedep(pagedep) == 0)
7201 		panic("Failed to free pagedep %p", pagedep);
7202 	return (0);
7203 }
7204 
7205 /*
7206  * Reclaim any dependency structures from a buffer that is about to
7207  * be reallocated to a new vnode. The buffer must be locked, thus,
7208  * no I/O completion operations can occur while we are manipulating
7209  * its associated dependencies. The mutex is held so that other I/O's
7210  * associated with related dependencies do not occur.
7211  */
7212 static int
7213 deallocate_dependencies(bp, freeblks, off)
7214 	struct buf *bp;
7215 	struct freeblks *freeblks;
7216 	int off;
7217 {
7218 	struct indirdep *indirdep;
7219 	struct pagedep *pagedep;
7220 	struct worklist *wk, *wkn;
7221 	struct ufsmount *ump;
7222 
7223 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
7224 		goto done;
7225 	ump = VFSTOUFS(wk->wk_mp);
7226 	ACQUIRE_LOCK(ump);
7227 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7228 		switch (wk->wk_type) {
7229 		case D_INDIRDEP:
7230 			indirdep = WK_INDIRDEP(wk);
7231 			if (bp->b_lblkno >= 0 ||
7232 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7233 				panic("deallocate_dependencies: not indir");
7234 			cancel_indirdep(indirdep, bp, freeblks);
7235 			continue;
7236 
7237 		case D_PAGEDEP:
7238 			pagedep = WK_PAGEDEP(wk);
7239 			if (cancel_pagedep(pagedep, freeblks, off)) {
7240 				FREE_LOCK(ump);
7241 				return (ERESTART);
7242 			}
7243 			continue;
7244 
7245 		case D_ALLOCINDIR:
7246 			/*
7247 			 * Simply remove the allocindir, we'll find it via
7248 			 * the indirdep where we can clear pointers if
7249 			 * needed.
7250 			 */
7251 			WORKLIST_REMOVE(wk);
7252 			continue;
7253 
7254 		case D_FREEWORK:
7255 			/*
7256 			 * A truncation is waiting for the zero'd pointers
7257 			 * to be written.  It can be freed when the freeblks
7258 			 * is journaled.
7259 			 */
7260 			WORKLIST_REMOVE(wk);
7261 			wk->wk_state |= ONDEPLIST;
7262 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7263 			break;
7264 
7265 		case D_ALLOCDIRECT:
7266 			if (off != 0)
7267 				continue;
7268 			/* FALLTHROUGH */
7269 		default:
7270 			panic("deallocate_dependencies: Unexpected type %s",
7271 			    TYPENAME(wk->wk_type));
7272 			/* NOTREACHED */
7273 		}
7274 	}
7275 	FREE_LOCK(ump);
7276 done:
7277 	/*
7278 	 * Don't throw away this buf, we were partially truncating and
7279 	 * some deps may always remain.
7280 	 */
7281 	if (off) {
7282 		allocbuf(bp, off);
7283 		bp->b_vflags |= BV_SCANNED;
7284 		return (EBUSY);
7285 	}
7286 	bp->b_flags |= B_INVAL | B_NOCACHE;
7287 
7288 	return (0);
7289 }
7290 
7291 /*
7292  * An allocdirect is being canceled due to a truncate.  We must make sure
7293  * the journal entry is released in concert with the blkfree that releases
7294  * the storage.  Completed journal entries must not be released until the
7295  * space is no longer pointed to by the inode or in the bitmap.
7296  */
7297 static void
7298 cancel_allocdirect(adphead, adp, freeblks)
7299 	struct allocdirectlst *adphead;
7300 	struct allocdirect *adp;
7301 	struct freeblks *freeblks;
7302 {
7303 	struct freework *freework;
7304 	struct newblk *newblk;
7305 	struct worklist *wk;
7306 
7307 	TAILQ_REMOVE(adphead, adp, ad_next);
7308 	newblk = (struct newblk *)adp;
7309 	freework = NULL;
7310 	/*
7311 	 * Find the correct freework structure.
7312 	 */
7313 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7314 		if (wk->wk_type != D_FREEWORK)
7315 			continue;
7316 		freework = WK_FREEWORK(wk);
7317 		if (freework->fw_blkno == newblk->nb_newblkno)
7318 			break;
7319 	}
7320 	if (freework == NULL)
7321 		panic("cancel_allocdirect: Freework not found");
7322 	/*
7323 	 * If a newblk exists at all we still have the journal entry that
7324 	 * initiated the allocation so we do not need to journal the free.
7325 	 */
7326 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7327 	/*
7328 	 * If the journal hasn't been written the jnewblk must be passed
7329 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7330 	 * this by linking the journal dependency into the freework to be
7331 	 * freed when freework_freeblock() is called.  If the journal has
7332 	 * been written we can simply reclaim the journal space when the
7333 	 * freeblks work is complete.
7334 	 */
7335 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7336 	    &freeblks->fb_jwork);
7337 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7338 }
7339 
7340 
7341 /*
7342  * Cancel a new block allocation.  May be an indirect or direct block.  We
7343  * remove it from various lists and return any journal record that needs to
7344  * be resolved by the caller.
7345  *
7346  * A special consideration is made for indirects which were never pointed
7347  * at on disk and will never be found once this block is released.
7348  */
7349 static struct jnewblk *
7350 cancel_newblk(newblk, wk, wkhd)
7351 	struct newblk *newblk;
7352 	struct worklist *wk;
7353 	struct workhead *wkhd;
7354 {
7355 	struct jnewblk *jnewblk;
7356 
7357 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7358 
7359 	newblk->nb_state |= GOINGAWAY;
7360 	/*
7361 	 * Previously we traversed the completedhd on each indirdep
7362 	 * attached to this newblk to cancel them and gather journal
7363 	 * work.  Since we need only the oldest journal segment and
7364 	 * the lowest point on the tree will always have the oldest
7365 	 * journal segment we are free to release the segments
7366 	 * of any subordinates and may leave the indirdep list to
7367 	 * indirdep_complete() when this newblk is freed.
7368 	 */
7369 	if (newblk->nb_state & ONDEPLIST) {
7370 		newblk->nb_state &= ~ONDEPLIST;
7371 		LIST_REMOVE(newblk, nb_deps);
7372 	}
7373 	if (newblk->nb_state & ONWORKLIST)
7374 		WORKLIST_REMOVE(&newblk->nb_list);
7375 	/*
7376 	 * If the journal entry hasn't been written we save a pointer to
7377 	 * the dependency that frees it until it is written or the
7378 	 * superseding operation completes.
7379 	 */
7380 	jnewblk = newblk->nb_jnewblk;
7381 	if (jnewblk != NULL && wk != NULL) {
7382 		newblk->nb_jnewblk = NULL;
7383 		jnewblk->jn_dep = wk;
7384 	}
7385 	if (!LIST_EMPTY(&newblk->nb_jwork))
7386 		jwork_move(wkhd, &newblk->nb_jwork);
7387 	/*
7388 	 * When truncating we must free the newdirblk early to remove
7389 	 * the pagedep from the hash before returning.
7390 	 */
7391 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7392 		free_newdirblk(WK_NEWDIRBLK(wk));
7393 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7394 		panic("cancel_newblk: extra newdirblk");
7395 
7396 	return (jnewblk);
7397 }
7398 
7399 /*
7400  * Schedule the freefrag associated with a newblk to be released once
7401  * the pointers are written and the previous block is no longer needed.
7402  */
7403 static void
7404 newblk_freefrag(newblk)
7405 	struct newblk *newblk;
7406 {
7407 	struct freefrag *freefrag;
7408 
7409 	if (newblk->nb_freefrag == NULL)
7410 		return;
7411 	freefrag = newblk->nb_freefrag;
7412 	newblk->nb_freefrag = NULL;
7413 	freefrag->ff_state |= COMPLETE;
7414 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7415 		add_to_worklist(&freefrag->ff_list, 0);
7416 }
7417 
7418 /*
7419  * Free a newblk. Generate a new freefrag work request if appropriate.
7420  * This must be called after the inode pointer and any direct block pointers
7421  * are valid or fully removed via truncate or frag extension.
7422  */
7423 static void
7424 free_newblk(newblk)
7425 	struct newblk *newblk;
7426 {
7427 	struct indirdep *indirdep;
7428 	struct worklist *wk;
7429 
7430 	KASSERT(newblk->nb_jnewblk == NULL,
7431 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7432 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7433 	    ("free_newblk: unclaimed newblk"));
7434 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7435 	newblk_freefrag(newblk);
7436 	if (newblk->nb_state & ONDEPLIST)
7437 		LIST_REMOVE(newblk, nb_deps);
7438 	if (newblk->nb_state & ONWORKLIST)
7439 		WORKLIST_REMOVE(&newblk->nb_list);
7440 	LIST_REMOVE(newblk, nb_hash);
7441 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7442 		free_newdirblk(WK_NEWDIRBLK(wk));
7443 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7444 		panic("free_newblk: extra newdirblk");
7445 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7446 		indirdep_complete(indirdep);
7447 	handle_jwork(&newblk->nb_jwork);
7448 	WORKITEM_FREE(newblk, D_NEWBLK);
7449 }
7450 
7451 /*
7452  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7453  * This routine must be called with splbio interrupts blocked.
7454  */
7455 static void
7456 free_newdirblk(newdirblk)
7457 	struct newdirblk *newdirblk;
7458 {
7459 	struct pagedep *pagedep;
7460 	struct diradd *dap;
7461 	struct worklist *wk;
7462 
7463 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7464 	WORKLIST_REMOVE(&newdirblk->db_list);
7465 	/*
7466 	 * If the pagedep is still linked onto the directory buffer
7467 	 * dependency chain, then some of the entries on the
7468 	 * pd_pendinghd list may not be committed to disk yet. In
7469 	 * this case, we will simply clear the NEWBLOCK flag and
7470 	 * let the pd_pendinghd list be processed when the pagedep
7471 	 * is next written. If the pagedep is no longer on the buffer
7472 	 * dependency chain, then all the entries on the pd_pending
7473 	 * list are committed to disk and we can free them here.
7474 	 */
7475 	pagedep = newdirblk->db_pagedep;
7476 	pagedep->pd_state &= ~NEWBLOCK;
7477 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7478 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7479 			free_diradd(dap, NULL);
7480 		/*
7481 		 * If no dependencies remain, the pagedep will be freed.
7482 		 */
7483 		free_pagedep(pagedep);
7484 	}
7485 	/* Should only ever be one item in the list. */
7486 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7487 		WORKLIST_REMOVE(wk);
7488 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7489 	}
7490 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7491 }
7492 
7493 /*
7494  * Prepare an inode to be freed. The actual free operation is not
7495  * done until the zero'ed inode has been written to disk.
7496  */
7497 void
7498 softdep_freefile(pvp, ino, mode)
7499 	struct vnode *pvp;
7500 	ino_t ino;
7501 	int mode;
7502 {
7503 	struct inode *ip = VTOI(pvp);
7504 	struct inodedep *inodedep;
7505 	struct freefile *freefile;
7506 	struct freeblks *freeblks;
7507 	struct ufsmount *ump;
7508 
7509 	ump = ip->i_ump;
7510 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7511 	    ("softdep_freefile called on non-softdep filesystem"));
7512 	/*
7513 	 * This sets up the inode de-allocation dependency.
7514 	 */
7515 	freefile = malloc(sizeof(struct freefile),
7516 		M_FREEFILE, M_SOFTDEP_FLAGS);
7517 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7518 	freefile->fx_mode = mode;
7519 	freefile->fx_oldinum = ino;
7520 	freefile->fx_devvp = ip->i_devvp;
7521 	LIST_INIT(&freefile->fx_jwork);
7522 	UFS_LOCK(ump);
7523 	ip->i_fs->fs_pendinginodes += 1;
7524 	UFS_UNLOCK(ump);
7525 
7526 	/*
7527 	 * If the inodedep does not exist, then the zero'ed inode has
7528 	 * been written to disk. If the allocated inode has never been
7529 	 * written to disk, then the on-disk inode is zero'ed. In either
7530 	 * case we can free the file immediately.  If the journal was
7531 	 * canceled before being written the inode will never make it to
7532 	 * disk and we must send the canceled journal entrys to
7533 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7534 	 * Any blocks waiting on the inode to write can be safely freed
7535 	 * here as it will never been written.
7536 	 */
7537 	ACQUIRE_LOCK(ump);
7538 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7539 	if (inodedep) {
7540 		/*
7541 		 * Clear out freeblks that no longer need to reference
7542 		 * this inode.
7543 		 */
7544 		while ((freeblks =
7545 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7546 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7547 			    fb_next);
7548 			freeblks->fb_state &= ~ONDEPLIST;
7549 		}
7550 		/*
7551 		 * Remove this inode from the unlinked list.
7552 		 */
7553 		if (inodedep->id_state & UNLINKED) {
7554 			/*
7555 			 * Save the journal work to be freed with the bitmap
7556 			 * before we clear UNLINKED.  Otherwise it can be lost
7557 			 * if the inode block is written.
7558 			 */
7559 			handle_bufwait(inodedep, &freefile->fx_jwork);
7560 			clear_unlinked_inodedep(inodedep);
7561 			/*
7562 			 * Re-acquire inodedep as we've dropped the
7563 			 * per-filesystem lock in clear_unlinked_inodedep().
7564 			 */
7565 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7566 		}
7567 	}
7568 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7569 		FREE_LOCK(ump);
7570 		handle_workitem_freefile(freefile);
7571 		return;
7572 	}
7573 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7574 		inodedep->id_state |= GOINGAWAY;
7575 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7576 	FREE_LOCK(ump);
7577 	if (ip->i_number == ino)
7578 		ip->i_flag |= IN_MODIFIED;
7579 }
7580 
7581 /*
7582  * Check to see if an inode has never been written to disk. If
7583  * so free the inodedep and return success, otherwise return failure.
7584  * This routine must be called with splbio interrupts blocked.
7585  *
7586  * If we still have a bitmap dependency, then the inode has never
7587  * been written to disk. Drop the dependency as it is no longer
7588  * necessary since the inode is being deallocated. We set the
7589  * ALLCOMPLETE flags since the bitmap now properly shows that the
7590  * inode is not allocated. Even if the inode is actively being
7591  * written, it has been rolled back to its zero'ed state, so we
7592  * are ensured that a zero inode is what is on the disk. For short
7593  * lived files, this change will usually result in removing all the
7594  * dependencies from the inode so that it can be freed immediately.
7595  */
7596 static int
7597 check_inode_unwritten(inodedep)
7598 	struct inodedep *inodedep;
7599 {
7600 
7601 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7602 
7603 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7604 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7605 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7606 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7607 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7608 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7609 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7610 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7611 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7612 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7613 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7614 	    inodedep->id_mkdiradd != NULL ||
7615 	    inodedep->id_nlinkdelta != 0)
7616 		return (0);
7617 	/*
7618 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7619 	 * trying to allocate memory without holding "Softdep Lock".
7620 	 */
7621 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7622 	    inodedep->id_savedino1 == NULL)
7623 		return (0);
7624 
7625 	if (inodedep->id_state & ONDEPLIST)
7626 		LIST_REMOVE(inodedep, id_deps);
7627 	inodedep->id_state &= ~ONDEPLIST;
7628 	inodedep->id_state |= ALLCOMPLETE;
7629 	inodedep->id_bmsafemap = NULL;
7630 	if (inodedep->id_state & ONWORKLIST)
7631 		WORKLIST_REMOVE(&inodedep->id_list);
7632 	if (inodedep->id_savedino1 != NULL) {
7633 		free(inodedep->id_savedino1, M_SAVEDINO);
7634 		inodedep->id_savedino1 = NULL;
7635 	}
7636 	if (free_inodedep(inodedep) == 0)
7637 		panic("check_inode_unwritten: busy inode");
7638 	return (1);
7639 }
7640 
7641 static int
7642 check_inodedep_free(inodedep)
7643 	struct inodedep *inodedep;
7644 {
7645 
7646 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7647 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7648 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7649 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7650 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7651 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7652 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7653 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7654 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7655 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7656 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7657 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7658 	    inodedep->id_mkdiradd != NULL ||
7659 	    inodedep->id_nlinkdelta != 0 ||
7660 	    inodedep->id_savedino1 != NULL)
7661 		return (0);
7662 	return (1);
7663 }
7664 
7665 /*
7666  * Try to free an inodedep structure. Return 1 if it could be freed.
7667  */
7668 static int
7669 free_inodedep(inodedep)
7670 	struct inodedep *inodedep;
7671 {
7672 
7673 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7674 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7675 	    !check_inodedep_free(inodedep))
7676 		return (0);
7677 	if (inodedep->id_state & ONDEPLIST)
7678 		LIST_REMOVE(inodedep, id_deps);
7679 	LIST_REMOVE(inodedep, id_hash);
7680 	WORKITEM_FREE(inodedep, D_INODEDEP);
7681 	return (1);
7682 }
7683 
7684 /*
7685  * Free the block referenced by a freework structure.  The parent freeblks
7686  * structure is released and completed when the final cg bitmap reaches
7687  * the disk.  This routine may be freeing a jnewblk which never made it to
7688  * disk in which case we do not have to wait as the operation is undone
7689  * in memory immediately.
7690  */
7691 static void
7692 freework_freeblock(freework)
7693 	struct freework *freework;
7694 {
7695 	struct freeblks *freeblks;
7696 	struct jnewblk *jnewblk;
7697 	struct ufsmount *ump;
7698 	struct workhead wkhd;
7699 	struct fs *fs;
7700 	int bsize;
7701 	int needj;
7702 
7703 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7704 	LOCK_OWNED(ump);
7705 	/*
7706 	 * Handle partial truncate separately.
7707 	 */
7708 	if (freework->fw_indir) {
7709 		complete_trunc_indir(freework);
7710 		return;
7711 	}
7712 	freeblks = freework->fw_freeblks;
7713 	fs = ump->um_fs;
7714 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7715 	bsize = lfragtosize(fs, freework->fw_frags);
7716 	LIST_INIT(&wkhd);
7717 	/*
7718 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7719 	 * on the indirblk hashtable and prevents premature freeing.
7720 	 */
7721 	freework->fw_state |= DEPCOMPLETE;
7722 	/*
7723 	 * SUJ needs to wait for the segment referencing freed indirect
7724 	 * blocks to expire so that we know the checker will not confuse
7725 	 * a re-allocated indirect block with its old contents.
7726 	 */
7727 	if (needj && freework->fw_lbn <= -NDADDR)
7728 		indirblk_insert(freework);
7729 	/*
7730 	 * If we are canceling an existing jnewblk pass it to the free
7731 	 * routine, otherwise pass the freeblk which will ultimately
7732 	 * release the freeblks.  If we're not journaling, we can just
7733 	 * free the freeblks immediately.
7734 	 */
7735 	jnewblk = freework->fw_jnewblk;
7736 	if (jnewblk != NULL) {
7737 		cancel_jnewblk(jnewblk, &wkhd);
7738 		needj = 0;
7739 	} else if (needj) {
7740 		freework->fw_state |= DELAYEDFREE;
7741 		freeblks->fb_cgwait++;
7742 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7743 	}
7744 	FREE_LOCK(ump);
7745 	freeblks_free(ump, freeblks, btodb(bsize));
7746 	CTR4(KTR_SUJ,
7747 	    "freework_freeblock: ino %d blkno %jd lbn %jd size %ld",
7748 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7749 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7750 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7751 	ACQUIRE_LOCK(ump);
7752 	/*
7753 	 * The jnewblk will be discarded and the bits in the map never
7754 	 * made it to disk.  We can immediately free the freeblk.
7755 	 */
7756 	if (needj == 0)
7757 		handle_written_freework(freework);
7758 }
7759 
7760 /*
7761  * We enqueue freework items that need processing back on the freeblks and
7762  * add the freeblks to the worklist.  This makes it easier to find all work
7763  * required to flush a truncation in process_truncates().
7764  */
7765 static void
7766 freework_enqueue(freework)
7767 	struct freework *freework;
7768 {
7769 	struct freeblks *freeblks;
7770 
7771 	freeblks = freework->fw_freeblks;
7772 	if ((freework->fw_state & INPROGRESS) == 0)
7773 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7774 	if ((freeblks->fb_state &
7775 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7776 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7777 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7778 }
7779 
7780 /*
7781  * Start, continue, or finish the process of freeing an indirect block tree.
7782  * The free operation may be paused at any point with fw_off containing the
7783  * offset to restart from.  This enables us to implement some flow control
7784  * for large truncates which may fan out and generate a huge number of
7785  * dependencies.
7786  */
7787 static void
7788 handle_workitem_indirblk(freework)
7789 	struct freework *freework;
7790 {
7791 	struct freeblks *freeblks;
7792 	struct ufsmount *ump;
7793 	struct fs *fs;
7794 
7795 	freeblks = freework->fw_freeblks;
7796 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7797 	fs = ump->um_fs;
7798 	if (freework->fw_state & DEPCOMPLETE) {
7799 		handle_written_freework(freework);
7800 		return;
7801 	}
7802 	if (freework->fw_off == NINDIR(fs)) {
7803 		freework_freeblock(freework);
7804 		return;
7805 	}
7806 	freework->fw_state |= INPROGRESS;
7807 	FREE_LOCK(ump);
7808 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7809 	    freework->fw_lbn);
7810 	ACQUIRE_LOCK(ump);
7811 }
7812 
7813 /*
7814  * Called when a freework structure attached to a cg buf is written.  The
7815  * ref on either the parent or the freeblks structure is released and
7816  * the freeblks is added back to the worklist if there is more work to do.
7817  */
7818 static void
7819 handle_written_freework(freework)
7820 	struct freework *freework;
7821 {
7822 	struct freeblks *freeblks;
7823 	struct freework *parent;
7824 
7825 	freeblks = freework->fw_freeblks;
7826 	parent = freework->fw_parent;
7827 	if (freework->fw_state & DELAYEDFREE)
7828 		freeblks->fb_cgwait--;
7829 	freework->fw_state |= COMPLETE;
7830 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7831 		WORKITEM_FREE(freework, D_FREEWORK);
7832 	if (parent) {
7833 		if (--parent->fw_ref == 0)
7834 			freework_enqueue(parent);
7835 		return;
7836 	}
7837 	if (--freeblks->fb_ref != 0)
7838 		return;
7839 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7840 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7841 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7842 }
7843 
7844 /*
7845  * This workitem routine performs the block de-allocation.
7846  * The workitem is added to the pending list after the updated
7847  * inode block has been written to disk.  As mentioned above,
7848  * checks regarding the number of blocks de-allocated (compared
7849  * to the number of blocks allocated for the file) are also
7850  * performed in this function.
7851  */
7852 static int
7853 handle_workitem_freeblocks(freeblks, flags)
7854 	struct freeblks *freeblks;
7855 	int flags;
7856 {
7857 	struct freework *freework;
7858 	struct newblk *newblk;
7859 	struct allocindir *aip;
7860 	struct ufsmount *ump;
7861 	struct worklist *wk;
7862 
7863 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7864 	    ("handle_workitem_freeblocks: Journal entries not written."));
7865 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7866 	ACQUIRE_LOCK(ump);
7867 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7868 		WORKLIST_REMOVE(wk);
7869 		switch (wk->wk_type) {
7870 		case D_DIRREM:
7871 			wk->wk_state |= COMPLETE;
7872 			add_to_worklist(wk, 0);
7873 			continue;
7874 
7875 		case D_ALLOCDIRECT:
7876 			free_newblk(WK_NEWBLK(wk));
7877 			continue;
7878 
7879 		case D_ALLOCINDIR:
7880 			aip = WK_ALLOCINDIR(wk);
7881 			freework = NULL;
7882 			if (aip->ai_state & DELAYEDFREE) {
7883 				FREE_LOCK(ump);
7884 				freework = newfreework(ump, freeblks, NULL,
7885 				    aip->ai_lbn, aip->ai_newblkno,
7886 				    ump->um_fs->fs_frag, 0, 0);
7887 				ACQUIRE_LOCK(ump);
7888 			}
7889 			newblk = WK_NEWBLK(wk);
7890 			if (newblk->nb_jnewblk) {
7891 				freework->fw_jnewblk = newblk->nb_jnewblk;
7892 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7893 				newblk->nb_jnewblk = NULL;
7894 			}
7895 			free_newblk(newblk);
7896 			continue;
7897 
7898 		case D_FREEWORK:
7899 			freework = WK_FREEWORK(wk);
7900 			if (freework->fw_lbn <= -NDADDR)
7901 				handle_workitem_indirblk(freework);
7902 			else
7903 				freework_freeblock(freework);
7904 			continue;
7905 		default:
7906 			panic("handle_workitem_freeblocks: Unknown type %s",
7907 			    TYPENAME(wk->wk_type));
7908 		}
7909 	}
7910 	if (freeblks->fb_ref != 0) {
7911 		freeblks->fb_state &= ~INPROGRESS;
7912 		wake_worklist(&freeblks->fb_list);
7913 		freeblks = NULL;
7914 	}
7915 	FREE_LOCK(ump);
7916 	if (freeblks)
7917 		return handle_complete_freeblocks(freeblks, flags);
7918 	return (0);
7919 }
7920 
7921 /*
7922  * Handle completion of block free via truncate.  This allows fs_pending
7923  * to track the actual free block count more closely than if we only updated
7924  * it at the end.  We must be careful to handle cases where the block count
7925  * on free was incorrect.
7926  */
7927 static void
7928 freeblks_free(ump, freeblks, blocks)
7929 	struct ufsmount *ump;
7930 	struct freeblks *freeblks;
7931 	int blocks;
7932 {
7933 	struct fs *fs;
7934 	ufs2_daddr_t remain;
7935 
7936 	UFS_LOCK(ump);
7937 	remain = -freeblks->fb_chkcnt;
7938 	freeblks->fb_chkcnt += blocks;
7939 	if (remain > 0) {
7940 		if (remain < blocks)
7941 			blocks = remain;
7942 		fs = ump->um_fs;
7943 		fs->fs_pendingblocks -= blocks;
7944 	}
7945 	UFS_UNLOCK(ump);
7946 }
7947 
7948 /*
7949  * Once all of the freework workitems are complete we can retire the
7950  * freeblocks dependency and any journal work awaiting completion.  This
7951  * can not be called until all other dependencies are stable on disk.
7952  */
7953 static int
7954 handle_complete_freeblocks(freeblks, flags)
7955 	struct freeblks *freeblks;
7956 	int flags;
7957 {
7958 	struct inodedep *inodedep;
7959 	struct inode *ip;
7960 	struct vnode *vp;
7961 	struct fs *fs;
7962 	struct ufsmount *ump;
7963 	ufs2_daddr_t spare;
7964 
7965 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7966 	fs = ump->um_fs;
7967 	flags = LK_EXCLUSIVE | flags;
7968 	spare = freeblks->fb_chkcnt;
7969 
7970 	/*
7971 	 * If we did not release the expected number of blocks we may have
7972 	 * to adjust the inode block count here.  Only do so if it wasn't
7973 	 * a truncation to zero and the modrev still matches.
7974 	 */
7975 	if (spare && freeblks->fb_len != 0) {
7976 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7977 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
7978 			return (EBUSY);
7979 		ip = VTOI(vp);
7980 		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
7981 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
7982 			ip->i_flag |= IN_CHANGE;
7983 			/*
7984 			 * We must wait so this happens before the
7985 			 * journal is reclaimed.
7986 			 */
7987 			ffs_update(vp, 1);
7988 		}
7989 		vput(vp);
7990 	}
7991 	if (spare < 0) {
7992 		UFS_LOCK(ump);
7993 		fs->fs_pendingblocks += spare;
7994 		UFS_UNLOCK(ump);
7995 	}
7996 #ifdef QUOTA
7997 	/* Handle spare. */
7998 	if (spare)
7999 		quotaadj(freeblks->fb_quota, ump, -spare);
8000 	quotarele(freeblks->fb_quota);
8001 #endif
8002 	ACQUIRE_LOCK(ump);
8003 	if (freeblks->fb_state & ONDEPLIST) {
8004 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8005 		    0, &inodedep);
8006 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8007 		freeblks->fb_state &= ~ONDEPLIST;
8008 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8009 			free_inodedep(inodedep);
8010 	}
8011 	/*
8012 	 * All of the freeblock deps must be complete prior to this call
8013 	 * so it's now safe to complete earlier outstanding journal entries.
8014 	 */
8015 	handle_jwork(&freeblks->fb_jwork);
8016 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8017 	FREE_LOCK(ump);
8018 	return (0);
8019 }
8020 
8021 /*
8022  * Release blocks associated with the freeblks and stored in the indirect
8023  * block dbn. If level is greater than SINGLE, the block is an indirect block
8024  * and recursive calls to indirtrunc must be used to cleanse other indirect
8025  * blocks.
8026  *
8027  * This handles partial and complete truncation of blocks.  Partial is noted
8028  * with goingaway == 0.  In this case the freework is completed after the
8029  * zero'd indirects are written to disk.  For full truncation the freework
8030  * is completed after the block is freed.
8031  */
8032 static void
8033 indir_trunc(freework, dbn, lbn)
8034 	struct freework *freework;
8035 	ufs2_daddr_t dbn;
8036 	ufs_lbn_t lbn;
8037 {
8038 	struct freework *nfreework;
8039 	struct workhead wkhd;
8040 	struct freeblks *freeblks;
8041 	struct buf *bp;
8042 	struct fs *fs;
8043 	struct indirdep *indirdep;
8044 	struct ufsmount *ump;
8045 	ufs1_daddr_t *bap1 = 0;
8046 	ufs2_daddr_t nb, nnb, *bap2 = 0;
8047 	ufs_lbn_t lbnadd, nlbn;
8048 	int i, nblocks, ufs1fmt;
8049 	int freedblocks;
8050 	int goingaway;
8051 	int freedeps;
8052 	int needj;
8053 	int level;
8054 	int cnt;
8055 
8056 	freeblks = freework->fw_freeblks;
8057 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8058 	fs = ump->um_fs;
8059 	/*
8060 	 * Get buffer of block pointers to be freed.  There are three cases:
8061 	 *
8062 	 * 1) Partial truncate caches the indirdep pointer in the freework
8063 	 *    which provides us a back copy to the save bp which holds the
8064 	 *    pointers we want to clear.  When this completes the zero
8065 	 *    pointers are written to the real copy.
8066 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8067 	 *    eliminated the real copy and placed the indirdep on the saved
8068 	 *    copy.  The indirdep and buf are discarded when this completes.
8069 	 * 3) The indirect was not in memory, we read a copy off of the disk
8070 	 *    using the devvp and drop and invalidate the buffer when we're
8071 	 *    done.
8072 	 */
8073 	goingaway = 1;
8074 	indirdep = NULL;
8075 	if (freework->fw_indir != NULL) {
8076 		goingaway = 0;
8077 		indirdep = freework->fw_indir;
8078 		bp = indirdep->ir_savebp;
8079 		if (bp == NULL || bp->b_blkno != dbn)
8080 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8081 			    bp, (intmax_t)dbn);
8082 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8083 		/*
8084 		 * The lock prevents the buf dep list from changing and
8085 	 	 * indirects on devvp should only ever have one dependency.
8086 		 */
8087 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8088 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8089 			panic("indir_trunc: Bad indirdep %p from buf %p",
8090 			    indirdep, bp);
8091 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8092 	    NOCRED, &bp) != 0) {
8093 		brelse(bp);
8094 		return;
8095 	}
8096 	ACQUIRE_LOCK(ump);
8097 	/* Protects against a race with complete_trunc_indir(). */
8098 	freework->fw_state &= ~INPROGRESS;
8099 	/*
8100 	 * If we have an indirdep we need to enforce the truncation order
8101 	 * and discard it when it is complete.
8102 	 */
8103 	if (indirdep) {
8104 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8105 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8106 			/*
8107 			 * Add the complete truncate to the list on the
8108 			 * indirdep to enforce in-order processing.
8109 			 */
8110 			if (freework->fw_indir == NULL)
8111 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8112 				    freework, fw_next);
8113 			FREE_LOCK(ump);
8114 			return;
8115 		}
8116 		/*
8117 		 * If we're goingaway, free the indirdep.  Otherwise it will
8118 		 * linger until the write completes.
8119 		 */
8120 		if (goingaway)
8121 			free_indirdep(indirdep);
8122 	}
8123 	FREE_LOCK(ump);
8124 	/* Initialize pointers depending on block size. */
8125 	if (ump->um_fstype == UFS1) {
8126 		bap1 = (ufs1_daddr_t *)bp->b_data;
8127 		nb = bap1[freework->fw_off];
8128 		ufs1fmt = 1;
8129 	} else {
8130 		bap2 = (ufs2_daddr_t *)bp->b_data;
8131 		nb = bap2[freework->fw_off];
8132 		ufs1fmt = 0;
8133 	}
8134 	level = lbn_level(lbn);
8135 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8136 	lbnadd = lbn_offset(fs, level);
8137 	nblocks = btodb(fs->fs_bsize);
8138 	nfreework = freework;
8139 	freedeps = 0;
8140 	cnt = 0;
8141 	/*
8142 	 * Reclaim blocks.  Traverses into nested indirect levels and
8143 	 * arranges for the current level to be freed when subordinates
8144 	 * are free when journaling.
8145 	 */
8146 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8147 		if (i != NINDIR(fs) - 1) {
8148 			if (ufs1fmt)
8149 				nnb = bap1[i+1];
8150 			else
8151 				nnb = bap2[i+1];
8152 		} else
8153 			nnb = 0;
8154 		if (nb == 0)
8155 			continue;
8156 		cnt++;
8157 		if (level != 0) {
8158 			nlbn = (lbn + 1) - (i * lbnadd);
8159 			if (needj != 0) {
8160 				nfreework = newfreework(ump, freeblks, freework,
8161 				    nlbn, nb, fs->fs_frag, 0, 0);
8162 				freedeps++;
8163 			}
8164 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8165 		} else {
8166 			struct freedep *freedep;
8167 
8168 			/*
8169 			 * Attempt to aggregate freedep dependencies for
8170 			 * all blocks being released to the same CG.
8171 			 */
8172 			LIST_INIT(&wkhd);
8173 			if (needj != 0 &&
8174 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8175 				freedep = newfreedep(freework);
8176 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8177 				    &freedep->fd_list);
8178 				freedeps++;
8179 			}
8180 			CTR3(KTR_SUJ,
8181 			    "indir_trunc: ino %d blkno %jd size %ld",
8182 			    freeblks->fb_inum, nb, fs->fs_bsize);
8183 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8184 			    fs->fs_bsize, freeblks->fb_inum,
8185 			    freeblks->fb_vtype, &wkhd);
8186 		}
8187 	}
8188 	if (goingaway) {
8189 		bp->b_flags |= B_INVAL | B_NOCACHE;
8190 		brelse(bp);
8191 	}
8192 	freedblocks = 0;
8193 	if (level == 0)
8194 		freedblocks = (nblocks * cnt);
8195 	if (needj == 0)
8196 		freedblocks += nblocks;
8197 	freeblks_free(ump, freeblks, freedblocks);
8198 	/*
8199 	 * If we are journaling set up the ref counts and offset so this
8200 	 * indirect can be completed when its children are free.
8201 	 */
8202 	if (needj) {
8203 		ACQUIRE_LOCK(ump);
8204 		freework->fw_off = i;
8205 		freework->fw_ref += freedeps;
8206 		freework->fw_ref -= NINDIR(fs) + 1;
8207 		if (level == 0)
8208 			freeblks->fb_cgwait += freedeps;
8209 		if (freework->fw_ref == 0)
8210 			freework_freeblock(freework);
8211 		FREE_LOCK(ump);
8212 		return;
8213 	}
8214 	/*
8215 	 * If we're not journaling we can free the indirect now.
8216 	 */
8217 	dbn = dbtofsb(fs, dbn);
8218 	CTR3(KTR_SUJ,
8219 	    "indir_trunc 2: ino %d blkno %jd size %ld",
8220 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8221 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8222 	    freeblks->fb_inum, freeblks->fb_vtype, NULL);
8223 	/* Non SUJ softdep does single-threaded truncations. */
8224 	if (freework->fw_blkno == dbn) {
8225 		freework->fw_state |= ALLCOMPLETE;
8226 		ACQUIRE_LOCK(ump);
8227 		handle_written_freework(freework);
8228 		FREE_LOCK(ump);
8229 	}
8230 	return;
8231 }
8232 
8233 /*
8234  * Cancel an allocindir when it is removed via truncation.  When bp is not
8235  * NULL the indirect never appeared on disk and is scheduled to be freed
8236  * independently of the indir so we can more easily track journal work.
8237  */
8238 static void
8239 cancel_allocindir(aip, bp, freeblks, trunc)
8240 	struct allocindir *aip;
8241 	struct buf *bp;
8242 	struct freeblks *freeblks;
8243 	int trunc;
8244 {
8245 	struct indirdep *indirdep;
8246 	struct freefrag *freefrag;
8247 	struct newblk *newblk;
8248 
8249 	newblk = (struct newblk *)aip;
8250 	LIST_REMOVE(aip, ai_next);
8251 	/*
8252 	 * We must eliminate the pointer in bp if it must be freed on its
8253 	 * own due to partial truncate or pending journal work.
8254 	 */
8255 	if (bp && (trunc || newblk->nb_jnewblk)) {
8256 		/*
8257 		 * Clear the pointer and mark the aip to be freed
8258 		 * directly if it never existed on disk.
8259 		 */
8260 		aip->ai_state |= DELAYEDFREE;
8261 		indirdep = aip->ai_indirdep;
8262 		if (indirdep->ir_state & UFS1FMT)
8263 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8264 		else
8265 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8266 	}
8267 	/*
8268 	 * When truncating the previous pointer will be freed via
8269 	 * savedbp.  Eliminate the freefrag which would dup free.
8270 	 */
8271 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8272 		newblk->nb_freefrag = NULL;
8273 		if (freefrag->ff_jdep)
8274 			cancel_jfreefrag(
8275 			    WK_JFREEFRAG(freefrag->ff_jdep));
8276 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8277 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8278 	}
8279 	/*
8280 	 * If the journal hasn't been written the jnewblk must be passed
8281 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8282 	 * this by leaving the journal dependency on the newblk to be freed
8283 	 * when a freework is created in handle_workitem_freeblocks().
8284 	 */
8285 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8286 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8287 }
8288 
8289 /*
8290  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8291  * in to a newdirblk so any subsequent additions are tracked properly.  The
8292  * caller is responsible for adding the mkdir1 dependency to the journal
8293  * and updating id_mkdiradd.  This function returns with the per-filesystem
8294  * lock held.
8295  */
8296 static struct mkdir *
8297 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8298 	struct diradd *dap;
8299 	ino_t newinum;
8300 	ino_t dinum;
8301 	struct buf *newdirbp;
8302 	struct mkdir **mkdirp;
8303 {
8304 	struct newblk *newblk;
8305 	struct pagedep *pagedep;
8306 	struct inodedep *inodedep;
8307 	struct newdirblk *newdirblk = 0;
8308 	struct mkdir *mkdir1, *mkdir2;
8309 	struct worklist *wk;
8310 	struct jaddref *jaddref;
8311 	struct ufsmount *ump;
8312 	struct mount *mp;
8313 
8314 	mp = dap->da_list.wk_mp;
8315 	ump = VFSTOUFS(mp);
8316 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8317 	    M_SOFTDEP_FLAGS);
8318 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8319 	LIST_INIT(&newdirblk->db_mkdir);
8320 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8321 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8322 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8323 	mkdir1->md_diradd = dap;
8324 	mkdir1->md_jaddref = NULL;
8325 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8326 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8327 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8328 	mkdir2->md_diradd = dap;
8329 	mkdir2->md_jaddref = NULL;
8330 	if (MOUNTEDSUJ(mp) == 0) {
8331 		mkdir1->md_state |= DEPCOMPLETE;
8332 		mkdir2->md_state |= DEPCOMPLETE;
8333 	}
8334 	/*
8335 	 * Dependency on "." and ".." being written to disk.
8336 	 */
8337 	mkdir1->md_buf = newdirbp;
8338 	ACQUIRE_LOCK(VFSTOUFS(mp));
8339 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8340 	/*
8341 	 * We must link the pagedep, allocdirect, and newdirblk for
8342 	 * the initial file page so the pointer to the new directory
8343 	 * is not written until the directory contents are live and
8344 	 * any subsequent additions are not marked live until the
8345 	 * block is reachable via the inode.
8346 	 */
8347 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8348 		panic("setup_newdir: lost pagedep");
8349 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8350 		if (wk->wk_type == D_ALLOCDIRECT)
8351 			break;
8352 	if (wk == NULL)
8353 		panic("setup_newdir: lost allocdirect");
8354 	if (pagedep->pd_state & NEWBLOCK)
8355 		panic("setup_newdir: NEWBLOCK already set");
8356 	newblk = WK_NEWBLK(wk);
8357 	pagedep->pd_state |= NEWBLOCK;
8358 	pagedep->pd_newdirblk = newdirblk;
8359 	newdirblk->db_pagedep = pagedep;
8360 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8361 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8362 	/*
8363 	 * Look up the inodedep for the parent directory so that we
8364 	 * can link mkdir2 into the pending dotdot jaddref or
8365 	 * the inode write if there is none.  If the inode is
8366 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8367 	 * been satisfied and mkdir2 can be freed.
8368 	 */
8369 	inodedep_lookup(mp, dinum, 0, &inodedep);
8370 	if (MOUNTEDSUJ(mp)) {
8371 		if (inodedep == NULL)
8372 			panic("setup_newdir: Lost parent.");
8373 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8374 		    inoreflst);
8375 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8376 		    (jaddref->ja_state & MKDIR_PARENT),
8377 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8378 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8379 		mkdir2->md_jaddref = jaddref;
8380 		jaddref->ja_mkdir = mkdir2;
8381 	} else if (inodedep == NULL ||
8382 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8383 		dap->da_state &= ~MKDIR_PARENT;
8384 		WORKITEM_FREE(mkdir2, D_MKDIR);
8385 		mkdir2 = NULL;
8386 	} else {
8387 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8388 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8389 	}
8390 	*mkdirp = mkdir2;
8391 
8392 	return (mkdir1);
8393 }
8394 
8395 /*
8396  * Directory entry addition dependencies.
8397  *
8398  * When adding a new directory entry, the inode (with its incremented link
8399  * count) must be written to disk before the directory entry's pointer to it.
8400  * Also, if the inode is newly allocated, the corresponding freemap must be
8401  * updated (on disk) before the directory entry's pointer. These requirements
8402  * are met via undo/redo on the directory entry's pointer, which consists
8403  * simply of the inode number.
8404  *
8405  * As directory entries are added and deleted, the free space within a
8406  * directory block can become fragmented.  The ufs filesystem will compact
8407  * a fragmented directory block to make space for a new entry. When this
8408  * occurs, the offsets of previously added entries change. Any "diradd"
8409  * dependency structures corresponding to these entries must be updated with
8410  * the new offsets.
8411  */
8412 
8413 /*
8414  * This routine is called after the in-memory inode's link
8415  * count has been incremented, but before the directory entry's
8416  * pointer to the inode has been set.
8417  */
8418 int
8419 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8420 	struct buf *bp;		/* buffer containing directory block */
8421 	struct inode *dp;	/* inode for directory */
8422 	off_t diroffset;	/* offset of new entry in directory */
8423 	ino_t newinum;		/* inode referenced by new directory entry */
8424 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8425 	int isnewblk;		/* entry is in a newly allocated block */
8426 {
8427 	int offset;		/* offset of new entry within directory block */
8428 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8429 	struct fs *fs;
8430 	struct diradd *dap;
8431 	struct newblk *newblk;
8432 	struct pagedep *pagedep;
8433 	struct inodedep *inodedep;
8434 	struct newdirblk *newdirblk = 0;
8435 	struct mkdir *mkdir1, *mkdir2;
8436 	struct jaddref *jaddref;
8437 	struct ufsmount *ump;
8438 	struct mount *mp;
8439 	int isindir;
8440 
8441 	ump = dp->i_ump;
8442 	mp = UFSTOVFS(ump);
8443 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8444 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8445 	/*
8446 	 * Whiteouts have no dependencies.
8447 	 */
8448 	if (newinum == WINO) {
8449 		if (newdirbp != NULL)
8450 			bdwrite(newdirbp);
8451 		return (0);
8452 	}
8453 	jaddref = NULL;
8454 	mkdir1 = mkdir2 = NULL;
8455 	fs = dp->i_fs;
8456 	lbn = lblkno(fs, diroffset);
8457 	offset = blkoff(fs, diroffset);
8458 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8459 		M_SOFTDEP_FLAGS|M_ZERO);
8460 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8461 	dap->da_offset = offset;
8462 	dap->da_newinum = newinum;
8463 	dap->da_state = ATTACHED;
8464 	LIST_INIT(&dap->da_jwork);
8465 	isindir = bp->b_lblkno >= NDADDR;
8466 	if (isnewblk &&
8467 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8468 		newdirblk = malloc(sizeof(struct newdirblk),
8469 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8470 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8471 		LIST_INIT(&newdirblk->db_mkdir);
8472 	}
8473 	/*
8474 	 * If we're creating a new directory setup the dependencies and set
8475 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8476 	 * we can move on.
8477 	 */
8478 	if (newdirbp == NULL) {
8479 		dap->da_state |= DEPCOMPLETE;
8480 		ACQUIRE_LOCK(ump);
8481 	} else {
8482 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8483 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8484 		    &mkdir2);
8485 	}
8486 	/*
8487 	 * Link into parent directory pagedep to await its being written.
8488 	 */
8489 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8490 #ifdef DEBUG
8491 	if (diradd_lookup(pagedep, offset) != NULL)
8492 		panic("softdep_setup_directory_add: %p already at off %d\n",
8493 		    diradd_lookup(pagedep, offset), offset);
8494 #endif
8495 	dap->da_pagedep = pagedep;
8496 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8497 	    da_pdlist);
8498 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8499 	/*
8500 	 * If we're journaling, link the diradd into the jaddref so it
8501 	 * may be completed after the journal entry is written.  Otherwise,
8502 	 * link the diradd into its inodedep.  If the inode is not yet
8503 	 * written place it on the bufwait list, otherwise do the post-inode
8504 	 * write processing to put it on the id_pendinghd list.
8505 	 */
8506 	if (MOUNTEDSUJ(mp)) {
8507 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8508 		    inoreflst);
8509 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8510 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8511 		jaddref->ja_diroff = diroffset;
8512 		jaddref->ja_diradd = dap;
8513 		add_to_journal(&jaddref->ja_list);
8514 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8515 		diradd_inode_written(dap, inodedep);
8516 	else
8517 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8518 	/*
8519 	 * Add the journal entries for . and .. links now that the primary
8520 	 * link is written.
8521 	 */
8522 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8523 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8524 		    inoreflst, if_deps);
8525 		KASSERT(jaddref != NULL &&
8526 		    jaddref->ja_ino == jaddref->ja_parent &&
8527 		    (jaddref->ja_state & MKDIR_BODY),
8528 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8529 		    jaddref));
8530 		mkdir1->md_jaddref = jaddref;
8531 		jaddref->ja_mkdir = mkdir1;
8532 		/*
8533 		 * It is important that the dotdot journal entry
8534 		 * is added prior to the dot entry since dot writes
8535 		 * both the dot and dotdot links.  These both must
8536 		 * be added after the primary link for the journal
8537 		 * to remain consistent.
8538 		 */
8539 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8540 		add_to_journal(&jaddref->ja_list);
8541 	}
8542 	/*
8543 	 * If we are adding a new directory remember this diradd so that if
8544 	 * we rename it we can keep the dot and dotdot dependencies.  If
8545 	 * we are adding a new name for an inode that has a mkdiradd we
8546 	 * must be in rename and we have to move the dot and dotdot
8547 	 * dependencies to this new name.  The old name is being orphaned
8548 	 * soon.
8549 	 */
8550 	if (mkdir1 != NULL) {
8551 		if (inodedep->id_mkdiradd != NULL)
8552 			panic("softdep_setup_directory_add: Existing mkdir");
8553 		inodedep->id_mkdiradd = dap;
8554 	} else if (inodedep->id_mkdiradd)
8555 		merge_diradd(inodedep, dap);
8556 	if (newdirblk) {
8557 		/*
8558 		 * There is nothing to do if we are already tracking
8559 		 * this block.
8560 		 */
8561 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8562 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8563 			FREE_LOCK(ump);
8564 			return (0);
8565 		}
8566 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8567 		    == 0)
8568 			panic("softdep_setup_directory_add: lost entry");
8569 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8570 		pagedep->pd_state |= NEWBLOCK;
8571 		pagedep->pd_newdirblk = newdirblk;
8572 		newdirblk->db_pagedep = pagedep;
8573 		FREE_LOCK(ump);
8574 		/*
8575 		 * If we extended into an indirect signal direnter to sync.
8576 		 */
8577 		if (isindir)
8578 			return (1);
8579 		return (0);
8580 	}
8581 	FREE_LOCK(ump);
8582 	return (0);
8583 }
8584 
8585 /*
8586  * This procedure is called to change the offset of a directory
8587  * entry when compacting a directory block which must be owned
8588  * exclusively by the caller. Note that the actual entry movement
8589  * must be done in this procedure to ensure that no I/O completions
8590  * occur while the move is in progress.
8591  */
8592 void
8593 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8594 	struct buf *bp;		/* Buffer holding directory block. */
8595 	struct inode *dp;	/* inode for directory */
8596 	caddr_t base;		/* address of dp->i_offset */
8597 	caddr_t oldloc;		/* address of old directory location */
8598 	caddr_t newloc;		/* address of new directory location */
8599 	int entrysize;		/* size of directory entry */
8600 {
8601 	int offset, oldoffset, newoffset;
8602 	struct pagedep *pagedep;
8603 	struct jmvref *jmvref;
8604 	struct diradd *dap;
8605 	struct direct *de;
8606 	struct mount *mp;
8607 	ufs_lbn_t lbn;
8608 	int flags;
8609 
8610 	mp = UFSTOVFS(dp->i_ump);
8611 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8612 	    ("softdep_change_directoryentry_offset called on "
8613 	     "non-softdep filesystem"));
8614 	de = (struct direct *)oldloc;
8615 	jmvref = NULL;
8616 	flags = 0;
8617 	/*
8618 	 * Moves are always journaled as it would be too complex to
8619 	 * determine if any affected adds or removes are present in the
8620 	 * journal.
8621 	 */
8622 	if (MOUNTEDSUJ(mp)) {
8623 		flags = DEPALLOC;
8624 		jmvref = newjmvref(dp, de->d_ino,
8625 		    dp->i_offset + (oldloc - base),
8626 		    dp->i_offset + (newloc - base));
8627 	}
8628 	lbn = lblkno(dp->i_fs, dp->i_offset);
8629 	offset = blkoff(dp->i_fs, dp->i_offset);
8630 	oldoffset = offset + (oldloc - base);
8631 	newoffset = offset + (newloc - base);
8632 	ACQUIRE_LOCK(dp->i_ump);
8633 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8634 		goto done;
8635 	dap = diradd_lookup(pagedep, oldoffset);
8636 	if (dap) {
8637 		dap->da_offset = newoffset;
8638 		newoffset = DIRADDHASH(newoffset);
8639 		oldoffset = DIRADDHASH(oldoffset);
8640 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8641 		    newoffset != oldoffset) {
8642 			LIST_REMOVE(dap, da_pdlist);
8643 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8644 			    dap, da_pdlist);
8645 		}
8646 	}
8647 done:
8648 	if (jmvref) {
8649 		jmvref->jm_pagedep = pagedep;
8650 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8651 		add_to_journal(&jmvref->jm_list);
8652 	}
8653 	bcopy(oldloc, newloc, entrysize);
8654 	FREE_LOCK(dp->i_ump);
8655 }
8656 
8657 /*
8658  * Move the mkdir dependencies and journal work from one diradd to another
8659  * when renaming a directory.  The new name must depend on the mkdir deps
8660  * completing as the old name did.  Directories can only have one valid link
8661  * at a time so one must be canonical.
8662  */
8663 static void
8664 merge_diradd(inodedep, newdap)
8665 	struct inodedep *inodedep;
8666 	struct diradd *newdap;
8667 {
8668 	struct diradd *olddap;
8669 	struct mkdir *mkdir, *nextmd;
8670 	struct ufsmount *ump;
8671 	short state;
8672 
8673 	olddap = inodedep->id_mkdiradd;
8674 	inodedep->id_mkdiradd = newdap;
8675 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8676 		newdap->da_state &= ~DEPCOMPLETE;
8677 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8678 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8679 		     mkdir = nextmd) {
8680 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8681 			if (mkdir->md_diradd != olddap)
8682 				continue;
8683 			mkdir->md_diradd = newdap;
8684 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8685 			newdap->da_state |= state;
8686 			olddap->da_state &= ~state;
8687 			if ((olddap->da_state &
8688 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8689 				break;
8690 		}
8691 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8692 			panic("merge_diradd: unfound ref");
8693 	}
8694 	/*
8695 	 * Any mkdir related journal items are not safe to be freed until
8696 	 * the new name is stable.
8697 	 */
8698 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8699 	olddap->da_state |= DEPCOMPLETE;
8700 	complete_diradd(olddap);
8701 }
8702 
8703 /*
8704  * Move the diradd to the pending list when all diradd dependencies are
8705  * complete.
8706  */
8707 static void
8708 complete_diradd(dap)
8709 	struct diradd *dap;
8710 {
8711 	struct pagedep *pagedep;
8712 
8713 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8714 		if (dap->da_state & DIRCHG)
8715 			pagedep = dap->da_previous->dm_pagedep;
8716 		else
8717 			pagedep = dap->da_pagedep;
8718 		LIST_REMOVE(dap, da_pdlist);
8719 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8720 	}
8721 }
8722 
8723 /*
8724  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8725  * add entries and conditonally journal the remove.
8726  */
8727 static void
8728 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8729 	struct diradd *dap;
8730 	struct dirrem *dirrem;
8731 	struct jremref *jremref;
8732 	struct jremref *dotremref;
8733 	struct jremref *dotdotremref;
8734 {
8735 	struct inodedep *inodedep;
8736 	struct jaddref *jaddref;
8737 	struct inoref *inoref;
8738 	struct ufsmount *ump;
8739 	struct mkdir *mkdir;
8740 
8741 	/*
8742 	 * If no remove references were allocated we're on a non-journaled
8743 	 * filesystem and can skip the cancel step.
8744 	 */
8745 	if (jremref == NULL) {
8746 		free_diradd(dap, NULL);
8747 		return;
8748 	}
8749 	/*
8750 	 * Cancel the primary name an free it if it does not require
8751 	 * journaling.
8752 	 */
8753 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8754 	    0, &inodedep) != 0) {
8755 		/* Abort the addref that reference this diradd.  */
8756 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8757 			if (inoref->if_list.wk_type != D_JADDREF)
8758 				continue;
8759 			jaddref = (struct jaddref *)inoref;
8760 			if (jaddref->ja_diradd != dap)
8761 				continue;
8762 			if (cancel_jaddref(jaddref, inodedep,
8763 			    &dirrem->dm_jwork) == 0) {
8764 				free_jremref(jremref);
8765 				jremref = NULL;
8766 			}
8767 			break;
8768 		}
8769 	}
8770 	/*
8771 	 * Cancel subordinate names and free them if they do not require
8772 	 * journaling.
8773 	 */
8774 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8775 		ump = VFSTOUFS(dap->da_list.wk_mp);
8776 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8777 			if (mkdir->md_diradd != dap)
8778 				continue;
8779 			if ((jaddref = mkdir->md_jaddref) == NULL)
8780 				continue;
8781 			mkdir->md_jaddref = NULL;
8782 			if (mkdir->md_state & MKDIR_PARENT) {
8783 				if (cancel_jaddref(jaddref, NULL,
8784 				    &dirrem->dm_jwork) == 0) {
8785 					free_jremref(dotdotremref);
8786 					dotdotremref = NULL;
8787 				}
8788 			} else {
8789 				if (cancel_jaddref(jaddref, inodedep,
8790 				    &dirrem->dm_jwork) == 0) {
8791 					free_jremref(dotremref);
8792 					dotremref = NULL;
8793 				}
8794 			}
8795 		}
8796 	}
8797 
8798 	if (jremref)
8799 		journal_jremref(dirrem, jremref, inodedep);
8800 	if (dotremref)
8801 		journal_jremref(dirrem, dotremref, inodedep);
8802 	if (dotdotremref)
8803 		journal_jremref(dirrem, dotdotremref, NULL);
8804 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8805 	free_diradd(dap, &dirrem->dm_jwork);
8806 }
8807 
8808 /*
8809  * Free a diradd dependency structure. This routine must be called
8810  * with splbio interrupts blocked.
8811  */
8812 static void
8813 free_diradd(dap, wkhd)
8814 	struct diradd *dap;
8815 	struct workhead *wkhd;
8816 {
8817 	struct dirrem *dirrem;
8818 	struct pagedep *pagedep;
8819 	struct inodedep *inodedep;
8820 	struct mkdir *mkdir, *nextmd;
8821 	struct ufsmount *ump;
8822 
8823 	ump = VFSTOUFS(dap->da_list.wk_mp);
8824 	LOCK_OWNED(ump);
8825 	LIST_REMOVE(dap, da_pdlist);
8826 	if (dap->da_state & ONWORKLIST)
8827 		WORKLIST_REMOVE(&dap->da_list);
8828 	if ((dap->da_state & DIRCHG) == 0) {
8829 		pagedep = dap->da_pagedep;
8830 	} else {
8831 		dirrem = dap->da_previous;
8832 		pagedep = dirrem->dm_pagedep;
8833 		dirrem->dm_dirinum = pagedep->pd_ino;
8834 		dirrem->dm_state |= COMPLETE;
8835 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8836 			add_to_worklist(&dirrem->dm_list, 0);
8837 	}
8838 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8839 	    0, &inodedep) != 0)
8840 		if (inodedep->id_mkdiradd == dap)
8841 			inodedep->id_mkdiradd = NULL;
8842 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8843 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8844 		     mkdir = nextmd) {
8845 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8846 			if (mkdir->md_diradd != dap)
8847 				continue;
8848 			dap->da_state &=
8849 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8850 			LIST_REMOVE(mkdir, md_mkdirs);
8851 			if (mkdir->md_state & ONWORKLIST)
8852 				WORKLIST_REMOVE(&mkdir->md_list);
8853 			if (mkdir->md_jaddref != NULL)
8854 				panic("free_diradd: Unexpected jaddref");
8855 			WORKITEM_FREE(mkdir, D_MKDIR);
8856 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8857 				break;
8858 		}
8859 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8860 			panic("free_diradd: unfound ref");
8861 	}
8862 	if (inodedep)
8863 		free_inodedep(inodedep);
8864 	/*
8865 	 * Free any journal segments waiting for the directory write.
8866 	 */
8867 	handle_jwork(&dap->da_jwork);
8868 	WORKITEM_FREE(dap, D_DIRADD);
8869 }
8870 
8871 /*
8872  * Directory entry removal dependencies.
8873  *
8874  * When removing a directory entry, the entry's inode pointer must be
8875  * zero'ed on disk before the corresponding inode's link count is decremented
8876  * (possibly freeing the inode for re-use). This dependency is handled by
8877  * updating the directory entry but delaying the inode count reduction until
8878  * after the directory block has been written to disk. After this point, the
8879  * inode count can be decremented whenever it is convenient.
8880  */
8881 
8882 /*
8883  * This routine should be called immediately after removing
8884  * a directory entry.  The inode's link count should not be
8885  * decremented by the calling procedure -- the soft updates
8886  * code will do this task when it is safe.
8887  */
8888 void
8889 softdep_setup_remove(bp, dp, ip, isrmdir)
8890 	struct buf *bp;		/* buffer containing directory block */
8891 	struct inode *dp;	/* inode for the directory being modified */
8892 	struct inode *ip;	/* inode for directory entry being removed */
8893 	int isrmdir;		/* indicates if doing RMDIR */
8894 {
8895 	struct dirrem *dirrem, *prevdirrem;
8896 	struct inodedep *inodedep;
8897 	int direct;
8898 
8899 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
8900 	    ("softdep_setup_remove called on non-softdep filesystem"));
8901 	/*
8902 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8903 	 * newdirrem() to setup the full directory remove which requires
8904 	 * isrmdir > 1.
8905 	 */
8906 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8907 	/*
8908 	 * Add the dirrem to the inodedep's pending remove list for quick
8909 	 * discovery later.
8910 	 */
8911 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8912 	    &inodedep) == 0)
8913 		panic("softdep_setup_remove: Lost inodedep.");
8914 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8915 	dirrem->dm_state |= ONDEPLIST;
8916 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8917 
8918 	/*
8919 	 * If the COMPLETE flag is clear, then there were no active
8920 	 * entries and we want to roll back to a zeroed entry until
8921 	 * the new inode is committed to disk. If the COMPLETE flag is
8922 	 * set then we have deleted an entry that never made it to
8923 	 * disk. If the entry we deleted resulted from a name change,
8924 	 * then the old name still resides on disk. We cannot delete
8925 	 * its inode (returned to us in prevdirrem) until the zeroed
8926 	 * directory entry gets to disk. The new inode has never been
8927 	 * referenced on the disk, so can be deleted immediately.
8928 	 */
8929 	if ((dirrem->dm_state & COMPLETE) == 0) {
8930 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8931 		    dm_next);
8932 		FREE_LOCK(ip->i_ump);
8933 	} else {
8934 		if (prevdirrem != NULL)
8935 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8936 			    prevdirrem, dm_next);
8937 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8938 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8939 		FREE_LOCK(ip->i_ump);
8940 		if (direct)
8941 			handle_workitem_remove(dirrem, 0);
8942 	}
8943 }
8944 
8945 /*
8946  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8947  * pd_pendinghd list of a pagedep.
8948  */
8949 static struct diradd *
8950 diradd_lookup(pagedep, offset)
8951 	struct pagedep *pagedep;
8952 	int offset;
8953 {
8954 	struct diradd *dap;
8955 
8956 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8957 		if (dap->da_offset == offset)
8958 			return (dap);
8959 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8960 		if (dap->da_offset == offset)
8961 			return (dap);
8962 	return (NULL);
8963 }
8964 
8965 /*
8966  * Search for a .. diradd dependency in a directory that is being removed.
8967  * If the directory was renamed to a new parent we have a diradd rather
8968  * than a mkdir for the .. entry.  We need to cancel it now before
8969  * it is found in truncate().
8970  */
8971 static struct jremref *
8972 cancel_diradd_dotdot(ip, dirrem, jremref)
8973 	struct inode *ip;
8974 	struct dirrem *dirrem;
8975 	struct jremref *jremref;
8976 {
8977 	struct pagedep *pagedep;
8978 	struct diradd *dap;
8979 	struct worklist *wk;
8980 
8981 	if (pagedep_lookup(UFSTOVFS(ip->i_ump), NULL, ip->i_number, 0, 0,
8982 	    &pagedep) == 0)
8983 		return (jremref);
8984 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
8985 	if (dap == NULL)
8986 		return (jremref);
8987 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
8988 	/*
8989 	 * Mark any journal work as belonging to the parent so it is freed
8990 	 * with the .. reference.
8991 	 */
8992 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
8993 		wk->wk_state |= MKDIR_PARENT;
8994 	return (NULL);
8995 }
8996 
8997 /*
8998  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
8999  * replace it with a dirrem/diradd pair as a result of re-parenting a
9000  * directory.  This ensures that we don't simultaneously have a mkdir and
9001  * a diradd for the same .. entry.
9002  */
9003 static struct jremref *
9004 cancel_mkdir_dotdot(ip, dirrem, jremref)
9005 	struct inode *ip;
9006 	struct dirrem *dirrem;
9007 	struct jremref *jremref;
9008 {
9009 	struct inodedep *inodedep;
9010 	struct jaddref *jaddref;
9011 	struct ufsmount *ump;
9012 	struct mkdir *mkdir;
9013 	struct diradd *dap;
9014 
9015 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
9016 	    &inodedep) == 0)
9017 		return (jremref);
9018 	dap = inodedep->id_mkdiradd;
9019 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9020 		return (jremref);
9021 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9022 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9023 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9024 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9025 			break;
9026 	if (mkdir == NULL)
9027 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9028 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9029 		mkdir->md_jaddref = NULL;
9030 		jaddref->ja_state &= ~MKDIR_PARENT;
9031 		if (inodedep_lookup(UFSTOVFS(ip->i_ump), jaddref->ja_ino, 0,
9032 		    &inodedep) == 0)
9033 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9034 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9035 			journal_jremref(dirrem, jremref, inodedep);
9036 			jremref = NULL;
9037 		}
9038 	}
9039 	if (mkdir->md_state & ONWORKLIST)
9040 		WORKLIST_REMOVE(&mkdir->md_list);
9041 	mkdir->md_state |= ALLCOMPLETE;
9042 	complete_mkdir(mkdir);
9043 	return (jremref);
9044 }
9045 
9046 static void
9047 journal_jremref(dirrem, jremref, inodedep)
9048 	struct dirrem *dirrem;
9049 	struct jremref *jremref;
9050 	struct inodedep *inodedep;
9051 {
9052 
9053 	if (inodedep == NULL)
9054 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9055 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9056 			panic("journal_jremref: Lost inodedep");
9057 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9058 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9059 	add_to_journal(&jremref->jr_list);
9060 }
9061 
9062 static void
9063 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9064 	struct dirrem *dirrem;
9065 	struct jremref *jremref;
9066 	struct jremref *dotremref;
9067 	struct jremref *dotdotremref;
9068 {
9069 	struct inodedep *inodedep;
9070 
9071 
9072 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9073 	    &inodedep) == 0)
9074 		panic("dirrem_journal: Lost inodedep");
9075 	journal_jremref(dirrem, jremref, inodedep);
9076 	if (dotremref)
9077 		journal_jremref(dirrem, dotremref, inodedep);
9078 	if (dotdotremref)
9079 		journal_jremref(dirrem, dotdotremref, NULL);
9080 }
9081 
9082 /*
9083  * Allocate a new dirrem if appropriate and return it along with
9084  * its associated pagedep. Called without a lock, returns with lock.
9085  */
9086 static struct dirrem *
9087 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9088 	struct buf *bp;		/* buffer containing directory block */
9089 	struct inode *dp;	/* inode for the directory being modified */
9090 	struct inode *ip;	/* inode for directory entry being removed */
9091 	int isrmdir;		/* indicates if doing RMDIR */
9092 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9093 {
9094 	int offset;
9095 	ufs_lbn_t lbn;
9096 	struct diradd *dap;
9097 	struct dirrem *dirrem;
9098 	struct pagedep *pagedep;
9099 	struct jremref *jremref;
9100 	struct jremref *dotremref;
9101 	struct jremref *dotdotremref;
9102 	struct vnode *dvp;
9103 
9104 	/*
9105 	 * Whiteouts have no deletion dependencies.
9106 	 */
9107 	if (ip == NULL)
9108 		panic("newdirrem: whiteout");
9109 	dvp = ITOV(dp);
9110 	/*
9111 	 * If the system is over its limit and our filesystem is
9112 	 * responsible for more than our share of that usage and
9113 	 * we are not a snapshot, request some inodedep cleanup.
9114 	 * Limiting the number of dirrem structures will also limit
9115 	 * the number of freefile and freeblks structures.
9116 	 */
9117 	ACQUIRE_LOCK(ip->i_ump);
9118 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ip->i_ump, D_DIRREM))
9119 		schedule_cleanup(ITOV(dp)->v_mount);
9120 	else
9121 		FREE_LOCK(ip->i_ump);
9122 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9123 	    M_ZERO);
9124 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9125 	LIST_INIT(&dirrem->dm_jremrefhd);
9126 	LIST_INIT(&dirrem->dm_jwork);
9127 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9128 	dirrem->dm_oldinum = ip->i_number;
9129 	*prevdirremp = NULL;
9130 	/*
9131 	 * Allocate remove reference structures to track journal write
9132 	 * dependencies.  We will always have one for the link and
9133 	 * when doing directories we will always have one more for dot.
9134 	 * When renaming a directory we skip the dotdot link change so
9135 	 * this is not needed.
9136 	 */
9137 	jremref = dotremref = dotdotremref = NULL;
9138 	if (DOINGSUJ(dvp)) {
9139 		if (isrmdir) {
9140 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9141 			    ip->i_effnlink + 2);
9142 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9143 			    ip->i_effnlink + 1);
9144 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9145 			    dp->i_effnlink + 1);
9146 			dotdotremref->jr_state |= MKDIR_PARENT;
9147 		} else
9148 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9149 			    ip->i_effnlink + 1);
9150 	}
9151 	ACQUIRE_LOCK(ip->i_ump);
9152 	lbn = lblkno(dp->i_fs, dp->i_offset);
9153 	offset = blkoff(dp->i_fs, dp->i_offset);
9154 	pagedep_lookup(UFSTOVFS(dp->i_ump), bp, dp->i_number, lbn, DEPALLOC,
9155 	    &pagedep);
9156 	dirrem->dm_pagedep = pagedep;
9157 	dirrem->dm_offset = offset;
9158 	/*
9159 	 * If we're renaming a .. link to a new directory, cancel any
9160 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9161 	 * the jremref is preserved for any potential diradd in this
9162 	 * location.  This can not coincide with a rmdir.
9163 	 */
9164 	if (dp->i_offset == DOTDOT_OFFSET) {
9165 		if (isrmdir)
9166 			panic("newdirrem: .. directory change during remove?");
9167 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9168 	}
9169 	/*
9170 	 * If we're removing a directory search for the .. dependency now and
9171 	 * cancel it.  Any pending journal work will be added to the dirrem
9172 	 * to be completed when the workitem remove completes.
9173 	 */
9174 	if (isrmdir)
9175 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9176 	/*
9177 	 * Check for a diradd dependency for the same directory entry.
9178 	 * If present, then both dependencies become obsolete and can
9179 	 * be de-allocated.
9180 	 */
9181 	dap = diradd_lookup(pagedep, offset);
9182 	if (dap == NULL) {
9183 		/*
9184 		 * Link the jremref structures into the dirrem so they are
9185 		 * written prior to the pagedep.
9186 		 */
9187 		if (jremref)
9188 			dirrem_journal(dirrem, jremref, dotremref,
9189 			    dotdotremref);
9190 		return (dirrem);
9191 	}
9192 	/*
9193 	 * Must be ATTACHED at this point.
9194 	 */
9195 	if ((dap->da_state & ATTACHED) == 0)
9196 		panic("newdirrem: not ATTACHED");
9197 	if (dap->da_newinum != ip->i_number)
9198 		panic("newdirrem: inum %ju should be %ju",
9199 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9200 	/*
9201 	 * If we are deleting a changed name that never made it to disk,
9202 	 * then return the dirrem describing the previous inode (which
9203 	 * represents the inode currently referenced from this entry on disk).
9204 	 */
9205 	if ((dap->da_state & DIRCHG) != 0) {
9206 		*prevdirremp = dap->da_previous;
9207 		dap->da_state &= ~DIRCHG;
9208 		dap->da_pagedep = pagedep;
9209 	}
9210 	/*
9211 	 * We are deleting an entry that never made it to disk.
9212 	 * Mark it COMPLETE so we can delete its inode immediately.
9213 	 */
9214 	dirrem->dm_state |= COMPLETE;
9215 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9216 #ifdef SUJ_DEBUG
9217 	if (isrmdir == 0) {
9218 		struct worklist *wk;
9219 
9220 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9221 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9222 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9223 	}
9224 #endif
9225 
9226 	return (dirrem);
9227 }
9228 
9229 /*
9230  * Directory entry change dependencies.
9231  *
9232  * Changing an existing directory entry requires that an add operation
9233  * be completed first followed by a deletion. The semantics for the addition
9234  * are identical to the description of adding a new entry above except
9235  * that the rollback is to the old inode number rather than zero. Once
9236  * the addition dependency is completed, the removal is done as described
9237  * in the removal routine above.
9238  */
9239 
9240 /*
9241  * This routine should be called immediately after changing
9242  * a directory entry.  The inode's link count should not be
9243  * decremented by the calling procedure -- the soft updates
9244  * code will perform this task when it is safe.
9245  */
9246 void
9247 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9248 	struct buf *bp;		/* buffer containing directory block */
9249 	struct inode *dp;	/* inode for the directory being modified */
9250 	struct inode *ip;	/* inode for directory entry being removed */
9251 	ino_t newinum;		/* new inode number for changed entry */
9252 	int isrmdir;		/* indicates if doing RMDIR */
9253 {
9254 	int offset;
9255 	struct diradd *dap = NULL;
9256 	struct dirrem *dirrem, *prevdirrem;
9257 	struct pagedep *pagedep;
9258 	struct inodedep *inodedep;
9259 	struct jaddref *jaddref;
9260 	struct mount *mp;
9261 
9262 	offset = blkoff(dp->i_fs, dp->i_offset);
9263 	mp = UFSTOVFS(dp->i_ump);
9264 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9265 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9266 
9267 	/*
9268 	 * Whiteouts do not need diradd dependencies.
9269 	 */
9270 	if (newinum != WINO) {
9271 		dap = malloc(sizeof(struct diradd),
9272 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9273 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9274 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9275 		dap->da_offset = offset;
9276 		dap->da_newinum = newinum;
9277 		LIST_INIT(&dap->da_jwork);
9278 	}
9279 
9280 	/*
9281 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9282 	 */
9283 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9284 	pagedep = dirrem->dm_pagedep;
9285 	/*
9286 	 * The possible values for isrmdir:
9287 	 *	0 - non-directory file rename
9288 	 *	1 - directory rename within same directory
9289 	 *   inum - directory rename to new directory of given inode number
9290 	 * When renaming to a new directory, we are both deleting and
9291 	 * creating a new directory entry, so the link count on the new
9292 	 * directory should not change. Thus we do not need the followup
9293 	 * dirrem which is usually done in handle_workitem_remove. We set
9294 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9295 	 * followup dirrem.
9296 	 */
9297 	if (isrmdir > 1)
9298 		dirrem->dm_state |= DIRCHG;
9299 
9300 	/*
9301 	 * Whiteouts have no additional dependencies,
9302 	 * so just put the dirrem on the correct list.
9303 	 */
9304 	if (newinum == WINO) {
9305 		if ((dirrem->dm_state & COMPLETE) == 0) {
9306 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9307 			    dm_next);
9308 		} else {
9309 			dirrem->dm_dirinum = pagedep->pd_ino;
9310 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9311 				add_to_worklist(&dirrem->dm_list, 0);
9312 		}
9313 		FREE_LOCK(dp->i_ump);
9314 		return;
9315 	}
9316 	/*
9317 	 * Add the dirrem to the inodedep's pending remove list for quick
9318 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9319 	 * will not fail.
9320 	 */
9321 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9322 		panic("softdep_setup_directory_change: Lost inodedep.");
9323 	dirrem->dm_state |= ONDEPLIST;
9324 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9325 
9326 	/*
9327 	 * If the COMPLETE flag is clear, then there were no active
9328 	 * entries and we want to roll back to the previous inode until
9329 	 * the new inode is committed to disk. If the COMPLETE flag is
9330 	 * set, then we have deleted an entry that never made it to disk.
9331 	 * If the entry we deleted resulted from a name change, then the old
9332 	 * inode reference still resides on disk. Any rollback that we do
9333 	 * needs to be to that old inode (returned to us in prevdirrem). If
9334 	 * the entry we deleted resulted from a create, then there is
9335 	 * no entry on the disk, so we want to roll back to zero rather
9336 	 * than the uncommitted inode. In either of the COMPLETE cases we
9337 	 * want to immediately free the unwritten and unreferenced inode.
9338 	 */
9339 	if ((dirrem->dm_state & COMPLETE) == 0) {
9340 		dap->da_previous = dirrem;
9341 	} else {
9342 		if (prevdirrem != NULL) {
9343 			dap->da_previous = prevdirrem;
9344 		} else {
9345 			dap->da_state &= ~DIRCHG;
9346 			dap->da_pagedep = pagedep;
9347 		}
9348 		dirrem->dm_dirinum = pagedep->pd_ino;
9349 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9350 			add_to_worklist(&dirrem->dm_list, 0);
9351 	}
9352 	/*
9353 	 * Lookup the jaddref for this journal entry.  We must finish
9354 	 * initializing it and make the diradd write dependent on it.
9355 	 * If we're not journaling, put it on the id_bufwait list if the
9356 	 * inode is not yet written. If it is written, do the post-inode
9357 	 * write processing to put it on the id_pendinghd list.
9358 	 */
9359 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9360 	if (MOUNTEDSUJ(mp)) {
9361 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9362 		    inoreflst);
9363 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9364 		    ("softdep_setup_directory_change: bad jaddref %p",
9365 		    jaddref));
9366 		jaddref->ja_diroff = dp->i_offset;
9367 		jaddref->ja_diradd = dap;
9368 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9369 		    dap, da_pdlist);
9370 		add_to_journal(&jaddref->ja_list);
9371 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9372 		dap->da_state |= COMPLETE;
9373 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9374 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9375 	} else {
9376 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9377 		    dap, da_pdlist);
9378 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9379 	}
9380 	/*
9381 	 * If we're making a new name for a directory that has not been
9382 	 * committed when need to move the dot and dotdot references to
9383 	 * this new name.
9384 	 */
9385 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9386 		merge_diradd(inodedep, dap);
9387 	FREE_LOCK(dp->i_ump);
9388 }
9389 
9390 /*
9391  * Called whenever the link count on an inode is changed.
9392  * It creates an inode dependency so that the new reference(s)
9393  * to the inode cannot be committed to disk until the updated
9394  * inode has been written.
9395  */
9396 void
9397 softdep_change_linkcnt(ip)
9398 	struct inode *ip;	/* the inode with the increased link count */
9399 {
9400 	struct inodedep *inodedep;
9401 
9402 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
9403 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9404 	ACQUIRE_LOCK(ip->i_ump);
9405 	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, DEPALLOC,
9406 	    &inodedep);
9407 	if (ip->i_nlink < ip->i_effnlink)
9408 		panic("softdep_change_linkcnt: bad delta");
9409 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9410 	FREE_LOCK(ip->i_ump);
9411 }
9412 
9413 /*
9414  * Attach a sbdep dependency to the superblock buf so that we can keep
9415  * track of the head of the linked list of referenced but unlinked inodes.
9416  */
9417 void
9418 softdep_setup_sbupdate(ump, fs, bp)
9419 	struct ufsmount *ump;
9420 	struct fs *fs;
9421 	struct buf *bp;
9422 {
9423 	struct sbdep *sbdep;
9424 	struct worklist *wk;
9425 
9426 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9427 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9428 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9429 		if (wk->wk_type == D_SBDEP)
9430 			break;
9431 	if (wk != NULL)
9432 		return;
9433 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9434 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9435 	sbdep->sb_fs = fs;
9436 	sbdep->sb_ump = ump;
9437 	ACQUIRE_LOCK(ump);
9438 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9439 	FREE_LOCK(ump);
9440 }
9441 
9442 /*
9443  * Return the first unlinked inodedep which is ready to be the head of the
9444  * list.  The inodedep and all those after it must have valid next pointers.
9445  */
9446 static struct inodedep *
9447 first_unlinked_inodedep(ump)
9448 	struct ufsmount *ump;
9449 {
9450 	struct inodedep *inodedep;
9451 	struct inodedep *idp;
9452 
9453 	LOCK_OWNED(ump);
9454 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9455 	    inodedep; inodedep = idp) {
9456 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9457 			return (NULL);
9458 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9459 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9460 			break;
9461 		if ((inodedep->id_state & UNLINKPREV) == 0)
9462 			break;
9463 	}
9464 	return (inodedep);
9465 }
9466 
9467 /*
9468  * Set the sujfree unlinked head pointer prior to writing a superblock.
9469  */
9470 static void
9471 initiate_write_sbdep(sbdep)
9472 	struct sbdep *sbdep;
9473 {
9474 	struct inodedep *inodedep;
9475 	struct fs *bpfs;
9476 	struct fs *fs;
9477 
9478 	bpfs = sbdep->sb_fs;
9479 	fs = sbdep->sb_ump->um_fs;
9480 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9481 	if (inodedep) {
9482 		fs->fs_sujfree = inodedep->id_ino;
9483 		inodedep->id_state |= UNLINKPREV;
9484 	} else
9485 		fs->fs_sujfree = 0;
9486 	bpfs->fs_sujfree = fs->fs_sujfree;
9487 }
9488 
9489 /*
9490  * After a superblock is written determine whether it must be written again
9491  * due to a changing unlinked list head.
9492  */
9493 static int
9494 handle_written_sbdep(sbdep, bp)
9495 	struct sbdep *sbdep;
9496 	struct buf *bp;
9497 {
9498 	struct inodedep *inodedep;
9499 	struct fs *fs;
9500 
9501 	LOCK_OWNED(sbdep->sb_ump);
9502 	fs = sbdep->sb_fs;
9503 	/*
9504 	 * If the superblock doesn't match the in-memory list start over.
9505 	 */
9506 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9507 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9508 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9509 		bdirty(bp);
9510 		return (1);
9511 	}
9512 	WORKITEM_FREE(sbdep, D_SBDEP);
9513 	if (fs->fs_sujfree == 0)
9514 		return (0);
9515 	/*
9516 	 * Now that we have a record of this inode in stable store allow it
9517 	 * to be written to free up pending work.  Inodes may see a lot of
9518 	 * write activity after they are unlinked which we must not hold up.
9519 	 */
9520 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9521 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9522 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9523 			    inodedep, inodedep->id_state);
9524 		if (inodedep->id_state & UNLINKONLIST)
9525 			break;
9526 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9527 	}
9528 
9529 	return (0);
9530 }
9531 
9532 /*
9533  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9534  */
9535 static void
9536 unlinked_inodedep(mp, inodedep)
9537 	struct mount *mp;
9538 	struct inodedep *inodedep;
9539 {
9540 	struct ufsmount *ump;
9541 
9542 	ump = VFSTOUFS(mp);
9543 	LOCK_OWNED(ump);
9544 	if (MOUNTEDSUJ(mp) == 0)
9545 		return;
9546 	ump->um_fs->fs_fmod = 1;
9547 	if (inodedep->id_state & UNLINKED)
9548 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9549 	inodedep->id_state |= UNLINKED;
9550 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9551 }
9552 
9553 /*
9554  * Remove an inodedep from the unlinked inodedep list.  This may require
9555  * disk writes if the inode has made it that far.
9556  */
9557 static void
9558 clear_unlinked_inodedep(inodedep)
9559 	struct inodedep *inodedep;
9560 {
9561 	struct ufsmount *ump;
9562 	struct inodedep *idp;
9563 	struct inodedep *idn;
9564 	struct fs *fs;
9565 	struct buf *bp;
9566 	ino_t ino;
9567 	ino_t nino;
9568 	ino_t pino;
9569 	int error;
9570 
9571 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9572 	fs = ump->um_fs;
9573 	ino = inodedep->id_ino;
9574 	error = 0;
9575 	for (;;) {
9576 		LOCK_OWNED(ump);
9577 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9578 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9579 		    inodedep));
9580 		/*
9581 		 * If nothing has yet been written simply remove us from
9582 		 * the in memory list and return.  This is the most common
9583 		 * case where handle_workitem_remove() loses the final
9584 		 * reference.
9585 		 */
9586 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9587 			break;
9588 		/*
9589 		 * If we have a NEXT pointer and no PREV pointer we can simply
9590 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9591 		 * careful not to clear PREV if the superblock points at
9592 		 * next as well.
9593 		 */
9594 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9595 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9596 			if (idn && fs->fs_sujfree != idn->id_ino)
9597 				idn->id_state &= ~UNLINKPREV;
9598 			break;
9599 		}
9600 		/*
9601 		 * Here we have an inodedep which is actually linked into
9602 		 * the list.  We must remove it by forcing a write to the
9603 		 * link before us, whether it be the superblock or an inode.
9604 		 * Unfortunately the list may change while we're waiting
9605 		 * on the buf lock for either resource so we must loop until
9606 		 * we lock the right one.  If both the superblock and an
9607 		 * inode point to this inode we must clear the inode first
9608 		 * followed by the superblock.
9609 		 */
9610 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9611 		pino = 0;
9612 		if (idp && (idp->id_state & UNLINKNEXT))
9613 			pino = idp->id_ino;
9614 		FREE_LOCK(ump);
9615 		if (pino == 0) {
9616 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9617 			    (int)fs->fs_sbsize, 0, 0, 0);
9618 		} else {
9619 			error = bread(ump->um_devvp,
9620 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9621 			    (int)fs->fs_bsize, NOCRED, &bp);
9622 			if (error)
9623 				brelse(bp);
9624 		}
9625 		ACQUIRE_LOCK(ump);
9626 		if (error)
9627 			break;
9628 		/* If the list has changed restart the loop. */
9629 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9630 		nino = 0;
9631 		if (idp && (idp->id_state & UNLINKNEXT))
9632 			nino = idp->id_ino;
9633 		if (nino != pino ||
9634 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9635 			FREE_LOCK(ump);
9636 			brelse(bp);
9637 			ACQUIRE_LOCK(ump);
9638 			continue;
9639 		}
9640 		nino = 0;
9641 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9642 		if (idn)
9643 			nino = idn->id_ino;
9644 		/*
9645 		 * Remove us from the in memory list.  After this we cannot
9646 		 * access the inodedep.
9647 		 */
9648 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9649 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9650 		    inodedep));
9651 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9652 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9653 		FREE_LOCK(ump);
9654 		/*
9655 		 * The predecessor's next pointer is manually updated here
9656 		 * so that the NEXT flag is never cleared for an element
9657 		 * that is in the list.
9658 		 */
9659 		if (pino == 0) {
9660 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9661 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9662 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9663 			    bp);
9664 		} else if (fs->fs_magic == FS_UFS1_MAGIC)
9665 			((struct ufs1_dinode *)bp->b_data +
9666 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9667 		else
9668 			((struct ufs2_dinode *)bp->b_data +
9669 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9670 		/*
9671 		 * If the bwrite fails we have no recourse to recover.  The
9672 		 * filesystem is corrupted already.
9673 		 */
9674 		bwrite(bp);
9675 		ACQUIRE_LOCK(ump);
9676 		/*
9677 		 * If the superblock pointer still needs to be cleared force
9678 		 * a write here.
9679 		 */
9680 		if (fs->fs_sujfree == ino) {
9681 			FREE_LOCK(ump);
9682 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9683 			    (int)fs->fs_sbsize, 0, 0, 0);
9684 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9685 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9686 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9687 			    bp);
9688 			bwrite(bp);
9689 			ACQUIRE_LOCK(ump);
9690 		}
9691 
9692 		if (fs->fs_sujfree != ino)
9693 			return;
9694 		panic("clear_unlinked_inodedep: Failed to clear free head");
9695 	}
9696 	if (inodedep->id_ino == fs->fs_sujfree)
9697 		panic("clear_unlinked_inodedep: Freeing head of free list");
9698 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9699 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9700 	return;
9701 }
9702 
9703 /*
9704  * This workitem decrements the inode's link count.
9705  * If the link count reaches zero, the file is removed.
9706  */
9707 static int
9708 handle_workitem_remove(dirrem, flags)
9709 	struct dirrem *dirrem;
9710 	int flags;
9711 {
9712 	struct inodedep *inodedep;
9713 	struct workhead dotdotwk;
9714 	struct worklist *wk;
9715 	struct ufsmount *ump;
9716 	struct mount *mp;
9717 	struct vnode *vp;
9718 	struct inode *ip;
9719 	ino_t oldinum;
9720 
9721 	if (dirrem->dm_state & ONWORKLIST)
9722 		panic("handle_workitem_remove: dirrem %p still on worklist",
9723 		    dirrem);
9724 	oldinum = dirrem->dm_oldinum;
9725 	mp = dirrem->dm_list.wk_mp;
9726 	ump = VFSTOUFS(mp);
9727 	flags |= LK_EXCLUSIVE;
9728 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9729 		return (EBUSY);
9730 	ip = VTOI(vp);
9731 	ACQUIRE_LOCK(ump);
9732 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9733 		panic("handle_workitem_remove: lost inodedep");
9734 	if (dirrem->dm_state & ONDEPLIST)
9735 		LIST_REMOVE(dirrem, dm_inonext);
9736 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9737 	    ("handle_workitem_remove:  Journal entries not written."));
9738 
9739 	/*
9740 	 * Move all dependencies waiting on the remove to complete
9741 	 * from the dirrem to the inode inowait list to be completed
9742 	 * after the inode has been updated and written to disk.  Any
9743 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9744 	 * is removed.
9745 	 */
9746 	LIST_INIT(&dotdotwk);
9747 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9748 		WORKLIST_REMOVE(wk);
9749 		if (wk->wk_state & MKDIR_PARENT) {
9750 			wk->wk_state &= ~MKDIR_PARENT;
9751 			WORKLIST_INSERT(&dotdotwk, wk);
9752 			continue;
9753 		}
9754 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9755 	}
9756 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9757 	/*
9758 	 * Normal file deletion.
9759 	 */
9760 	if ((dirrem->dm_state & RMDIR) == 0) {
9761 		ip->i_nlink--;
9762 		DIP_SET(ip, i_nlink, ip->i_nlink);
9763 		ip->i_flag |= IN_CHANGE;
9764 		if (ip->i_nlink < ip->i_effnlink)
9765 			panic("handle_workitem_remove: bad file delta");
9766 		if (ip->i_nlink == 0)
9767 			unlinked_inodedep(mp, inodedep);
9768 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9769 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9770 		    ("handle_workitem_remove: worklist not empty. %s",
9771 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9772 		WORKITEM_FREE(dirrem, D_DIRREM);
9773 		FREE_LOCK(ump);
9774 		goto out;
9775 	}
9776 	/*
9777 	 * Directory deletion. Decrement reference count for both the
9778 	 * just deleted parent directory entry and the reference for ".".
9779 	 * Arrange to have the reference count on the parent decremented
9780 	 * to account for the loss of "..".
9781 	 */
9782 	ip->i_nlink -= 2;
9783 	DIP_SET(ip, i_nlink, ip->i_nlink);
9784 	ip->i_flag |= IN_CHANGE;
9785 	if (ip->i_nlink < ip->i_effnlink)
9786 		panic("handle_workitem_remove: bad dir delta");
9787 	if (ip->i_nlink == 0)
9788 		unlinked_inodedep(mp, inodedep);
9789 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9790 	/*
9791 	 * Rename a directory to a new parent. Since, we are both deleting
9792 	 * and creating a new directory entry, the link count on the new
9793 	 * directory should not change. Thus we skip the followup dirrem.
9794 	 */
9795 	if (dirrem->dm_state & DIRCHG) {
9796 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9797 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9798 		WORKITEM_FREE(dirrem, D_DIRREM);
9799 		FREE_LOCK(ump);
9800 		goto out;
9801 	}
9802 	dirrem->dm_state = ONDEPLIST;
9803 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9804 	/*
9805 	 * Place the dirrem on the parent's diremhd list.
9806 	 */
9807 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9808 		panic("handle_workitem_remove: lost dir inodedep");
9809 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9810 	/*
9811 	 * If the allocated inode has never been written to disk, then
9812 	 * the on-disk inode is zero'ed and we can remove the file
9813 	 * immediately.  When journaling if the inode has been marked
9814 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9815 	 */
9816 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9817 	if (inodedep == NULL ||
9818 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9819 	    check_inode_unwritten(inodedep)) {
9820 		FREE_LOCK(ump);
9821 		vput(vp);
9822 		return handle_workitem_remove(dirrem, flags);
9823 	}
9824 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9825 	FREE_LOCK(ump);
9826 	ip->i_flag |= IN_CHANGE;
9827 out:
9828 	ffs_update(vp, 0);
9829 	vput(vp);
9830 	return (0);
9831 }
9832 
9833 /*
9834  * Inode de-allocation dependencies.
9835  *
9836  * When an inode's link count is reduced to zero, it can be de-allocated. We
9837  * found it convenient to postpone de-allocation until after the inode is
9838  * written to disk with its new link count (zero).  At this point, all of the
9839  * on-disk inode's block pointers are nullified and, with careful dependency
9840  * list ordering, all dependencies related to the inode will be satisfied and
9841  * the corresponding dependency structures de-allocated.  So, if/when the
9842  * inode is reused, there will be no mixing of old dependencies with new
9843  * ones.  This artificial dependency is set up by the block de-allocation
9844  * procedure above (softdep_setup_freeblocks) and completed by the
9845  * following procedure.
9846  */
9847 static void
9848 handle_workitem_freefile(freefile)
9849 	struct freefile *freefile;
9850 {
9851 	struct workhead wkhd;
9852 	struct fs *fs;
9853 	struct inodedep *idp;
9854 	struct ufsmount *ump;
9855 	int error;
9856 
9857 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9858 	fs = ump->um_fs;
9859 #ifdef DEBUG
9860 	ACQUIRE_LOCK(ump);
9861 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9862 	FREE_LOCK(ump);
9863 	if (error)
9864 		panic("handle_workitem_freefile: inodedep %p survived", idp);
9865 #endif
9866 	UFS_LOCK(ump);
9867 	fs->fs_pendinginodes -= 1;
9868 	UFS_UNLOCK(ump);
9869 	LIST_INIT(&wkhd);
9870 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9871 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9872 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9873 		softdep_error("handle_workitem_freefile", error);
9874 	ACQUIRE_LOCK(ump);
9875 	WORKITEM_FREE(freefile, D_FREEFILE);
9876 	FREE_LOCK(ump);
9877 }
9878 
9879 
9880 /*
9881  * Helper function which unlinks marker element from work list and returns
9882  * the next element on the list.
9883  */
9884 static __inline struct worklist *
9885 markernext(struct worklist *marker)
9886 {
9887 	struct worklist *next;
9888 
9889 	next = LIST_NEXT(marker, wk_list);
9890 	LIST_REMOVE(marker, wk_list);
9891 	return next;
9892 }
9893 
9894 /*
9895  * Disk writes.
9896  *
9897  * The dependency structures constructed above are most actively used when file
9898  * system blocks are written to disk.  No constraints are placed on when a
9899  * block can be written, but unsatisfied update dependencies are made safe by
9900  * modifying (or replacing) the source memory for the duration of the disk
9901  * write.  When the disk write completes, the memory block is again brought
9902  * up-to-date.
9903  *
9904  * In-core inode structure reclamation.
9905  *
9906  * Because there are a finite number of "in-core" inode structures, they are
9907  * reused regularly.  By transferring all inode-related dependencies to the
9908  * in-memory inode block and indexing them separately (via "inodedep"s), we
9909  * can allow "in-core" inode structures to be reused at any time and avoid
9910  * any increase in contention.
9911  *
9912  * Called just before entering the device driver to initiate a new disk I/O.
9913  * The buffer must be locked, thus, no I/O completion operations can occur
9914  * while we are manipulating its associated dependencies.
9915  */
9916 static void
9917 softdep_disk_io_initiation(bp)
9918 	struct buf *bp;		/* structure describing disk write to occur */
9919 {
9920 	struct worklist *wk;
9921 	struct worklist marker;
9922 	struct inodedep *inodedep;
9923 	struct freeblks *freeblks;
9924 	struct jblkdep *jblkdep;
9925 	struct newblk *newblk;
9926 	struct ufsmount *ump;
9927 
9928 	/*
9929 	 * We only care about write operations. There should never
9930 	 * be dependencies for reads.
9931 	 */
9932 	if (bp->b_iocmd != BIO_WRITE)
9933 		panic("softdep_disk_io_initiation: not write");
9934 
9935 	if (bp->b_vflags & BV_BKGRDINPROG)
9936 		panic("softdep_disk_io_initiation: Writing buffer with "
9937 		    "background write in progress: %p", bp);
9938 
9939 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
9940 		return;
9941 	ump = VFSTOUFS(wk->wk_mp);
9942 
9943 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
9944 	PHOLD(curproc);			/* Don't swap out kernel stack */
9945 	ACQUIRE_LOCK(ump);
9946 	/*
9947 	 * Do any necessary pre-I/O processing.
9948 	 */
9949 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9950 	     wk = markernext(&marker)) {
9951 		LIST_INSERT_AFTER(wk, &marker, wk_list);
9952 		switch (wk->wk_type) {
9953 
9954 		case D_PAGEDEP:
9955 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
9956 			continue;
9957 
9958 		case D_INODEDEP:
9959 			inodedep = WK_INODEDEP(wk);
9960 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
9961 				initiate_write_inodeblock_ufs1(inodedep, bp);
9962 			else
9963 				initiate_write_inodeblock_ufs2(inodedep, bp);
9964 			continue;
9965 
9966 		case D_INDIRDEP:
9967 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
9968 			continue;
9969 
9970 		case D_BMSAFEMAP:
9971 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
9972 			continue;
9973 
9974 		case D_JSEG:
9975 			WK_JSEG(wk)->js_buf = NULL;
9976 			continue;
9977 
9978 		case D_FREEBLKS:
9979 			freeblks = WK_FREEBLKS(wk);
9980 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
9981 			/*
9982 			 * We have to wait for the freeblks to be journaled
9983 			 * before we can write an inodeblock with updated
9984 			 * pointers.  Be careful to arrange the marker so
9985 			 * we revisit the freeblks if it's not removed by
9986 			 * the first jwait().
9987 			 */
9988 			if (jblkdep != NULL) {
9989 				LIST_REMOVE(&marker, wk_list);
9990 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
9991 				jwait(&jblkdep->jb_list, MNT_WAIT);
9992 			}
9993 			continue;
9994 		case D_ALLOCDIRECT:
9995 		case D_ALLOCINDIR:
9996 			/*
9997 			 * We have to wait for the jnewblk to be journaled
9998 			 * before we can write to a block if the contents
9999 			 * may be confused with an earlier file's indirect
10000 			 * at recovery time.  Handle the marker as described
10001 			 * above.
10002 			 */
10003 			newblk = WK_NEWBLK(wk);
10004 			if (newblk->nb_jnewblk != NULL &&
10005 			    indirblk_lookup(newblk->nb_list.wk_mp,
10006 			    newblk->nb_newblkno)) {
10007 				LIST_REMOVE(&marker, wk_list);
10008 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10009 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10010 			}
10011 			continue;
10012 
10013 		case D_SBDEP:
10014 			initiate_write_sbdep(WK_SBDEP(wk));
10015 			continue;
10016 
10017 		case D_MKDIR:
10018 		case D_FREEWORK:
10019 		case D_FREEDEP:
10020 		case D_JSEGDEP:
10021 			continue;
10022 
10023 		default:
10024 			panic("handle_disk_io_initiation: Unexpected type %s",
10025 			    TYPENAME(wk->wk_type));
10026 			/* NOTREACHED */
10027 		}
10028 	}
10029 	FREE_LOCK(ump);
10030 	PRELE(curproc);			/* Allow swapout of kernel stack */
10031 }
10032 
10033 /*
10034  * Called from within the procedure above to deal with unsatisfied
10035  * allocation dependencies in a directory. The buffer must be locked,
10036  * thus, no I/O completion operations can occur while we are
10037  * manipulating its associated dependencies.
10038  */
10039 static void
10040 initiate_write_filepage(pagedep, bp)
10041 	struct pagedep *pagedep;
10042 	struct buf *bp;
10043 {
10044 	struct jremref *jremref;
10045 	struct jmvref *jmvref;
10046 	struct dirrem *dirrem;
10047 	struct diradd *dap;
10048 	struct direct *ep;
10049 	int i;
10050 
10051 	if (pagedep->pd_state & IOSTARTED) {
10052 		/*
10053 		 * This can only happen if there is a driver that does not
10054 		 * understand chaining. Here biodone will reissue the call
10055 		 * to strategy for the incomplete buffers.
10056 		 */
10057 		printf("initiate_write_filepage: already started\n");
10058 		return;
10059 	}
10060 	pagedep->pd_state |= IOSTARTED;
10061 	/*
10062 	 * Wait for all journal remove dependencies to hit the disk.
10063 	 * We can not allow any potentially conflicting directory adds
10064 	 * to be visible before removes and rollback is too difficult.
10065 	 * The per-filesystem lock may be dropped and re-acquired, however
10066 	 * we hold the buf locked so the dependency can not go away.
10067 	 */
10068 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10069 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10070 			jwait(&jremref->jr_list, MNT_WAIT);
10071 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10072 		jwait(&jmvref->jm_list, MNT_WAIT);
10073 	for (i = 0; i < DAHASHSZ; i++) {
10074 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10075 			ep = (struct direct *)
10076 			    ((char *)bp->b_data + dap->da_offset);
10077 			if (ep->d_ino != dap->da_newinum)
10078 				panic("%s: dir inum %ju != new %ju",
10079 				    "initiate_write_filepage",
10080 				    (uintmax_t)ep->d_ino,
10081 				    (uintmax_t)dap->da_newinum);
10082 			if (dap->da_state & DIRCHG)
10083 				ep->d_ino = dap->da_previous->dm_oldinum;
10084 			else
10085 				ep->d_ino = 0;
10086 			dap->da_state &= ~ATTACHED;
10087 			dap->da_state |= UNDONE;
10088 		}
10089 	}
10090 }
10091 
10092 /*
10093  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10094  * Note that any bug fixes made to this routine must be done in the
10095  * version found below.
10096  *
10097  * Called from within the procedure above to deal with unsatisfied
10098  * allocation dependencies in an inodeblock. The buffer must be
10099  * locked, thus, no I/O completion operations can occur while we
10100  * are manipulating its associated dependencies.
10101  */
10102 static void
10103 initiate_write_inodeblock_ufs1(inodedep, bp)
10104 	struct inodedep *inodedep;
10105 	struct buf *bp;			/* The inode block */
10106 {
10107 	struct allocdirect *adp, *lastadp;
10108 	struct ufs1_dinode *dp;
10109 	struct ufs1_dinode *sip;
10110 	struct inoref *inoref;
10111 	struct ufsmount *ump;
10112 	struct fs *fs;
10113 	ufs_lbn_t i;
10114 #ifdef INVARIANTS
10115 	ufs_lbn_t prevlbn = 0;
10116 #endif
10117 	int deplist;
10118 
10119 	if (inodedep->id_state & IOSTARTED)
10120 		panic("initiate_write_inodeblock_ufs1: already started");
10121 	inodedep->id_state |= IOSTARTED;
10122 	fs = inodedep->id_fs;
10123 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10124 	LOCK_OWNED(ump);
10125 	dp = (struct ufs1_dinode *)bp->b_data +
10126 	    ino_to_fsbo(fs, inodedep->id_ino);
10127 
10128 	/*
10129 	 * If we're on the unlinked list but have not yet written our
10130 	 * next pointer initialize it here.
10131 	 */
10132 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10133 		struct inodedep *inon;
10134 
10135 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10136 		dp->di_freelink = inon ? inon->id_ino : 0;
10137 	}
10138 	/*
10139 	 * If the bitmap is not yet written, then the allocated
10140 	 * inode cannot be written to disk.
10141 	 */
10142 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10143 		if (inodedep->id_savedino1 != NULL)
10144 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10145 		FREE_LOCK(ump);
10146 		sip = malloc(sizeof(struct ufs1_dinode),
10147 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10148 		ACQUIRE_LOCK(ump);
10149 		inodedep->id_savedino1 = sip;
10150 		*inodedep->id_savedino1 = *dp;
10151 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10152 		dp->di_gen = inodedep->id_savedino1->di_gen;
10153 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10154 		return;
10155 	}
10156 	/*
10157 	 * If no dependencies, then there is nothing to roll back.
10158 	 */
10159 	inodedep->id_savedsize = dp->di_size;
10160 	inodedep->id_savedextsize = 0;
10161 	inodedep->id_savednlink = dp->di_nlink;
10162 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10163 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10164 		return;
10165 	/*
10166 	 * Revert the link count to that of the first unwritten journal entry.
10167 	 */
10168 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10169 	if (inoref)
10170 		dp->di_nlink = inoref->if_nlink;
10171 	/*
10172 	 * Set the dependencies to busy.
10173 	 */
10174 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10175 	     adp = TAILQ_NEXT(adp, ad_next)) {
10176 #ifdef INVARIANTS
10177 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10178 			panic("softdep_write_inodeblock: lbn order");
10179 		prevlbn = adp->ad_offset;
10180 		if (adp->ad_offset < NDADDR &&
10181 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10182 			panic("%s: direct pointer #%jd mismatch %d != %jd",
10183 			    "softdep_write_inodeblock",
10184 			    (intmax_t)adp->ad_offset,
10185 			    dp->di_db[adp->ad_offset],
10186 			    (intmax_t)adp->ad_newblkno);
10187 		if (adp->ad_offset >= NDADDR &&
10188 		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
10189 			panic("%s: indirect pointer #%jd mismatch %d != %jd",
10190 			    "softdep_write_inodeblock",
10191 			    (intmax_t)adp->ad_offset - NDADDR,
10192 			    dp->di_ib[adp->ad_offset - NDADDR],
10193 			    (intmax_t)adp->ad_newblkno);
10194 		deplist |= 1 << adp->ad_offset;
10195 		if ((adp->ad_state & ATTACHED) == 0)
10196 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10197 			    adp->ad_state);
10198 #endif /* INVARIANTS */
10199 		adp->ad_state &= ~ATTACHED;
10200 		adp->ad_state |= UNDONE;
10201 	}
10202 	/*
10203 	 * The on-disk inode cannot claim to be any larger than the last
10204 	 * fragment that has been written. Otherwise, the on-disk inode
10205 	 * might have fragments that were not the last block in the file
10206 	 * which would corrupt the filesystem.
10207 	 */
10208 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10209 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10210 		if (adp->ad_offset >= NDADDR)
10211 			break;
10212 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10213 		/* keep going until hitting a rollback to a frag */
10214 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10215 			continue;
10216 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10217 		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
10218 #ifdef INVARIANTS
10219 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10220 				panic("softdep_write_inodeblock: lost dep1");
10221 #endif /* INVARIANTS */
10222 			dp->di_db[i] = 0;
10223 		}
10224 		for (i = 0; i < NIADDR; i++) {
10225 #ifdef INVARIANTS
10226 			if (dp->di_ib[i] != 0 &&
10227 			    (deplist & ((1 << NDADDR) << i)) == 0)
10228 				panic("softdep_write_inodeblock: lost dep2");
10229 #endif /* INVARIANTS */
10230 			dp->di_ib[i] = 0;
10231 		}
10232 		return;
10233 	}
10234 	/*
10235 	 * If we have zero'ed out the last allocated block of the file,
10236 	 * roll back the size to the last currently allocated block.
10237 	 * We know that this last allocated block is a full-sized as
10238 	 * we already checked for fragments in the loop above.
10239 	 */
10240 	if (lastadp != NULL &&
10241 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10242 		for (i = lastadp->ad_offset; i >= 0; i--)
10243 			if (dp->di_db[i] != 0)
10244 				break;
10245 		dp->di_size = (i + 1) * fs->fs_bsize;
10246 	}
10247 	/*
10248 	 * The only dependencies are for indirect blocks.
10249 	 *
10250 	 * The file size for indirect block additions is not guaranteed.
10251 	 * Such a guarantee would be non-trivial to achieve. The conventional
10252 	 * synchronous write implementation also does not make this guarantee.
10253 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10254 	 * can be over-estimated without destroying integrity when the file
10255 	 * moves into the indirect blocks (i.e., is large). If we want to
10256 	 * postpone fsck, we are stuck with this argument.
10257 	 */
10258 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10259 		dp->di_ib[adp->ad_offset - NDADDR] = 0;
10260 }
10261 
10262 /*
10263  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10264  * Note that any bug fixes made to this routine must be done in the
10265  * version found above.
10266  *
10267  * Called from within the procedure above to deal with unsatisfied
10268  * allocation dependencies in an inodeblock. The buffer must be
10269  * locked, thus, no I/O completion operations can occur while we
10270  * are manipulating its associated dependencies.
10271  */
10272 static void
10273 initiate_write_inodeblock_ufs2(inodedep, bp)
10274 	struct inodedep *inodedep;
10275 	struct buf *bp;			/* The inode block */
10276 {
10277 	struct allocdirect *adp, *lastadp;
10278 	struct ufs2_dinode *dp;
10279 	struct ufs2_dinode *sip;
10280 	struct inoref *inoref;
10281 	struct ufsmount *ump;
10282 	struct fs *fs;
10283 	ufs_lbn_t i;
10284 #ifdef INVARIANTS
10285 	ufs_lbn_t prevlbn = 0;
10286 #endif
10287 	int deplist;
10288 
10289 	if (inodedep->id_state & IOSTARTED)
10290 		panic("initiate_write_inodeblock_ufs2: already started");
10291 	inodedep->id_state |= IOSTARTED;
10292 	fs = inodedep->id_fs;
10293 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10294 	LOCK_OWNED(ump);
10295 	dp = (struct ufs2_dinode *)bp->b_data +
10296 	    ino_to_fsbo(fs, inodedep->id_ino);
10297 
10298 	/*
10299 	 * If we're on the unlinked list but have not yet written our
10300 	 * next pointer initialize it here.
10301 	 */
10302 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10303 		struct inodedep *inon;
10304 
10305 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10306 		dp->di_freelink = inon ? inon->id_ino : 0;
10307 	}
10308 	/*
10309 	 * If the bitmap is not yet written, then the allocated
10310 	 * inode cannot be written to disk.
10311 	 */
10312 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10313 		if (inodedep->id_savedino2 != NULL)
10314 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10315 		FREE_LOCK(ump);
10316 		sip = malloc(sizeof(struct ufs2_dinode),
10317 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10318 		ACQUIRE_LOCK(ump);
10319 		inodedep->id_savedino2 = sip;
10320 		*inodedep->id_savedino2 = *dp;
10321 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10322 		dp->di_gen = inodedep->id_savedino2->di_gen;
10323 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10324 		return;
10325 	}
10326 	/*
10327 	 * If no dependencies, then there is nothing to roll back.
10328 	 */
10329 	inodedep->id_savedsize = dp->di_size;
10330 	inodedep->id_savedextsize = dp->di_extsize;
10331 	inodedep->id_savednlink = dp->di_nlink;
10332 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10333 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10334 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10335 		return;
10336 	/*
10337 	 * Revert the link count to that of the first unwritten journal entry.
10338 	 */
10339 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10340 	if (inoref)
10341 		dp->di_nlink = inoref->if_nlink;
10342 
10343 	/*
10344 	 * Set the ext data dependencies to busy.
10345 	 */
10346 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10347 	     adp = TAILQ_NEXT(adp, ad_next)) {
10348 #ifdef INVARIANTS
10349 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10350 			panic("softdep_write_inodeblock: lbn order");
10351 		prevlbn = adp->ad_offset;
10352 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10353 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10354 			    "softdep_write_inodeblock",
10355 			    (intmax_t)adp->ad_offset,
10356 			    (intmax_t)dp->di_extb[adp->ad_offset],
10357 			    (intmax_t)adp->ad_newblkno);
10358 		deplist |= 1 << adp->ad_offset;
10359 		if ((adp->ad_state & ATTACHED) == 0)
10360 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10361 			    adp->ad_state);
10362 #endif /* INVARIANTS */
10363 		adp->ad_state &= ~ATTACHED;
10364 		adp->ad_state |= UNDONE;
10365 	}
10366 	/*
10367 	 * The on-disk inode cannot claim to be any larger than the last
10368 	 * fragment that has been written. Otherwise, the on-disk inode
10369 	 * might have fragments that were not the last block in the ext
10370 	 * data which would corrupt the filesystem.
10371 	 */
10372 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10373 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10374 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10375 		/* keep going until hitting a rollback to a frag */
10376 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10377 			continue;
10378 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10379 		for (i = adp->ad_offset + 1; i < NXADDR; i++) {
10380 #ifdef INVARIANTS
10381 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10382 				panic("softdep_write_inodeblock: lost dep1");
10383 #endif /* INVARIANTS */
10384 			dp->di_extb[i] = 0;
10385 		}
10386 		lastadp = NULL;
10387 		break;
10388 	}
10389 	/*
10390 	 * If we have zero'ed out the last allocated block of the ext
10391 	 * data, roll back the size to the last currently allocated block.
10392 	 * We know that this last allocated block is a full-sized as
10393 	 * we already checked for fragments in the loop above.
10394 	 */
10395 	if (lastadp != NULL &&
10396 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10397 		for (i = lastadp->ad_offset; i >= 0; i--)
10398 			if (dp->di_extb[i] != 0)
10399 				break;
10400 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10401 	}
10402 	/*
10403 	 * Set the file data dependencies to busy.
10404 	 */
10405 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10406 	     adp = TAILQ_NEXT(adp, ad_next)) {
10407 #ifdef INVARIANTS
10408 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10409 			panic("softdep_write_inodeblock: lbn order");
10410 		if ((adp->ad_state & ATTACHED) == 0)
10411 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10412 		prevlbn = adp->ad_offset;
10413 		if (adp->ad_offset < NDADDR &&
10414 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10415 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10416 			    "softdep_write_inodeblock",
10417 			    (intmax_t)adp->ad_offset,
10418 			    (intmax_t)dp->di_db[adp->ad_offset],
10419 			    (intmax_t)adp->ad_newblkno);
10420 		if (adp->ad_offset >= NDADDR &&
10421 		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
10422 			panic("%s indirect pointer #%jd mismatch %jd != %jd",
10423 			    "softdep_write_inodeblock:",
10424 			    (intmax_t)adp->ad_offset - NDADDR,
10425 			    (intmax_t)dp->di_ib[adp->ad_offset - NDADDR],
10426 			    (intmax_t)adp->ad_newblkno);
10427 		deplist |= 1 << adp->ad_offset;
10428 		if ((adp->ad_state & ATTACHED) == 0)
10429 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10430 			    adp->ad_state);
10431 #endif /* INVARIANTS */
10432 		adp->ad_state &= ~ATTACHED;
10433 		adp->ad_state |= UNDONE;
10434 	}
10435 	/*
10436 	 * The on-disk inode cannot claim to be any larger than the last
10437 	 * fragment that has been written. Otherwise, the on-disk inode
10438 	 * might have fragments that were not the last block in the file
10439 	 * which would corrupt the filesystem.
10440 	 */
10441 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10442 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10443 		if (adp->ad_offset >= NDADDR)
10444 			break;
10445 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10446 		/* keep going until hitting a rollback to a frag */
10447 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10448 			continue;
10449 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10450 		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
10451 #ifdef INVARIANTS
10452 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10453 				panic("softdep_write_inodeblock: lost dep2");
10454 #endif /* INVARIANTS */
10455 			dp->di_db[i] = 0;
10456 		}
10457 		for (i = 0; i < NIADDR; i++) {
10458 #ifdef INVARIANTS
10459 			if (dp->di_ib[i] != 0 &&
10460 			    (deplist & ((1 << NDADDR) << i)) == 0)
10461 				panic("softdep_write_inodeblock: lost dep3");
10462 #endif /* INVARIANTS */
10463 			dp->di_ib[i] = 0;
10464 		}
10465 		return;
10466 	}
10467 	/*
10468 	 * If we have zero'ed out the last allocated block of the file,
10469 	 * roll back the size to the last currently allocated block.
10470 	 * We know that this last allocated block is a full-sized as
10471 	 * we already checked for fragments in the loop above.
10472 	 */
10473 	if (lastadp != NULL &&
10474 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10475 		for (i = lastadp->ad_offset; i >= 0; i--)
10476 			if (dp->di_db[i] != 0)
10477 				break;
10478 		dp->di_size = (i + 1) * fs->fs_bsize;
10479 	}
10480 	/*
10481 	 * The only dependencies are for indirect blocks.
10482 	 *
10483 	 * The file size for indirect block additions is not guaranteed.
10484 	 * Such a guarantee would be non-trivial to achieve. The conventional
10485 	 * synchronous write implementation also does not make this guarantee.
10486 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10487 	 * can be over-estimated without destroying integrity when the file
10488 	 * moves into the indirect blocks (i.e., is large). If we want to
10489 	 * postpone fsck, we are stuck with this argument.
10490 	 */
10491 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10492 		dp->di_ib[adp->ad_offset - NDADDR] = 0;
10493 }
10494 
10495 /*
10496  * Cancel an indirdep as a result of truncation.  Release all of the
10497  * children allocindirs and place their journal work on the appropriate
10498  * list.
10499  */
10500 static void
10501 cancel_indirdep(indirdep, bp, freeblks)
10502 	struct indirdep *indirdep;
10503 	struct buf *bp;
10504 	struct freeblks *freeblks;
10505 {
10506 	struct allocindir *aip;
10507 
10508 	/*
10509 	 * None of the indirect pointers will ever be visible,
10510 	 * so they can simply be tossed. GOINGAWAY ensures
10511 	 * that allocated pointers will be saved in the buffer
10512 	 * cache until they are freed. Note that they will
10513 	 * only be able to be found by their physical address
10514 	 * since the inode mapping the logical address will
10515 	 * be gone. The save buffer used for the safe copy
10516 	 * was allocated in setup_allocindir_phase2 using
10517 	 * the physical address so it could be used for this
10518 	 * purpose. Hence we swap the safe copy with the real
10519 	 * copy, allowing the safe copy to be freed and holding
10520 	 * on to the real copy for later use in indir_trunc.
10521 	 */
10522 	if (indirdep->ir_state & GOINGAWAY)
10523 		panic("cancel_indirdep: already gone");
10524 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10525 		indirdep->ir_state |= DEPCOMPLETE;
10526 		LIST_REMOVE(indirdep, ir_next);
10527 	}
10528 	indirdep->ir_state |= GOINGAWAY;
10529 	/*
10530 	 * Pass in bp for blocks still have journal writes
10531 	 * pending so we can cancel them on their own.
10532 	 */
10533 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
10534 		cancel_allocindir(aip, bp, freeblks, 0);
10535 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0)
10536 		cancel_allocindir(aip, NULL, freeblks, 0);
10537 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0)
10538 		cancel_allocindir(aip, NULL, freeblks, 0);
10539 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != 0)
10540 		cancel_allocindir(aip, NULL, freeblks, 0);
10541 	/*
10542 	 * If there are pending partial truncations we need to keep the
10543 	 * old block copy around until they complete.  This is because
10544 	 * the current b_data is not a perfect superset of the available
10545 	 * blocks.
10546 	 */
10547 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10548 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10549 	else
10550 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10551 	WORKLIST_REMOVE(&indirdep->ir_list);
10552 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10553 	indirdep->ir_bp = NULL;
10554 	indirdep->ir_freeblks = freeblks;
10555 }
10556 
10557 /*
10558  * Free an indirdep once it no longer has new pointers to track.
10559  */
10560 static void
10561 free_indirdep(indirdep)
10562 	struct indirdep *indirdep;
10563 {
10564 
10565 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10566 	    ("free_indirdep: Indir trunc list not empty."));
10567 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10568 	    ("free_indirdep: Complete head not empty."));
10569 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10570 	    ("free_indirdep: write head not empty."));
10571 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10572 	    ("free_indirdep: done head not empty."));
10573 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10574 	    ("free_indirdep: deplist head not empty."));
10575 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10576 	    ("free_indirdep: %p still on newblk list.", indirdep));
10577 	KASSERT(indirdep->ir_saveddata == NULL,
10578 	    ("free_indirdep: %p still has saved data.", indirdep));
10579 	if (indirdep->ir_state & ONWORKLIST)
10580 		WORKLIST_REMOVE(&indirdep->ir_list);
10581 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10582 }
10583 
10584 /*
10585  * Called before a write to an indirdep.  This routine is responsible for
10586  * rolling back pointers to a safe state which includes only those
10587  * allocindirs which have been completed.
10588  */
10589 static void
10590 initiate_write_indirdep(indirdep, bp)
10591 	struct indirdep *indirdep;
10592 	struct buf *bp;
10593 {
10594 	struct ufsmount *ump;
10595 
10596 	indirdep->ir_state |= IOSTARTED;
10597 	if (indirdep->ir_state & GOINGAWAY)
10598 		panic("disk_io_initiation: indirdep gone");
10599 	/*
10600 	 * If there are no remaining dependencies, this will be writing
10601 	 * the real pointers.
10602 	 */
10603 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10604 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10605 		return;
10606 	/*
10607 	 * Replace up-to-date version with safe version.
10608 	 */
10609 	if (indirdep->ir_saveddata == NULL) {
10610 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10611 		LOCK_OWNED(ump);
10612 		FREE_LOCK(ump);
10613 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10614 		    M_SOFTDEP_FLAGS);
10615 		ACQUIRE_LOCK(ump);
10616 	}
10617 	indirdep->ir_state &= ~ATTACHED;
10618 	indirdep->ir_state |= UNDONE;
10619 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10620 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10621 	    bp->b_bcount);
10622 }
10623 
10624 /*
10625  * Called when an inode has been cleared in a cg bitmap.  This finally
10626  * eliminates any canceled jaddrefs
10627  */
10628 void
10629 softdep_setup_inofree(mp, bp, ino, wkhd)
10630 	struct mount *mp;
10631 	struct buf *bp;
10632 	ino_t ino;
10633 	struct workhead *wkhd;
10634 {
10635 	struct worklist *wk, *wkn;
10636 	struct inodedep *inodedep;
10637 	struct ufsmount *ump;
10638 	uint8_t *inosused;
10639 	struct cg *cgp;
10640 	struct fs *fs;
10641 
10642 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10643 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10644 	ump = VFSTOUFS(mp);
10645 	ACQUIRE_LOCK(ump);
10646 	fs = ump->um_fs;
10647 	cgp = (struct cg *)bp->b_data;
10648 	inosused = cg_inosused(cgp);
10649 	if (isset(inosused, ino % fs->fs_ipg))
10650 		panic("softdep_setup_inofree: inode %ju not freed.",
10651 		    (uintmax_t)ino);
10652 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10653 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10654 		    (uintmax_t)ino, inodedep);
10655 	if (wkhd) {
10656 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10657 			if (wk->wk_type != D_JADDREF)
10658 				continue;
10659 			WORKLIST_REMOVE(wk);
10660 			/*
10661 			 * We can free immediately even if the jaddref
10662 			 * isn't attached in a background write as now
10663 			 * the bitmaps are reconciled.
10664 			 */
10665 			wk->wk_state |= COMPLETE | ATTACHED;
10666 			free_jaddref(WK_JADDREF(wk));
10667 		}
10668 		jwork_move(&bp->b_dep, wkhd);
10669 	}
10670 	FREE_LOCK(ump);
10671 }
10672 
10673 
10674 /*
10675  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10676  * map.  Any dependencies waiting for the write to clear are added to the
10677  * buf's list and any jnewblks that are being canceled are discarded
10678  * immediately.
10679  */
10680 void
10681 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10682 	struct mount *mp;
10683 	struct buf *bp;
10684 	ufs2_daddr_t blkno;
10685 	int frags;
10686 	struct workhead *wkhd;
10687 {
10688 	struct bmsafemap *bmsafemap;
10689 	struct jnewblk *jnewblk;
10690 	struct ufsmount *ump;
10691 	struct worklist *wk;
10692 	struct fs *fs;
10693 #ifdef SUJ_DEBUG
10694 	uint8_t *blksfree;
10695 	struct cg *cgp;
10696 	ufs2_daddr_t jstart;
10697 	ufs2_daddr_t jend;
10698 	ufs2_daddr_t end;
10699 	long bno;
10700 	int i;
10701 #endif
10702 
10703 	CTR3(KTR_SUJ,
10704 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10705 	    blkno, frags, wkhd);
10706 
10707 	ump = VFSTOUFS(mp);
10708 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10709 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10710 	ACQUIRE_LOCK(ump);
10711 	/* Lookup the bmsafemap so we track when it is dirty. */
10712 	fs = ump->um_fs;
10713 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10714 	/*
10715 	 * Detach any jnewblks which have been canceled.  They must linger
10716 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10717 	 * an unjournaled allocation from hitting the disk.
10718 	 */
10719 	if (wkhd) {
10720 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10721 			CTR2(KTR_SUJ,
10722 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10723 			    blkno, wk->wk_type);
10724 			WORKLIST_REMOVE(wk);
10725 			if (wk->wk_type != D_JNEWBLK) {
10726 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10727 				continue;
10728 			}
10729 			jnewblk = WK_JNEWBLK(wk);
10730 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10731 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10732 #ifdef SUJ_DEBUG
10733 			/*
10734 			 * Assert that this block is free in the bitmap
10735 			 * before we discard the jnewblk.
10736 			 */
10737 			cgp = (struct cg *)bp->b_data;
10738 			blksfree = cg_blksfree(cgp);
10739 			bno = dtogd(fs, jnewblk->jn_blkno);
10740 			for (i = jnewblk->jn_oldfrags;
10741 			    i < jnewblk->jn_frags; i++) {
10742 				if (isset(blksfree, bno + i))
10743 					continue;
10744 				panic("softdep_setup_blkfree: not free");
10745 			}
10746 #endif
10747 			/*
10748 			 * Even if it's not attached we can free immediately
10749 			 * as the new bitmap is correct.
10750 			 */
10751 			wk->wk_state |= COMPLETE | ATTACHED;
10752 			free_jnewblk(jnewblk);
10753 		}
10754 	}
10755 
10756 #ifdef SUJ_DEBUG
10757 	/*
10758 	 * Assert that we are not freeing a block which has an outstanding
10759 	 * allocation dependency.
10760 	 */
10761 	fs = VFSTOUFS(mp)->um_fs;
10762 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10763 	end = blkno + frags;
10764 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10765 		/*
10766 		 * Don't match against blocks that will be freed when the
10767 		 * background write is done.
10768 		 */
10769 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10770 		    (COMPLETE | DEPCOMPLETE))
10771 			continue;
10772 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10773 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10774 		if ((blkno >= jstart && blkno < jend) ||
10775 		    (end > jstart && end <= jend)) {
10776 			printf("state 0x%X %jd - %d %d dep %p\n",
10777 			    jnewblk->jn_state, jnewblk->jn_blkno,
10778 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10779 			    jnewblk->jn_dep);
10780 			panic("softdep_setup_blkfree: "
10781 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10782 			    blkno, end, frags, jstart, jend);
10783 		}
10784 	}
10785 #endif
10786 	FREE_LOCK(ump);
10787 }
10788 
10789 /*
10790  * Revert a block allocation when the journal record that describes it
10791  * is not yet written.
10792  */
10793 static int
10794 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10795 	struct jnewblk *jnewblk;
10796 	struct fs *fs;
10797 	struct cg *cgp;
10798 	uint8_t *blksfree;
10799 {
10800 	ufs1_daddr_t fragno;
10801 	long cgbno, bbase;
10802 	int frags, blk;
10803 	int i;
10804 
10805 	frags = 0;
10806 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10807 	/*
10808 	 * We have to test which frags need to be rolled back.  We may
10809 	 * be operating on a stale copy when doing background writes.
10810 	 */
10811 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10812 		if (isclr(blksfree, cgbno + i))
10813 			frags++;
10814 	if (frags == 0)
10815 		return (0);
10816 	/*
10817 	 * This is mostly ffs_blkfree() sans some validation and
10818 	 * superblock updates.
10819 	 */
10820 	if (frags == fs->fs_frag) {
10821 		fragno = fragstoblks(fs, cgbno);
10822 		ffs_setblock(fs, blksfree, fragno);
10823 		ffs_clusteracct(fs, cgp, fragno, 1);
10824 		cgp->cg_cs.cs_nbfree++;
10825 	} else {
10826 		cgbno += jnewblk->jn_oldfrags;
10827 		bbase = cgbno - fragnum(fs, cgbno);
10828 		/* Decrement the old frags.  */
10829 		blk = blkmap(fs, blksfree, bbase);
10830 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10831 		/* Deallocate the fragment */
10832 		for (i = 0; i < frags; i++)
10833 			setbit(blksfree, cgbno + i);
10834 		cgp->cg_cs.cs_nffree += frags;
10835 		/* Add back in counts associated with the new frags */
10836 		blk = blkmap(fs, blksfree, bbase);
10837 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10838 		/* If a complete block has been reassembled, account for it. */
10839 		fragno = fragstoblks(fs, bbase);
10840 		if (ffs_isblock(fs, blksfree, fragno)) {
10841 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10842 			ffs_clusteracct(fs, cgp, fragno, 1);
10843 			cgp->cg_cs.cs_nbfree++;
10844 		}
10845 	}
10846 	stat_jnewblk++;
10847 	jnewblk->jn_state &= ~ATTACHED;
10848 	jnewblk->jn_state |= UNDONE;
10849 
10850 	return (frags);
10851 }
10852 
10853 static void
10854 initiate_write_bmsafemap(bmsafemap, bp)
10855 	struct bmsafemap *bmsafemap;
10856 	struct buf *bp;			/* The cg block. */
10857 {
10858 	struct jaddref *jaddref;
10859 	struct jnewblk *jnewblk;
10860 	uint8_t *inosused;
10861 	uint8_t *blksfree;
10862 	struct cg *cgp;
10863 	struct fs *fs;
10864 	ino_t ino;
10865 
10866 	if (bmsafemap->sm_state & IOSTARTED)
10867 		return;
10868 	bmsafemap->sm_state |= IOSTARTED;
10869 	/*
10870 	 * Clear any inode allocations which are pending journal writes.
10871 	 */
10872 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10873 		cgp = (struct cg *)bp->b_data;
10874 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10875 		inosused = cg_inosused(cgp);
10876 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10877 			ino = jaddref->ja_ino % fs->fs_ipg;
10878 			if (isset(inosused, ino)) {
10879 				if ((jaddref->ja_mode & IFMT) == IFDIR)
10880 					cgp->cg_cs.cs_ndir--;
10881 				cgp->cg_cs.cs_nifree++;
10882 				clrbit(inosused, ino);
10883 				jaddref->ja_state &= ~ATTACHED;
10884 				jaddref->ja_state |= UNDONE;
10885 				stat_jaddref++;
10886 			} else
10887 				panic("initiate_write_bmsafemap: inode %ju "
10888 				    "marked free", (uintmax_t)jaddref->ja_ino);
10889 		}
10890 	}
10891 	/*
10892 	 * Clear any block allocations which are pending journal writes.
10893 	 */
10894 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10895 		cgp = (struct cg *)bp->b_data;
10896 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10897 		blksfree = cg_blksfree(cgp);
10898 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10899 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10900 				continue;
10901 			panic("initiate_write_bmsafemap: block %jd "
10902 			    "marked free", jnewblk->jn_blkno);
10903 		}
10904 	}
10905 	/*
10906 	 * Move allocation lists to the written lists so they can be
10907 	 * cleared once the block write is complete.
10908 	 */
10909 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10910 	    inodedep, id_deps);
10911 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10912 	    newblk, nb_deps);
10913 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10914 	    wk_list);
10915 }
10916 
10917 /*
10918  * This routine is called during the completion interrupt
10919  * service routine for a disk write (from the procedure called
10920  * by the device driver to inform the filesystem caches of
10921  * a request completion).  It should be called early in this
10922  * procedure, before the block is made available to other
10923  * processes or other routines are called.
10924  *
10925  */
10926 static void
10927 softdep_disk_write_complete(bp)
10928 	struct buf *bp;		/* describes the completed disk write */
10929 {
10930 	struct worklist *wk;
10931 	struct worklist *owk;
10932 	struct ufsmount *ump;
10933 	struct workhead reattach;
10934 	struct freeblks *freeblks;
10935 	struct buf *sbp;
10936 
10937 	/*
10938 	 * If an error occurred while doing the write, then the data
10939 	 * has not hit the disk and the dependencies cannot be unrolled.
10940 	 */
10941 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0)
10942 		return;
10943 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
10944 		return;
10945 	ump = VFSTOUFS(wk->wk_mp);
10946 	LIST_INIT(&reattach);
10947 	/*
10948 	 * This lock must not be released anywhere in this code segment.
10949 	 */
10950 	sbp = NULL;
10951 	owk = NULL;
10952 	ACQUIRE_LOCK(ump);
10953 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
10954 		WORKLIST_REMOVE(wk);
10955 		atomic_add_long(&dep_write[wk->wk_type], 1);
10956 		if (wk == owk)
10957 			panic("duplicate worklist: %p\n", wk);
10958 		owk = wk;
10959 		switch (wk->wk_type) {
10960 
10961 		case D_PAGEDEP:
10962 			if (handle_written_filepage(WK_PAGEDEP(wk), bp))
10963 				WORKLIST_INSERT(&reattach, wk);
10964 			continue;
10965 
10966 		case D_INODEDEP:
10967 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
10968 				WORKLIST_INSERT(&reattach, wk);
10969 			continue;
10970 
10971 		case D_BMSAFEMAP:
10972 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp))
10973 				WORKLIST_INSERT(&reattach, wk);
10974 			continue;
10975 
10976 		case D_MKDIR:
10977 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
10978 			continue;
10979 
10980 		case D_ALLOCDIRECT:
10981 			wk->wk_state |= COMPLETE;
10982 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
10983 			continue;
10984 
10985 		case D_ALLOCINDIR:
10986 			wk->wk_state |= COMPLETE;
10987 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
10988 			continue;
10989 
10990 		case D_INDIRDEP:
10991 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp))
10992 				WORKLIST_INSERT(&reattach, wk);
10993 			continue;
10994 
10995 		case D_FREEBLKS:
10996 			wk->wk_state |= COMPLETE;
10997 			freeblks = WK_FREEBLKS(wk);
10998 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
10999 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11000 				add_to_worklist(wk, WK_NODELAY);
11001 			continue;
11002 
11003 		case D_FREEWORK:
11004 			handle_written_freework(WK_FREEWORK(wk));
11005 			break;
11006 
11007 		case D_JSEGDEP:
11008 			free_jsegdep(WK_JSEGDEP(wk));
11009 			continue;
11010 
11011 		case D_JSEG:
11012 			handle_written_jseg(WK_JSEG(wk), bp);
11013 			continue;
11014 
11015 		case D_SBDEP:
11016 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11017 				WORKLIST_INSERT(&reattach, wk);
11018 			continue;
11019 
11020 		case D_FREEDEP:
11021 			free_freedep(WK_FREEDEP(wk));
11022 			continue;
11023 
11024 		default:
11025 			panic("handle_disk_write_complete: Unknown type %s",
11026 			    TYPENAME(wk->wk_type));
11027 			/* NOTREACHED */
11028 		}
11029 	}
11030 	/*
11031 	 * Reattach any requests that must be redone.
11032 	 */
11033 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11034 		WORKLIST_REMOVE(wk);
11035 		WORKLIST_INSERT(&bp->b_dep, wk);
11036 	}
11037 	FREE_LOCK(ump);
11038 	if (sbp)
11039 		brelse(sbp);
11040 }
11041 
11042 /*
11043  * Called from within softdep_disk_write_complete above. Note that
11044  * this routine is always called from interrupt level with further
11045  * splbio interrupts blocked.
11046  */
11047 static void
11048 handle_allocdirect_partdone(adp, wkhd)
11049 	struct allocdirect *adp;	/* the completed allocdirect */
11050 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11051 {
11052 	struct allocdirectlst *listhead;
11053 	struct allocdirect *listadp;
11054 	struct inodedep *inodedep;
11055 	long bsize;
11056 
11057 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11058 		return;
11059 	/*
11060 	 * The on-disk inode cannot claim to be any larger than the last
11061 	 * fragment that has been written. Otherwise, the on-disk inode
11062 	 * might have fragments that were not the last block in the file
11063 	 * which would corrupt the filesystem. Thus, we cannot free any
11064 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11065 	 * these blocks must be rolled back to zero before writing the inode.
11066 	 * We check the currently active set of allocdirects in id_inoupdt
11067 	 * or id_extupdt as appropriate.
11068 	 */
11069 	inodedep = adp->ad_inodedep;
11070 	bsize = inodedep->id_fs->fs_bsize;
11071 	if (adp->ad_state & EXTDATA)
11072 		listhead = &inodedep->id_extupdt;
11073 	else
11074 		listhead = &inodedep->id_inoupdt;
11075 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11076 		/* found our block */
11077 		if (listadp == adp)
11078 			break;
11079 		/* continue if ad_oldlbn is not a fragment */
11080 		if (listadp->ad_oldsize == 0 ||
11081 		    listadp->ad_oldsize == bsize)
11082 			continue;
11083 		/* hit a fragment */
11084 		return;
11085 	}
11086 	/*
11087 	 * If we have reached the end of the current list without
11088 	 * finding the just finished dependency, then it must be
11089 	 * on the future dependency list. Future dependencies cannot
11090 	 * be freed until they are moved to the current list.
11091 	 */
11092 	if (listadp == NULL) {
11093 #ifdef DEBUG
11094 		if (adp->ad_state & EXTDATA)
11095 			listhead = &inodedep->id_newextupdt;
11096 		else
11097 			listhead = &inodedep->id_newinoupdt;
11098 		TAILQ_FOREACH(listadp, listhead, ad_next)
11099 			/* found our block */
11100 			if (listadp == adp)
11101 				break;
11102 		if (listadp == NULL)
11103 			panic("handle_allocdirect_partdone: lost dep");
11104 #endif /* DEBUG */
11105 		return;
11106 	}
11107 	/*
11108 	 * If we have found the just finished dependency, then queue
11109 	 * it along with anything that follows it that is complete.
11110 	 * Since the pointer has not yet been written in the inode
11111 	 * as the dependency prevents it, place the allocdirect on the
11112 	 * bufwait list where it will be freed once the pointer is
11113 	 * valid.
11114 	 */
11115 	if (wkhd == NULL)
11116 		wkhd = &inodedep->id_bufwait;
11117 	for (; adp; adp = listadp) {
11118 		listadp = TAILQ_NEXT(adp, ad_next);
11119 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11120 			return;
11121 		TAILQ_REMOVE(listhead, adp, ad_next);
11122 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11123 	}
11124 }
11125 
11126 /*
11127  * Called from within softdep_disk_write_complete above.  This routine
11128  * completes successfully written allocindirs.
11129  */
11130 static void
11131 handle_allocindir_partdone(aip)
11132 	struct allocindir *aip;		/* the completed allocindir */
11133 {
11134 	struct indirdep *indirdep;
11135 
11136 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11137 		return;
11138 	indirdep = aip->ai_indirdep;
11139 	LIST_REMOVE(aip, ai_next);
11140 	/*
11141 	 * Don't set a pointer while the buffer is undergoing IO or while
11142 	 * we have active truncations.
11143 	 */
11144 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11145 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11146 		return;
11147 	}
11148 	if (indirdep->ir_state & UFS1FMT)
11149 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11150 		    aip->ai_newblkno;
11151 	else
11152 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11153 		    aip->ai_newblkno;
11154 	/*
11155 	 * Await the pointer write before freeing the allocindir.
11156 	 */
11157 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11158 }
11159 
11160 /*
11161  * Release segments held on a jwork list.
11162  */
11163 static void
11164 handle_jwork(wkhd)
11165 	struct workhead *wkhd;
11166 {
11167 	struct worklist *wk;
11168 
11169 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11170 		WORKLIST_REMOVE(wk);
11171 		switch (wk->wk_type) {
11172 		case D_JSEGDEP:
11173 			free_jsegdep(WK_JSEGDEP(wk));
11174 			continue;
11175 		case D_FREEDEP:
11176 			free_freedep(WK_FREEDEP(wk));
11177 			continue;
11178 		case D_FREEFRAG:
11179 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11180 			WORKITEM_FREE(wk, D_FREEFRAG);
11181 			continue;
11182 		case D_FREEWORK:
11183 			handle_written_freework(WK_FREEWORK(wk));
11184 			continue;
11185 		default:
11186 			panic("handle_jwork: Unknown type %s\n",
11187 			    TYPENAME(wk->wk_type));
11188 		}
11189 	}
11190 }
11191 
11192 /*
11193  * Handle the bufwait list on an inode when it is safe to release items
11194  * held there.  This normally happens after an inode block is written but
11195  * may be delayed and handled later if there are pending journal items that
11196  * are not yet safe to be released.
11197  */
11198 static struct freefile *
11199 handle_bufwait(inodedep, refhd)
11200 	struct inodedep *inodedep;
11201 	struct workhead *refhd;
11202 {
11203 	struct jaddref *jaddref;
11204 	struct freefile *freefile;
11205 	struct worklist *wk;
11206 
11207 	freefile = NULL;
11208 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11209 		WORKLIST_REMOVE(wk);
11210 		switch (wk->wk_type) {
11211 		case D_FREEFILE:
11212 			/*
11213 			 * We defer adding freefile to the worklist
11214 			 * until all other additions have been made to
11215 			 * ensure that it will be done after all the
11216 			 * old blocks have been freed.
11217 			 */
11218 			if (freefile != NULL)
11219 				panic("handle_bufwait: freefile");
11220 			freefile = WK_FREEFILE(wk);
11221 			continue;
11222 
11223 		case D_MKDIR:
11224 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11225 			continue;
11226 
11227 		case D_DIRADD:
11228 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11229 			continue;
11230 
11231 		case D_FREEFRAG:
11232 			wk->wk_state |= COMPLETE;
11233 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11234 				add_to_worklist(wk, 0);
11235 			continue;
11236 
11237 		case D_DIRREM:
11238 			wk->wk_state |= COMPLETE;
11239 			add_to_worklist(wk, 0);
11240 			continue;
11241 
11242 		case D_ALLOCDIRECT:
11243 		case D_ALLOCINDIR:
11244 			free_newblk(WK_NEWBLK(wk));
11245 			continue;
11246 
11247 		case D_JNEWBLK:
11248 			wk->wk_state |= COMPLETE;
11249 			free_jnewblk(WK_JNEWBLK(wk));
11250 			continue;
11251 
11252 		/*
11253 		 * Save freed journal segments and add references on
11254 		 * the supplied list which will delay their release
11255 		 * until the cg bitmap is cleared on disk.
11256 		 */
11257 		case D_JSEGDEP:
11258 			if (refhd == NULL)
11259 				free_jsegdep(WK_JSEGDEP(wk));
11260 			else
11261 				WORKLIST_INSERT(refhd, wk);
11262 			continue;
11263 
11264 		case D_JADDREF:
11265 			jaddref = WK_JADDREF(wk);
11266 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11267 			    if_deps);
11268 			/*
11269 			 * Transfer any jaddrefs to the list to be freed with
11270 			 * the bitmap if we're handling a removed file.
11271 			 */
11272 			if (refhd == NULL) {
11273 				wk->wk_state |= COMPLETE;
11274 				free_jaddref(jaddref);
11275 			} else
11276 				WORKLIST_INSERT(refhd, wk);
11277 			continue;
11278 
11279 		default:
11280 			panic("handle_bufwait: Unknown type %p(%s)",
11281 			    wk, TYPENAME(wk->wk_type));
11282 			/* NOTREACHED */
11283 		}
11284 	}
11285 	return (freefile);
11286 }
11287 /*
11288  * Called from within softdep_disk_write_complete above to restore
11289  * in-memory inode block contents to their most up-to-date state. Note
11290  * that this routine is always called from interrupt level with further
11291  * splbio interrupts blocked.
11292  */
11293 static int
11294 handle_written_inodeblock(inodedep, bp)
11295 	struct inodedep *inodedep;
11296 	struct buf *bp;		/* buffer containing the inode block */
11297 {
11298 	struct freefile *freefile;
11299 	struct allocdirect *adp, *nextadp;
11300 	struct ufs1_dinode *dp1 = NULL;
11301 	struct ufs2_dinode *dp2 = NULL;
11302 	struct workhead wkhd;
11303 	int hadchanges, fstype;
11304 	ino_t freelink;
11305 
11306 	LIST_INIT(&wkhd);
11307 	hadchanges = 0;
11308 	freefile = NULL;
11309 	if ((inodedep->id_state & IOSTARTED) == 0)
11310 		panic("handle_written_inodeblock: not started");
11311 	inodedep->id_state &= ~IOSTARTED;
11312 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11313 		fstype = UFS1;
11314 		dp1 = (struct ufs1_dinode *)bp->b_data +
11315 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11316 		freelink = dp1->di_freelink;
11317 	} else {
11318 		fstype = UFS2;
11319 		dp2 = (struct ufs2_dinode *)bp->b_data +
11320 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11321 		freelink = dp2->di_freelink;
11322 	}
11323 	/*
11324 	 * Leave this inodeblock dirty until it's in the list.
11325 	 */
11326 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED) {
11327 		struct inodedep *inon;
11328 
11329 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11330 		if ((inon == NULL && freelink == 0) ||
11331 		    (inon && inon->id_ino == freelink)) {
11332 			if (inon)
11333 				inon->id_state |= UNLINKPREV;
11334 			inodedep->id_state |= UNLINKNEXT;
11335 		}
11336 		hadchanges = 1;
11337 	}
11338 	/*
11339 	 * If we had to rollback the inode allocation because of
11340 	 * bitmaps being incomplete, then simply restore it.
11341 	 * Keep the block dirty so that it will not be reclaimed until
11342 	 * all associated dependencies have been cleared and the
11343 	 * corresponding updates written to disk.
11344 	 */
11345 	if (inodedep->id_savedino1 != NULL) {
11346 		hadchanges = 1;
11347 		if (fstype == UFS1)
11348 			*dp1 = *inodedep->id_savedino1;
11349 		else
11350 			*dp2 = *inodedep->id_savedino2;
11351 		free(inodedep->id_savedino1, M_SAVEDINO);
11352 		inodedep->id_savedino1 = NULL;
11353 		if ((bp->b_flags & B_DELWRI) == 0)
11354 			stat_inode_bitmap++;
11355 		bdirty(bp);
11356 		/*
11357 		 * If the inode is clear here and GOINGAWAY it will never
11358 		 * be written.  Process the bufwait and clear any pending
11359 		 * work which may include the freefile.
11360 		 */
11361 		if (inodedep->id_state & GOINGAWAY)
11362 			goto bufwait;
11363 		return (1);
11364 	}
11365 	inodedep->id_state |= COMPLETE;
11366 	/*
11367 	 * Roll forward anything that had to be rolled back before
11368 	 * the inode could be updated.
11369 	 */
11370 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11371 		nextadp = TAILQ_NEXT(adp, ad_next);
11372 		if (adp->ad_state & ATTACHED)
11373 			panic("handle_written_inodeblock: new entry");
11374 		if (fstype == UFS1) {
11375 			if (adp->ad_offset < NDADDR) {
11376 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11377 					panic("%s %s #%jd mismatch %d != %jd",
11378 					    "handle_written_inodeblock:",
11379 					    "direct pointer",
11380 					    (intmax_t)adp->ad_offset,
11381 					    dp1->di_db[adp->ad_offset],
11382 					    (intmax_t)adp->ad_oldblkno);
11383 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11384 			} else {
11385 				if (dp1->di_ib[adp->ad_offset - NDADDR] != 0)
11386 					panic("%s: %s #%jd allocated as %d",
11387 					    "handle_written_inodeblock",
11388 					    "indirect pointer",
11389 					    (intmax_t)adp->ad_offset - NDADDR,
11390 					    dp1->di_ib[adp->ad_offset - NDADDR]);
11391 				dp1->di_ib[adp->ad_offset - NDADDR] =
11392 				    adp->ad_newblkno;
11393 			}
11394 		} else {
11395 			if (adp->ad_offset < NDADDR) {
11396 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11397 					panic("%s: %s #%jd %s %jd != %jd",
11398 					    "handle_written_inodeblock",
11399 					    "direct pointer",
11400 					    (intmax_t)adp->ad_offset, "mismatch",
11401 					    (intmax_t)dp2->di_db[adp->ad_offset],
11402 					    (intmax_t)adp->ad_oldblkno);
11403 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11404 			} else {
11405 				if (dp2->di_ib[adp->ad_offset - NDADDR] != 0)
11406 					panic("%s: %s #%jd allocated as %jd",
11407 					    "handle_written_inodeblock",
11408 					    "indirect pointer",
11409 					    (intmax_t)adp->ad_offset - NDADDR,
11410 					    (intmax_t)
11411 					    dp2->di_ib[adp->ad_offset - NDADDR]);
11412 				dp2->di_ib[adp->ad_offset - NDADDR] =
11413 				    adp->ad_newblkno;
11414 			}
11415 		}
11416 		adp->ad_state &= ~UNDONE;
11417 		adp->ad_state |= ATTACHED;
11418 		hadchanges = 1;
11419 	}
11420 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11421 		nextadp = TAILQ_NEXT(adp, ad_next);
11422 		if (adp->ad_state & ATTACHED)
11423 			panic("handle_written_inodeblock: new entry");
11424 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11425 			panic("%s: direct pointers #%jd %s %jd != %jd",
11426 			    "handle_written_inodeblock",
11427 			    (intmax_t)adp->ad_offset, "mismatch",
11428 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11429 			    (intmax_t)adp->ad_oldblkno);
11430 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11431 		adp->ad_state &= ~UNDONE;
11432 		adp->ad_state |= ATTACHED;
11433 		hadchanges = 1;
11434 	}
11435 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11436 		stat_direct_blk_ptrs++;
11437 	/*
11438 	 * Reset the file size to its most up-to-date value.
11439 	 */
11440 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11441 		panic("handle_written_inodeblock: bad size");
11442 	if (inodedep->id_savednlink > LINK_MAX)
11443 		panic("handle_written_inodeblock: Invalid link count "
11444 		    "%d for inodedep %p", inodedep->id_savednlink, inodedep);
11445 	if (fstype == UFS1) {
11446 		if (dp1->di_nlink != inodedep->id_savednlink) {
11447 			dp1->di_nlink = inodedep->id_savednlink;
11448 			hadchanges = 1;
11449 		}
11450 		if (dp1->di_size != inodedep->id_savedsize) {
11451 			dp1->di_size = inodedep->id_savedsize;
11452 			hadchanges = 1;
11453 		}
11454 	} else {
11455 		if (dp2->di_nlink != inodedep->id_savednlink) {
11456 			dp2->di_nlink = inodedep->id_savednlink;
11457 			hadchanges = 1;
11458 		}
11459 		if (dp2->di_size != inodedep->id_savedsize) {
11460 			dp2->di_size = inodedep->id_savedsize;
11461 			hadchanges = 1;
11462 		}
11463 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11464 			dp2->di_extsize = inodedep->id_savedextsize;
11465 			hadchanges = 1;
11466 		}
11467 	}
11468 	inodedep->id_savedsize = -1;
11469 	inodedep->id_savedextsize = -1;
11470 	inodedep->id_savednlink = -1;
11471 	/*
11472 	 * If there were any rollbacks in the inode block, then it must be
11473 	 * marked dirty so that its will eventually get written back in
11474 	 * its correct form.
11475 	 */
11476 	if (hadchanges)
11477 		bdirty(bp);
11478 bufwait:
11479 	/*
11480 	 * Process any allocdirects that completed during the update.
11481 	 */
11482 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11483 		handle_allocdirect_partdone(adp, &wkhd);
11484 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11485 		handle_allocdirect_partdone(adp, &wkhd);
11486 	/*
11487 	 * Process deallocations that were held pending until the
11488 	 * inode had been written to disk. Freeing of the inode
11489 	 * is delayed until after all blocks have been freed to
11490 	 * avoid creation of new <vfsid, inum, lbn> triples
11491 	 * before the old ones have been deleted.  Completely
11492 	 * unlinked inodes are not processed until the unlinked
11493 	 * inode list is written or the last reference is removed.
11494 	 */
11495 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11496 		freefile = handle_bufwait(inodedep, NULL);
11497 		if (freefile && !LIST_EMPTY(&wkhd)) {
11498 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11499 			freefile = NULL;
11500 		}
11501 	}
11502 	/*
11503 	 * Move rolled forward dependency completions to the bufwait list
11504 	 * now that those that were already written have been processed.
11505 	 */
11506 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11507 		panic("handle_written_inodeblock: bufwait but no changes");
11508 	jwork_move(&inodedep->id_bufwait, &wkhd);
11509 
11510 	if (freefile != NULL) {
11511 		/*
11512 		 * If the inode is goingaway it was never written.  Fake up
11513 		 * the state here so free_inodedep() can succeed.
11514 		 */
11515 		if (inodedep->id_state & GOINGAWAY)
11516 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11517 		if (free_inodedep(inodedep) == 0)
11518 			panic("handle_written_inodeblock: live inodedep %p",
11519 			    inodedep);
11520 		add_to_worklist(&freefile->fx_list, 0);
11521 		return (0);
11522 	}
11523 
11524 	/*
11525 	 * If no outstanding dependencies, free it.
11526 	 */
11527 	if (free_inodedep(inodedep) ||
11528 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11529 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11530 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11531 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11532 		return (0);
11533 	return (hadchanges);
11534 }
11535 
11536 static int
11537 handle_written_indirdep(indirdep, bp, bpp)
11538 	struct indirdep *indirdep;
11539 	struct buf *bp;
11540 	struct buf **bpp;
11541 {
11542 	struct allocindir *aip;
11543 	struct buf *sbp;
11544 	int chgs;
11545 
11546 	if (indirdep->ir_state & GOINGAWAY)
11547 		panic("handle_written_indirdep: indirdep gone");
11548 	if ((indirdep->ir_state & IOSTARTED) == 0)
11549 		panic("handle_written_indirdep: IO not started");
11550 	chgs = 0;
11551 	/*
11552 	 * If there were rollbacks revert them here.
11553 	 */
11554 	if (indirdep->ir_saveddata) {
11555 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11556 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11557 			free(indirdep->ir_saveddata, M_INDIRDEP);
11558 			indirdep->ir_saveddata = NULL;
11559 		}
11560 		chgs = 1;
11561 	}
11562 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11563 	indirdep->ir_state |= ATTACHED;
11564 	/*
11565 	 * Move allocindirs with written pointers to the completehd if
11566 	 * the indirdep's pointer is not yet written.  Otherwise
11567 	 * free them here.
11568 	 */
11569 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0) {
11570 		LIST_REMOVE(aip, ai_next);
11571 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11572 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11573 			    ai_next);
11574 			newblk_freefrag(&aip->ai_block);
11575 			continue;
11576 		}
11577 		free_newblk(&aip->ai_block);
11578 	}
11579 	/*
11580 	 * Move allocindirs that have finished dependency processing from
11581 	 * the done list to the write list after updating the pointers.
11582 	 */
11583 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11584 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
11585 			handle_allocindir_partdone(aip);
11586 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11587 				panic("disk_write_complete: not gone");
11588 			chgs = 1;
11589 		}
11590 	}
11591 	/*
11592 	 * Preserve the indirdep if there were any changes or if it is not
11593 	 * yet valid on disk.
11594 	 */
11595 	if (chgs) {
11596 		stat_indir_blk_ptrs++;
11597 		bdirty(bp);
11598 		return (1);
11599 	}
11600 	/*
11601 	 * If there were no changes we can discard the savedbp and detach
11602 	 * ourselves from the buf.  We are only carrying completed pointers
11603 	 * in this case.
11604 	 */
11605 	sbp = indirdep->ir_savebp;
11606 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11607 	indirdep->ir_savebp = NULL;
11608 	indirdep->ir_bp = NULL;
11609 	if (*bpp != NULL)
11610 		panic("handle_written_indirdep: bp already exists.");
11611 	*bpp = sbp;
11612 	/*
11613 	 * The indirdep may not be freed until its parent points at it.
11614 	 */
11615 	if (indirdep->ir_state & DEPCOMPLETE)
11616 		free_indirdep(indirdep);
11617 
11618 	return (0);
11619 }
11620 
11621 /*
11622  * Process a diradd entry after its dependent inode has been written.
11623  * This routine must be called with splbio interrupts blocked.
11624  */
11625 static void
11626 diradd_inode_written(dap, inodedep)
11627 	struct diradd *dap;
11628 	struct inodedep *inodedep;
11629 {
11630 
11631 	dap->da_state |= COMPLETE;
11632 	complete_diradd(dap);
11633 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11634 }
11635 
11636 /*
11637  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11638  * be called with the per-filesystem lock and the buf lock on the cg held.
11639  */
11640 static int
11641 bmsafemap_backgroundwrite(bmsafemap, bp)
11642 	struct bmsafemap *bmsafemap;
11643 	struct buf *bp;
11644 {
11645 	int dirty;
11646 
11647 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11648 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11649 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11650 	/*
11651 	 * If we're initiating a background write we need to process the
11652 	 * rollbacks as they exist now, not as they exist when IO starts.
11653 	 * No other consumers will look at the contents of the shadowed
11654 	 * buf so this is safe to do here.
11655 	 */
11656 	if (bp->b_xflags & BX_BKGRDMARKER)
11657 		initiate_write_bmsafemap(bmsafemap, bp);
11658 
11659 	return (dirty);
11660 }
11661 
11662 /*
11663  * Re-apply an allocation when a cg write is complete.
11664  */
11665 static int
11666 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11667 	struct jnewblk *jnewblk;
11668 	struct fs *fs;
11669 	struct cg *cgp;
11670 	uint8_t *blksfree;
11671 {
11672 	ufs1_daddr_t fragno;
11673 	ufs2_daddr_t blkno;
11674 	long cgbno, bbase;
11675 	int frags, blk;
11676 	int i;
11677 
11678 	frags = 0;
11679 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11680 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11681 		if (isclr(blksfree, cgbno + i))
11682 			panic("jnewblk_rollforward: re-allocated fragment");
11683 		frags++;
11684 	}
11685 	if (frags == fs->fs_frag) {
11686 		blkno = fragstoblks(fs, cgbno);
11687 		ffs_clrblock(fs, blksfree, (long)blkno);
11688 		ffs_clusteracct(fs, cgp, blkno, -1);
11689 		cgp->cg_cs.cs_nbfree--;
11690 	} else {
11691 		bbase = cgbno - fragnum(fs, cgbno);
11692 		cgbno += jnewblk->jn_oldfrags;
11693                 /* If a complete block had been reassembled, account for it. */
11694 		fragno = fragstoblks(fs, bbase);
11695 		if (ffs_isblock(fs, blksfree, fragno)) {
11696 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11697 			ffs_clusteracct(fs, cgp, fragno, -1);
11698 			cgp->cg_cs.cs_nbfree--;
11699 		}
11700 		/* Decrement the old frags.  */
11701 		blk = blkmap(fs, blksfree, bbase);
11702 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11703 		/* Allocate the fragment */
11704 		for (i = 0; i < frags; i++)
11705 			clrbit(blksfree, cgbno + i);
11706 		cgp->cg_cs.cs_nffree -= frags;
11707 		/* Add back in counts associated with the new frags */
11708 		blk = blkmap(fs, blksfree, bbase);
11709 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11710 	}
11711 	return (frags);
11712 }
11713 
11714 /*
11715  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11716  * changes if it's not a background write.  Set all written dependencies
11717  * to DEPCOMPLETE and free the structure if possible.
11718  */
11719 static int
11720 handle_written_bmsafemap(bmsafemap, bp)
11721 	struct bmsafemap *bmsafemap;
11722 	struct buf *bp;
11723 {
11724 	struct newblk *newblk;
11725 	struct inodedep *inodedep;
11726 	struct jaddref *jaddref, *jatmp;
11727 	struct jnewblk *jnewblk, *jntmp;
11728 	struct ufsmount *ump;
11729 	uint8_t *inosused;
11730 	uint8_t *blksfree;
11731 	struct cg *cgp;
11732 	struct fs *fs;
11733 	ino_t ino;
11734 	int foreground;
11735 	int chgs;
11736 
11737 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11738 		panic("initiate_write_bmsafemap: Not started\n");
11739 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11740 	chgs = 0;
11741 	bmsafemap->sm_state &= ~IOSTARTED;
11742 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11743 	/*
11744 	 * Release journal work that was waiting on the write.
11745 	 */
11746 	handle_jwork(&bmsafemap->sm_freewr);
11747 
11748 	/*
11749 	 * Restore unwritten inode allocation pending jaddref writes.
11750 	 */
11751 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11752 		cgp = (struct cg *)bp->b_data;
11753 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11754 		inosused = cg_inosused(cgp);
11755 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11756 		    ja_bmdeps, jatmp) {
11757 			if ((jaddref->ja_state & UNDONE) == 0)
11758 				continue;
11759 			ino = jaddref->ja_ino % fs->fs_ipg;
11760 			if (isset(inosused, ino))
11761 				panic("handle_written_bmsafemap: "
11762 				    "re-allocated inode");
11763 			/* Do the roll-forward only if it's a real copy. */
11764 			if (foreground) {
11765 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11766 					cgp->cg_cs.cs_ndir++;
11767 				cgp->cg_cs.cs_nifree--;
11768 				setbit(inosused, ino);
11769 				chgs = 1;
11770 			}
11771 			jaddref->ja_state &= ~UNDONE;
11772 			jaddref->ja_state |= ATTACHED;
11773 			free_jaddref(jaddref);
11774 		}
11775 	}
11776 	/*
11777 	 * Restore any block allocations which are pending journal writes.
11778 	 */
11779 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11780 		cgp = (struct cg *)bp->b_data;
11781 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11782 		blksfree = cg_blksfree(cgp);
11783 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11784 		    jntmp) {
11785 			if ((jnewblk->jn_state & UNDONE) == 0)
11786 				continue;
11787 			/* Do the roll-forward only if it's a real copy. */
11788 			if (foreground &&
11789 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11790 				chgs = 1;
11791 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11792 			jnewblk->jn_state |= ATTACHED;
11793 			free_jnewblk(jnewblk);
11794 		}
11795 	}
11796 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11797 		newblk->nb_state |= DEPCOMPLETE;
11798 		newblk->nb_state &= ~ONDEPLIST;
11799 		newblk->nb_bmsafemap = NULL;
11800 		LIST_REMOVE(newblk, nb_deps);
11801 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11802 			handle_allocdirect_partdone(
11803 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11804 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11805 			handle_allocindir_partdone(
11806 			    WK_ALLOCINDIR(&newblk->nb_list));
11807 		else if (newblk->nb_list.wk_type != D_NEWBLK)
11808 			panic("handle_written_bmsafemap: Unexpected type: %s",
11809 			    TYPENAME(newblk->nb_list.wk_type));
11810 	}
11811 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11812 		inodedep->id_state |= DEPCOMPLETE;
11813 		inodedep->id_state &= ~ONDEPLIST;
11814 		LIST_REMOVE(inodedep, id_deps);
11815 		inodedep->id_bmsafemap = NULL;
11816 	}
11817 	LIST_REMOVE(bmsafemap, sm_next);
11818 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11819 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11820 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11821 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11822 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
11823 		LIST_REMOVE(bmsafemap, sm_hash);
11824 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11825 		return (0);
11826 	}
11827 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11828 	if (foreground)
11829 		bdirty(bp);
11830 	return (1);
11831 }
11832 
11833 /*
11834  * Try to free a mkdir dependency.
11835  */
11836 static void
11837 complete_mkdir(mkdir)
11838 	struct mkdir *mkdir;
11839 {
11840 	struct diradd *dap;
11841 
11842 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11843 		return;
11844 	LIST_REMOVE(mkdir, md_mkdirs);
11845 	dap = mkdir->md_diradd;
11846 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11847 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11848 		dap->da_state |= DEPCOMPLETE;
11849 		complete_diradd(dap);
11850 	}
11851 	WORKITEM_FREE(mkdir, D_MKDIR);
11852 }
11853 
11854 /*
11855  * Handle the completion of a mkdir dependency.
11856  */
11857 static void
11858 handle_written_mkdir(mkdir, type)
11859 	struct mkdir *mkdir;
11860 	int type;
11861 {
11862 
11863 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
11864 		panic("handle_written_mkdir: bad type");
11865 	mkdir->md_state |= COMPLETE;
11866 	complete_mkdir(mkdir);
11867 }
11868 
11869 static int
11870 free_pagedep(pagedep)
11871 	struct pagedep *pagedep;
11872 {
11873 	int i;
11874 
11875 	if (pagedep->pd_state & NEWBLOCK)
11876 		return (0);
11877 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
11878 		return (0);
11879 	for (i = 0; i < DAHASHSZ; i++)
11880 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
11881 			return (0);
11882 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
11883 		return (0);
11884 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
11885 		return (0);
11886 	if (pagedep->pd_state & ONWORKLIST)
11887 		WORKLIST_REMOVE(&pagedep->pd_list);
11888 	LIST_REMOVE(pagedep, pd_hash);
11889 	WORKITEM_FREE(pagedep, D_PAGEDEP);
11890 
11891 	return (1);
11892 }
11893 
11894 /*
11895  * Called from within softdep_disk_write_complete above.
11896  * A write operation was just completed. Removed inodes can
11897  * now be freed and associated block pointers may be committed.
11898  * Note that this routine is always called from interrupt level
11899  * with further splbio interrupts blocked.
11900  */
11901 static int
11902 handle_written_filepage(pagedep, bp)
11903 	struct pagedep *pagedep;
11904 	struct buf *bp;		/* buffer containing the written page */
11905 {
11906 	struct dirrem *dirrem;
11907 	struct diradd *dap, *nextdap;
11908 	struct direct *ep;
11909 	int i, chgs;
11910 
11911 	if ((pagedep->pd_state & IOSTARTED) == 0)
11912 		panic("handle_written_filepage: not started");
11913 	pagedep->pd_state &= ~IOSTARTED;
11914 	/*
11915 	 * Process any directory removals that have been committed.
11916 	 */
11917 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
11918 		LIST_REMOVE(dirrem, dm_next);
11919 		dirrem->dm_state |= COMPLETE;
11920 		dirrem->dm_dirinum = pagedep->pd_ino;
11921 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
11922 		    ("handle_written_filepage: Journal entries not written."));
11923 		add_to_worklist(&dirrem->dm_list, 0);
11924 	}
11925 	/*
11926 	 * Free any directory additions that have been committed.
11927 	 * If it is a newly allocated block, we have to wait until
11928 	 * the on-disk directory inode claims the new block.
11929 	 */
11930 	if ((pagedep->pd_state & NEWBLOCK) == 0)
11931 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
11932 			free_diradd(dap, NULL);
11933 	/*
11934 	 * Uncommitted directory entries must be restored.
11935 	 */
11936 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
11937 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
11938 		     dap = nextdap) {
11939 			nextdap = LIST_NEXT(dap, da_pdlist);
11940 			if (dap->da_state & ATTACHED)
11941 				panic("handle_written_filepage: attached");
11942 			ep = (struct direct *)
11943 			    ((char *)bp->b_data + dap->da_offset);
11944 			ep->d_ino = dap->da_newinum;
11945 			dap->da_state &= ~UNDONE;
11946 			dap->da_state |= ATTACHED;
11947 			chgs = 1;
11948 			/*
11949 			 * If the inode referenced by the directory has
11950 			 * been written out, then the dependency can be
11951 			 * moved to the pending list.
11952 			 */
11953 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
11954 				LIST_REMOVE(dap, da_pdlist);
11955 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
11956 				    da_pdlist);
11957 			}
11958 		}
11959 	}
11960 	/*
11961 	 * If there were any rollbacks in the directory, then it must be
11962 	 * marked dirty so that its will eventually get written back in
11963 	 * its correct form.
11964 	 */
11965 	if (chgs) {
11966 		if ((bp->b_flags & B_DELWRI) == 0)
11967 			stat_dir_entry++;
11968 		bdirty(bp);
11969 		return (1);
11970 	}
11971 	/*
11972 	 * If we are not waiting for a new directory block to be
11973 	 * claimed by its inode, then the pagedep will be freed.
11974 	 * Otherwise it will remain to track any new entries on
11975 	 * the page in case they are fsync'ed.
11976 	 */
11977 	free_pagedep(pagedep);
11978 	return (0);
11979 }
11980 
11981 /*
11982  * Writing back in-core inode structures.
11983  *
11984  * The filesystem only accesses an inode's contents when it occupies an
11985  * "in-core" inode structure.  These "in-core" structures are separate from
11986  * the page frames used to cache inode blocks.  Only the latter are
11987  * transferred to/from the disk.  So, when the updated contents of the
11988  * "in-core" inode structure are copied to the corresponding in-memory inode
11989  * block, the dependencies are also transferred.  The following procedure is
11990  * called when copying a dirty "in-core" inode to a cached inode block.
11991  */
11992 
11993 /*
11994  * Called when an inode is loaded from disk. If the effective link count
11995  * differed from the actual link count when it was last flushed, then we
11996  * need to ensure that the correct effective link count is put back.
11997  */
11998 void
11999 softdep_load_inodeblock(ip)
12000 	struct inode *ip;	/* the "in_core" copy of the inode */
12001 {
12002 	struct inodedep *inodedep;
12003 
12004 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
12005 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12006 	/*
12007 	 * Check for alternate nlink count.
12008 	 */
12009 	ip->i_effnlink = ip->i_nlink;
12010 	ACQUIRE_LOCK(ip->i_ump);
12011 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
12012 	    &inodedep) == 0) {
12013 		FREE_LOCK(ip->i_ump);
12014 		return;
12015 	}
12016 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12017 	FREE_LOCK(ip->i_ump);
12018 }
12019 
12020 /*
12021  * This routine is called just before the "in-core" inode
12022  * information is to be copied to the in-memory inode block.
12023  * Recall that an inode block contains several inodes. If
12024  * the force flag is set, then the dependencies will be
12025  * cleared so that the update can always be made. Note that
12026  * the buffer is locked when this routine is called, so we
12027  * will never be in the middle of writing the inode block
12028  * to disk.
12029  */
12030 void
12031 softdep_update_inodeblock(ip, bp, waitfor)
12032 	struct inode *ip;	/* the "in_core" copy of the inode */
12033 	struct buf *bp;		/* the buffer containing the inode block */
12034 	int waitfor;		/* nonzero => update must be allowed */
12035 {
12036 	struct inodedep *inodedep;
12037 	struct inoref *inoref;
12038 	struct ufsmount *ump;
12039 	struct worklist *wk;
12040 	struct mount *mp;
12041 	struct buf *ibp;
12042 	struct fs *fs;
12043 	int error;
12044 
12045 	ump = ip->i_ump;
12046 	mp = UFSTOVFS(ump);
12047 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12048 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12049 	fs = ip->i_fs;
12050 	/*
12051 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12052 	 * does not have access to the in-core ip so must write directly into
12053 	 * the inode block buffer when setting freelink.
12054 	 */
12055 	if (fs->fs_magic == FS_UFS1_MAGIC)
12056 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12057 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12058 	else
12059 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12060 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12061 	/*
12062 	 * If the effective link count is not equal to the actual link
12063 	 * count, then we must track the difference in an inodedep while
12064 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12065 	 * if there is no existing inodedep, then there are no dependencies
12066 	 * to track.
12067 	 */
12068 	ACQUIRE_LOCK(ump);
12069 again:
12070 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12071 		FREE_LOCK(ump);
12072 		if (ip->i_effnlink != ip->i_nlink)
12073 			panic("softdep_update_inodeblock: bad link count");
12074 		return;
12075 	}
12076 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12077 		panic("softdep_update_inodeblock: bad delta");
12078 	/*
12079 	 * If we're flushing all dependencies we must also move any waiting
12080 	 * for journal writes onto the bufwait list prior to I/O.
12081 	 */
12082 	if (waitfor) {
12083 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12084 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12085 			    == DEPCOMPLETE) {
12086 				jwait(&inoref->if_list, MNT_WAIT);
12087 				goto again;
12088 			}
12089 		}
12090 	}
12091 	/*
12092 	 * Changes have been initiated. Anything depending on these
12093 	 * changes cannot occur until this inode has been written.
12094 	 */
12095 	inodedep->id_state &= ~COMPLETE;
12096 	if ((inodedep->id_state & ONWORKLIST) == 0)
12097 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12098 	/*
12099 	 * Any new dependencies associated with the incore inode must
12100 	 * now be moved to the list associated with the buffer holding
12101 	 * the in-memory copy of the inode. Once merged process any
12102 	 * allocdirects that are completed by the merger.
12103 	 */
12104 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12105 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12106 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12107 		    NULL);
12108 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12109 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12110 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12111 		    NULL);
12112 	/*
12113 	 * Now that the inode has been pushed into the buffer, the
12114 	 * operations dependent on the inode being written to disk
12115 	 * can be moved to the id_bufwait so that they will be
12116 	 * processed when the buffer I/O completes.
12117 	 */
12118 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12119 		WORKLIST_REMOVE(wk);
12120 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12121 	}
12122 	/*
12123 	 * Newly allocated inodes cannot be written until the bitmap
12124 	 * that allocates them have been written (indicated by
12125 	 * DEPCOMPLETE being set in id_state). If we are doing a
12126 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12127 	 * to be written so that the update can be done.
12128 	 */
12129 	if (waitfor == 0) {
12130 		FREE_LOCK(ump);
12131 		return;
12132 	}
12133 retry:
12134 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12135 		FREE_LOCK(ump);
12136 		return;
12137 	}
12138 	ibp = inodedep->id_bmsafemap->sm_buf;
12139 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12140 	if (ibp == NULL) {
12141 		/*
12142 		 * If ibp came back as NULL, the dependency could have been
12143 		 * freed while we slept.  Look it up again, and check to see
12144 		 * that it has completed.
12145 		 */
12146 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12147 			goto retry;
12148 		FREE_LOCK(ump);
12149 		return;
12150 	}
12151 	FREE_LOCK(ump);
12152 	if ((error = bwrite(ibp)) != 0)
12153 		softdep_error("softdep_update_inodeblock: bwrite", error);
12154 }
12155 
12156 /*
12157  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12158  * old inode dependency list (such as id_inoupdt). This routine must be
12159  * called with splbio interrupts blocked.
12160  */
12161 static void
12162 merge_inode_lists(newlisthead, oldlisthead)
12163 	struct allocdirectlst *newlisthead;
12164 	struct allocdirectlst *oldlisthead;
12165 {
12166 	struct allocdirect *listadp, *newadp;
12167 
12168 	newadp = TAILQ_FIRST(newlisthead);
12169 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12170 		if (listadp->ad_offset < newadp->ad_offset) {
12171 			listadp = TAILQ_NEXT(listadp, ad_next);
12172 			continue;
12173 		}
12174 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12175 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12176 		if (listadp->ad_offset == newadp->ad_offset) {
12177 			allocdirect_merge(oldlisthead, newadp,
12178 			    listadp);
12179 			listadp = newadp;
12180 		}
12181 		newadp = TAILQ_FIRST(newlisthead);
12182 	}
12183 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12184 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12185 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12186 	}
12187 }
12188 
12189 /*
12190  * If we are doing an fsync, then we must ensure that any directory
12191  * entries for the inode have been written after the inode gets to disk.
12192  */
12193 int
12194 softdep_fsync(vp)
12195 	struct vnode *vp;	/* the "in_core" copy of the inode */
12196 {
12197 	struct inodedep *inodedep;
12198 	struct pagedep *pagedep;
12199 	struct inoref *inoref;
12200 	struct ufsmount *ump;
12201 	struct worklist *wk;
12202 	struct diradd *dap;
12203 	struct mount *mp;
12204 	struct vnode *pvp;
12205 	struct inode *ip;
12206 	struct buf *bp;
12207 	struct fs *fs;
12208 	struct thread *td = curthread;
12209 	int error, flushparent, pagedep_new_block;
12210 	ino_t parentino;
12211 	ufs_lbn_t lbn;
12212 
12213 	ip = VTOI(vp);
12214 	fs = ip->i_fs;
12215 	ump = ip->i_ump;
12216 	mp = vp->v_mount;
12217 	if (MOUNTEDSOFTDEP(mp) == 0)
12218 		return (0);
12219 	ACQUIRE_LOCK(ump);
12220 restart:
12221 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12222 		FREE_LOCK(ump);
12223 		return (0);
12224 	}
12225 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12226 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12227 		    == DEPCOMPLETE) {
12228 			jwait(&inoref->if_list, MNT_WAIT);
12229 			goto restart;
12230 		}
12231 	}
12232 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12233 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12234 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12235 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12236 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12237 		panic("softdep_fsync: pending ops %p", inodedep);
12238 	for (error = 0, flushparent = 0; ; ) {
12239 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12240 			break;
12241 		if (wk->wk_type != D_DIRADD)
12242 			panic("softdep_fsync: Unexpected type %s",
12243 			    TYPENAME(wk->wk_type));
12244 		dap = WK_DIRADD(wk);
12245 		/*
12246 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12247 		 * dependency or is contained in a newly allocated block.
12248 		 */
12249 		if (dap->da_state & DIRCHG)
12250 			pagedep = dap->da_previous->dm_pagedep;
12251 		else
12252 			pagedep = dap->da_pagedep;
12253 		parentino = pagedep->pd_ino;
12254 		lbn = pagedep->pd_lbn;
12255 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12256 			panic("softdep_fsync: dirty");
12257 		if ((dap->da_state & MKDIR_PARENT) ||
12258 		    (pagedep->pd_state & NEWBLOCK))
12259 			flushparent = 1;
12260 		else
12261 			flushparent = 0;
12262 		/*
12263 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12264 		 * then we will not be able to release and recover the
12265 		 * vnode below, so we just have to give up on writing its
12266 		 * directory entry out. It will eventually be written, just
12267 		 * not now, but then the user was not asking to have it
12268 		 * written, so we are not breaking any promises.
12269 		 */
12270 		if (vp->v_iflag & VI_DOOMED)
12271 			break;
12272 		/*
12273 		 * We prevent deadlock by always fetching inodes from the
12274 		 * root, moving down the directory tree. Thus, when fetching
12275 		 * our parent directory, we first try to get the lock. If
12276 		 * that fails, we must unlock ourselves before requesting
12277 		 * the lock on our parent. See the comment in ufs_lookup
12278 		 * for details on possible races.
12279 		 */
12280 		FREE_LOCK(ump);
12281 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12282 		    FFSV_FORCEINSMQ)) {
12283 			error = vfs_busy(mp, MBF_NOWAIT);
12284 			if (error != 0) {
12285 				vfs_ref(mp);
12286 				VOP_UNLOCK(vp, 0);
12287 				error = vfs_busy(mp, 0);
12288 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12289 				vfs_rel(mp);
12290 				if (error != 0)
12291 					return (ENOENT);
12292 				if (vp->v_iflag & VI_DOOMED) {
12293 					vfs_unbusy(mp);
12294 					return (ENOENT);
12295 				}
12296 			}
12297 			VOP_UNLOCK(vp, 0);
12298 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12299 			    &pvp, FFSV_FORCEINSMQ);
12300 			vfs_unbusy(mp);
12301 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12302 			if (vp->v_iflag & VI_DOOMED) {
12303 				if (error == 0)
12304 					vput(pvp);
12305 				error = ENOENT;
12306 			}
12307 			if (error != 0)
12308 				return (error);
12309 		}
12310 		/*
12311 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12312 		 * that are contained in direct blocks will be resolved by
12313 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12314 		 * may require a complete sync'ing of the directory. So, we
12315 		 * try the cheap and fast ffs_update first, and if that fails,
12316 		 * then we do the slower ffs_syncvnode of the directory.
12317 		 */
12318 		if (flushparent) {
12319 			int locked;
12320 
12321 			if ((error = ffs_update(pvp, 1)) != 0) {
12322 				vput(pvp);
12323 				return (error);
12324 			}
12325 			ACQUIRE_LOCK(ump);
12326 			locked = 1;
12327 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12328 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12329 					if (wk->wk_type != D_DIRADD)
12330 						panic("softdep_fsync: Unexpected type %s",
12331 						      TYPENAME(wk->wk_type));
12332 					dap = WK_DIRADD(wk);
12333 					if (dap->da_state & DIRCHG)
12334 						pagedep = dap->da_previous->dm_pagedep;
12335 					else
12336 						pagedep = dap->da_pagedep;
12337 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12338 					FREE_LOCK(ump);
12339 					locked = 0;
12340 					if (pagedep_new_block && (error =
12341 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12342 						vput(pvp);
12343 						return (error);
12344 					}
12345 				}
12346 			}
12347 			if (locked)
12348 				FREE_LOCK(ump);
12349 		}
12350 		/*
12351 		 * Flush directory page containing the inode's name.
12352 		 */
12353 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12354 		    &bp);
12355 		if (error == 0)
12356 			error = bwrite(bp);
12357 		else
12358 			brelse(bp);
12359 		vput(pvp);
12360 		if (error != 0)
12361 			return (error);
12362 		ACQUIRE_LOCK(ump);
12363 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12364 			break;
12365 	}
12366 	FREE_LOCK(ump);
12367 	return (0);
12368 }
12369 
12370 /*
12371  * Flush all the dirty bitmaps associated with the block device
12372  * before flushing the rest of the dirty blocks so as to reduce
12373  * the number of dependencies that will have to be rolled back.
12374  *
12375  * XXX Unused?
12376  */
12377 void
12378 softdep_fsync_mountdev(vp)
12379 	struct vnode *vp;
12380 {
12381 	struct buf *bp, *nbp;
12382 	struct worklist *wk;
12383 	struct bufobj *bo;
12384 
12385 	if (!vn_isdisk(vp, NULL))
12386 		panic("softdep_fsync_mountdev: vnode not a disk");
12387 	bo = &vp->v_bufobj;
12388 restart:
12389 	BO_LOCK(bo);
12390 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12391 		/*
12392 		 * If it is already scheduled, skip to the next buffer.
12393 		 */
12394 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12395 			continue;
12396 
12397 		if ((bp->b_flags & B_DELWRI) == 0)
12398 			panic("softdep_fsync_mountdev: not dirty");
12399 		/*
12400 		 * We are only interested in bitmaps with outstanding
12401 		 * dependencies.
12402 		 */
12403 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12404 		    wk->wk_type != D_BMSAFEMAP ||
12405 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12406 			BUF_UNLOCK(bp);
12407 			continue;
12408 		}
12409 		BO_UNLOCK(bo);
12410 		bremfree(bp);
12411 		(void) bawrite(bp);
12412 		goto restart;
12413 	}
12414 	drain_output(vp);
12415 	BO_UNLOCK(bo);
12416 }
12417 
12418 /*
12419  * Sync all cylinder groups that were dirty at the time this function is
12420  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12421  * is used to flush freedep activity that may be holding up writes to a
12422  * indirect block.
12423  */
12424 static int
12425 sync_cgs(mp, waitfor)
12426 	struct mount *mp;
12427 	int waitfor;
12428 {
12429 	struct bmsafemap *bmsafemap;
12430 	struct bmsafemap *sentinel;
12431 	struct ufsmount *ump;
12432 	struct buf *bp;
12433 	int error;
12434 
12435 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12436 	sentinel->sm_cg = -1;
12437 	ump = VFSTOUFS(mp);
12438 	error = 0;
12439 	ACQUIRE_LOCK(ump);
12440 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12441 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12442 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12443 		/* Skip sentinels and cgs with no work to release. */
12444 		if (bmsafemap->sm_cg == -1 ||
12445 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12446 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12447 			LIST_REMOVE(sentinel, sm_next);
12448 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12449 			continue;
12450 		}
12451 		/*
12452 		 * If we don't get the lock and we're waiting try again, if
12453 		 * not move on to the next buf and try to sync it.
12454 		 */
12455 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12456 		if (bp == NULL && waitfor == MNT_WAIT)
12457 			continue;
12458 		LIST_REMOVE(sentinel, sm_next);
12459 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12460 		if (bp == NULL)
12461 			continue;
12462 		FREE_LOCK(ump);
12463 		if (waitfor == MNT_NOWAIT)
12464 			bawrite(bp);
12465 		else
12466 			error = bwrite(bp);
12467 		ACQUIRE_LOCK(ump);
12468 		if (error)
12469 			break;
12470 	}
12471 	LIST_REMOVE(sentinel, sm_next);
12472 	FREE_LOCK(ump);
12473 	free(sentinel, M_BMSAFEMAP);
12474 	return (error);
12475 }
12476 
12477 /*
12478  * This routine is called when we are trying to synchronously flush a
12479  * file. This routine must eliminate any filesystem metadata dependencies
12480  * so that the syncing routine can succeed.
12481  */
12482 int
12483 softdep_sync_metadata(struct vnode *vp)
12484 {
12485 	struct inode *ip;
12486 	int error;
12487 
12488 	ip = VTOI(vp);
12489 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
12490 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12491 	/*
12492 	 * Ensure that any direct block dependencies have been cleared,
12493 	 * truncations are started, and inode references are journaled.
12494 	 */
12495 	ACQUIRE_LOCK(ip->i_ump);
12496 	/*
12497 	 * Write all journal records to prevent rollbacks on devvp.
12498 	 */
12499 	if (vp->v_type == VCHR)
12500 		softdep_flushjournal(vp->v_mount);
12501 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12502 	/*
12503 	 * Ensure that all truncates are written so we won't find deps on
12504 	 * indirect blocks.
12505 	 */
12506 	process_truncates(vp);
12507 	FREE_LOCK(ip->i_ump);
12508 
12509 	return (error);
12510 }
12511 
12512 /*
12513  * This routine is called when we are attempting to sync a buf with
12514  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12515  * other IO it can but returns EBUSY if the buffer is not yet able to
12516  * be written.  Dependencies which will not cause rollbacks will always
12517  * return 0.
12518  */
12519 int
12520 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12521 {
12522 	struct indirdep *indirdep;
12523 	struct pagedep *pagedep;
12524 	struct allocindir *aip;
12525 	struct newblk *newblk;
12526 	struct ufsmount *ump;
12527 	struct buf *nbp;
12528 	struct worklist *wk;
12529 	int i, error;
12530 
12531 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12532 	    ("softdep_sync_buf called on non-softdep filesystem"));
12533 	/*
12534 	 * For VCHR we just don't want to force flush any dependencies that
12535 	 * will cause rollbacks.
12536 	 */
12537 	if (vp->v_type == VCHR) {
12538 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12539 			return (EBUSY);
12540 		return (0);
12541 	}
12542 	ump = VTOI(vp)->i_ump;
12543 	ACQUIRE_LOCK(ump);
12544 	/*
12545 	 * As we hold the buffer locked, none of its dependencies
12546 	 * will disappear.
12547 	 */
12548 	error = 0;
12549 top:
12550 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12551 		switch (wk->wk_type) {
12552 
12553 		case D_ALLOCDIRECT:
12554 		case D_ALLOCINDIR:
12555 			newblk = WK_NEWBLK(wk);
12556 			if (newblk->nb_jnewblk != NULL) {
12557 				if (waitfor == MNT_NOWAIT) {
12558 					error = EBUSY;
12559 					goto out_unlock;
12560 				}
12561 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12562 				goto top;
12563 			}
12564 			if (newblk->nb_state & DEPCOMPLETE ||
12565 			    waitfor == MNT_NOWAIT)
12566 				continue;
12567 			nbp = newblk->nb_bmsafemap->sm_buf;
12568 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12569 			if (nbp == NULL)
12570 				goto top;
12571 			FREE_LOCK(ump);
12572 			if ((error = bwrite(nbp)) != 0)
12573 				goto out;
12574 			ACQUIRE_LOCK(ump);
12575 			continue;
12576 
12577 		case D_INDIRDEP:
12578 			indirdep = WK_INDIRDEP(wk);
12579 			if (waitfor == MNT_NOWAIT) {
12580 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12581 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12582 					error = EBUSY;
12583 					goto out_unlock;
12584 				}
12585 			}
12586 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12587 				panic("softdep_sync_buf: truncation pending.");
12588 		restart:
12589 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12590 				newblk = (struct newblk *)aip;
12591 				if (newblk->nb_jnewblk != NULL) {
12592 					jwait(&newblk->nb_jnewblk->jn_list,
12593 					    waitfor);
12594 					goto restart;
12595 				}
12596 				if (newblk->nb_state & DEPCOMPLETE)
12597 					continue;
12598 				nbp = newblk->nb_bmsafemap->sm_buf;
12599 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12600 				if (nbp == NULL)
12601 					goto restart;
12602 				FREE_LOCK(ump);
12603 				if ((error = bwrite(nbp)) != 0)
12604 					goto out;
12605 				ACQUIRE_LOCK(ump);
12606 				goto restart;
12607 			}
12608 			continue;
12609 
12610 		case D_PAGEDEP:
12611 			/*
12612 			 * Only flush directory entries in synchronous passes.
12613 			 */
12614 			if (waitfor != MNT_WAIT) {
12615 				error = EBUSY;
12616 				goto out_unlock;
12617 			}
12618 			/*
12619 			 * While syncing snapshots, we must allow recursive
12620 			 * lookups.
12621 			 */
12622 			BUF_AREC(bp);
12623 			/*
12624 			 * We are trying to sync a directory that may
12625 			 * have dependencies on both its own metadata
12626 			 * and/or dependencies on the inodes of any
12627 			 * recently allocated files. We walk its diradd
12628 			 * lists pushing out the associated inode.
12629 			 */
12630 			pagedep = WK_PAGEDEP(wk);
12631 			for (i = 0; i < DAHASHSZ; i++) {
12632 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12633 					continue;
12634 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12635 				    &pagedep->pd_diraddhd[i]))) {
12636 					BUF_NOREC(bp);
12637 					goto out_unlock;
12638 				}
12639 			}
12640 			BUF_NOREC(bp);
12641 			continue;
12642 
12643 		case D_FREEWORK:
12644 		case D_FREEDEP:
12645 		case D_JSEGDEP:
12646 		case D_JNEWBLK:
12647 			continue;
12648 
12649 		default:
12650 			panic("softdep_sync_buf: Unknown type %s",
12651 			    TYPENAME(wk->wk_type));
12652 			/* NOTREACHED */
12653 		}
12654 	}
12655 out_unlock:
12656 	FREE_LOCK(ump);
12657 out:
12658 	return (error);
12659 }
12660 
12661 /*
12662  * Flush the dependencies associated with an inodedep.
12663  * Called with splbio blocked.
12664  */
12665 static int
12666 flush_inodedep_deps(vp, mp, ino)
12667 	struct vnode *vp;
12668 	struct mount *mp;
12669 	ino_t ino;
12670 {
12671 	struct inodedep *inodedep;
12672 	struct inoref *inoref;
12673 	struct ufsmount *ump;
12674 	int error, waitfor;
12675 
12676 	/*
12677 	 * This work is done in two passes. The first pass grabs most
12678 	 * of the buffers and begins asynchronously writing them. The
12679 	 * only way to wait for these asynchronous writes is to sleep
12680 	 * on the filesystem vnode which may stay busy for a long time
12681 	 * if the filesystem is active. So, instead, we make a second
12682 	 * pass over the dependencies blocking on each write. In the
12683 	 * usual case we will be blocking against a write that we
12684 	 * initiated, so when it is done the dependency will have been
12685 	 * resolved. Thus the second pass is expected to end quickly.
12686 	 * We give a brief window at the top of the loop to allow
12687 	 * any pending I/O to complete.
12688 	 */
12689 	ump = VFSTOUFS(mp);
12690 	LOCK_OWNED(ump);
12691 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12692 		if (error)
12693 			return (error);
12694 		FREE_LOCK(ump);
12695 		ACQUIRE_LOCK(ump);
12696 restart:
12697 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12698 			return (0);
12699 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12700 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12701 			    == DEPCOMPLETE) {
12702 				jwait(&inoref->if_list, MNT_WAIT);
12703 				goto restart;
12704 			}
12705 		}
12706 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12707 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12708 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12709 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12710 			continue;
12711 		/*
12712 		 * If pass2, we are done, otherwise do pass 2.
12713 		 */
12714 		if (waitfor == MNT_WAIT)
12715 			break;
12716 		waitfor = MNT_WAIT;
12717 	}
12718 	/*
12719 	 * Try freeing inodedep in case all dependencies have been removed.
12720 	 */
12721 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12722 		(void) free_inodedep(inodedep);
12723 	return (0);
12724 }
12725 
12726 /*
12727  * Flush an inode dependency list.
12728  * Called with splbio blocked.
12729  */
12730 static int
12731 flush_deplist(listhead, waitfor, errorp)
12732 	struct allocdirectlst *listhead;
12733 	int waitfor;
12734 	int *errorp;
12735 {
12736 	struct allocdirect *adp;
12737 	struct newblk *newblk;
12738 	struct ufsmount *ump;
12739 	struct buf *bp;
12740 
12741 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
12742 		return (0);
12743 	ump = VFSTOUFS(adp->ad_list.wk_mp);
12744 	LOCK_OWNED(ump);
12745 	TAILQ_FOREACH(adp, listhead, ad_next) {
12746 		newblk = (struct newblk *)adp;
12747 		if (newblk->nb_jnewblk != NULL) {
12748 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12749 			return (1);
12750 		}
12751 		if (newblk->nb_state & DEPCOMPLETE)
12752 			continue;
12753 		bp = newblk->nb_bmsafemap->sm_buf;
12754 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12755 		if (bp == NULL) {
12756 			if (waitfor == MNT_NOWAIT)
12757 				continue;
12758 			return (1);
12759 		}
12760 		FREE_LOCK(ump);
12761 		if (waitfor == MNT_NOWAIT)
12762 			bawrite(bp);
12763 		else
12764 			*errorp = bwrite(bp);
12765 		ACQUIRE_LOCK(ump);
12766 		return (1);
12767 	}
12768 	return (0);
12769 }
12770 
12771 /*
12772  * Flush dependencies associated with an allocdirect block.
12773  */
12774 static int
12775 flush_newblk_dep(vp, mp, lbn)
12776 	struct vnode *vp;
12777 	struct mount *mp;
12778 	ufs_lbn_t lbn;
12779 {
12780 	struct newblk *newblk;
12781 	struct ufsmount *ump;
12782 	struct bufobj *bo;
12783 	struct inode *ip;
12784 	struct buf *bp;
12785 	ufs2_daddr_t blkno;
12786 	int error;
12787 
12788 	error = 0;
12789 	bo = &vp->v_bufobj;
12790 	ip = VTOI(vp);
12791 	blkno = DIP(ip, i_db[lbn]);
12792 	if (blkno == 0)
12793 		panic("flush_newblk_dep: Missing block");
12794 	ump = VFSTOUFS(mp);
12795 	ACQUIRE_LOCK(ump);
12796 	/*
12797 	 * Loop until all dependencies related to this block are satisfied.
12798 	 * We must be careful to restart after each sleep in case a write
12799 	 * completes some part of this process for us.
12800 	 */
12801 	for (;;) {
12802 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12803 			FREE_LOCK(ump);
12804 			break;
12805 		}
12806 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12807 			panic("flush_newblk_deps: Bad newblk %p", newblk);
12808 		/*
12809 		 * Flush the journal.
12810 		 */
12811 		if (newblk->nb_jnewblk != NULL) {
12812 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12813 			continue;
12814 		}
12815 		/*
12816 		 * Write the bitmap dependency.
12817 		 */
12818 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12819 			bp = newblk->nb_bmsafemap->sm_buf;
12820 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
12821 			if (bp == NULL)
12822 				continue;
12823 			FREE_LOCK(ump);
12824 			error = bwrite(bp);
12825 			if (error)
12826 				break;
12827 			ACQUIRE_LOCK(ump);
12828 			continue;
12829 		}
12830 		/*
12831 		 * Write the buffer.
12832 		 */
12833 		FREE_LOCK(ump);
12834 		BO_LOCK(bo);
12835 		bp = gbincore(bo, lbn);
12836 		if (bp != NULL) {
12837 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12838 			    LK_INTERLOCK, BO_LOCKPTR(bo));
12839 			if (error == ENOLCK) {
12840 				ACQUIRE_LOCK(ump);
12841 				continue; /* Slept, retry */
12842 			}
12843 			if (error != 0)
12844 				break;	/* Failed */
12845 			if (bp->b_flags & B_DELWRI) {
12846 				bremfree(bp);
12847 				error = bwrite(bp);
12848 				if (error)
12849 					break;
12850 			} else
12851 				BUF_UNLOCK(bp);
12852 		} else
12853 			BO_UNLOCK(bo);
12854 		/*
12855 		 * We have to wait for the direct pointers to
12856 		 * point at the newdirblk before the dependency
12857 		 * will go away.
12858 		 */
12859 		error = ffs_update(vp, 1);
12860 		if (error)
12861 			break;
12862 		ACQUIRE_LOCK(ump);
12863 	}
12864 	return (error);
12865 }
12866 
12867 /*
12868  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
12869  * Called with splbio blocked.
12870  */
12871 static int
12872 flush_pagedep_deps(pvp, mp, diraddhdp)
12873 	struct vnode *pvp;
12874 	struct mount *mp;
12875 	struct diraddhd *diraddhdp;
12876 {
12877 	struct inodedep *inodedep;
12878 	struct inoref *inoref;
12879 	struct ufsmount *ump;
12880 	struct diradd *dap;
12881 	struct vnode *vp;
12882 	int error = 0;
12883 	struct buf *bp;
12884 	ino_t inum;
12885 	struct diraddhd unfinished;
12886 
12887 	LIST_INIT(&unfinished);
12888 	ump = VFSTOUFS(mp);
12889 	LOCK_OWNED(ump);
12890 restart:
12891 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
12892 		/*
12893 		 * Flush ourselves if this directory entry
12894 		 * has a MKDIR_PARENT dependency.
12895 		 */
12896 		if (dap->da_state & MKDIR_PARENT) {
12897 			FREE_LOCK(ump);
12898 			if ((error = ffs_update(pvp, 1)) != 0)
12899 				break;
12900 			ACQUIRE_LOCK(ump);
12901 			/*
12902 			 * If that cleared dependencies, go on to next.
12903 			 */
12904 			if (dap != LIST_FIRST(diraddhdp))
12905 				continue;
12906 			/*
12907 			 * All MKDIR_PARENT dependencies and all the
12908 			 * NEWBLOCK pagedeps that are contained in direct
12909 			 * blocks were resolved by doing above ffs_update.
12910 			 * Pagedeps contained in indirect blocks may
12911 			 * require a complete sync'ing of the directory.
12912 			 * We are in the midst of doing a complete sync,
12913 			 * so if they are not resolved in this pass we
12914 			 * defer them for now as they will be sync'ed by
12915 			 * our caller shortly.
12916 			 */
12917 			LIST_REMOVE(dap, da_pdlist);
12918 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
12919 			continue;
12920 		}
12921 		/*
12922 		 * A newly allocated directory must have its "." and
12923 		 * ".." entries written out before its name can be
12924 		 * committed in its parent.
12925 		 */
12926 		inum = dap->da_newinum;
12927 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12928 			panic("flush_pagedep_deps: lost inode1");
12929 		/*
12930 		 * Wait for any pending journal adds to complete so we don't
12931 		 * cause rollbacks while syncing.
12932 		 */
12933 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12934 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12935 			    == DEPCOMPLETE) {
12936 				jwait(&inoref->if_list, MNT_WAIT);
12937 				goto restart;
12938 			}
12939 		}
12940 		if (dap->da_state & MKDIR_BODY) {
12941 			FREE_LOCK(ump);
12942 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12943 			    FFSV_FORCEINSMQ)))
12944 				break;
12945 			error = flush_newblk_dep(vp, mp, 0);
12946 			/*
12947 			 * If we still have the dependency we might need to
12948 			 * update the vnode to sync the new link count to
12949 			 * disk.
12950 			 */
12951 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
12952 				error = ffs_update(vp, 1);
12953 			vput(vp);
12954 			if (error != 0)
12955 				break;
12956 			ACQUIRE_LOCK(ump);
12957 			/*
12958 			 * If that cleared dependencies, go on to next.
12959 			 */
12960 			if (dap != LIST_FIRST(diraddhdp))
12961 				continue;
12962 			if (dap->da_state & MKDIR_BODY) {
12963 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
12964 				    &inodedep);
12965 				panic("flush_pagedep_deps: MKDIR_BODY "
12966 				    "inodedep %p dap %p vp %p",
12967 				    inodedep, dap, vp);
12968 			}
12969 		}
12970 		/*
12971 		 * Flush the inode on which the directory entry depends.
12972 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
12973 		 * the only remaining dependency is that the updated inode
12974 		 * count must get pushed to disk. The inode has already
12975 		 * been pushed into its inode buffer (via VOP_UPDATE) at
12976 		 * the time of the reference count change. So we need only
12977 		 * locate that buffer, ensure that there will be no rollback
12978 		 * caused by a bitmap dependency, then write the inode buffer.
12979 		 */
12980 retry:
12981 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12982 			panic("flush_pagedep_deps: lost inode");
12983 		/*
12984 		 * If the inode still has bitmap dependencies,
12985 		 * push them to disk.
12986 		 */
12987 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
12988 			bp = inodedep->id_bmsafemap->sm_buf;
12989 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
12990 			if (bp == NULL)
12991 				goto retry;
12992 			FREE_LOCK(ump);
12993 			if ((error = bwrite(bp)) != 0)
12994 				break;
12995 			ACQUIRE_LOCK(ump);
12996 			if (dap != LIST_FIRST(diraddhdp))
12997 				continue;
12998 		}
12999 		/*
13000 		 * If the inode is still sitting in a buffer waiting
13001 		 * to be written or waiting for the link count to be
13002 		 * adjusted update it here to flush it to disk.
13003 		 */
13004 		if (dap == LIST_FIRST(diraddhdp)) {
13005 			FREE_LOCK(ump);
13006 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13007 			    FFSV_FORCEINSMQ)))
13008 				break;
13009 			error = ffs_update(vp, 1);
13010 			vput(vp);
13011 			if (error)
13012 				break;
13013 			ACQUIRE_LOCK(ump);
13014 		}
13015 		/*
13016 		 * If we have failed to get rid of all the dependencies
13017 		 * then something is seriously wrong.
13018 		 */
13019 		if (dap == LIST_FIRST(diraddhdp)) {
13020 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13021 			panic("flush_pagedep_deps: failed to flush "
13022 			    "inodedep %p ino %ju dap %p",
13023 			    inodedep, (uintmax_t)inum, dap);
13024 		}
13025 	}
13026 	if (error)
13027 		ACQUIRE_LOCK(ump);
13028 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13029 		LIST_REMOVE(dap, da_pdlist);
13030 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13031 	}
13032 	return (error);
13033 }
13034 
13035 /*
13036  * A large burst of file addition or deletion activity can drive the
13037  * memory load excessively high. First attempt to slow things down
13038  * using the techniques below. If that fails, this routine requests
13039  * the offending operations to fall back to running synchronously
13040  * until the memory load returns to a reasonable level.
13041  */
13042 int
13043 softdep_slowdown(vp)
13044 	struct vnode *vp;
13045 {
13046 	struct ufsmount *ump;
13047 	int jlow;
13048 	int max_softdeps_hard;
13049 
13050 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13051 	    ("softdep_slowdown called on non-softdep filesystem"));
13052 	ump = VFSTOUFS(vp->v_mount);
13053 	ACQUIRE_LOCK(ump);
13054 	jlow = 0;
13055 	/*
13056 	 * Check for journal space if needed.
13057 	 */
13058 	if (DOINGSUJ(vp)) {
13059 		if (journal_space(ump, 0) == 0)
13060 			jlow = 1;
13061 	}
13062 	/*
13063 	 * If the system is under its limits and our filesystem is
13064 	 * not responsible for more than our share of the usage and
13065 	 * we are not low on journal space, then no need to slow down.
13066 	 */
13067 	max_softdeps_hard = max_softdeps * 11 / 10;
13068 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13069 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13070 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13071 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13072 	    ump->softdep_curdeps[D_DIRREM] <
13073 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13074 	    ump->softdep_curdeps[D_INODEDEP] <
13075 	    max_softdeps_hard / stat_flush_threads &&
13076 	    ump->softdep_curdeps[D_INDIRDEP] <
13077 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13078 	    ump->softdep_curdeps[D_FREEBLKS] <
13079 	    max_softdeps_hard / stat_flush_threads) {
13080 		FREE_LOCK(ump);
13081   		return (0);
13082 	}
13083 	/*
13084 	 * If the journal is low or our filesystem is over its limit
13085 	 * then speedup the cleanup.
13086 	 */
13087 	if (ump->softdep_curdeps[D_INDIRDEP] <
13088 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13089 		softdep_speedup(ump);
13090 	stat_sync_limit_hit += 1;
13091 	FREE_LOCK(ump);
13092 	/*
13093 	 * We only slow down the rate at which new dependencies are
13094 	 * generated if we are not using journaling. With journaling,
13095 	 * the cleanup should always be sufficient to keep things
13096 	 * under control.
13097 	 */
13098 	if (DOINGSUJ(vp))
13099 		return (0);
13100 	return (1);
13101 }
13102 
13103 /*
13104  * Called by the allocation routines when they are about to fail
13105  * in the hope that we can free up the requested resource (inodes
13106  * or disk space).
13107  *
13108  * First check to see if the work list has anything on it. If it has,
13109  * clean up entries until we successfully free the requested resource.
13110  * Because this process holds inodes locked, we cannot handle any remove
13111  * requests that might block on a locked inode as that could lead to
13112  * deadlock. If the worklist yields none of the requested resource,
13113  * start syncing out vnodes to free up the needed space.
13114  */
13115 int
13116 softdep_request_cleanup(fs, vp, cred, resource)
13117 	struct fs *fs;
13118 	struct vnode *vp;
13119 	struct ucred *cred;
13120 	int resource;
13121 {
13122 	struct ufsmount *ump;
13123 	struct mount *mp;
13124 	struct vnode *lvp, *mvp;
13125 	long starttime;
13126 	ufs2_daddr_t needed;
13127 	int error;
13128 
13129 	/*
13130 	 * If we are being called because of a process doing a
13131 	 * copy-on-write, then it is not safe to process any
13132 	 * worklist items as we will recurse into the copyonwrite
13133 	 * routine.  This will result in an incoherent snapshot.
13134 	 * If the vnode that we hold is a snapshot, we must avoid
13135 	 * handling other resources that could cause deadlock.
13136 	 */
13137 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13138 		return (0);
13139 
13140 	if (resource == FLUSH_BLOCKS_WAIT)
13141 		stat_cleanup_blkrequests += 1;
13142 	else
13143 		stat_cleanup_inorequests += 1;
13144 
13145 	mp = vp->v_mount;
13146 	ump = VFSTOUFS(mp);
13147 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13148 	UFS_UNLOCK(ump);
13149 	error = ffs_update(vp, 1);
13150 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13151 		UFS_LOCK(ump);
13152 		return (0);
13153 	}
13154 	/*
13155 	 * If we are in need of resources, start by cleaning up
13156 	 * any block removals associated with our inode.
13157 	 */
13158 	ACQUIRE_LOCK(ump);
13159 	process_removes(vp);
13160 	process_truncates(vp);
13161 	FREE_LOCK(ump);
13162 	/*
13163 	 * Now clean up at least as many resources as we will need.
13164 	 *
13165 	 * When requested to clean up inodes, the number that are needed
13166 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13167 	 * plus a bit of slop (2) in case some more writers show up while
13168 	 * we are cleaning.
13169 	 *
13170 	 * When requested to free up space, the amount of space that
13171 	 * we need is enough blocks to allocate a full-sized segment
13172 	 * (fs_contigsumsize). The number of such segments that will
13173 	 * be needed is set by the number of simultaneous writers
13174 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13175 	 * writers show up while we are cleaning.
13176 	 *
13177 	 * Additionally, if we are unpriviledged and allocating space,
13178 	 * we need to ensure that we clean up enough blocks to get the
13179 	 * needed number of blocks over the threshhold of the minimum
13180 	 * number of blocks required to be kept free by the filesystem
13181 	 * (fs_minfree).
13182 	 */
13183 	if (resource == FLUSH_INODES_WAIT) {
13184 		needed = vp->v_mount->mnt_writeopcount + 2;
13185 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13186 		needed = (vp->v_mount->mnt_writeopcount + 2) *
13187 		    fs->fs_contigsumsize;
13188 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
13189 			needed += fragstoblks(fs,
13190 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13191 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13192 	} else {
13193 		UFS_LOCK(ump);
13194 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13195 		    resource);
13196 		return (0);
13197 	}
13198 	starttime = time_second;
13199 retry:
13200 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13201 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13202 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13203 	    fs->fs_cstotal.cs_nifree <= needed)) {
13204 		ACQUIRE_LOCK(ump);
13205 		if (ump->softdep_on_worklist > 0 &&
13206 		    process_worklist_item(UFSTOVFS(ump),
13207 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13208 			stat_worklist_push += 1;
13209 		FREE_LOCK(ump);
13210 	}
13211 	/*
13212 	 * If we still need resources and there are no more worklist
13213 	 * entries to process to obtain them, we have to start flushing
13214 	 * the dirty vnodes to force the release of additional requests
13215 	 * to the worklist that we can then process to reap addition
13216 	 * resources. We walk the vnodes associated with the mount point
13217 	 * until we get the needed worklist requests that we can reap.
13218 	 */
13219 	if ((resource == FLUSH_BLOCKS_WAIT &&
13220 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13221 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13222 	     fs->fs_cstotal.cs_nifree <= needed)) {
13223 		MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13224 			if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13225 				VI_UNLOCK(lvp);
13226 				continue;
13227 			}
13228 			if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13229 			    curthread))
13230 				continue;
13231 			if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13232 				vput(lvp);
13233 				continue;
13234 			}
13235 			(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13236 			vput(lvp);
13237 		}
13238 		lvp = ump->um_devvp;
13239 		if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13240 			VOP_FSYNC(lvp, MNT_NOWAIT, curthread);
13241 			VOP_UNLOCK(lvp, 0);
13242 		}
13243 		if (ump->softdep_on_worklist > 0) {
13244 			stat_cleanup_retries += 1;
13245 			goto retry;
13246 		}
13247 		stat_cleanup_failures += 1;
13248 	}
13249 	if (time_second - starttime > stat_cleanup_high_delay)
13250 		stat_cleanup_high_delay = time_second - starttime;
13251 	UFS_LOCK(ump);
13252 	return (1);
13253 }
13254 
13255 static bool
13256 softdep_excess_items(struct ufsmount *ump, int item)
13257 {
13258 
13259 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13260 	return (dep_current[item] > max_softdeps &&
13261 	    ump->softdep_curdeps[item] > max_softdeps /
13262 	    stat_flush_threads);
13263 }
13264 
13265 static void
13266 schedule_cleanup(struct mount *mp)
13267 {
13268 	struct ufsmount *ump;
13269 	struct thread *td;
13270 
13271 	ump = VFSTOUFS(mp);
13272 	LOCK_OWNED(ump);
13273 	FREE_LOCK(ump);
13274 	td = curthread;
13275 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13276 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13277 		/*
13278 		 * No ast is delivered to kernel threads, so nobody
13279 		 * would deref the mp.  Some kernel threads
13280 		 * explicitely check for AST, e.g. NFS daemon does
13281 		 * this in the serving loop.
13282 		 */
13283 		return;
13284 	}
13285 	if (td->td_su != NULL)
13286 		vfs_rel(td->td_su);
13287 	vfs_ref(mp);
13288 	td->td_su = mp;
13289 	thread_lock(td);
13290 	td->td_flags |= TDF_ASTPENDING;
13291 	thread_unlock(td);
13292 }
13293 
13294 static void
13295 softdep_ast_cleanup_proc(void)
13296 {
13297 	struct thread *td;
13298 	struct mount *mp;
13299 	struct ufsmount *ump;
13300 	int error;
13301 	bool req;
13302 
13303 	td = curthread;
13304 	while ((mp = td->td_su) != NULL) {
13305 		td->td_su = NULL;
13306 		error = vfs_busy(mp, MBF_NOWAIT);
13307 		vfs_rel(mp);
13308 		if (error != 0)
13309 			return;
13310 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13311 			ump = VFSTOUFS(mp);
13312 			for (;;) {
13313 				req = false;
13314 				ACQUIRE_LOCK(ump);
13315 				if (softdep_excess_items(ump, D_INODEDEP)) {
13316 					req = true;
13317 					request_cleanup(mp, FLUSH_INODES);
13318 				}
13319 				if (softdep_excess_items(ump, D_DIRREM)) {
13320 					req = true;
13321 					request_cleanup(mp, FLUSH_BLOCKS);
13322 				}
13323 				FREE_LOCK(ump);
13324 				if (softdep_excess_items(ump, D_NEWBLK) ||
13325 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13326 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13327 					error = vn_start_write(NULL, &mp,
13328 					    V_WAIT);
13329 					if (error == 0) {
13330 						req = true;
13331 						VFS_SYNC(mp, MNT_WAIT);
13332 						vn_finished_write(mp);
13333 					}
13334 				}
13335 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13336 					break;
13337 			}
13338 		}
13339 		vfs_unbusy(mp);
13340 	}
13341 }
13342 
13343 /*
13344  * If memory utilization has gotten too high, deliberately slow things
13345  * down and speed up the I/O processing.
13346  */
13347 static int
13348 request_cleanup(mp, resource)
13349 	struct mount *mp;
13350 	int resource;
13351 {
13352 	struct thread *td = curthread;
13353 	struct ufsmount *ump;
13354 
13355 	ump = VFSTOUFS(mp);
13356 	LOCK_OWNED(ump);
13357 	/*
13358 	 * We never hold up the filesystem syncer or buf daemon.
13359 	 */
13360 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13361 		return (0);
13362 	/*
13363 	 * First check to see if the work list has gotten backlogged.
13364 	 * If it has, co-opt this process to help clean up two entries.
13365 	 * Because this process may hold inodes locked, we cannot
13366 	 * handle any remove requests that might block on a locked
13367 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13368 	 * to avoid recursively processing the worklist.
13369 	 */
13370 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13371 		td->td_pflags |= TDP_SOFTDEP;
13372 		process_worklist_item(mp, 2, LK_NOWAIT);
13373 		td->td_pflags &= ~TDP_SOFTDEP;
13374 		stat_worklist_push += 2;
13375 		return(1);
13376 	}
13377 	/*
13378 	 * Next, we attempt to speed up the syncer process. If that
13379 	 * is successful, then we allow the process to continue.
13380 	 */
13381 	if (softdep_speedup(ump) &&
13382 	    resource != FLUSH_BLOCKS_WAIT &&
13383 	    resource != FLUSH_INODES_WAIT)
13384 		return(0);
13385 	/*
13386 	 * If we are resource constrained on inode dependencies, try
13387 	 * flushing some dirty inodes. Otherwise, we are constrained
13388 	 * by file deletions, so try accelerating flushes of directories
13389 	 * with removal dependencies. We would like to do the cleanup
13390 	 * here, but we probably hold an inode locked at this point and
13391 	 * that might deadlock against one that we try to clean. So,
13392 	 * the best that we can do is request the syncer daemon to do
13393 	 * the cleanup for us.
13394 	 */
13395 	switch (resource) {
13396 
13397 	case FLUSH_INODES:
13398 	case FLUSH_INODES_WAIT:
13399 		ACQUIRE_GBLLOCK(&lk);
13400 		stat_ino_limit_push += 1;
13401 		req_clear_inodedeps += 1;
13402 		FREE_GBLLOCK(&lk);
13403 		stat_countp = &stat_ino_limit_hit;
13404 		break;
13405 
13406 	case FLUSH_BLOCKS:
13407 	case FLUSH_BLOCKS_WAIT:
13408 		ACQUIRE_GBLLOCK(&lk);
13409 		stat_blk_limit_push += 1;
13410 		req_clear_remove += 1;
13411 		FREE_GBLLOCK(&lk);
13412 		stat_countp = &stat_blk_limit_hit;
13413 		break;
13414 
13415 	default:
13416 		panic("request_cleanup: unknown type");
13417 	}
13418 	/*
13419 	 * Hopefully the syncer daemon will catch up and awaken us.
13420 	 * We wait at most tickdelay before proceeding in any case.
13421 	 */
13422 	ACQUIRE_GBLLOCK(&lk);
13423 	FREE_LOCK(ump);
13424 	proc_waiting += 1;
13425 	if (callout_pending(&softdep_callout) == FALSE)
13426 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13427 		    pause_timer, 0);
13428 
13429 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13430 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13431 	proc_waiting -= 1;
13432 	FREE_GBLLOCK(&lk);
13433 	ACQUIRE_LOCK(ump);
13434 	return (1);
13435 }
13436 
13437 /*
13438  * Awaken processes pausing in request_cleanup and clear proc_waiting
13439  * to indicate that there is no longer a timer running. Pause_timer
13440  * will be called with the global softdep mutex (&lk) locked.
13441  */
13442 static void
13443 pause_timer(arg)
13444 	void *arg;
13445 {
13446 
13447 	GBLLOCK_OWNED(&lk);
13448 	/*
13449 	 * The callout_ API has acquired mtx and will hold it around this
13450 	 * function call.
13451 	 */
13452 	*stat_countp += proc_waiting;
13453 	wakeup(&proc_waiting);
13454 }
13455 
13456 /*
13457  * If requested, try removing inode or removal dependencies.
13458  */
13459 static void
13460 check_clear_deps(mp)
13461 	struct mount *mp;
13462 {
13463 
13464 	/*
13465 	 * If we are suspended, it may be because of our using
13466 	 * too many inodedeps, so help clear them out.
13467 	 */
13468 	if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13469 		clear_inodedeps(mp);
13470 	/*
13471 	 * General requests for cleanup of backed up dependencies
13472 	 */
13473 	ACQUIRE_GBLLOCK(&lk);
13474 	if (req_clear_inodedeps) {
13475 		req_clear_inodedeps -= 1;
13476 		FREE_GBLLOCK(&lk);
13477 		clear_inodedeps(mp);
13478 		ACQUIRE_GBLLOCK(&lk);
13479 		wakeup(&proc_waiting);
13480 	}
13481 	if (req_clear_remove) {
13482 		req_clear_remove -= 1;
13483 		FREE_GBLLOCK(&lk);
13484 		clear_remove(mp);
13485 		ACQUIRE_GBLLOCK(&lk);
13486 		wakeup(&proc_waiting);
13487 	}
13488 	FREE_GBLLOCK(&lk);
13489 }
13490 
13491 /*
13492  * Flush out a directory with at least one removal dependency in an effort to
13493  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13494  */
13495 static void
13496 clear_remove(mp)
13497 	struct mount *mp;
13498 {
13499 	struct pagedep_hashhead *pagedephd;
13500 	struct pagedep *pagedep;
13501 	struct ufsmount *ump;
13502 	struct vnode *vp;
13503 	struct bufobj *bo;
13504 	int error, cnt;
13505 	ino_t ino;
13506 
13507 	ump = VFSTOUFS(mp);
13508 	LOCK_OWNED(ump);
13509 
13510 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13511 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13512 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13513 			ump->pagedep_nextclean = 0;
13514 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13515 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13516 				continue;
13517 			ino = pagedep->pd_ino;
13518 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13519 				continue;
13520 			FREE_LOCK(ump);
13521 
13522 			/*
13523 			 * Let unmount clear deps
13524 			 */
13525 			error = vfs_busy(mp, MBF_NOWAIT);
13526 			if (error != 0)
13527 				goto finish_write;
13528 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13529 			     FFSV_FORCEINSMQ);
13530 			vfs_unbusy(mp);
13531 			if (error != 0) {
13532 				softdep_error("clear_remove: vget", error);
13533 				goto finish_write;
13534 			}
13535 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13536 				softdep_error("clear_remove: fsync", error);
13537 			bo = &vp->v_bufobj;
13538 			BO_LOCK(bo);
13539 			drain_output(vp);
13540 			BO_UNLOCK(bo);
13541 			vput(vp);
13542 		finish_write:
13543 			vn_finished_write(mp);
13544 			ACQUIRE_LOCK(ump);
13545 			return;
13546 		}
13547 	}
13548 }
13549 
13550 /*
13551  * Clear out a block of dirty inodes in an effort to reduce
13552  * the number of inodedep dependency structures.
13553  */
13554 static void
13555 clear_inodedeps(mp)
13556 	struct mount *mp;
13557 {
13558 	struct inodedep_hashhead *inodedephd;
13559 	struct inodedep *inodedep;
13560 	struct ufsmount *ump;
13561 	struct vnode *vp;
13562 	struct fs *fs;
13563 	int error, cnt;
13564 	ino_t firstino, lastino, ino;
13565 
13566 	ump = VFSTOUFS(mp);
13567 	fs = ump->um_fs;
13568 	LOCK_OWNED(ump);
13569 	/*
13570 	 * Pick a random inode dependency to be cleared.
13571 	 * We will then gather up all the inodes in its block
13572 	 * that have dependencies and flush them out.
13573 	 */
13574 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13575 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13576 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13577 			ump->inodedep_nextclean = 0;
13578 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13579 			break;
13580 	}
13581 	if (inodedep == NULL)
13582 		return;
13583 	/*
13584 	 * Find the last inode in the block with dependencies.
13585 	 */
13586 	firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
13587 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13588 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13589 			break;
13590 	/*
13591 	 * Asynchronously push all but the last inode with dependencies.
13592 	 * Synchronously push the last inode with dependencies to ensure
13593 	 * that the inode block gets written to free up the inodedeps.
13594 	 */
13595 	for (ino = firstino; ino <= lastino; ino++) {
13596 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13597 			continue;
13598 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13599 			continue;
13600 		FREE_LOCK(ump);
13601 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13602 		if (error != 0) {
13603 			vn_finished_write(mp);
13604 			ACQUIRE_LOCK(ump);
13605 			return;
13606 		}
13607 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13608 		    FFSV_FORCEINSMQ)) != 0) {
13609 			softdep_error("clear_inodedeps: vget", error);
13610 			vfs_unbusy(mp);
13611 			vn_finished_write(mp);
13612 			ACQUIRE_LOCK(ump);
13613 			return;
13614 		}
13615 		vfs_unbusy(mp);
13616 		if (ino == lastino) {
13617 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13618 				softdep_error("clear_inodedeps: fsync1", error);
13619 		} else {
13620 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13621 				softdep_error("clear_inodedeps: fsync2", error);
13622 			BO_LOCK(&vp->v_bufobj);
13623 			drain_output(vp);
13624 			BO_UNLOCK(&vp->v_bufobj);
13625 		}
13626 		vput(vp);
13627 		vn_finished_write(mp);
13628 		ACQUIRE_LOCK(ump);
13629 	}
13630 }
13631 
13632 void
13633 softdep_buf_append(bp, wkhd)
13634 	struct buf *bp;
13635 	struct workhead *wkhd;
13636 {
13637 	struct worklist *wk;
13638 	struct ufsmount *ump;
13639 
13640 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13641 		return;
13642 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13643 	    ("softdep_buf_append called on non-softdep filesystem"));
13644 	ump = VFSTOUFS(wk->wk_mp);
13645 	ACQUIRE_LOCK(ump);
13646 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13647 		WORKLIST_REMOVE(wk);
13648 		WORKLIST_INSERT(&bp->b_dep, wk);
13649 	}
13650 	FREE_LOCK(ump);
13651 
13652 }
13653 
13654 void
13655 softdep_inode_append(ip, cred, wkhd)
13656 	struct inode *ip;
13657 	struct ucred *cred;
13658 	struct workhead *wkhd;
13659 {
13660 	struct buf *bp;
13661 	struct fs *fs;
13662 	int error;
13663 
13664 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
13665 	    ("softdep_inode_append called on non-softdep filesystem"));
13666 	fs = ip->i_fs;
13667 	error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13668 	    (int)fs->fs_bsize, cred, &bp);
13669 	if (error) {
13670 		bqrelse(bp);
13671 		softdep_freework(wkhd);
13672 		return;
13673 	}
13674 	softdep_buf_append(bp, wkhd);
13675 	bqrelse(bp);
13676 }
13677 
13678 void
13679 softdep_freework(wkhd)
13680 	struct workhead *wkhd;
13681 {
13682 	struct worklist *wk;
13683 	struct ufsmount *ump;
13684 
13685 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13686 		return;
13687 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13688 	    ("softdep_freework called on non-softdep filesystem"));
13689 	ump = VFSTOUFS(wk->wk_mp);
13690 	ACQUIRE_LOCK(ump);
13691 	handle_jwork(wkhd);
13692 	FREE_LOCK(ump);
13693 }
13694 
13695 /*
13696  * Function to determine if the buffer has outstanding dependencies
13697  * that will cause a roll-back if the buffer is written. If wantcount
13698  * is set, return number of dependencies, otherwise just yes or no.
13699  */
13700 static int
13701 softdep_count_dependencies(bp, wantcount)
13702 	struct buf *bp;
13703 	int wantcount;
13704 {
13705 	struct worklist *wk;
13706 	struct ufsmount *ump;
13707 	struct bmsafemap *bmsafemap;
13708 	struct freework *freework;
13709 	struct inodedep *inodedep;
13710 	struct indirdep *indirdep;
13711 	struct freeblks *freeblks;
13712 	struct allocindir *aip;
13713 	struct pagedep *pagedep;
13714 	struct dirrem *dirrem;
13715 	struct newblk *newblk;
13716 	struct mkdir *mkdir;
13717 	struct diradd *dap;
13718 	int i, retval;
13719 
13720 	retval = 0;
13721 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
13722 		return (0);
13723 	ump = VFSTOUFS(wk->wk_mp);
13724 	ACQUIRE_LOCK(ump);
13725 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13726 		switch (wk->wk_type) {
13727 
13728 		case D_INODEDEP:
13729 			inodedep = WK_INODEDEP(wk);
13730 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13731 				/* bitmap allocation dependency */
13732 				retval += 1;
13733 				if (!wantcount)
13734 					goto out;
13735 			}
13736 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13737 				/* direct block pointer dependency */
13738 				retval += 1;
13739 				if (!wantcount)
13740 					goto out;
13741 			}
13742 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13743 				/* direct block pointer dependency */
13744 				retval += 1;
13745 				if (!wantcount)
13746 					goto out;
13747 			}
13748 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13749 				/* Add reference dependency. */
13750 				retval += 1;
13751 				if (!wantcount)
13752 					goto out;
13753 			}
13754 			continue;
13755 
13756 		case D_INDIRDEP:
13757 			indirdep = WK_INDIRDEP(wk);
13758 
13759 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
13760 				/* indirect truncation dependency */
13761 				retval += 1;
13762 				if (!wantcount)
13763 					goto out;
13764 			}
13765 
13766 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13767 				/* indirect block pointer dependency */
13768 				retval += 1;
13769 				if (!wantcount)
13770 					goto out;
13771 			}
13772 			continue;
13773 
13774 		case D_PAGEDEP:
13775 			pagedep = WK_PAGEDEP(wk);
13776 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
13777 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
13778 					/* Journal remove ref dependency. */
13779 					retval += 1;
13780 					if (!wantcount)
13781 						goto out;
13782 				}
13783 			}
13784 			for (i = 0; i < DAHASHSZ; i++) {
13785 
13786 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
13787 					/* directory entry dependency */
13788 					retval += 1;
13789 					if (!wantcount)
13790 						goto out;
13791 				}
13792 			}
13793 			continue;
13794 
13795 		case D_BMSAFEMAP:
13796 			bmsafemap = WK_BMSAFEMAP(wk);
13797 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
13798 				/* Add reference dependency. */
13799 				retval += 1;
13800 				if (!wantcount)
13801 					goto out;
13802 			}
13803 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
13804 				/* Allocate block dependency. */
13805 				retval += 1;
13806 				if (!wantcount)
13807 					goto out;
13808 			}
13809 			continue;
13810 
13811 		case D_FREEBLKS:
13812 			freeblks = WK_FREEBLKS(wk);
13813 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
13814 				/* Freeblk journal dependency. */
13815 				retval += 1;
13816 				if (!wantcount)
13817 					goto out;
13818 			}
13819 			continue;
13820 
13821 		case D_ALLOCDIRECT:
13822 		case D_ALLOCINDIR:
13823 			newblk = WK_NEWBLK(wk);
13824 			if (newblk->nb_jnewblk) {
13825 				/* Journal allocate dependency. */
13826 				retval += 1;
13827 				if (!wantcount)
13828 					goto out;
13829 			}
13830 			continue;
13831 
13832 		case D_MKDIR:
13833 			mkdir = WK_MKDIR(wk);
13834 			if (mkdir->md_jaddref) {
13835 				/* Journal reference dependency. */
13836 				retval += 1;
13837 				if (!wantcount)
13838 					goto out;
13839 			}
13840 			continue;
13841 
13842 		case D_FREEWORK:
13843 		case D_FREEDEP:
13844 		case D_JSEGDEP:
13845 		case D_JSEG:
13846 		case D_SBDEP:
13847 			/* never a dependency on these blocks */
13848 			continue;
13849 
13850 		default:
13851 			panic("softdep_count_dependencies: Unexpected type %s",
13852 			    TYPENAME(wk->wk_type));
13853 			/* NOTREACHED */
13854 		}
13855 	}
13856 out:
13857 	FREE_LOCK(ump);
13858 	return retval;
13859 }
13860 
13861 /*
13862  * Acquire exclusive access to a buffer.
13863  * Must be called with a locked mtx parameter.
13864  * Return acquired buffer or NULL on failure.
13865  */
13866 static struct buf *
13867 getdirtybuf(bp, lock, waitfor)
13868 	struct buf *bp;
13869 	struct rwlock *lock;
13870 	int waitfor;
13871 {
13872 	int error;
13873 
13874 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
13875 		if (waitfor != MNT_WAIT)
13876 			return (NULL);
13877 		error = BUF_LOCK(bp,
13878 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
13879 		/*
13880 		 * Even if we sucessfully acquire bp here, we have dropped
13881 		 * lock, which may violates our guarantee.
13882 		 */
13883 		if (error == 0)
13884 			BUF_UNLOCK(bp);
13885 		else if (error != ENOLCK)
13886 			panic("getdirtybuf: inconsistent lock: %d", error);
13887 		rw_wlock(lock);
13888 		return (NULL);
13889 	}
13890 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13891 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
13892 			rw_wunlock(lock);
13893 			BO_LOCK(bp->b_bufobj);
13894 			BUF_UNLOCK(bp);
13895 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13896 				bp->b_vflags |= BV_BKGRDWAIT;
13897 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
13898 				       PRIBIO | PDROP, "getbuf", 0);
13899 			} else
13900 				BO_UNLOCK(bp->b_bufobj);
13901 			rw_wlock(lock);
13902 			return (NULL);
13903 		}
13904 		BUF_UNLOCK(bp);
13905 		if (waitfor != MNT_WAIT)
13906 			return (NULL);
13907 		/*
13908 		 * The lock argument must be bp->b_vp's mutex in
13909 		 * this case.
13910 		 */
13911 #ifdef	DEBUG_VFS_LOCKS
13912 		if (bp->b_vp->v_type != VCHR)
13913 			ASSERT_BO_WLOCKED(bp->b_bufobj);
13914 #endif
13915 		bp->b_vflags |= BV_BKGRDWAIT;
13916 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
13917 		return (NULL);
13918 	}
13919 	if ((bp->b_flags & B_DELWRI) == 0) {
13920 		BUF_UNLOCK(bp);
13921 		return (NULL);
13922 	}
13923 	bremfree(bp);
13924 	return (bp);
13925 }
13926 
13927 
13928 /*
13929  * Check if it is safe to suspend the file system now.  On entry,
13930  * the vnode interlock for devvp should be held.  Return 0 with
13931  * the mount interlock held if the file system can be suspended now,
13932  * otherwise return EAGAIN with the mount interlock held.
13933  */
13934 int
13935 softdep_check_suspend(struct mount *mp,
13936 		      struct vnode *devvp,
13937 		      int softdep_depcnt,
13938 		      int softdep_accdepcnt,
13939 		      int secondary_writes,
13940 		      int secondary_accwrites)
13941 {
13942 	struct bufobj *bo;
13943 	struct ufsmount *ump;
13944 	struct inodedep *inodedep;
13945 	int error, unlinked;
13946 
13947 	bo = &devvp->v_bufobj;
13948 	ASSERT_BO_WLOCKED(bo);
13949 
13950 	/*
13951 	 * If we are not running with soft updates, then we need only
13952 	 * deal with secondary writes as we try to suspend.
13953 	 */
13954 	if (MOUNTEDSOFTDEP(mp) == 0) {
13955 		MNT_ILOCK(mp);
13956 		while (mp->mnt_secondary_writes != 0) {
13957 			BO_UNLOCK(bo);
13958 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
13959 			    (PUSER - 1) | PDROP, "secwr", 0);
13960 			BO_LOCK(bo);
13961 			MNT_ILOCK(mp);
13962 		}
13963 
13964 		/*
13965 		 * Reasons for needing more work before suspend:
13966 		 * - Dirty buffers on devvp.
13967 		 * - Secondary writes occurred after start of vnode sync loop
13968 		 */
13969 		error = 0;
13970 		if (bo->bo_numoutput > 0 ||
13971 		    bo->bo_dirty.bv_cnt > 0 ||
13972 		    secondary_writes != 0 ||
13973 		    mp->mnt_secondary_writes != 0 ||
13974 		    secondary_accwrites != mp->mnt_secondary_accwrites)
13975 			error = EAGAIN;
13976 		BO_UNLOCK(bo);
13977 		return (error);
13978 	}
13979 
13980 	/*
13981 	 * If we are running with soft updates, then we need to coordinate
13982 	 * with them as we try to suspend.
13983 	 */
13984 	ump = VFSTOUFS(mp);
13985 	for (;;) {
13986 		if (!TRY_ACQUIRE_LOCK(ump)) {
13987 			BO_UNLOCK(bo);
13988 			ACQUIRE_LOCK(ump);
13989 			FREE_LOCK(ump);
13990 			BO_LOCK(bo);
13991 			continue;
13992 		}
13993 		MNT_ILOCK(mp);
13994 		if (mp->mnt_secondary_writes != 0) {
13995 			FREE_LOCK(ump);
13996 			BO_UNLOCK(bo);
13997 			msleep(&mp->mnt_secondary_writes,
13998 			       MNT_MTX(mp),
13999 			       (PUSER - 1) | PDROP, "secwr", 0);
14000 			BO_LOCK(bo);
14001 			continue;
14002 		}
14003 		break;
14004 	}
14005 
14006 	unlinked = 0;
14007 	if (MOUNTEDSUJ(mp)) {
14008 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14009 		    inodedep != NULL;
14010 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14011 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14012 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14013 			    UNLINKONLIST) ||
14014 			    !check_inodedep_free(inodedep))
14015 				continue;
14016 			unlinked++;
14017 		}
14018 	}
14019 
14020 	/*
14021 	 * Reasons for needing more work before suspend:
14022 	 * - Dirty buffers on devvp.
14023 	 * - Softdep activity occurred after start of vnode sync loop
14024 	 * - Secondary writes occurred after start of vnode sync loop
14025 	 */
14026 	error = 0;
14027 	if (bo->bo_numoutput > 0 ||
14028 	    bo->bo_dirty.bv_cnt > 0 ||
14029 	    softdep_depcnt != unlinked ||
14030 	    ump->softdep_deps != unlinked ||
14031 	    softdep_accdepcnt != ump->softdep_accdeps ||
14032 	    secondary_writes != 0 ||
14033 	    mp->mnt_secondary_writes != 0 ||
14034 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14035 		error = EAGAIN;
14036 	FREE_LOCK(ump);
14037 	BO_UNLOCK(bo);
14038 	return (error);
14039 }
14040 
14041 
14042 /*
14043  * Get the number of dependency structures for the file system, both
14044  * the current number and the total number allocated.  These will
14045  * later be used to detect that softdep processing has occurred.
14046  */
14047 void
14048 softdep_get_depcounts(struct mount *mp,
14049 		      int *softdep_depsp,
14050 		      int *softdep_accdepsp)
14051 {
14052 	struct ufsmount *ump;
14053 
14054 	if (MOUNTEDSOFTDEP(mp) == 0) {
14055 		*softdep_depsp = 0;
14056 		*softdep_accdepsp = 0;
14057 		return;
14058 	}
14059 	ump = VFSTOUFS(mp);
14060 	ACQUIRE_LOCK(ump);
14061 	*softdep_depsp = ump->softdep_deps;
14062 	*softdep_accdepsp = ump->softdep_accdeps;
14063 	FREE_LOCK(ump);
14064 }
14065 
14066 /*
14067  * Wait for pending output on a vnode to complete.
14068  * Must be called with vnode lock and interlock locked.
14069  *
14070  * XXX: Should just be a call to bufobj_wwait().
14071  */
14072 static void
14073 drain_output(vp)
14074 	struct vnode *vp;
14075 {
14076 	struct bufobj *bo;
14077 
14078 	bo = &vp->v_bufobj;
14079 	ASSERT_VOP_LOCKED(vp, "drain_output");
14080 	ASSERT_BO_WLOCKED(bo);
14081 
14082 	while (bo->bo_numoutput) {
14083 		bo->bo_flag |= BO_WWAIT;
14084 		msleep((caddr_t)&bo->bo_numoutput,
14085 		    BO_LOCKPTR(bo), PRIBIO + 1, "drainvp", 0);
14086 	}
14087 }
14088 
14089 /*
14090  * Called whenever a buffer that is being invalidated or reallocated
14091  * contains dependencies. This should only happen if an I/O error has
14092  * occurred. The routine is called with the buffer locked.
14093  */
14094 static void
14095 softdep_deallocate_dependencies(bp)
14096 	struct buf *bp;
14097 {
14098 
14099 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14100 		panic("softdep_deallocate_dependencies: dangling deps");
14101 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14102 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14103 	else
14104 		printf("softdep_deallocate_dependencies: "
14105 		    "got error %d while accessing filesystem\n", bp->b_error);
14106 	if (bp->b_error != ENXIO)
14107 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14108 }
14109 
14110 /*
14111  * Function to handle asynchronous write errors in the filesystem.
14112  */
14113 static void
14114 softdep_error(func, error)
14115 	char *func;
14116 	int error;
14117 {
14118 
14119 	/* XXX should do something better! */
14120 	printf("%s: got error %d while accessing filesystem\n", func, error);
14121 }
14122 
14123 #ifdef DDB
14124 
14125 static void
14126 inodedep_print(struct inodedep *inodedep, int verbose)
14127 {
14128 	db_printf("%p fs %p st %x ino %jd inoblk %jd delta %d nlink %d"
14129 	    " saveino %p\n",
14130 	    inodedep, inodedep->id_fs, inodedep->id_state,
14131 	    (intmax_t)inodedep->id_ino,
14132 	    (intmax_t)fsbtodb(inodedep->id_fs,
14133 	    ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14134 	    inodedep->id_nlinkdelta, inodedep->id_savednlink,
14135 	    inodedep->id_savedino1);
14136 
14137 	if (verbose == 0)
14138 		return;
14139 
14140 	db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
14141 	    "mkdiradd %p\n",
14142 	    LIST_FIRST(&inodedep->id_pendinghd),
14143 	    LIST_FIRST(&inodedep->id_bufwait),
14144 	    LIST_FIRST(&inodedep->id_inowait),
14145 	    TAILQ_FIRST(&inodedep->id_inoreflst),
14146 	    inodedep->id_mkdiradd);
14147 	db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
14148 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14149 	    TAILQ_FIRST(&inodedep->id_newinoupdt),
14150 	    TAILQ_FIRST(&inodedep->id_extupdt),
14151 	    TAILQ_FIRST(&inodedep->id_newextupdt));
14152 }
14153 
14154 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
14155 {
14156 
14157 	if (have_addr == 0) {
14158 		db_printf("Address required\n");
14159 		return;
14160 	}
14161 	inodedep_print((struct inodedep*)addr, 1);
14162 }
14163 
14164 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
14165 {
14166 	struct inodedep_hashhead *inodedephd;
14167 	struct inodedep *inodedep;
14168 	struct ufsmount *ump;
14169 	int cnt;
14170 
14171 	if (have_addr == 0) {
14172 		db_printf("Address required\n");
14173 		return;
14174 	}
14175 	ump = (struct ufsmount *)addr;
14176 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14177 		inodedephd = &ump->inodedep_hashtbl[cnt];
14178 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14179 			inodedep_print(inodedep, 0);
14180 		}
14181 	}
14182 }
14183 
14184 DB_SHOW_COMMAND(worklist, db_show_worklist)
14185 {
14186 	struct worklist *wk;
14187 
14188 	if (have_addr == 0) {
14189 		db_printf("Address required\n");
14190 		return;
14191 	}
14192 	wk = (struct worklist *)addr;
14193 	printf("worklist: %p type %s state 0x%X\n",
14194 	    wk, TYPENAME(wk->wk_type), wk->wk_state);
14195 }
14196 
14197 DB_SHOW_COMMAND(workhead, db_show_workhead)
14198 {
14199 	struct workhead *wkhd;
14200 	struct worklist *wk;
14201 	int i;
14202 
14203 	if (have_addr == 0) {
14204 		db_printf("Address required\n");
14205 		return;
14206 	}
14207 	wkhd = (struct workhead *)addr;
14208 	wk = LIST_FIRST(wkhd);
14209 	for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
14210 		db_printf("worklist: %p type %s state 0x%X",
14211 		    wk, TYPENAME(wk->wk_type), wk->wk_state);
14212 	if (i == 100)
14213 		db_printf("workhead overflow");
14214 	printf("\n");
14215 }
14216 
14217 
14218 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
14219 {
14220 	struct mkdirlist *mkdirlisthd;
14221 	struct jaddref *jaddref;
14222 	struct diradd *diradd;
14223 	struct mkdir *mkdir;
14224 
14225 	if (have_addr == 0) {
14226 		db_printf("Address required\n");
14227 		return;
14228 	}
14229 	mkdirlisthd = (struct mkdirlist *)addr;
14230 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14231 		diradd = mkdir->md_diradd;
14232 		db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
14233 		    mkdir, mkdir->md_state, diradd, diradd->da_state);
14234 		if ((jaddref = mkdir->md_jaddref) != NULL)
14235 			db_printf(" jaddref %p jaddref state 0x%X",
14236 			    jaddref, jaddref->ja_state);
14237 		db_printf("\n");
14238 	}
14239 }
14240 
14241 /* exported to ffs_vfsops.c */
14242 extern void db_print_ffs(struct ufsmount *ump);
14243 void
14244 db_print_ffs(struct ufsmount *ump)
14245 {
14246 	db_printf("mp %p %s devvp %p fs %p su_wl %d su_deps %d su_req %d\n",
14247 	    ump->um_mountp, ump->um_mountp->mnt_stat.f_mntonname,
14248 	    ump->um_devvp, ump->um_fs, ump->softdep_on_worklist,
14249 	    ump->softdep_deps, ump->softdep_req);
14250 }
14251 
14252 #endif /* DDB */
14253 
14254 #endif /* SOFTUPDATES */
14255